Merge remote-tracking branch 'joncham/sgen-msvc2'
[mono.git] / mono / mini / mini-gc.c
1 /*
2  * mini-gc.c: GC interface for the mono JIT
3  *
4  * Author:
5  *   Zoltan Varga (vargaz@gmail.com)
6  *
7  * Copyright 2009 Novell, Inc (http://www.novell.com)
8  * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
9  */
10
11 #include "config.h"
12 #include "mini-gc.h"
13 #include <mono/metadata/gc-internal.h>
14
15 //#if 0
16 #if defined(MONO_ARCH_GC_MAPS_SUPPORTED)
17
18 #include <mono/metadata/gc-internal.h>
19 #include <mono/utils/mono-counters.h>
20
21 #if SIZEOF_VOID_P == 4
22 typedef guint32 mword;
23 #else
24 typedef guint64 mword;
25 #endif
26
27 #define SIZEOF_SLOT ((int)sizeof (mgreg_t))
28
29 #define GC_BITS_PER_WORD (sizeof (mword) * 8)
30
31 /* Contains state needed by the GC Map construction code */
32 typedef struct {
33         /*
34          * This contains information about stack slots initialized in the prolog, encoded using
35          * (slot_index << 16) | slot_type. The slot_index is relative to the CFA, i.e. 0
36          * means cfa+0, 1 means cfa-4/8, etc.
37          */
38         GSList *stack_slots_from_cfa;
39         /* Same for stack slots relative to the frame pointer */
40         GSList *stack_slots_from_fp;
41
42         /* Number of slots in the map */
43         int nslots;
44         /* The number of registers in the map */
45         int nregs;
46         /* Min and Max offsets of the stack frame relative to fp */
47         int min_offset, max_offset;
48         /* Same for the locals area */
49         int locals_min_offset, locals_max_offset;
50
51         /* The call sites where this frame can be stopped during GC */
52         GCCallSite **callsites;
53         /* The number of call sites */
54         int ncallsites;
55
56         /*
57          * The width of the stack bitmaps in bytes. This is not equal to the bitmap width at
58      * runtime, since it includes columns which are 0.
59          */
60         int stack_bitmap_width;
61         /* 
62          * A bitmap whose width equals nslots, and whose height equals ncallsites.
63          * The bitmap contains a 1 if the corresponding stack slot has type SLOT_REF at the
64          * given callsite.
65          */
66         guint8 *stack_ref_bitmap;
67         /* Same for SLOT_PIN */
68         guint8 *stack_pin_bitmap;
69
70         /*
71          * Similar bitmaps for registers. These have width MONO_MAX_IREGS in bits.
72          */
73         int reg_bitmap_width;
74         guint8 *reg_ref_bitmap;
75         guint8 *reg_pin_bitmap;
76 } MonoCompileGC;
77
78 #define ALIGN_TO(val,align) ((((mgreg_t)val) + ((align) - 1)) & ~((align) - 1))
79
80 #undef DEBUG
81
82 #if 0
83 /* We don't support debug levels, its all-or-nothing */
84 #define DEBUG(s) do { s; fflush (logfile); } while (0)
85 #define DEBUG_ENABLED 1
86 #else
87 #define DEBUG(s)
88 #endif
89
90 #ifdef DEBUG_ENABLED
91 //#if 1
92 #define DEBUG_PRECISE(s) do { s; } while (0)
93 #define DEBUG_PRECISE_ENABLED
94 #else
95 #define DEBUG_PRECISE(s)
96 #endif
97
98 /*
99  * Contains information collected during the conservative stack marking pass,
100  * used during the precise pass. This helps to avoid doing a stack walk twice, which
101  * is expensive.
102  */
103 typedef struct {
104         guint8 *bitmap;
105         int nslots;
106     int frame_start_offset;
107         int nreg_locations;
108         /* Relative to stack_start */
109         int reg_locations [MONO_MAX_IREGS];
110 #ifdef DEBUG_PRECISE_ENABLED
111         MonoJitInfo *ji;
112         gpointer fp;
113         int regs [MONO_MAX_IREGS];
114 #endif
115 } FrameInfo;
116
117 /* Max number of frames stored in the TLS data */
118 #define MAX_FRAMES 50
119
120 /*
121  * Per-thread data kept by this module. This is stored in the GC and passed to us as
122  * parameters, instead of being stored in a TLS variable, since during a collection,
123  * only the collection thread is active.
124  */
125 typedef struct {
126         MonoThreadUnwindState unwind_state;
127         MonoThreadInfo *info;
128         /* For debugging */
129         mgreg_t tid;
130         gpointer ref_to_track;
131         /* Number of frames collected during the !precise pass */
132         int nframes;
133         FrameInfo frames [MAX_FRAMES];
134 } TlsData;
135
136 /* These are constant so don't store them in the GC Maps */
137 /* Number of registers stored in gc maps */
138 #define NREGS MONO_MAX_IREGS
139
140 /* 
141  * The GC Map itself.
142  * Contains information needed to mark a stack frame.
143  * This is a transient structure, created from a compressed representation on-demand.
144  */
145 typedef struct {
146         /*
147          * The offsets of the GC tracked area inside the stack frame relative to the frame pointer.
148          * This includes memory which is NOREF thus doesn't need GC maps.
149          */
150         int start_offset;
151         int end_offset;
152         /*
153          * The offset relative to frame_offset where the the memory described by the GC maps
154          * begins.
155          */
156         int map_offset;
157         /* The number of stack slots in the map */
158         int nslots;
159         /* The frame pointer register */
160         guint8 frame_reg;
161         /* The size of each callsite table entry */
162         guint8 callsite_entry_size;
163         guint has_pin_slots : 1;
164         guint has_ref_slots : 1;
165         guint has_ref_regs : 1;
166         guint has_pin_regs : 1;
167
168         /* The offsets below are into an external bitmaps array */
169
170         /* 
171          * A bitmap whose width is equal to bitmap_width, and whose height is equal to ncallsites.
172          * The bitmap contains a 1 if the corresponding stack slot has type SLOT_REF at the
173          * given callsite.
174          */
175         guint32 stack_ref_bitmap_offset;
176         /*
177          * Same for SLOT_PIN. It is possible that the same bit is set in both bitmaps at
178      * different callsites, if the slot starts out as PIN, and later changes to REF.
179          */
180         guint32 stack_pin_bitmap_offset;
181
182         /*
183          * Corresponding bitmaps for registers
184          * These have width equal to the number of bits set in reg_ref_mask/reg_pin_mask.
185          * FIXME: Merge these with the normal bitmaps, i.e. reserve the first x slots for them ?
186          */
187         guint32 reg_pin_bitmap_offset;
188         guint32 reg_ref_bitmap_offset;
189
190         guint32 used_int_regs, reg_ref_mask, reg_pin_mask;
191
192         /* The number of bits set in the two masks above */
193         guint8 nref_regs, npin_regs;
194
195         /*
196          * A bit array marking slots which contain refs.
197          * This is used only for debugging.
198          */
199         //guint8 *ref_slots;
200
201         /* Callsite offsets */
202         /* These can take up a lot of space, so encode them compactly */
203         union {
204                 guint8 *offsets8;
205                 guint16 *offsets16;
206                 guint32 *offsets32;
207         } callsites;
208         int ncallsites;
209 } GCMap;
210
211 /*
212  * A compressed version of GCMap. This is what gets stored in MonoJitInfo.
213  */
214 typedef struct {
215         //guint8 *ref_slots;
216         //guint8 encoded_size;
217
218         /*
219          * The arrays below are embedded after the struct.
220          * Their address needs to be computed.
221          */
222
223         /* The fixed fields of the GCMap encoded using LEB128 */
224         guint8 encoded [MONO_ZERO_LEN_ARRAY];
225
226         /* An array of ncallsites entries, each entry is callsite_entry_size bytes long */
227         guint8 callsites [MONO_ZERO_LEN_ARRAY];
228
229         /* The GC bitmaps */
230         guint8 bitmaps [MONO_ZERO_LEN_ARRAY];
231 } GCEncodedMap;
232
233 static int precise_frame_count [2], precise_frame_limit = -1;
234 static gboolean precise_frame_limit_inited;
235
236 /* Stats */
237 typedef struct {
238         int scanned_stacks;
239         int scanned;
240         int scanned_precisely;
241         int scanned_conservatively;
242         int scanned_registers;
243         int scanned_native;
244         int scanned_other;
245         
246         int all_slots;
247         int noref_slots;
248         int ref_slots;
249         int pin_slots;
250
251         int gc_maps_size;
252         int gc_callsites_size;
253         int gc_callsites8_size;
254         int gc_callsites16_size;
255         int gc_callsites32_size;
256         int gc_bitmaps_size;
257         int gc_map_struct_size;
258         int tlsdata_size;
259 } JITGCStats;
260
261 static JITGCStats stats;
262
263 static FILE *logfile;
264
265 // FIXME: Move these to a shared place
266
267 static inline void
268 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
269 {
270         guint8 *p = buf;
271
272         do {
273                 guint8 b = value & 0x7f;
274                 value >>= 7;
275                 if (value != 0) /* more bytes to come */
276                         b |= 0x80;
277                 *p ++ = b;
278         } while (value);
279
280         *endbuf = p;
281 }
282
283 static G_GNUC_UNUSED void
284 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
285 {
286         gboolean more = 1;
287         gboolean negative = (value < 0);
288         guint32 size = 32;
289         guint8 byte;
290         guint8 *p = buf;
291
292         while (more) {
293                 byte = value & 0x7f;
294                 value >>= 7;
295                 /* the following is unnecessary if the
296                  * implementation of >>= uses an arithmetic rather
297                  * than logical shift for a signed left operand
298                  */
299                 if (negative)
300                         /* sign extend */
301                         value |= - (1 <<(size - 7));
302                 /* sign bit of byte is second high order bit (0x40) */
303                 if ((value == 0 && !(byte & 0x40)) ||
304                         (value == -1 && (byte & 0x40)))
305                         more = 0;
306                 else
307                         byte |= 0x80;
308                 *p ++= byte;
309         }
310
311         *endbuf = p;
312 }
313
314 static inline guint32
315 decode_uleb128 (guint8 *buf, guint8 **endbuf)
316 {
317         guint8 *p = buf;
318         guint32 res = 0;
319         int shift = 0;
320
321         while (TRUE) {
322                 guint8 b = *p;
323                 p ++;
324
325                 res = res | (((int)(b & 0x7f)) << shift);
326                 if (!(b & 0x80))
327                         break;
328                 shift += 7;
329         }
330
331         *endbuf = p;
332
333         return res;
334 }
335
336 static inline gint32
337 decode_sleb128 (guint8 *buf, guint8 **endbuf)
338 {
339         guint8 *p = buf;
340         gint32 res = 0;
341         int shift = 0;
342
343         while (TRUE) {
344                 guint8 b = *p;
345                 p ++;
346
347                 res = res | (((int)(b & 0x7f)) << shift);
348                 shift += 7;
349                 if (!(b & 0x80)) {
350                         if (shift < 32 && (b & 0x40))
351                                 res |= - (1 << shift);
352                         break;
353                 }
354         }
355
356         *endbuf = p;
357
358         return res;
359 }
360
361 static int
362 encode_frame_reg (int frame_reg)
363 {
364 #ifdef TARGET_AMD64
365         if (frame_reg == AMD64_RSP)
366                 return 0;
367         else if (frame_reg == AMD64_RBP)
368                 return 1;
369 #elif defined(TARGET_X86)
370         if (frame_reg == X86_EBP)
371                 return 0;
372         else if (frame_reg == X86_ESP)
373                 return 1;
374 #elif defined(TARGET_ARM)
375         if (frame_reg == ARMREG_SP)
376                 return 0;
377         else if (frame_reg == ARMREG_FP)
378                 return 1;
379 #elif defined(TARGET_S390X)
380         if (frame_reg == S390_SP)
381                 return 0;
382         else if (frame_reg == S390_FP)
383                 return 1;
384 #else
385         NOT_IMPLEMENTED;
386 #endif
387         g_assert_not_reached ();
388         return -1;
389 }
390
391 static int
392 decode_frame_reg (int encoded)
393 {
394 #ifdef TARGET_AMD64
395         if (encoded == 0)
396                 return AMD64_RSP;
397         else if (encoded == 1)
398                 return AMD64_RBP;
399 #elif defined(TARGET_X86)
400         if (encoded == 0)
401                 return X86_EBP;
402         else if (encoded == 1)
403                 return X86_ESP;
404 #elif defined(TARGET_ARM)
405         if (encoded == 0)
406                 return ARMREG_SP;
407         else if (encoded == 1)
408                 return ARMREG_FP;
409 #elif defined(TARGET_S390X)
410         if (encoded == 0)
411                 return S390_SP;
412         else if (encoded == 1)
413                 return S390_FP;
414 #else
415         NOT_IMPLEMENTED;
416 #endif
417         g_assert_not_reached ();
418         return -1;
419 }
420
421 #ifdef TARGET_AMD64
422 #ifdef HOST_WIN32
423 static int callee_saved_regs [] = { AMD64_RBP, AMD64_RBX, AMD64_R12, AMD64_R13, AMD64_R14, AMD64_R15, AMD64_RDI, AMD64_RSI };
424 #else
425 static int callee_saved_regs [] = { AMD64_RBP, AMD64_RBX, AMD64_R12, AMD64_R13, AMD64_R14, AMD64_R15 };
426 #endif
427 #elif defined(TARGET_X86)
428 static int callee_saved_regs [] = { X86_EBX, X86_ESI, X86_EDI };
429 #elif defined(TARGET_ARM)
430 static int callee_saved_regs [] = { ARMREG_V1, ARMREG_V2, ARMREG_V3, ARMREG_V4, ARMREG_V5, ARMREG_V7, ARMREG_FP };
431 #elif defined(TARGET_S390X)
432 static int callee_saved_regs [] = { s390_r6, s390_r7, s390_r8, s390_r9, s390_r10, s390_r11, s390_r12, s390_r13, s390_r14 };
433 #endif
434
435 static guint32
436 encode_regmask (guint32 regmask)
437 {
438         int i;
439         guint32 res;
440
441         res = 0;
442         for (i = 0; i < sizeof (callee_saved_regs) / sizeof (int); ++i) {
443                 if (regmask & (1 << callee_saved_regs [i])) {
444                         res |= (1 << i);
445                         regmask -= (1 << callee_saved_regs [i]);
446                 }
447         }
448         g_assert (regmask == 0);
449         return res;
450 }
451
452 static guint32
453 decode_regmask (guint32 regmask)
454 {
455         int i;
456         guint32 res;
457
458         res = 0;
459         for (i = 0; i < sizeof (callee_saved_regs) / sizeof (int); ++i)
460                 if (regmask & (1 << i))
461                         res |= (1 << callee_saved_regs [i]);
462         return res;
463 }
464
465 /*
466  * encode_gc_map:
467  *
468  *   Encode the fixed fields of MAP into a buffer pointed to by BUF.
469  */
470 static void
471 encode_gc_map (GCMap *map, guint8 *buf, guint8 **endbuf)
472 {
473         guint32 flags, freg;
474
475         encode_sleb128 (map->start_offset / SIZEOF_SLOT, buf, &buf);
476         encode_sleb128 (map->end_offset / SIZEOF_SLOT, buf, &buf);
477         encode_sleb128 (map->map_offset / SIZEOF_SLOT, buf, &buf);
478         encode_uleb128 (map->nslots, buf, &buf);
479         g_assert (map->callsite_entry_size <= 4);
480         freg = encode_frame_reg (map->frame_reg);
481         g_assert (freg < 2);
482         flags = (map->has_ref_slots ? 1 : 0) | (map->has_pin_slots ? 2 : 0) | (map->has_ref_regs ? 4 : 0) | (map->has_pin_regs ? 8 : 0) | ((map->callsite_entry_size - 1) << 4) | (freg << 6);
483         encode_uleb128 (flags, buf, &buf);
484         encode_uleb128 (encode_regmask (map->used_int_regs), buf, &buf);
485         if (map->has_ref_regs)
486                 encode_uleb128 (encode_regmask (map->reg_ref_mask), buf, &buf);
487         if (map->has_pin_regs)
488                 encode_uleb128 (encode_regmask (map->reg_pin_mask), buf, &buf);
489         encode_uleb128 (map->ncallsites, buf, &buf);
490
491         *endbuf = buf;
492 }       
493
494 /*
495  * decode_gc_map:
496  *
497  *   Decode the encoded GC map representation in BUF and store the result into MAP.
498  */
499 static void
500 decode_gc_map (guint8 *buf, GCMap *map, guint8 **endbuf)
501 {
502         guint32 flags;
503         int stack_bitmap_size, reg_ref_bitmap_size, reg_pin_bitmap_size, offset, freg;
504         int i, n;
505
506         map->start_offset = decode_sleb128 (buf, &buf) * SIZEOF_SLOT;
507         map->end_offset = decode_sleb128 (buf, &buf) * SIZEOF_SLOT;
508         map->map_offset = decode_sleb128 (buf, &buf) * SIZEOF_SLOT;
509         map->nslots = decode_uleb128 (buf, &buf);
510         flags = decode_uleb128 (buf, &buf);
511         map->has_ref_slots = (flags & 1) ? 1 : 0;
512         map->has_pin_slots = (flags & 2) ? 1 : 0;
513         map->has_ref_regs = (flags & 4) ? 1 : 0;
514         map->has_pin_regs = (flags & 8) ? 1 : 0;
515         map->callsite_entry_size = ((flags >> 4) & 0x3) + 1;
516         freg = flags >> 6;
517         map->frame_reg = decode_frame_reg (freg);
518         map->used_int_regs = decode_regmask (decode_uleb128 (buf, &buf));
519         if (map->has_ref_regs) {
520                 map->reg_ref_mask = decode_regmask (decode_uleb128 (buf, &buf));
521                 n = 0;
522                 for (i = 0; i < NREGS; ++i)
523                         if (map->reg_ref_mask & (1 << i))
524                                 n ++;
525                 map->nref_regs = n;
526         }
527         if (map->has_pin_regs) {
528                 map->reg_pin_mask = decode_regmask (decode_uleb128 (buf, &buf));
529                 n = 0;
530                 for (i = 0; i < NREGS; ++i)
531                         if (map->reg_pin_mask & (1 << i))
532                                 n ++;
533                 map->npin_regs = n;
534         }
535         map->ncallsites = decode_uleb128 (buf, &buf);
536
537         stack_bitmap_size = (ALIGN_TO (map->nslots, 8) / 8) * map->ncallsites;
538         reg_ref_bitmap_size = (ALIGN_TO (map->nref_regs, 8) / 8) * map->ncallsites;
539         reg_pin_bitmap_size = (ALIGN_TO (map->npin_regs, 8) / 8) * map->ncallsites;
540         offset = 0;
541         map->stack_ref_bitmap_offset = offset;
542         if (map->has_ref_slots)
543                 offset += stack_bitmap_size;
544         map->stack_pin_bitmap_offset = offset;
545         if (map->has_pin_slots)
546                 offset += stack_bitmap_size;
547         map->reg_ref_bitmap_offset = offset;
548         if (map->has_ref_regs)
549                 offset += reg_ref_bitmap_size;
550         map->reg_pin_bitmap_offset = offset;
551         if (map->has_pin_regs)
552                 offset += reg_pin_bitmap_size;
553
554         *endbuf = buf;
555 }
556
557 static gpointer
558 thread_attach_func (void)
559 {
560         TlsData *tls;
561
562         tls = g_new0 (TlsData, 1);
563         tls->tid = GetCurrentThreadId ();
564         tls->info = mono_thread_info_current ();
565         stats.tlsdata_size += sizeof (TlsData);
566
567         return tls;
568 }
569
570 static void
571 thread_detach_func (gpointer user_data)
572 {
573         TlsData *tls = user_data;
574
575         g_free (tls);
576 }
577
578 static void
579 thread_suspend_func (gpointer user_data, void *sigctx, MonoContext *ctx)
580 {
581         TlsData *tls = user_data;
582
583         if (!tls) {
584                 /* Happens during startup */
585                 tls->unwind_state.valid = FALSE;
586                 return;
587         }
588
589         if (tls->tid != GetCurrentThreadId ()) {
590                 /* Happens on osx because threads are not suspended using signals */
591                 gboolean res;
592
593                 g_assert (tls->info);
594                 res = mono_thread_state_init_from_handle (&tls->unwind_state, (MonoNativeThreadId)tls->tid, tls->info->native_handle);
595         } else {
596                 tls->unwind_state.unwind_data [MONO_UNWIND_DATA_LMF] = mono_get_lmf ();
597                 if (sigctx) {
598                         mono_arch_sigctx_to_monoctx (sigctx, &tls->unwind_state.ctx);
599                         tls->unwind_state.valid = TRUE;
600                 } else if (ctx) {
601                         memcpy (&tls->unwind_state.ctx, ctx, sizeof (MonoContext));
602                         tls->unwind_state.valid = TRUE;
603                 } else {
604                         tls->unwind_state.valid = FALSE;
605                 }
606                 tls->unwind_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = mono_native_tls_get_value (mono_jit_tls_id);
607                 tls->unwind_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
608         }
609
610         if (!tls->unwind_state.unwind_data [MONO_UNWIND_DATA_DOMAIN]) {
611                 /* Happens during startup */
612                 tls->unwind_state.valid = FALSE;
613                 return;
614         }
615 }
616
617 #define DEAD_REF ((gpointer)(gssize)0x2a2a2a2a2a2a2a2aULL)
618
619 static inline void
620 set_bit (guint8 *bitmap, int width, int y, int x)
621 {
622         bitmap [(width * y) + (x / 8)] |= (1 << (x % 8));
623 }
624
625 static inline void
626 clear_bit (guint8 *bitmap, int width, int y, int x)
627 {
628         bitmap [(width * y) + (x / 8)] &= ~(1 << (x % 8));
629 }
630
631 static inline int
632 get_bit (guint8 *bitmap, int width, int y, int x)
633 {
634         return bitmap [(width * y) + (x / 8)] & (1 << (x % 8));
635 }
636
637 static const char*
638 slot_type_to_string (GCSlotType type)
639 {
640         switch (type) {
641         case SLOT_REF:
642                 return "ref";
643         case SLOT_NOREF:
644                 return "noref";
645         case SLOT_PIN:
646                 return "pin";
647         default:
648                 g_assert_not_reached ();
649                 return NULL;
650         }
651 }
652
653 static inline mgreg_t
654 get_frame_pointer (MonoContext *ctx, int frame_reg)
655 {
656 #if defined(TARGET_AMD64)
657                 if (frame_reg == AMD64_RSP)
658                         return ctx->rsp;
659                 else if (frame_reg == AMD64_RBP)
660                         return ctx->rbp;
661 #elif defined(TARGET_X86)
662                 if (frame_reg == X86_ESP)
663                         return ctx->esp;
664                 else if (frame_reg == X86_EBP)
665                         return ctx->ebp;
666 #elif defined(TARGET_ARM)
667                 if (frame_reg == ARMREG_SP)
668                         return (mgreg_t)MONO_CONTEXT_GET_SP (ctx);
669                 else if (frame_reg == ARMREG_FP)
670                         return (mgreg_t)MONO_CONTEXT_GET_BP (ctx);
671 #elif defined(TARGET_S390X)
672                 if (frame_reg == S390_SP)
673                         return (mgreg_t)MONO_CONTEXT_GET_SP (ctx);
674                 else if (frame_reg == S390_FP)
675                         return (mgreg_t)MONO_CONTEXT_GET_BP (ctx);
676 #endif
677                 g_assert_not_reached ();
678                 return 0;
679 }
680
681 /*
682  * conservatively_pass:
683  *
684  *   Mark a thread stack conservatively and collect information needed by the precise pass.
685  */
686 static void
687 conservative_pass (TlsData *tls, guint8 *stack_start, guint8 *stack_end)
688 {
689         MonoJitInfo *ji;
690         MonoContext ctx, new_ctx;
691         MonoLMF *lmf;
692         guint8 *stack_limit;
693         gboolean last = TRUE;
694         GCMap *map;
695         GCMap map_tmp;
696         GCEncodedMap *emap;
697         guint8* fp, *p, *real_frame_start, *frame_start, *frame_end;
698         int i, pc_offset, cindex, bitmap_width;
699         int scanned = 0, scanned_precisely, scanned_conservatively, scanned_registers;
700         gboolean res;
701         StackFrameInfo frame;
702         mgreg_t *reg_locations [MONO_MAX_IREGS];
703         mgreg_t *new_reg_locations [MONO_MAX_IREGS];
704         guint8 *bitmaps;
705         FrameInfo *fi;
706         guint32 precise_regmask;
707
708         if (tls) {
709                 tls->nframes = 0;
710                 tls->ref_to_track = NULL;
711         }
712
713         /* tls == NULL can happen during startup */
714         if (mono_thread_internal_current () == NULL || !tls) {
715                 mono_gc_conservatively_scan_area (stack_start, stack_end);
716                 stats.scanned_stacks += stack_end - stack_start;
717                 return;
718         }
719
720         lmf = tls->unwind_state.unwind_data [MONO_UNWIND_DATA_LMF];
721         frame.domain = NULL;
722
723         /* Number of bytes scanned based on GC map data */
724         scanned = 0;
725         /* Number of bytes scanned precisely based on GC map data */
726         scanned_precisely = 0;
727         /* Number of bytes scanned conservatively based on GC map data */
728         scanned_conservatively = 0;
729         /* Number of bytes scanned conservatively in register save areas */
730         scanned_registers = 0;
731
732         /* This is one past the last address which we have scanned */
733         stack_limit = stack_start;
734
735         if (!tls->unwind_state.valid)
736                 memset (&new_ctx, 0, sizeof (ctx));
737         else
738                 memcpy (&new_ctx, &tls->unwind_state.ctx, sizeof (MonoContext));
739
740         memset (reg_locations, 0, sizeof (reg_locations));
741         memset (new_reg_locations, 0, sizeof (new_reg_locations));
742
743         while (TRUE) {
744                 if (!tls->unwind_state.valid)
745                         break;
746
747                 memcpy (&ctx, &new_ctx, sizeof (ctx));
748
749                 for (i = 0; i < MONO_MAX_IREGS; ++i) {
750                         if (new_reg_locations [i]) {
751                                 /*
752                                  * If the current frame saves the register, it means it might modify its
753                                  * value, thus the old location might not contain the same value, so
754                                  * we have to mark it conservatively.
755                                  */
756                                 if (reg_locations [i]) {
757                                         DEBUG (fprintf (logfile, "\tscan saved reg %s location %p.\n", mono_arch_regname (i), reg_locations [i]));
758                                         mono_gc_conservatively_scan_area (reg_locations [i], (char*)reg_locations [i] + SIZEOF_SLOT);
759                                         scanned_registers += SIZEOF_SLOT;
760                                 }
761
762                                 reg_locations [i] = new_reg_locations [i];
763
764                                 DEBUG (fprintf (logfile, "\treg %s is now at location %p.\n", mono_arch_regname (i), reg_locations [i]));
765                         }
766                 }
767
768                 g_assert ((mgreg_t)stack_limit % SIZEOF_SLOT == 0);
769
770                 res = mono_find_jit_info_ext (frame.domain ? frame.domain : tls->unwind_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], tls->unwind_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS], NULL, &ctx, &new_ctx, NULL, &lmf, new_reg_locations, &frame);
771                 if (!res)
772                         break;
773
774                 ji = frame.ji;
775
776                 if (frame.type == FRAME_TYPE_MANAGED_TO_NATIVE) {
777                         /*
778                          * These frames are problematic for several reasons:
779                          * - they are unwound through an LMF, and we have no precise register tracking for those.
780                          * - the LMF might not contain a precise ip, so we can't compute the call site.
781                          * - the LMF only unwinds to the wrapper frame, so we get these methods twice.
782                          */
783                         DEBUG (fprintf (logfile, "Mark(0): <Managed-to-native transition>\n"));
784                         for (i = 0; i < MONO_MAX_IREGS; ++i) {
785                                 if (reg_locations [i]) {
786                                         DEBUG (fprintf (logfile, "\tscan saved reg %s location %p.\n", mono_arch_regname (i), reg_locations [i]));
787                                         mono_gc_conservatively_scan_area (reg_locations [i], (char*)reg_locations [i] + SIZEOF_SLOT);
788                                         scanned_registers += SIZEOF_SLOT;
789                                 }
790                                 reg_locations [i] = NULL;
791                                 new_reg_locations [i] = NULL;
792                         }
793                         ctx = new_ctx;
794                         continue;
795                 }
796
797                 /* The last frame can be in any state so mark conservatively */
798                 if (last) {
799                         if (ji) {
800                                 DEBUG (char *fname = mono_method_full_name (ji->method, TRUE); fprintf (logfile, "Mark(0): %s+0x%x (%p)\n", fname, pc_offset, (gpointer)MONO_CONTEXT_GET_IP (&ctx)); g_free (fname));
801                         }
802                         DEBUG (fprintf (logfile, "\t <Last frame>\n"));
803                         last = FALSE;
804                         continue;
805                 }
806
807                 pc_offset = (guint8*)MONO_CONTEXT_GET_IP (&ctx) - (guint8*)ji->code_start;
808
809                 /* These frames are very problematic */
810                 if (ji->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
811                         DEBUG (char *fname = mono_method_full_name (ji->method, TRUE); fprintf (logfile, "Mark(0): %s+0x%x (%p)\n", fname, pc_offset, (gpointer)MONO_CONTEXT_GET_IP (&ctx)); g_free (fname));
812                         DEBUG (fprintf (logfile, "\tSkip.\n"));
813                         continue;
814                 }
815
816                 /* All the other frames are at a call site */
817
818                 if (tls->nframes == MAX_FRAMES) {
819                         /* 
820                          * Can't save information since the array is full. So scan the rest of the
821                          * stack conservatively.
822                          */
823                         DEBUG (fprintf (logfile, "Mark (0): Frame stack full.\n"));
824                         break;
825                 }
826
827                 /* Scan the frame of this method */
828
829                 /*
830                  * A frame contains the following:
831                  * - saved registers
832                  * - saved args
833                  * - locals
834                  * - spill area
835                  * - localloc-ed memory
836                  */
837                 g_assert (pc_offset >= 0);
838
839                 emap = ji->gc_info;
840
841                 if (!emap) {
842                         DEBUG (char *fname = mono_method_full_name (ji->method, TRUE); fprintf (logfile, "Mark(0): %s+0x%x (%p)\n", fname, pc_offset, (gpointer)MONO_CONTEXT_GET_IP (&ctx)); g_free (fname));
843                         DEBUG (fprintf (logfile, "\tNo GC Map.\n"));
844                         continue;
845                 }
846
847                 /* The embedded callsite table requires this */
848                 g_assert (((mgreg_t)emap % 4) == 0);
849
850                 /*
851                  * Debugging aid to control the number of frames scanned precisely
852                  */
853                 if (!precise_frame_limit_inited) {
854                         if (getenv ("MONO_PRECISE_COUNT"))
855                                 precise_frame_limit = atoi (getenv ("MONO_PRECISE_COUNT"));
856                         precise_frame_limit_inited = TRUE;
857                 }
858                                 
859                 if (precise_frame_limit != -1) {
860                         if (precise_frame_count [FALSE] == precise_frame_limit)
861                                 printf ("LAST PRECISE FRAME: %s\n", mono_method_full_name (ji->method, TRUE));
862                         if (precise_frame_count [FALSE] > precise_frame_limit)
863                                 continue;
864                 }
865                 precise_frame_count [FALSE] ++;
866
867                 /* Decode the encoded GC map */
868                 map = &map_tmp;
869                 memset (map, 0, sizeof (GCMap));
870                 decode_gc_map (&emap->encoded [0], map, &p);
871                 p = (guint8*)ALIGN_TO (p, map->callsite_entry_size);
872                 map->callsites.offsets8 = p;
873                 p += map->callsite_entry_size * map->ncallsites;
874                 bitmaps = p;
875
876                 fp = (guint8*)get_frame_pointer (&ctx, map->frame_reg);
877
878                 real_frame_start = fp + map->start_offset;
879                 frame_start = fp + map->start_offset + map->map_offset;
880                 frame_end = fp + map->end_offset;
881
882                 DEBUG (char *fname = mono_method_full_name (ji->method, TRUE); fprintf (logfile, "Mark(0): %s+0x%x (%p) limit=%p fp=%p frame=%p-%p (%d)\n", fname, pc_offset, (gpointer)MONO_CONTEXT_GET_IP (&ctx), stack_limit, fp, frame_start, frame_end, (int)(frame_end - frame_start)); g_free (fname));
883
884                 /* Find the callsite index */
885                 if (map->callsite_entry_size == 1) {
886                         for (i = 0; i < map->ncallsites; ++i)
887                                 /* ip points inside the call instruction */
888                                 if (map->callsites.offsets8 [i] == pc_offset + 1)
889                                         break;
890                 } else if (map->callsite_entry_size == 2) {
891                         // FIXME: Use a binary search
892                         for (i = 0; i < map->ncallsites; ++i)
893                                 /* ip points inside the call instruction */
894                                 if (map->callsites.offsets16 [i] == pc_offset + 1)
895                                         break;
896                 } else {
897                         // FIXME: Use a binary search
898                         for (i = 0; i < map->ncallsites; ++i)
899                                 /* ip points inside the call instruction */
900                                 if (map->callsites.offsets32 [i] == pc_offset + 1)
901                                         break;
902                 }
903                 if (i == map->ncallsites) {
904                         printf ("Unable to find ip offset 0x%x in callsite list of %s.\n", pc_offset + 1, mono_method_full_name (ji->method, TRUE));
905                         g_assert_not_reached ();
906                 }
907                 cindex = i;
908
909                 /* 
910                  * This is not neccessary true on x86 because frames have a different size at each
911                  * call site.
912                  */
913                 //g_assert (real_frame_start >= stack_limit);
914
915                 if (real_frame_start > stack_limit) {
916                         /* This scans the previously skipped frames as well */
917                         DEBUG (fprintf (logfile, "\tscan area %p-%p (%d).\n", stack_limit, real_frame_start, (int)(real_frame_start - stack_limit)));
918                         mono_gc_conservatively_scan_area (stack_limit, real_frame_start);
919                         stats.scanned_other += real_frame_start - stack_limit;
920                 }
921
922                 /* Mark stack slots */
923                 if (map->has_pin_slots) {
924                         int bitmap_width = ALIGN_TO (map->nslots, 8) / 8;
925                         guint8 *pin_bitmap = &bitmaps [map->stack_pin_bitmap_offset + (bitmap_width * cindex)];
926                         guint8 *p;
927                         gboolean pinned;
928
929                         p = frame_start;
930                         for (i = 0; i < map->nslots; ++i) {
931                                 pinned = pin_bitmap [i / 8] & (1 << (i % 8));
932                                 if (pinned) {
933                                         DEBUG (fprintf (logfile, "\tscan slot %s0x%x(fp)=%p.\n", (guint8*)p > (guint8*)fp ? "" : "-", ABS ((int)((gssize)p - (gssize)fp)), p));
934                                         mono_gc_conservatively_scan_area (p, p + SIZEOF_SLOT);
935                                         scanned_conservatively += SIZEOF_SLOT;
936                                 } else {
937                                         scanned_precisely += SIZEOF_SLOT;
938                                 }
939                                 p += SIZEOF_SLOT;
940                         }
941                 } else {
942                         scanned_precisely += (map->nslots * SIZEOF_SLOT);
943                 }
944
945                 /* The area outside of start-end is NOREF */
946                 scanned_precisely += (map->end_offset - map->start_offset) - (map->nslots * SIZEOF_SLOT);
947
948                 /* Mark registers */
949                 precise_regmask = map->used_int_regs | (1 << map->frame_reg);
950                 if (map->has_pin_regs) {
951                         int bitmap_width = ALIGN_TO (map->npin_regs, 8) / 8;
952                         guint8 *pin_bitmap = &bitmaps [map->reg_pin_bitmap_offset + (bitmap_width * cindex)];
953                         int bindex = 0;
954                         for (i = 0; i < NREGS; ++i) {
955                                 if (!(map->used_int_regs & (1 << i)))
956                                         continue;
957                                 
958                                 if (!(map->reg_pin_mask & (1 << i)))
959                                         continue;
960
961                                 if (pin_bitmap [bindex / 8] & (1 << (bindex % 8))) {
962                                         DEBUG (fprintf (logfile, "\treg %s saved at 0x%p is pinning.\n", mono_arch_regname (i), reg_locations [i]));
963                                         precise_regmask &= ~(1 << i);
964                                 }
965                                 bindex ++;
966                         }
967                 }
968
969                 scanned += map->end_offset - map->start_offset;
970
971                 g_assert (scanned == scanned_precisely + scanned_conservatively);
972
973                 stack_limit = frame_end;
974
975                 /* Save information for the precise pass */
976                 fi = &tls->frames [tls->nframes];
977                 fi->nslots = map->nslots;
978                 bitmap_width = ALIGN_TO (map->nslots, 8) / 8;
979                 if (map->has_ref_slots)
980                         fi->bitmap = &bitmaps [map->stack_ref_bitmap_offset + (bitmap_width * cindex)];
981                 else
982                         fi->bitmap = NULL;
983                 fi->frame_start_offset = frame_start - stack_start;
984                 fi->nreg_locations = 0;
985                 DEBUG_PRECISE (fi->ji = ji);
986                 DEBUG_PRECISE (fi->fp = fp);
987
988                 if (map->has_ref_regs) {
989                         int bitmap_width = ALIGN_TO (map->nref_regs, 8) / 8;
990                         guint8 *ref_bitmap = &bitmaps [map->reg_ref_bitmap_offset + (bitmap_width * cindex)];
991                         int bindex = 0;
992                         for (i = 0; i < NREGS; ++i) {
993                                 if (!(map->reg_ref_mask & (1 << i)))
994                                         continue;
995
996                                 if (reg_locations [i] && (ref_bitmap [bindex / 8] & (1 << (bindex % 8)))) {
997                                         DEBUG_PRECISE (fi->regs [fi->nreg_locations] = i);
998                                         DEBUG (fprintf (logfile, "\treg %s saved at 0x%p is ref.\n", mono_arch_regname (i), reg_locations [i]));
999                                         fi->reg_locations [fi->nreg_locations] = (guint8*)reg_locations [i] - stack_start;
1000                                         fi->nreg_locations ++;
1001                                 }
1002                                 bindex ++;
1003                         }
1004                 }
1005
1006                 /*
1007                  * Clear locations of precisely stacked registers.
1008                  */
1009                 if (precise_regmask) {
1010                         for (i = 0; i < NREGS; ++i) {
1011                                 if (precise_regmask & (1 << i)) {
1012                                         /*
1013                                          * The method uses this register, and we have precise info for it.
1014                                          * This means the location will be scanned precisely.
1015                                          * Tell the code at the beginning of the loop that this location is
1016                                          * processed.
1017                                          */
1018                                         if (reg_locations [i])
1019                                                 DEBUG (fprintf (logfile, "\treg %s at location %p (==%p) is precise.\n", mono_arch_regname (i), reg_locations [i], (gpointer)*reg_locations [i]));
1020                                         reg_locations [i] = NULL;
1021                                 }
1022                         }
1023                 }
1024
1025                 tls->nframes ++;
1026         }
1027
1028         /* Scan the remaining register save locations */
1029         for (i = 0; i < MONO_MAX_IREGS; ++i) {
1030                 if (reg_locations [i]) {
1031                         DEBUG (fprintf (logfile, "\tscan saved reg location %p.\n", reg_locations [i]));
1032                         mono_gc_conservatively_scan_area (reg_locations [i], (char*)reg_locations [i] + SIZEOF_SLOT);
1033                         scanned_registers += SIZEOF_SLOT;
1034                 }
1035                 if (new_reg_locations [i]) {
1036                         DEBUG (fprintf (logfile, "\tscan saved reg location %p.\n", new_reg_locations [i]));
1037                         mono_gc_conservatively_scan_area (new_reg_locations [i], (char*)new_reg_locations [i] + SIZEOF_SLOT);
1038                         scanned_registers += SIZEOF_SLOT;
1039                 }
1040         }
1041
1042         if (stack_limit < stack_end) {
1043                 DEBUG (fprintf (logfile, "\tscan remaining stack %p-%p (%d).\n", stack_limit, stack_end, (int)(stack_end - stack_limit)));
1044                 mono_gc_conservatively_scan_area (stack_limit, stack_end);
1045                 stats.scanned_native += stack_end - stack_limit;
1046         }
1047
1048         DEBUG (fprintf (logfile, "Marked %d bytes, p=%d,c=%d out of %d.\n", scanned, scanned_precisely, scanned_conservatively, (int)(stack_end - stack_start)));
1049
1050         stats.scanned_stacks += stack_end - stack_start;
1051         stats.scanned += scanned;
1052         stats.scanned_precisely += scanned_precisely;
1053         stats.scanned_conservatively += scanned_conservatively;
1054         stats.scanned_registers += scanned_registers;
1055
1056         //mono_gc_conservatively_scan_area (stack_start, stack_end);
1057 }
1058
1059 /*
1060  * precise_pass:
1061  *
1062  *   Mark a thread stack precisely based on information saved during the conservative
1063  * pass.
1064  */
1065 static void
1066 precise_pass (TlsData *tls, guint8 *stack_start, guint8 *stack_end)
1067 {
1068         int findex, i;
1069         FrameInfo *fi;
1070         guint8 *frame_start;
1071
1072         if (!tls)
1073                 return;
1074
1075         if (!tls->unwind_state.valid)
1076                 return;
1077
1078         for (findex = 0; findex < tls->nframes; findex ++) {
1079                 /* Load information saved by the !precise pass */
1080                 fi = &tls->frames [findex];
1081                 frame_start = stack_start + fi->frame_start_offset;
1082
1083                 DEBUG (char *fname = mono_method_full_name (fi->ji->method, TRUE); fprintf (logfile, "Mark(1): %s\n", fname); g_free (fname));
1084
1085                 /* 
1086                  * FIXME: Add a function to mark using a bitmap, to avoid doing a 
1087                  * call for each object.
1088                  */
1089
1090                 /* Mark stack slots */
1091                 if (fi->bitmap) {
1092                         guint8 *ref_bitmap = fi->bitmap;
1093                         gboolean live;
1094
1095                         for (i = 0; i < fi->nslots; ++i) {
1096                                 MonoObject **ptr = (MonoObject**)(frame_start + (i * SIZEOF_SLOT));
1097
1098                                 live = ref_bitmap [i / 8] & (1 << (i % 8));
1099
1100                                 if (live) {
1101                                         MonoObject *obj = *ptr;
1102                                         if (obj) {
1103                                                 DEBUG (fprintf (logfile, "\tref %s0x%x(fp)=%p: %p ->", (guint8*)ptr >= (guint8*)fi->fp ? "" : "-", ABS ((int)((gssize)ptr - (gssize)fi->fp)), ptr, obj));
1104                                                 *ptr = mono_gc_scan_object (obj);
1105                                                 DEBUG (fprintf (logfile, " %p.\n", *ptr));
1106                                         } else {
1107                                                 DEBUG (fprintf (logfile, "\tref %s0x%x(fp)=%p: %p.\n", (guint8*)ptr >= (guint8*)fi->fp ? "" : "-", ABS ((int)((gssize)ptr - (gssize)fi->fp)), ptr, obj));
1108                                         }
1109                                 } else {
1110 #if 0
1111                                         /*
1112                                          * This is disabled because the pointer takes up a lot of space.
1113                                          * Stack slots might be shared between ref and non-ref variables ?
1114                                          */
1115                                         if (map->ref_slots [i / 8] & (1 << (i % 8))) {
1116                                                 DEBUG (fprintf (logfile, "\tref %s0x%x(fp)=%p: dead (%p)\n", (guint8*)ptr >= (guint8*)fi->fp ? "" : "-", ABS ((int)((gssize)ptr - (gssize)fi->fp)), ptr, *ptr));
1117                                                 /*
1118                                                  * Fail fast if the live range is incorrect, and
1119                                                  * the JITted code tries to access this object
1120                                                  */
1121                                                 *ptr = DEAD_REF;
1122                                         }
1123 #endif
1124                                 }
1125                         }
1126                 }
1127
1128                 /* Mark registers */
1129
1130                 /*
1131                  * Registers are different from stack slots, they have no address where they
1132                  * are stored. Instead, some frame below this frame in the stack saves them
1133                  * in its prolog to the stack. We can mark this location precisely.
1134                  */
1135                 for (i = 0; i < fi->nreg_locations; ++i) {
1136                         /*
1137                          * reg_locations [i] contains the address of the stack slot where
1138                          * a reg was last saved, so mark that slot.
1139                          */
1140                         MonoObject **ptr = (MonoObject**)((guint8*)stack_start + fi->reg_locations [i]);
1141                         MonoObject *obj = *ptr;
1142
1143                         if (obj) {
1144                                 DEBUG (fprintf (logfile, "\treg %s saved at %p: %p ->", mono_arch_regname (fi->regs [i]), ptr, obj));
1145                                 *ptr = mono_gc_scan_object (obj);
1146                                 DEBUG (fprintf (logfile, " %p.\n", *ptr));
1147                         } else {
1148                                 DEBUG (fprintf (logfile, "\treg %s saved at %p: %p\n", mono_arch_regname (fi->regs [i]), ptr, obj));
1149                         }
1150                 }       
1151         }
1152
1153         /*
1154          * Debugging aid to check for missed refs.
1155          */
1156         if (tls->ref_to_track) {
1157                 mgreg_t *p;
1158
1159                 for (p = (mgreg_t*)stack_start; p < (mgreg_t*)stack_end; ++p)
1160                         if (*p == (mgreg_t)tls->ref_to_track)
1161                                 printf ("REF AT %p.\n", p);
1162         }
1163 }
1164
1165 /*
1166  * thread_mark_func:
1167  *
1168  *   This is called by the GC twice to mark a thread stack. PRECISE is FALSE at the first
1169  * call, and TRUE at the second. USER_DATA points to a TlsData
1170  * structure filled up by thread_suspend_func. 
1171  */
1172 static void
1173 thread_mark_func (gpointer user_data, guint8 *stack_start, guint8 *stack_end, gboolean precise)
1174 {
1175         TlsData *tls = user_data;
1176
1177         DEBUG (fprintf (logfile, "****************************************\n"));
1178         DEBUG (fprintf (logfile, "*** %s stack marking for thread %p (%p-%p) ***\n", precise ? "Precise" : "Conservative", tls ? GUINT_TO_POINTER (tls->tid) : NULL, stack_start, stack_end));
1179         DEBUG (fprintf (logfile, "****************************************\n"));
1180
1181         if (!precise)
1182                 conservative_pass (tls, stack_start, stack_end);
1183         else
1184                 precise_pass (tls, stack_start, stack_end);
1185 }
1186
1187 static void
1188 mini_gc_init_gc_map (MonoCompile *cfg)
1189 {
1190         if (COMPILE_LLVM (cfg))
1191                 return;
1192
1193         if (!mono_gc_is_moving ())
1194                 return;
1195
1196         if (!cfg->compile_aot && !mono_gc_precise_stack_mark_enabled ())
1197                 return;
1198
1199 #if 1
1200         /* Debugging support */
1201         {
1202                 static int precise_count;
1203
1204                 precise_count ++;
1205                 if (getenv ("MONO_GCMAP_COUNT")) {
1206                         if (precise_count == atoi (getenv ("MONO_GCMAP_COUNT")))
1207                                 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
1208                         if (precise_count > atoi (getenv ("MONO_GCMAP_COUNT")))
1209                                 return;
1210                 }
1211         }
1212 #endif
1213
1214         cfg->compute_gc_maps = TRUE;
1215
1216         cfg->gc_info = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoCompileGC));
1217 }
1218
1219 /*
1220  * mini_gc_set_slot_type_from_fp:
1221  *
1222  *   Set the GC slot type of the stack slot identified by SLOT_OFFSET, which should be
1223  * relative to the frame pointer. By default, all stack slots are type PIN, so there is no
1224  * need to call this function for those slots.
1225  */
1226 void
1227 mini_gc_set_slot_type_from_fp (MonoCompile *cfg, int slot_offset, GCSlotType type)
1228 {
1229         MonoCompileGC *gcfg = (MonoCompileGC*)cfg->gc_info;
1230
1231         if (!cfg->compute_gc_maps)
1232                 return;
1233
1234         g_assert (slot_offset % SIZEOF_SLOT == 0);
1235
1236         gcfg->stack_slots_from_fp = g_slist_prepend_mempool (cfg->mempool, gcfg->stack_slots_from_fp, GINT_TO_POINTER (((slot_offset) << 16) | type));
1237 }
1238
1239 /*
1240  * mini_gc_set_slot_type_from_cfa:
1241  *
1242  *   Set the GC slot type of the stack slot identified by SLOT_OFFSET, which should be
1243  * relative to the DWARF CFA value. This should be called from mono_arch_emit_prolog ().
1244  * If type is STACK_REF, the slot is assumed to be live from the end of the prolog until
1245  * the end of the method. By default, all stack slots are type PIN, so there is no need to
1246  * call this function for those slots.
1247  */
1248 void
1249 mini_gc_set_slot_type_from_cfa (MonoCompile *cfg, int slot_offset, GCSlotType type)
1250 {
1251         MonoCompileGC *gcfg = (MonoCompileGC*)cfg->gc_info;
1252         int slot = - (slot_offset / SIZEOF_SLOT);
1253
1254         if (!cfg->compute_gc_maps)
1255                 return;
1256
1257         g_assert (slot_offset <= 0);
1258         g_assert (slot_offset % SIZEOF_SLOT == 0);
1259
1260         gcfg->stack_slots_from_cfa = g_slist_prepend_mempool (cfg->mempool, gcfg->stack_slots_from_cfa, GUINT_TO_POINTER (((slot) << 16) | type));
1261 }
1262
1263 static inline int
1264 fp_offset_to_slot (MonoCompile *cfg, int offset)
1265 {
1266         MonoCompileGC *gcfg = cfg->gc_info;
1267
1268         return (offset - gcfg->min_offset) / SIZEOF_SLOT;
1269 }
1270
1271 static inline int
1272 slot_to_fp_offset (MonoCompile *cfg, int slot)
1273 {
1274         MonoCompileGC *gcfg = cfg->gc_info;
1275
1276         return (slot * SIZEOF_SLOT) + gcfg->min_offset;
1277 }
1278
1279 static inline void
1280 set_slot (MonoCompileGC *gcfg, int slot, int callsite_index, GCSlotType type)
1281 {
1282         g_assert (slot >= 0 && slot < gcfg->nslots);
1283
1284         if (type == SLOT_PIN) {
1285                 clear_bit (gcfg->stack_ref_bitmap, gcfg->stack_bitmap_width, callsite_index, slot);
1286                 set_bit (gcfg->stack_pin_bitmap, gcfg->stack_bitmap_width, callsite_index, slot);
1287         } else if (type == SLOT_REF) {
1288                 set_bit (gcfg->stack_ref_bitmap, gcfg->stack_bitmap_width, callsite_index, slot);
1289                 clear_bit (gcfg->stack_pin_bitmap, gcfg->stack_bitmap_width, callsite_index, slot);
1290         } else if (type == SLOT_NOREF) {
1291                 clear_bit (gcfg->stack_ref_bitmap, gcfg->stack_bitmap_width, callsite_index, slot);
1292                 clear_bit (gcfg->stack_pin_bitmap, gcfg->stack_bitmap_width, callsite_index, slot);
1293         }
1294 }
1295
1296 static inline void
1297 set_slot_everywhere (MonoCompileGC *gcfg, int slot, GCSlotType type)
1298 {
1299         int cindex;
1300
1301         for (cindex = 0; cindex < gcfg->ncallsites; ++cindex)
1302                 set_slot (gcfg, slot, cindex, type);
1303 }
1304
1305 static inline void
1306 set_slot_in_range (MonoCompileGC *gcfg, int slot, int from, int to, GCSlotType type)
1307 {
1308         int cindex;
1309
1310         for (cindex = 0; cindex < gcfg->ncallsites; ++cindex) {
1311                 int callsite_offset = gcfg->callsites [cindex]->pc_offset;
1312                 if (callsite_offset >= from && callsite_offset < to)
1313                         set_slot (gcfg, slot, cindex, type);
1314         }
1315 }
1316
1317 static inline void
1318 set_reg_slot (MonoCompileGC *gcfg, int slot, int callsite_index, GCSlotType type)
1319 {
1320         g_assert (slot >= 0 && slot < gcfg->nregs);
1321
1322         if (type == SLOT_PIN) {
1323                 clear_bit (gcfg->reg_ref_bitmap, gcfg->reg_bitmap_width, callsite_index, slot);
1324                 set_bit (gcfg->reg_pin_bitmap, gcfg->reg_bitmap_width, callsite_index, slot);
1325         } else if (type == SLOT_REF) {
1326                 set_bit (gcfg->reg_ref_bitmap, gcfg->reg_bitmap_width, callsite_index, slot);
1327                 clear_bit (gcfg->reg_pin_bitmap, gcfg->reg_bitmap_width, callsite_index, slot);
1328         } else if (type == SLOT_NOREF) {
1329                 clear_bit (gcfg->reg_ref_bitmap, gcfg->reg_bitmap_width, callsite_index, slot);
1330                 clear_bit (gcfg->reg_pin_bitmap, gcfg->reg_bitmap_width, callsite_index, slot);
1331         }
1332 }
1333
1334 static inline void
1335 set_reg_slot_everywhere (MonoCompileGC *gcfg, int slot, GCSlotType type)
1336 {
1337         int cindex;
1338
1339         for (cindex = 0; cindex < gcfg->ncallsites; ++cindex)
1340                 set_reg_slot (gcfg, slot, cindex, type);
1341 }
1342
1343 static inline void
1344 set_reg_slot_in_range (MonoCompileGC *gcfg, int slot, int from, int to, GCSlotType type)
1345 {
1346         int cindex;
1347
1348         for (cindex = 0; cindex < gcfg->ncallsites; ++cindex) {
1349                 int callsite_offset = gcfg->callsites [cindex]->pc_offset;
1350                 if (callsite_offset >= from && callsite_offset < to)
1351                         set_reg_slot (gcfg, slot, cindex, type);
1352         }
1353 }
1354
1355 static void
1356 process_spill_slots (MonoCompile *cfg)
1357 {
1358         MonoCompileGC *gcfg = cfg->gc_info;
1359         MonoBasicBlock *bb;
1360         GSList *l;
1361         int i;
1362
1363         /* Mark all ref/pin spill slots as NOREF by default outside of their live range */
1364         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
1365                 for (l = bb->spill_slot_defs; l; l = l->next) {
1366                         MonoInst *def = l->data;
1367                         int spill_slot = def->inst_c0;
1368                         int bank = def->inst_c1;
1369                         int offset = cfg->spill_info [bank][spill_slot].offset;
1370                         int slot = fp_offset_to_slot (cfg, offset);
1371
1372                         if (bank == MONO_REG_INT_MP || bank == MONO_REG_INT_REF)
1373                                 set_slot_everywhere (gcfg, slot, SLOT_NOREF);
1374                 }
1375         }
1376
1377         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
1378                 for (l = bb->spill_slot_defs; l; l = l->next) {
1379                         MonoInst *def = l->data;
1380                         int spill_slot = def->inst_c0;
1381                         int bank = def->inst_c1;
1382                         int offset = cfg->spill_info [bank][spill_slot].offset;
1383                         int slot = fp_offset_to_slot (cfg, offset);
1384                         GCSlotType type;
1385
1386                         if (bank == MONO_REG_INT_MP)
1387                                 type = SLOT_PIN;
1388                         else
1389                                 type = SLOT_REF;
1390
1391                         /*
1392                          * Extend the live interval for the GC tracked spill slots
1393                          * defined in this bblock.
1394                          * FIXME: This is not needed.
1395                          */
1396                         set_slot_in_range (gcfg, slot, def->backend.pc_offset, bb->native_offset + bb->native_length, type);
1397
1398                         if (cfg->verbose_level > 1)
1399                                 printf ("\t%s spill slot at %s0x%x(fp) (slot = %d)\n", slot_type_to_string (type), offset >= 0 ? "" : "-", ABS (offset), slot);
1400                 }
1401         }
1402
1403         /* Set fp spill slots to NOREF */
1404         for (i = 0; i < cfg->spill_info_len [MONO_REG_DOUBLE]; ++i) {
1405                 int offset = cfg->spill_info [MONO_REG_DOUBLE][i].offset;
1406                 int slot;
1407
1408                 if (offset == -1)
1409                         continue;
1410
1411                 slot = fp_offset_to_slot (cfg, offset);
1412
1413                 set_slot_everywhere (gcfg, slot, SLOT_NOREF);
1414                 /* FIXME: 32 bit */
1415                 if (cfg->verbose_level > 1)
1416                         printf ("\tfp spill slot at %s0x%x(fp) (slot = %d)\n", offset >= 0 ? "" : "-", ABS (offset), slot);
1417         }
1418
1419         /* Set int spill slots to NOREF */
1420         for (i = 0; i < cfg->spill_info_len [MONO_REG_INT]; ++i) {
1421                 int offset = cfg->spill_info [MONO_REG_INT][i].offset;
1422                 int slot;
1423
1424                 if (offset == -1)
1425                         continue;
1426
1427                 slot = fp_offset_to_slot (cfg, offset);
1428
1429                 set_slot_everywhere (gcfg, slot, SLOT_NOREF);
1430                 if (cfg->verbose_level > 1)
1431                         printf ("\tint spill slot at %s0x%x(fp) (slot = %d)\n", offset >= 0 ? "" : "-", ABS (offset), slot);
1432         }
1433 }
1434
1435 /*
1436  * process_other_slots:
1437  *
1438  *   Process stack slots registered using mini_gc_set_slot_type_... ().
1439  */
1440 static void
1441 process_other_slots (MonoCompile *cfg)
1442 {
1443         MonoCompileGC *gcfg = cfg->gc_info;
1444         GSList *l;
1445
1446         /* Relative to the CFA */
1447         for (l = gcfg->stack_slots_from_cfa; l; l = l->next) {
1448                 guint data = GPOINTER_TO_UINT (l->data);
1449                 int cfa_slot = data >> 16;
1450                 GCSlotType type = data & 0xff;
1451                 int slot;
1452                 
1453                 /*
1454                  * Map the cfa relative slot to an fp relative slot.
1455                  * slot_addr == cfa - <cfa_slot>*4/8
1456                  * fp + cfa_offset == cfa
1457                  * -> slot_addr == fp + (cfa_offset - <cfa_slot>*4/8)
1458                  */
1459                 slot = (cfg->cfa_offset / SIZEOF_SLOT) - cfa_slot - (gcfg->min_offset / SIZEOF_SLOT);
1460
1461                 set_slot_everywhere (gcfg, slot, type);
1462
1463                 if (cfg->verbose_level > 1) {
1464                         int fp_offset = slot_to_fp_offset (cfg, slot);
1465                         if (type == SLOT_NOREF)
1466                                 printf ("\tnoref slot at %s0x%x(fp) (slot = %d) (cfa - 0x%x)\n", fp_offset >= 0 ? "" : "-", ABS (fp_offset), slot, (int)(cfa_slot * SIZEOF_SLOT));
1467                 }
1468         }
1469
1470         /* Relative to the FP */
1471         for (l = gcfg->stack_slots_from_fp; l; l = l->next) {
1472                 gint data = GPOINTER_TO_INT (l->data);
1473                 int offset = data >> 16;
1474                 GCSlotType type = data & 0xff;
1475                 int slot;
1476                 
1477                 slot = fp_offset_to_slot (cfg, offset);
1478
1479                 set_slot_everywhere (gcfg, slot, type);
1480
1481                 /* Liveness for these slots is handled by process_spill_slots () */
1482
1483                 if (cfg->verbose_level > 1) {
1484                         if (type == SLOT_REF)
1485                                 printf ("\tref slot at fp+0x%x (slot = %d)\n", offset, slot);
1486                         else if (type == SLOT_NOREF)
1487                                 printf ("\tnoref slot at 0x%x(fp) (slot = %d)\n", offset, slot);
1488                 }
1489         }
1490 }
1491
1492 static gsize*
1493 get_vtype_bitmap (MonoType *t, int *numbits)
1494 {
1495         MonoClass *klass = mono_class_from_mono_type (t);
1496
1497         if (klass->generic_container || mono_class_is_open_constructed_type (t)) {
1498                 /* FIXME: Generic sharing */
1499                 return NULL;
1500         } else {
1501                 mono_class_compute_gc_descriptor (klass);
1502
1503                 return mono_gc_get_bitmap_for_descr (klass->gc_descr, numbits);
1504         }
1505 }
1506
1507 static inline const char*
1508 get_offset_sign (int offset)
1509 {
1510         return offset < 0 ? "-" : "+";
1511 }
1512
1513 static inline int
1514 get_offset_val (int offset)
1515 {
1516         return offset < 0 ? (- offset) : offset;
1517 }
1518
1519 static void
1520 process_variables (MonoCompile *cfg)
1521 {
1522         MonoCompileGC *gcfg = cfg->gc_info;
1523         MonoMethodSignature *sig = mono_method_signature (cfg->method);
1524         int i, locals_min_slot, locals_max_slot, cindex;
1525         MonoBasicBlock *bb;
1526         MonoInst *tmp;
1527         int *pc_offsets;
1528         int locals_min_offset = gcfg->locals_min_offset;
1529         int locals_max_offset = gcfg->locals_max_offset;
1530
1531         /* Slots for locals are NOREF by default */
1532         locals_min_slot = (locals_min_offset - gcfg->min_offset) / SIZEOF_SLOT;
1533         locals_max_slot = (locals_max_offset - gcfg->min_offset) / SIZEOF_SLOT;
1534         for (i = locals_min_slot; i < locals_max_slot; ++i) {
1535                 set_slot_everywhere (gcfg, i, SLOT_NOREF);
1536         }
1537
1538         /*
1539          * Compute the offset where variables are initialized in the first bblock, if any.
1540          */
1541         pc_offsets = g_new0 (int, cfg->next_vreg);
1542
1543         bb = cfg->bb_entry->next_bb;
1544         MONO_BB_FOR_EACH_INS (bb, tmp) {
1545                 if (tmp->opcode == OP_GC_LIVENESS_DEF) {
1546                         int vreg = tmp->inst_c1;
1547                         if (pc_offsets [vreg] == 0) {
1548                                 g_assert (tmp->backend.pc_offset > 0);
1549                                 pc_offsets [vreg] = tmp->backend.pc_offset;
1550                         }
1551                 }
1552         }
1553
1554         /*
1555          * Stack slots holding arguments are initialized in the prolog.
1556          * This means we can treat them alive for the whole method.
1557          */
1558         for (i = 0; i < cfg->num_varinfo; i++) {
1559                 MonoInst *ins = cfg->varinfo [i];
1560                 MonoType *t = ins->inst_vtype;
1561                 MonoMethodVar *vmv;
1562                 guint32 pos;
1563                 gboolean byref, is_this = FALSE;
1564                 gboolean is_arg = i < cfg->locals_start;
1565
1566                 if (ins == cfg->ret) {
1567                         if (!(ins->opcode == OP_REGOFFSET && MONO_TYPE_ISSTRUCT (t)))
1568                                 continue;
1569                 }
1570
1571                 vmv = MONO_VARINFO (cfg, i);
1572
1573                 /* For some reason, 'this' is byref */
1574                 if (sig->hasthis && ins == cfg->args [0] && !cfg->method->klass->valuetype) {
1575                         t = &cfg->method->klass->byval_arg;
1576                         is_this = TRUE;
1577                 }
1578
1579                 byref = t->byref;
1580
1581                 if (ins->opcode == OP_REGVAR) {
1582                         int hreg;
1583                         GCSlotType slot_type;
1584
1585                         t = mini_type_get_underlying_type (NULL, t);
1586
1587                         hreg = ins->dreg;
1588                         g_assert (hreg < MONO_MAX_IREGS);
1589
1590                         if (byref)
1591                                 slot_type = SLOT_PIN;
1592                         else
1593                                 slot_type = mini_type_is_reference (cfg, t) ? SLOT_REF : SLOT_NOREF;
1594
1595                         if (slot_type == SLOT_PIN) {
1596                                 /* These have no live interval, be conservative */
1597                                 set_reg_slot_everywhere (gcfg, hreg, slot_type);
1598                         } else {
1599                                 /*
1600                                  * Unlike variables allocated to the stack, we generate liveness info
1601                                  * for noref vars in registers in mono_spill_global_vars (), because
1602                                  * knowing that a register doesn't contain a ref allows us to mark its save
1603                                  * locations precisely.
1604                                  */
1605                                 for (cindex = 0; cindex < gcfg->ncallsites; ++cindex)
1606                                         if (gcfg->callsites [cindex]->liveness [i / 8] & (1 << (i % 8)))
1607                                                 set_reg_slot (gcfg, hreg, cindex, slot_type);
1608                         }
1609
1610                         if (cfg->verbose_level > 1) {
1611                                 printf ("\t%s %sreg %s(R%d)\n", slot_type_to_string (slot_type), is_arg ? "arg " : "", mono_arch_regname (hreg), vmv->vreg);
1612                         }
1613
1614                         continue;
1615                 }
1616
1617                 if (ins->opcode != OP_REGOFFSET)
1618                         continue;
1619
1620                 if (ins->inst_offset % SIZEOF_SLOT != 0)
1621                         continue;
1622
1623                 if (is_arg && ins->inst_offset >= gcfg->max_offset)
1624                         /* In parent frame */
1625                         continue;
1626
1627                 pos = fp_offset_to_slot (cfg, ins->inst_offset);
1628
1629                 if (is_arg && ins->flags & MONO_INST_IS_DEAD) {
1630                         /* These do not get stored in the prolog */
1631                         set_slot_everywhere (gcfg, pos, SLOT_NOREF);
1632
1633                         if (cfg->verbose_level > 1) {
1634                                 printf ("\tdead arg at fp%s0x%x (slot = %d): %s\n", get_offset_sign (ins->inst_offset), get_offset_val (ins->inst_offset), pos, mono_type_full_name (ins->inst_vtype));
1635                         }
1636                         continue;
1637                 }
1638
1639                 if (MONO_TYPE_ISSTRUCT (t)) {
1640                         int numbits = 0, j;
1641                         gsize *bitmap = NULL;
1642                         gboolean pin = FALSE;
1643                         int size;
1644                         int size_in_slots;
1645                         
1646                         if (ins->backend.is_pinvoke)
1647                                 size = mono_class_native_size (ins->klass, NULL);
1648                         else
1649                                 size = mono_class_value_size (ins->klass, NULL);
1650                         size_in_slots = ALIGN_TO (size, SIZEOF_SLOT) / SIZEOF_SLOT;
1651
1652                         if (cfg->verbose_level > 1)
1653                                 printf ("\tvtype R%d at %s0x%x(fp)-%s0x%x(fp) (slot %d-%d): %s\n", vmv->vreg, get_offset_sign (ins->inst_offset), get_offset_val (ins->inst_offset), get_offset_sign (ins->inst_offset), get_offset_val (ins->inst_offset + (size_in_slots * SIZEOF_SLOT)), pos, pos + size_in_slots, mono_type_full_name (ins->inst_vtype));
1654
1655                         if (!ins->klass->has_references) {
1656                                 if (is_arg) {
1657                                         for (j = 0; j < size_in_slots; ++j)
1658                                                 set_slot_everywhere (gcfg, pos + j, SLOT_NOREF);
1659                                 }
1660                                 continue;
1661                         }
1662
1663                         bitmap = get_vtype_bitmap (t, &numbits);
1664                         if (!bitmap)
1665                                 pin = TRUE;
1666
1667                         /*
1668                          * Most vtypes are marked volatile because of the LDADDR instructions,
1669                          * and they have no liveness information since they are decomposed
1670                          * before the liveness pass. We emit OP_GC_LIVENESS_DEF instructions for
1671                          * them during VZERO decomposition.
1672                          */
1673                         if (!pc_offsets [vmv->vreg])
1674                                 pin = TRUE;
1675
1676                         if (ins->backend.is_pinvoke)
1677                                 pin = TRUE;
1678
1679                         if (bitmap) {
1680                                 for (cindex = 0; cindex < gcfg->ncallsites; ++cindex) {
1681                                         if (gcfg->callsites [cindex]->pc_offset > pc_offsets [vmv->vreg]) {
1682                                                 for (j = 0; j < numbits; ++j) {
1683                                                         if (bitmap [j / GC_BITS_PER_WORD] & ((gsize)1 << (j % GC_BITS_PER_WORD))) {
1684                                                                 /* The descriptor is for the boxed object */
1685                                                                 set_slot (gcfg, (pos + j - (sizeof (MonoObject) / SIZEOF_SLOT)), cindex, pin ? SLOT_PIN : SLOT_REF);
1686                                                         }
1687                                                 }
1688                                         }
1689                                 }
1690
1691                                 if (cfg->verbose_level > 1) {
1692                                         for (j = 0; j < numbits; ++j) {
1693                                                 if (bitmap [j / GC_BITS_PER_WORD] & ((gsize)1 << (j % GC_BITS_PER_WORD)))
1694                                                         printf ("\t\t%s slot at 0x%x(fp) (slot = %d)\n", pin ? "pin" : "ref", (int)(ins->inst_offset + (j * SIZEOF_SLOT)), (int)(pos + j - (sizeof (MonoObject) / SIZEOF_SLOT)));
1695                                         }
1696                                 }
1697                         } else {
1698                                 if (cfg->verbose_level > 1)
1699                                         printf ("\t\tpinned\n");
1700                                 for (j = 0; j < size_in_slots; ++j) {
1701                                         set_slot_everywhere (gcfg, pos + j, SLOT_PIN);
1702                                 }
1703                         }
1704
1705                         g_free (bitmap);
1706
1707                         continue;
1708                 }
1709
1710                 if (!is_arg && (ins->inst_offset < gcfg->min_offset || ins->inst_offset >= gcfg->max_offset))
1711                         /* Vret addr etc. */
1712                         continue;
1713
1714                 if (t->byref) {
1715                         if (is_arg) {
1716                                 set_slot_everywhere (gcfg, pos, SLOT_PIN);
1717                         } else {
1718                                 for (cindex = 0; cindex < gcfg->ncallsites; ++cindex)
1719                                         if (gcfg->callsites [cindex]->liveness [i / 8] & (1 << (i % 8)))
1720                                                 set_slot (gcfg, pos, cindex, SLOT_PIN);
1721                         }
1722                         if (cfg->verbose_level > 1)
1723                                 printf ("\tbyref at %s0x%x(fp) (R%d, slot = %d): %s\n", ins->inst_offset < 0 ? "-" : "", (ins->inst_offset < 0) ? -(int)ins->inst_offset : (int)ins->inst_offset, vmv->vreg, pos, mono_type_full_name (ins->inst_vtype));
1724                         continue;
1725                 }
1726
1727                 /*
1728                  * This is currently disabled, but could be enabled to debug crashes.
1729                  */
1730 #if 0
1731                 if (t->type == MONO_TYPE_I) {
1732                         /*
1733                          * Variables created in mono_handle_global_vregs have type I, but they
1734                          * could hold GC refs since the vregs they were created from might not been
1735                          * marked as holding a GC ref. So be conservative.
1736                          */
1737                         set_slot_everywhere (gcfg, pos, SLOT_PIN);
1738                         continue;
1739                 }
1740 #endif
1741
1742                 t = mini_type_get_underlying_type (NULL, t);
1743
1744                 if (!mini_type_is_reference (cfg, t)) {
1745                         set_slot_everywhere (gcfg, pos, SLOT_NOREF);
1746                         if (cfg->verbose_level > 1)
1747                                 printf ("\tnoref at %s0x%x(fp) (R%d, slot = %d): %s\n", ins->inst_offset < 0 ? "-" : "", (ins->inst_offset < 0) ? -(int)ins->inst_offset : (int)ins->inst_offset, vmv->vreg, pos, mono_type_full_name (ins->inst_vtype));
1748                         if (!t->byref && sizeof (mgreg_t) == 4 && (t->type == MONO_TYPE_I8 || t->type == MONO_TYPE_U8 || t->type == MONO_TYPE_R8)) {
1749                                 set_slot_everywhere (gcfg, pos + 1, SLOT_NOREF);
1750                                 if (cfg->verbose_level > 1)
1751                                         printf ("\tnoref at %s0x%x(fp) (R%d, slot = %d): %s\n", ins->inst_offset < 0 ? "-" : "", (ins->inst_offset < 0) ? -(int)(ins->inst_offset + 4) : (int)ins->inst_offset + 4, vmv->vreg, pos + 1, mono_type_full_name (ins->inst_vtype));
1752                         }
1753                         continue;
1754                 }
1755
1756                 /* 'this' is marked INDIRECT for gshared methods */
1757                 if (ins->flags & (MONO_INST_VOLATILE | MONO_INST_INDIRECT) && !is_this) {
1758                         /*
1759                          * For volatile variables, treat them alive from the point they are
1760                          * initialized in the first bblock until the end of the method.
1761                          */
1762                         if (is_arg) {
1763                                 set_slot_everywhere (gcfg, pos, SLOT_REF);
1764                         } else if (pc_offsets [vmv->vreg]) {
1765                                 set_slot_in_range (gcfg, pos, 0, pc_offsets [vmv->vreg], SLOT_PIN);
1766                                 set_slot_in_range (gcfg, pos, pc_offsets [vmv->vreg], cfg->code_size, SLOT_REF);
1767                         } else {
1768                                 set_slot_everywhere (gcfg, pos, SLOT_PIN);
1769                         }
1770                         if (cfg->verbose_level > 1)
1771                                 printf ("\tvolatile ref at %s0x%x(fp) (R%d, slot = %d): %s\n", ins->inst_offset < 0 ? "-" : "", (ins->inst_offset < 0) ? -(int)ins->inst_offset : (int)ins->inst_offset, vmv->vreg, pos, mono_type_full_name (ins->inst_vtype));
1772                         continue;
1773                 }
1774
1775                 if (is_arg) {
1776                         /* Live for the whole method */
1777                         set_slot_everywhere (gcfg, pos, SLOT_REF);
1778                 } else {
1779                         for (cindex = 0; cindex < gcfg->ncallsites; ++cindex)
1780                                 if (gcfg->callsites [cindex]->liveness [i / 8] & (1 << (i % 8)))
1781                                         set_slot (gcfg, pos, cindex, SLOT_REF);
1782                 }
1783
1784                 if (cfg->verbose_level > 1) {
1785                         printf ("\tref at %s0x%x(fp) (R%d, slot = %d): %s\n", ins->inst_offset < 0 ? "-" : "", (ins->inst_offset < 0) ? -(int)ins->inst_offset : (int)ins->inst_offset, vmv->vreg, pos, mono_type_full_name (ins->inst_vtype));
1786                 }
1787         }
1788
1789         g_free (pc_offsets);
1790 }
1791
1792 static int
1793 sp_offset_to_fp_offset (MonoCompile *cfg, int sp_offset)
1794 {
1795         /* 
1796          * Convert a sp relative offset to a slot index. This is
1797          * platform specific.
1798          */
1799 #ifdef TARGET_AMD64
1800         /* fp = sp + offset */
1801         g_assert (cfg->frame_reg == AMD64_RBP);
1802         return (- cfg->arch.sp_fp_offset + sp_offset);
1803 #elif defined(TARGET_X86)
1804         /* The offset is computed from the sp at the start of the call sequence */
1805         g_assert (cfg->frame_reg == X86_EBP);
1806         return (- cfg->arch.sp_fp_offset - sp_offset);  
1807 #else
1808         NOT_IMPLEMENTED;
1809         return -1;
1810 #endif
1811 }
1812
1813 static GCSlotType
1814 type_to_gc_slot_type (MonoCompile *cfg, MonoType *t)
1815 {
1816         if (t->byref)
1817                 return SLOT_PIN;
1818         t = mini_type_get_underlying_type (NULL, t);
1819         if (mini_type_is_reference (cfg, t))
1820                 return SLOT_REF;
1821         else {
1822                 if (MONO_TYPE_ISSTRUCT (t)) {
1823                         MonoClass *klass = mono_class_from_mono_type (t);
1824                         if (!klass->has_references) {
1825                                 return SLOT_NOREF;
1826                         } else {
1827                                 // FIXME:
1828                                 return SLOT_PIN;
1829                         }
1830                 }
1831                 return SLOT_NOREF;
1832         }
1833 }
1834
1835 static void
1836 process_param_area_slots (MonoCompile *cfg)
1837 {
1838         MonoCompileGC *gcfg = cfg->gc_info;
1839         int cindex, i;
1840         gboolean *is_param;
1841
1842         /*
1843          * These slots are used for passing parameters during calls. They are sp relative, not
1844          * fp relative, so they are harder to handle.
1845          */
1846         if (cfg->flags & MONO_CFG_HAS_ALLOCA)
1847                 /* The distance between fp and sp is not constant */
1848                 return;
1849
1850         is_param = mono_mempool_alloc0 (cfg->mempool, gcfg->nslots * sizeof (gboolean));
1851
1852         for (cindex = 0; cindex < gcfg->ncallsites; ++cindex) {
1853                 GCCallSite *callsite = gcfg->callsites [cindex];
1854                 GSList *l;
1855
1856                 for (l = callsite->param_slots; l; l = l->next) {
1857                         MonoInst *def = l->data;
1858                         MonoType *t = def->inst_vtype;
1859                         int sp_offset = def->inst_offset;
1860                         int fp_offset = sp_offset_to_fp_offset (cfg, sp_offset);
1861                         int slot = fp_offset_to_slot (cfg, fp_offset);
1862                         guint32 align;
1863                         guint32 size;
1864
1865                         if (MONO_TYPE_ISSTRUCT (t)) {
1866                                 size = mini_type_stack_size_full (cfg->generic_sharing_context, t, &align, FALSE);
1867                         } else {
1868                                 size = sizeof (mgreg_t);
1869                         }
1870
1871                         for (i = 0; i < size / sizeof (mgreg_t); ++i) {
1872                                 g_assert (slot + i >= 0 && slot + i < gcfg->nslots);
1873                                 is_param [slot + i] = TRUE;
1874                         }
1875                 }
1876         }
1877
1878         /* All param area slots are noref by default */
1879         for (i = 0; i < gcfg->nslots; ++i) {
1880                 if (is_param [i])
1881                         set_slot_everywhere (gcfg, i, SLOT_NOREF);
1882         }
1883
1884         for (cindex = 0; cindex < gcfg->ncallsites; ++cindex) {
1885                 GCCallSite *callsite = gcfg->callsites [cindex];
1886                 GSList *l;
1887
1888                 for (l = callsite->param_slots; l; l = l->next) {
1889                         MonoInst *def = l->data;
1890                         MonoType *t = def->inst_vtype;
1891                         int sp_offset = def->inst_offset;
1892                         int fp_offset = sp_offset_to_fp_offset (cfg, sp_offset);
1893                         int slot = fp_offset_to_slot (cfg, fp_offset);
1894                         GCSlotType type = type_to_gc_slot_type (cfg, t);
1895
1896                         if (MONO_TYPE_ISSTRUCT (t)) {
1897                                 guint32 align;
1898                                 guint32 size;
1899                                 int size_in_slots;
1900                                 gsize *bitmap;
1901                                 int j, numbits;
1902
1903                                 size = mini_type_stack_size_full (cfg->generic_sharing_context, t, &align, FALSE);
1904                                 size_in_slots = ALIGN_TO (size, SIZEOF_SLOT) / SIZEOF_SLOT;
1905
1906                                 bitmap = get_vtype_bitmap (t, &numbits);
1907                                 if (type == SLOT_NOREF || !bitmap) {
1908                                         for (i = 0; i < size_in_slots; ++i) {
1909                                                 set_slot_in_range (gcfg, slot + i, def->backend.pc_offset, callsite->pc_offset + 1, type);
1910                                         }
1911                                         if (cfg->verbose_level > 1)
1912                                                 printf ("\t%s param area slots at %s0x%x(fp)=0x%x(sp) (slot = %d-%d) [0x%x-0x%x]\n", slot_type_to_string (type), get_offset_sign (fp_offset), get_offset_val (fp_offset), sp_offset, slot, slot + (size / (int)sizeof (mgreg_t)), def->backend.pc_offset, callsite->pc_offset + 1);
1913                                 } else {
1914                                         for (j = 0; j < numbits; ++j) {
1915                                                 if (bitmap [j / GC_BITS_PER_WORD] & ((gsize)1 << (j % GC_BITS_PER_WORD))) {
1916                                                         /* The descriptor is for the boxed object */
1917                                                         set_slot (gcfg, (slot + j - (sizeof (MonoObject) / SIZEOF_SLOT)), cindex, SLOT_REF);
1918                                                 }
1919                                         }
1920                                         if (cfg->verbose_level > 1)
1921                                                 printf ("\tvtype param area slots at %s0x%x(fp)=0x%x(sp) (slot = %d-%d) [0x%x-0x%x]\n", get_offset_sign (fp_offset), get_offset_val (fp_offset), sp_offset, slot, slot + (size / (int)sizeof (mgreg_t)), def->backend.pc_offset, callsite->pc_offset + 1);
1922                                 }
1923                                 g_free (bitmap);
1924                         } else {
1925                                 /* The slot is live between the def instruction and the call */
1926                                 set_slot_in_range (gcfg, slot, def->backend.pc_offset, callsite->pc_offset + 1, type);
1927                                 if (cfg->verbose_level > 1)
1928                                         printf ("\t%s param area slot at %s0x%x(fp)=0x%x(sp) (slot = %d) [0x%x-0x%x]\n", slot_type_to_string (type), get_offset_sign (fp_offset), get_offset_val (fp_offset), sp_offset, slot, def->backend.pc_offset, callsite->pc_offset + 1);
1929                         }
1930                 }
1931         }
1932 }
1933
1934 static void
1935 process_finally_clauses (MonoCompile *cfg)
1936 {
1937         MonoCompileGC *gcfg = cfg->gc_info;
1938         GCCallSite **callsites;
1939         int ncallsites;
1940         gboolean has_finally;
1941         int i, j, nslots, nregs;
1942
1943         ncallsites = gcfg->ncallsites;
1944         nslots = gcfg->nslots;
1945         nregs = gcfg->nregs;
1946         callsites = gcfg->callsites;
1947
1948         /*
1949          * The calls to the finally clauses don't show up in the cfg. See
1950          * test_0_liveness_8 ().
1951          * Variables accessed inside the finally clause are already marked VOLATILE by
1952          * mono_liveness_handle_exception_clauses (). Variables not accessed inside the finally clause have
1953          * correct liveness outside the finally clause. So mark them PIN inside the finally clauses.
1954          */
1955         has_finally = FALSE;
1956         for (i = 0; i < cfg->header->num_clauses; ++i) {
1957                 MonoExceptionClause *clause = &cfg->header->clauses [i];
1958
1959                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY) {
1960                         has_finally = TRUE;
1961                 }
1962         }
1963         if (has_finally) {
1964                 if (cfg->verbose_level > 1)
1965                         printf ("\tMethod has finally clauses, pessimizing live ranges.\n");
1966                 for (j = 0; j < ncallsites; ++j) {
1967                         MonoBasicBlock *bb = callsites [j]->bb;
1968                         MonoExceptionClause *clause;
1969                         gboolean is_in_finally = FALSE;
1970
1971                         for (i = 0; i < cfg->header->num_clauses; ++i) {
1972                                 clause = &cfg->header->clauses [i];
1973                            
1974                                 if (MONO_OFFSET_IN_HANDLER (clause, bb->real_offset)) {
1975                                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY) {
1976                                                 is_in_finally = TRUE;
1977                                                 break;
1978                                         }
1979                                 }
1980                         }
1981
1982                         if (is_in_finally) {
1983                                 for (i = 0; i < nslots; ++i)
1984                                         set_slot (gcfg, i, j, SLOT_PIN);
1985                                 for (i = 0; i < nregs; ++i)
1986                                         set_reg_slot (gcfg, i, j, SLOT_PIN);
1987                         }
1988                 }
1989         }
1990 }
1991
1992 static void
1993 compute_frame_size (MonoCompile *cfg)
1994 {
1995         int i, locals_min_offset, locals_max_offset, cfa_min_offset, cfa_max_offset;
1996         int min_offset, max_offset;
1997         MonoCompileGC *gcfg = cfg->gc_info;
1998         MonoMethodSignature *sig = mono_method_signature (cfg->method);
1999         GSList *l;
2000
2001         /* Compute min/max offsets from the fp */
2002
2003         /* Locals */
2004 #if defined(TARGET_AMD64) || defined(TARGET_X86) || defined(TARGET_ARM) || defined(TARGET_S390X)
2005         locals_min_offset = ALIGN_TO (cfg->locals_min_stack_offset, SIZEOF_SLOT);
2006         locals_max_offset = cfg->locals_max_stack_offset;
2007 #else
2008         /* min/max stack offset needs to be computed in mono_arch_allocate_vars () */
2009         NOT_IMPLEMENTED;
2010 #endif
2011
2012         locals_min_offset = ALIGN_TO (locals_min_offset, SIZEOF_SLOT);
2013         locals_max_offset = ALIGN_TO (locals_max_offset, SIZEOF_SLOT);
2014
2015         min_offset = locals_min_offset;
2016         max_offset = locals_max_offset;
2017
2018         /* Arguments */
2019         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
2020                 MonoInst *ins = cfg->args [i];
2021
2022                 if (ins->opcode == OP_REGOFFSET)
2023                         min_offset = MIN (min_offset, ins->inst_offset);
2024         }
2025
2026         /* Cfa slots */
2027         g_assert (cfg->frame_reg == cfg->cfa_reg);
2028         g_assert (cfg->cfa_offset > 0);
2029         cfa_min_offset = 0;
2030         cfa_max_offset = cfg->cfa_offset;
2031
2032         min_offset = MIN (min_offset, cfa_min_offset);
2033         max_offset = MAX (max_offset, cfa_max_offset);
2034
2035         /* Fp relative slots */
2036         for (l = gcfg->stack_slots_from_fp; l; l = l->next) {
2037                 gint data = GPOINTER_TO_INT (l->data);
2038                 int offset = data >> 16;
2039
2040                 min_offset = MIN (min_offset, offset);
2041         }
2042
2043         /* Spill slots */
2044         if (!(cfg->flags & MONO_CFG_HAS_SPILLUP)) {
2045                 int stack_offset = ALIGN_TO (cfg->stack_offset, SIZEOF_SLOT);
2046                 min_offset = MIN (min_offset, (-stack_offset));
2047         }
2048
2049         /* Param area slots */
2050 #ifdef TARGET_AMD64
2051         min_offset = MIN (min_offset, -cfg->arch.sp_fp_offset);
2052 #elif defined(TARGET_X86)
2053         min_offset = MIN (min_offset, - (cfg->arch.sp_fp_offset + cfg->arch.param_area_size));
2054 #elif defined(TARGET_ARM)
2055         // FIXME:
2056 #elif defined(TARGET_s390X)
2057         // FIXME:
2058 #else
2059         NOT_IMPLEMENTED;
2060 #endif
2061
2062         gcfg->min_offset = min_offset;
2063         gcfg->max_offset = max_offset;
2064         gcfg->locals_min_offset = locals_min_offset;
2065         gcfg->locals_max_offset = locals_max_offset;
2066 }
2067
2068 static void
2069 init_gcfg (MonoCompile *cfg)
2070 {
2071         int i, nregs, nslots;
2072         MonoCompileGC *gcfg = cfg->gc_info;
2073         GCCallSite **callsites;
2074         int ncallsites;
2075         MonoBasicBlock *bb;
2076         GSList *l;
2077
2078         /*
2079          * Collect callsites
2080          */
2081         ncallsites = 0;
2082         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
2083                 ncallsites += g_slist_length (bb->gc_callsites);
2084         }
2085         callsites = mono_mempool_alloc0 (cfg->mempool, ncallsites * sizeof (GCCallSite*));
2086         i = 0;
2087         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
2088                 for (l = bb->gc_callsites; l; l = l->next)
2089                         callsites [i++] = l->data;
2090         }
2091
2092         /* The callsites should already be ordered by pc offset */
2093         for (i = 1; i < ncallsites; ++i)
2094                 g_assert (callsites [i - 1]->pc_offset < callsites [i]->pc_offset);
2095
2096         /*
2097          * The stack frame looks like this:
2098          *
2099          * <fp + max_offset> == cfa ->  <end of previous frame>
2100          *                              <other stack slots>
2101          *                              <locals>
2102          *                              <other stack slots>
2103          * fp + min_offset          ->
2104          * ...
2105          * fp                       ->
2106          */
2107
2108         if (cfg->verbose_level > 1)
2109                 printf ("GC Map for %s: 0x%x-0x%x\n", mono_method_full_name (cfg->method, TRUE), gcfg->min_offset, gcfg->max_offset);
2110
2111         nslots = (gcfg->max_offset - gcfg->min_offset) / SIZEOF_SLOT;
2112         nregs = NREGS;
2113
2114         gcfg->nslots = nslots;
2115         gcfg->nregs = nregs;
2116         gcfg->callsites = callsites;
2117         gcfg->ncallsites = ncallsites;
2118         gcfg->stack_bitmap_width = ALIGN_TO (nslots, 8) / 8;
2119         gcfg->reg_bitmap_width = ALIGN_TO (nregs, 8) / 8;
2120         gcfg->stack_ref_bitmap = mono_mempool_alloc0 (cfg->mempool, gcfg->stack_bitmap_width * ncallsites);
2121         gcfg->stack_pin_bitmap = mono_mempool_alloc0 (cfg->mempool, gcfg->stack_bitmap_width * ncallsites);
2122         gcfg->reg_ref_bitmap = mono_mempool_alloc0 (cfg->mempool, gcfg->reg_bitmap_width * ncallsites);
2123         gcfg->reg_pin_bitmap = mono_mempool_alloc0 (cfg->mempool, gcfg->reg_bitmap_width * ncallsites);
2124
2125         /* All slots start out as PIN */
2126         memset (gcfg->stack_pin_bitmap, 0xff, gcfg->stack_bitmap_width * ncallsites);
2127         for (i = 0; i < nregs; ++i) {
2128                 /*
2129                  * By default, registers are NOREF.
2130                  * It is possible for a callee to save them before being defined in this method,
2131                  * but the saved value is dead too, so it doesn't need to be marked.
2132                  */
2133                 if ((cfg->used_int_regs & (1 << i)))
2134                         set_reg_slot_everywhere (gcfg, i, SLOT_NOREF);
2135         }
2136 }
2137
2138 static void
2139 create_map (MonoCompile *cfg)
2140 {
2141         GCMap *map;
2142         int i, j, nregs, nslots, nref_regs, npin_regs, alloc_size, bitmaps_size, bitmaps_offset;
2143         int ntypes [16];
2144         int stack_bitmap_width, stack_bitmap_size, reg_ref_bitmap_width, reg_ref_bitmap_size;
2145         int reg_pin_bitmap_width, reg_pin_bitmap_size, bindex;
2146         int start, end;
2147         gboolean has_ref_slots, has_pin_slots, has_ref_regs, has_pin_regs;
2148         MonoCompileGC *gcfg = cfg->gc_info;
2149         GCCallSite **callsites;
2150         int ncallsites;
2151         guint8 *bitmap, *bitmaps;
2152         guint32 reg_ref_mask, reg_pin_mask;
2153
2154         ncallsites = gcfg->ncallsites;
2155         nslots = gcfg->nslots;
2156         nregs = gcfg->nregs;
2157         callsites = gcfg->callsites;
2158
2159         /* 
2160          * Compute the real size of the bitmap i.e. ignore NOREF columns at the beginning and at
2161          * the end. Also, compute whenever the map needs ref/pin bitmaps, and collect stats.
2162          */
2163         has_ref_slots = FALSE;
2164         has_pin_slots = FALSE;
2165         start = -1;
2166         end = -1;
2167         memset (ntypes, 0, sizeof (ntypes));
2168         for (i = 0; i < nslots; ++i) {
2169                 gboolean has_ref = FALSE;
2170                 gboolean has_pin = FALSE;
2171
2172                 for (j = 0; j < ncallsites; ++j) {
2173                         if (get_bit (gcfg->stack_pin_bitmap, gcfg->stack_bitmap_width, j, i))
2174                                 has_pin = TRUE;
2175                         if (get_bit (gcfg->stack_ref_bitmap, gcfg->stack_bitmap_width, j, i))
2176                                 has_ref = TRUE;
2177                 }
2178
2179                 if (has_ref)
2180                         has_ref_slots = TRUE;
2181                 if (has_pin)
2182                         has_pin_slots = TRUE;
2183
2184                 if (has_ref)
2185                         ntypes [SLOT_REF] ++;
2186                 else if (has_pin)
2187                         ntypes [SLOT_PIN] ++;
2188                 else
2189                         ntypes [SLOT_NOREF] ++;
2190
2191                 if (has_ref || has_pin) {
2192                         if (start == -1)
2193                                 start = i;
2194                         end = i + 1;
2195                 }
2196         }
2197         if (start == -1) {
2198                 start = end = nslots;
2199         } else {
2200                 g_assert (start != -1);
2201                 g_assert (start < end);
2202         }
2203
2204         has_ref_regs = FALSE;
2205         has_pin_regs = FALSE;
2206         reg_ref_mask = 0;
2207         reg_pin_mask = 0;
2208         nref_regs = 0;
2209         npin_regs = 0;
2210         for (i = 0; i < nregs; ++i) {
2211                 gboolean has_ref = FALSE;
2212                 gboolean has_pin = FALSE;
2213
2214                 if (!(cfg->used_int_regs & (1 << i)))
2215                         continue;
2216
2217                 for (j = 0; j < ncallsites; ++j) {
2218                         if (get_bit (gcfg->reg_ref_bitmap, gcfg->reg_bitmap_width, j, i)) {
2219                                 has_ref = TRUE;
2220                                 break;
2221                         }
2222                 }
2223                 for (j = 0; j < ncallsites; ++j) {
2224                         if (get_bit (gcfg->reg_pin_bitmap, gcfg->reg_bitmap_width, j, i)) {
2225                                 has_pin = TRUE;
2226                                 break;
2227                         }
2228                 }
2229
2230                 if (has_ref) {
2231                         reg_ref_mask |= (1 << i);
2232                         has_ref_regs = TRUE;
2233                         nref_regs ++;
2234                 }
2235                 if (has_pin) {
2236                         reg_pin_mask |= (1 << i);
2237                         has_pin_regs = TRUE;
2238                         npin_regs ++;
2239                 }
2240         }
2241
2242         if (cfg->verbose_level > 1)
2243                 printf ("Slots: %d Start: %d End: %d Refs: %d NoRefs: %d Pin: %d Callsites: %d\n", nslots, start, end, ntypes [SLOT_REF], ntypes [SLOT_NOREF], ntypes [SLOT_PIN], ncallsites);
2244
2245         /* Create the GC Map */
2246
2247         stack_bitmap_width = ALIGN_TO (end - start, 8) / 8;
2248         stack_bitmap_size = stack_bitmap_width * ncallsites;
2249         reg_ref_bitmap_width = ALIGN_TO (nref_regs, 8) / 8;
2250         reg_ref_bitmap_size = reg_ref_bitmap_width * ncallsites;
2251         reg_pin_bitmap_width = ALIGN_TO (npin_regs, 8) / 8;
2252         reg_pin_bitmap_size = reg_pin_bitmap_width * ncallsites;
2253         bitmaps_size = (has_ref_slots ? stack_bitmap_size : 0) + (has_pin_slots ? stack_bitmap_size : 0) + (has_ref_regs ? reg_ref_bitmap_size : 0) + (has_pin_regs ? reg_pin_bitmap_size : 0);
2254         
2255         map = mono_mempool_alloc0 (cfg->mempool, sizeof (GCMap));
2256
2257         map->frame_reg = cfg->frame_reg;
2258         map->start_offset = gcfg->min_offset;
2259         map->end_offset = gcfg->min_offset + (nslots * SIZEOF_SLOT);
2260         map->map_offset = start * SIZEOF_SLOT;
2261         map->nslots = end - start;
2262         map->has_ref_slots = has_ref_slots;
2263         map->has_pin_slots = has_pin_slots;
2264         map->has_ref_regs = has_ref_regs;
2265         map->has_pin_regs = has_pin_regs;
2266         g_assert (nregs < 32);
2267         map->used_int_regs = cfg->used_int_regs;
2268         map->reg_ref_mask = reg_ref_mask;
2269         map->reg_pin_mask = reg_pin_mask;
2270         map->nref_regs = nref_regs;
2271         map->npin_regs = npin_regs;
2272
2273         bitmaps = mono_mempool_alloc0 (cfg->mempool, bitmaps_size);
2274
2275         bitmaps_offset = 0;
2276         if (has_ref_slots) {
2277                 map->stack_ref_bitmap_offset = bitmaps_offset;
2278                 bitmaps_offset += stack_bitmap_size;
2279
2280                 bitmap = &bitmaps [map->stack_ref_bitmap_offset];
2281                 for (i = 0; i < nslots; ++i) {
2282                         for (j = 0; j < ncallsites; ++j) {
2283                                 if (get_bit (gcfg->stack_ref_bitmap, gcfg->stack_bitmap_width, j, i))
2284                                         set_bit (bitmap, stack_bitmap_width, j, i - start);
2285                         }
2286                 }
2287         }
2288         if (has_pin_slots) {
2289                 map->stack_pin_bitmap_offset = bitmaps_offset;
2290                 bitmaps_offset += stack_bitmap_size;
2291
2292                 bitmap = &bitmaps [map->stack_pin_bitmap_offset];
2293                 for (i = 0; i < nslots; ++i) {
2294                         for (j = 0; j < ncallsites; ++j) {
2295                                 if (get_bit (gcfg->stack_pin_bitmap, gcfg->stack_bitmap_width, j, i))
2296                                         set_bit (bitmap, stack_bitmap_width, j, i - start);
2297                         }
2298                 }
2299         }
2300         if (has_ref_regs) {
2301                 map->reg_ref_bitmap_offset = bitmaps_offset;
2302                 bitmaps_offset += reg_ref_bitmap_size;
2303
2304                 bitmap = &bitmaps [map->reg_ref_bitmap_offset];
2305                 bindex = 0;
2306                 for (i = 0; i < nregs; ++i) {
2307                         if (reg_ref_mask & (1 << i)) {
2308                                 for (j = 0; j < ncallsites; ++j) {
2309                                         if (get_bit (gcfg->reg_ref_bitmap, gcfg->reg_bitmap_width, j, i))
2310                                                 set_bit (bitmap, reg_ref_bitmap_width, j, bindex);
2311                                 }
2312                                 bindex ++;
2313                         }
2314                 }
2315         }
2316         if (has_pin_regs) {
2317                 map->reg_pin_bitmap_offset = bitmaps_offset;
2318                 bitmaps_offset += reg_pin_bitmap_size;
2319
2320                 bitmap = &bitmaps [map->reg_pin_bitmap_offset];
2321                 bindex = 0;
2322                 for (i = 0; i < nregs; ++i) {
2323                         if (reg_pin_mask & (1 << i)) {
2324                                 for (j = 0; j < ncallsites; ++j) {
2325                                         if (get_bit (gcfg->reg_pin_bitmap, gcfg->reg_bitmap_width, j, i))
2326                                                 set_bit (bitmap, reg_pin_bitmap_width, j, bindex);
2327                                 }
2328                                 bindex ++;
2329                         }
2330                 }
2331         }
2332
2333         /* Call sites */
2334         map->ncallsites = ncallsites;
2335         if (cfg->code_len < 256)
2336                 map->callsite_entry_size = 1;
2337         else if (cfg->code_len < 65536)
2338                 map->callsite_entry_size = 2;
2339         else
2340                 map->callsite_entry_size = 4;
2341
2342         /* Encode the GC Map */
2343         {
2344                 guint8 buf [256];
2345                 guint8 *endbuf;
2346                 GCEncodedMap *emap;
2347                 int encoded_size;
2348                 guint8 *p;
2349
2350                 encode_gc_map (map, buf, &endbuf);
2351                 g_assert (endbuf - buf < 256);
2352
2353                 encoded_size = endbuf - buf;
2354                 alloc_size = sizeof (GCEncodedMap) + ALIGN_TO (encoded_size, map->callsite_entry_size) + (map->callsite_entry_size * map->ncallsites) + bitmaps_size;
2355
2356                 emap = mono_domain_alloc0 (cfg->domain, alloc_size);
2357                 //emap->ref_slots = map->ref_slots;
2358
2359                 /* Encoded fixed fields */
2360                 p = &emap->encoded [0];
2361                 //emap->encoded_size = encoded_size;
2362                 memcpy (p, buf, encoded_size);
2363                 p += encoded_size;
2364
2365                 /* Callsite table */
2366                 p = (guint8*)ALIGN_TO ((mgreg_t)p, map->callsite_entry_size);
2367                 if (map->callsite_entry_size == 1) {
2368                         guint8 *offsets = p;
2369                         for (i = 0; i < ncallsites; ++i)
2370                                 offsets [i] = callsites [i]->pc_offset;
2371                         stats.gc_callsites8_size += ncallsites * sizeof (guint8);
2372                 } else if (map->callsite_entry_size == 2) {
2373                         guint16 *offsets = (guint16*)p;
2374                         for (i = 0; i < ncallsites; ++i)
2375                                 offsets [i] = callsites [i]->pc_offset;
2376                         stats.gc_callsites16_size += ncallsites * sizeof (guint16);
2377                 } else {
2378                         guint32 *offsets = (guint32*)p;
2379                         for (i = 0; i < ncallsites; ++i)
2380                                 offsets [i] = callsites [i]->pc_offset;
2381                         stats.gc_callsites32_size += ncallsites * sizeof (guint32);
2382                 }
2383                 p += ncallsites * map->callsite_entry_size;
2384
2385                 /* Bitmaps */
2386                 memcpy (p, bitmaps, bitmaps_size);
2387                 p += bitmaps_size;
2388
2389                 g_assert ((guint8*)p - (guint8*)emap <= alloc_size);
2390
2391                 stats.gc_maps_size += alloc_size;
2392                 stats.gc_callsites_size += ncallsites * map->callsite_entry_size;
2393                 stats.gc_bitmaps_size += bitmaps_size;
2394                 stats.gc_map_struct_size += sizeof (GCEncodedMap) + encoded_size;
2395
2396                 cfg->jit_info->gc_info = emap;
2397
2398                 cfg->gc_map = (guint8*)emap;
2399                 cfg->gc_map_size = alloc_size;
2400         }
2401
2402         stats.all_slots += nslots;
2403         stats.ref_slots += ntypes [SLOT_REF];
2404         stats.noref_slots += ntypes [SLOT_NOREF];
2405         stats.pin_slots += ntypes [SLOT_PIN];
2406 }
2407
2408 void
2409 mini_gc_create_gc_map (MonoCompile *cfg)
2410 {
2411         if (!cfg->compute_gc_maps)
2412                 return;
2413
2414         /*
2415          * During marking, all frames except the top frame are at a call site, and we mark the
2416          * top frame conservatively. This means that we only need to compute and record
2417          * GC maps for call sites.
2418          */
2419
2420         if (!(cfg->comp_done & MONO_COMP_LIVENESS))
2421                 /* Without liveness info, the live ranges are not precise enough */
2422                 return;
2423
2424         mono_analyze_liveness_gc (cfg);
2425
2426         compute_frame_size (cfg);
2427
2428         init_gcfg (cfg);
2429
2430         process_spill_slots (cfg);
2431         process_other_slots (cfg);
2432         process_param_area_slots (cfg);
2433         process_variables (cfg);
2434         process_finally_clauses (cfg);
2435
2436         create_map (cfg);
2437 }
2438
2439 static void
2440 parse_debug_options (void)
2441 {
2442         char **opts, **ptr;
2443         char *env;
2444
2445         env = getenv ("MONO_GCMAP_DEBUG");
2446         if (!env)
2447                 return;
2448
2449         opts = g_strsplit (env, ",", -1);
2450         for (ptr = opts; ptr && *ptr; ptr ++) {
2451                 /* No options yet */
2452                 fprintf (stderr, "Invalid format for the MONO_GCMAP_DEBUG env variable: '%s'\n", env);
2453                 exit (1);
2454         }
2455         g_strfreev (opts);
2456 }
2457
2458 void
2459 mini_gc_init (void)
2460 {
2461         MonoGCCallbacks cb;
2462
2463         memset (&cb, 0, sizeof (cb));
2464         cb.thread_attach_func = thread_attach_func;
2465         cb.thread_detach_func = thread_detach_func;
2466         cb.thread_suspend_func = thread_suspend_func;
2467         /* Comment this out to disable precise stack marking */
2468         cb.thread_mark_func = thread_mark_func;
2469         mono_gc_set_gc_callbacks (&cb);
2470
2471         logfile = mono_gc_get_logfile ();
2472
2473         parse_debug_options ();
2474
2475         mono_counters_register ("GC Maps size",
2476                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.gc_maps_size);
2477         mono_counters_register ("GC Call Sites size",
2478                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.gc_callsites_size);
2479         mono_counters_register ("GC Bitmaps size",
2480                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.gc_bitmaps_size);
2481         mono_counters_register ("GC Map struct size",
2482                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.gc_map_struct_size);
2483         mono_counters_register ("GC Call Sites encoded using 8 bits",
2484                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.gc_callsites8_size);
2485         mono_counters_register ("GC Call Sites encoded using 16 bits",
2486                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.gc_callsites16_size);
2487         mono_counters_register ("GC Call Sites encoded using 32 bits",
2488                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.gc_callsites32_size);
2489
2490         mono_counters_register ("GC Map slots (all)",
2491                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.all_slots);
2492         mono_counters_register ("GC Map slots (ref)",
2493                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.ref_slots);
2494         mono_counters_register ("GC Map slots (noref)",
2495                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.noref_slots);
2496         mono_counters_register ("GC Map slots (pin)",
2497                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.pin_slots);
2498
2499         mono_counters_register ("GC TLS Data size",
2500                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.tlsdata_size);
2501
2502         mono_counters_register ("Stack space scanned (all)",
2503                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.scanned_stacks);
2504         mono_counters_register ("Stack space scanned (native)",
2505                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.scanned_native);
2506         mono_counters_register ("Stack space scanned (other)",
2507                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.scanned_other);
2508         mono_counters_register ("Stack space scanned (using GC Maps)",
2509                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.scanned);
2510         mono_counters_register ("Stack space scanned (precise)",
2511                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.scanned_precisely);
2512         mono_counters_register ("Stack space scanned (pin)",
2513                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.scanned_conservatively);
2514         mono_counters_register ("Stack space scanned (pin registers)",
2515                                                         MONO_COUNTER_GC | MONO_COUNTER_INT, &stats.scanned_registers);
2516 }
2517
2518 #else
2519
2520 void
2521 mini_gc_init (void)
2522 {
2523 }
2524
2525 static void
2526 mini_gc_init_gc_map (MonoCompile *cfg)
2527 {
2528 }
2529
2530 void
2531 mini_gc_create_gc_map (MonoCompile *cfg)
2532 {
2533 }
2534
2535 void
2536 mini_gc_set_slot_type_from_fp (MonoCompile *cfg, int slot_offset, GCSlotType type)
2537 {
2538 }
2539
2540 void
2541 mini_gc_set_slot_type_from_cfa (MonoCompile *cfg, int slot_offset, GCSlotType type)
2542 {
2543 }
2544
2545 #endif
2546
2547 /*
2548  * mini_gc_init_cfg:
2549  *
2550  *   Set GC specific options in CFG.
2551  */
2552 void
2553 mini_gc_init_cfg (MonoCompile *cfg)
2554 {
2555         if (mono_gc_is_moving ()) {
2556                 cfg->disable_ref_noref_stack_slot_share = TRUE;
2557                 cfg->gen_write_barriers = TRUE;
2558         }
2559
2560         mini_gc_init_gc_map (cfg);
2561 }
2562
2563 /*
2564  * Problems with the current code:
2565  * - the stack walk is slow
2566  * - vtypes/refs used in EH regions are treated conservatively
2567  * - if the code is finished, less pinning will be done, causing problems because
2568  *   we promote all surviving objects to old-gen.
2569  * - the unwind code can't handle a method stopped inside a finally region, it thinks the caller is
2570  *   another method, but in reality it is either the exception handling code or the CALL_HANDLER opcode.
2571  *   This manifests in "Unable to find ip offset x in callsite list" assertions.
2572  * - the unwind code also can't handle frames which are in the epilog, since the unwind info is not
2573  *   precise there.
2574  */
2575
2576 /*
2577  * Ideas for creating smaller GC maps:
2578  * - remove empty columns from the bitmaps. This requires adding a mask bit array for
2579  *   each bitmap.
2580  * - merge reg and stack slot bitmaps, so the unused bits at the end of the reg bitmap are
2581  *   not wasted.
2582  * - if the bitmap width is not a multiple of 8, the remaining bits are wasted.
2583  * - group ref and non-ref stack slots together in mono_allocate_stack_slots ().
2584  * - add an index for the callsite table so that each entry can be encoded as a 1 byte difference
2585  *   from an index entry.
2586  */