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