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