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