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