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