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