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