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