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