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