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