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