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