2009-10-28 Mark Probst <mark.probst@gmail.com>
[mono.git] / mono / metadata / boehm-gc.c
1 /*
2  * boehm-gc.c: GC implementation using either the installed or included Boehm GC.
3  *
4  * Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
5  * Copyright 2004-2009 Novell, Inc (http://www.novell.com)
6  */
7
8 #include "config.h"
9 #define GC_I_HIDE_POINTERS
10 #include <mono/metadata/gc-internal.h>
11 #include <mono/metadata/mono-gc.h>
12 #include <mono/metadata/gc-internal.h>
13 #include <mono/metadata/profiler-private.h>
14 #include <mono/metadata/class-internals.h>
15 #include <mono/metadata/method-builder.h>
16 #include <mono/metadata/opcodes.h>
17 #include <mono/metadata/domain-internals.h>
18 #include <mono/metadata/metadata-internals.h>
19 #include <mono/utils/mono-logger.h>
20 #include <mono/utils/mono-time.h>
21 #include <mono/utils/dtrace.h>
22
23 #if HAVE_BOEHM_GC
24
25 #ifdef USE_INCLUDED_LIBGC
26 #undef TRUE
27 #undef FALSE
28 #define THREAD_LOCAL_ALLOC 1
29 #include "private/pthread_support.h"
30 #endif
31
32 #define GC_NO_DESCRIPTOR ((gpointer)(0 | GC_DS_LENGTH))
33
34 static gboolean gc_initialized = FALSE;
35
36 static void
37 mono_gc_warning (char *msg, GC_word arg)
38 {
39         mono_trace (G_LOG_LEVEL_WARNING, MONO_TRACE_GC, msg, (unsigned long)arg);
40 }
41
42 void
43 mono_gc_base_init (void)
44 {
45         if (gc_initialized)
46                 return;
47
48         /*
49          * Handle the case when we are called from a thread different from the main thread,
50          * confusing libgc.
51          * FIXME: Move this to libgc where it belongs.
52          *
53          * we used to do this only when running on valgrind,
54          * but it happens also in other setups.
55          */
56 #if defined(HAVE_PTHREAD_GETATTR_NP) && defined(HAVE_PTHREAD_ATTR_GETSTACK)
57         {
58                 size_t size;
59                 void *sstart;
60                 pthread_attr_t attr;
61                 pthread_getattr_np (pthread_self (), &attr);
62                 pthread_attr_getstack (&attr, &sstart, &size);
63                 pthread_attr_destroy (&attr); 
64                 /*g_print ("stackbottom pth is: %p\n", (char*)sstart + size);*/
65 #ifdef __ia64__
66                 /*
67                  * The calculation above doesn't seem to work on ia64, also we need to set
68                  * GC_register_stackbottom as well, but don't know how.
69                  */
70 #else
71                 /* apparently with some linuxthreads implementations sstart can be NULL,
72                  * fallback to the more imprecise method (bug# 78096).
73                  */
74                 if (sstart) {
75                         GC_stackbottom = (char*)sstart + size;
76                 } else {
77                         int dummy;
78                         gsize stack_bottom = (gsize)&dummy;
79                         stack_bottom += 4095;
80                         stack_bottom &= ~4095;
81                         GC_stackbottom = (char*)stack_bottom;
82                 }
83 #endif
84         }
85 #elif defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
86                 GC_stackbottom = (char*)pthread_get_stackaddr_np (pthread_self ());
87 #else
88         {
89                 int dummy;
90                 gsize stack_bottom = (gsize)&dummy;
91                 stack_bottom += 4095;
92                 stack_bottom &= ~4095;
93                 /*g_print ("stackbottom is: %p\n", (char*)stack_bottom);*/
94                 GC_stackbottom = (char*)stack_bottom;
95         }
96 #endif
97
98         GC_no_dls = TRUE;
99         GC_init ();
100         GC_oom_fn = mono_gc_out_of_memory;
101         GC_set_warn_proc (mono_gc_warning);
102         GC_finalize_on_demand = 1;
103         GC_finalizer_notifier = mono_gc_finalize_notify;
104
105 #ifdef HAVE_GC_GCJ_MALLOC
106         GC_init_gcj_malloc (5, NULL);
107 #endif
108         mono_gc_enable_events ();
109         gc_initialized = TRUE;
110 }
111
112 void
113 mono_gc_collect (int generation)
114 {
115         MONO_PROBE_GC_BEGIN (generation);
116
117         mono_perfcounters->gc_induced++;
118         GC_gcollect ();
119         
120         MONO_PROBE_GC_END (generation);
121 #if defined(ENABLE_DTRACE) && defined(__sun__)
122         /* This works around a dtrace -G problem on Solaris.
123            Limit its actual use to when the probe is enabled. */
124         if (MONO_PROBE_GC_END_ENABLED ())
125                 sleep(0);
126 #endif
127 }
128
129 int
130 mono_gc_max_generation (void)
131 {
132         return 0;
133 }
134
135 int
136 mono_gc_get_generation  (MonoObject *object)
137 {
138         return 0;
139 }
140
141 int
142 mono_gc_collection_count (int generation)
143 {
144         return GC_gc_no;
145 }
146
147 void
148 mono_gc_add_memory_pressure (gint64 value)
149 {
150 }
151
152 gint64
153 mono_gc_get_used_size (void)
154 {
155         return GC_get_heap_size () - GC_get_free_bytes ();
156 }
157
158 gint64
159 mono_gc_get_heap_size (void)
160 {
161         return GC_get_heap_size ();
162 }
163
164 void
165 mono_gc_disable (void)
166 {
167 #ifdef HAVE_GC_ENABLE
168         GC_disable ();
169 #else
170         g_assert_not_reached ();
171 #endif
172 }
173
174 void
175 mono_gc_enable (void)
176 {
177 #ifdef HAVE_GC_ENABLE
178         GC_enable ();
179 #else
180         g_assert_not_reached ();
181 #endif
182 }
183
184 gboolean
185 mono_gc_is_gc_thread (void)
186 {
187 #if GC_VERSION_MAJOR >= 7
188         return TRUE;
189 #elif defined(USE_INCLUDED_LIBGC)
190         return GC_thread_is_registered ();
191 #else
192         return TRUE;
193 #endif
194 }
195
196 extern int GC_thread_register_foreign (void *base_addr);
197
198 gboolean
199 mono_gc_register_thread (void *baseptr)
200 {
201 #if GC_VERSION_MAJOR >= 7
202         struct GC_stack_base sb;
203         int res;
204
205         res = GC_get_stack_base (&sb);
206         if (res != GC_SUCCESS) {
207                 sb.mem_base = baseptr;
208 #ifdef __ia64__
209                 /* Can't determine the register stack bounds */
210                 g_error ("mono_gc_register_thread failed ().\n");
211 #endif
212         }
213         res = GC_register_my_thread (&sb);
214         if ((res != GC_SUCCESS) && (res != GC_DUPLICATE)) {
215                 g_warning ("GC_register_my_thread () failed.\n");
216                 return FALSE;
217         }
218         return TRUE;
219 #else
220         if (mono_gc_is_gc_thread())
221                 return TRUE;
222 #if defined(USE_INCLUDED_LIBGC) && !defined(PLATFORM_WIN32)
223         return GC_thread_register_foreign (baseptr);
224 #else
225         return FALSE;
226 #endif
227 #endif
228 }
229
230 gboolean
231 mono_object_is_alive (MonoObject* o)
232 {
233 #ifdef USE_INCLUDED_LIBGC
234         return GC_is_marked ((gpointer)o);
235 #else
236         return TRUE;
237 #endif
238 }
239
240 #ifdef USE_INCLUDED_LIBGC
241
242 static gint64 gc_start_time;
243
244 static void
245 on_gc_notification (GCEventType event)
246 {
247         if (event == MONO_GC_EVENT_START) {
248                 mono_perfcounters->gc_collections0++;
249                 mono_stats.major_gc_count ++;
250                 gc_start_time = mono_100ns_ticks ();
251         } else if (event == MONO_GC_EVENT_END) {
252                 guint64 heap_size = GC_get_heap_size ();
253                 guint64 used_size = heap_size - GC_get_free_bytes ();
254                 mono_perfcounters->gc_total_bytes = used_size;
255                 mono_perfcounters->gc_committed_bytes = heap_size;
256                 mono_perfcounters->gc_reserved_bytes = heap_size;
257                 mono_perfcounters->gc_gen0size = heap_size;
258                 mono_stats.major_gc_time_usecs += (mono_100ns_ticks () - gc_start_time) / 10;
259                 mono_trace_message (MONO_TRACE_GC, "gc took %d usecs", (mono_100ns_ticks () - gc_start_time) / 10);
260         }
261         mono_profiler_gc_event ((MonoGCEvent) event, 0);
262 }
263  
264 static void
265 on_gc_heap_resize (size_t new_size)
266 {
267         guint64 heap_size = GC_get_heap_size ();
268         mono_perfcounters->gc_committed_bytes = heap_size;
269         mono_perfcounters->gc_reserved_bytes = heap_size;
270         mono_perfcounters->gc_gen0size = heap_size;
271         mono_profiler_gc_heap_resize (new_size);
272 }
273
274 void
275 mono_gc_enable_events (void)
276 {
277         GC_notify_event = on_gc_notification;
278         GC_on_heap_resize = on_gc_heap_resize;
279 }
280
281 #else
282
283 void
284 mono_gc_enable_events (void)
285 {
286 }
287
288 #endif
289
290 int
291 mono_gc_register_root (char *start, size_t size, void *descr)
292 {
293         /* for some strange reason, they want one extra byte on the end */
294         GC_add_roots (start, start + size + 1);
295
296         return TRUE;
297 }
298
299 void
300 mono_gc_deregister_root (char* addr)
301 {
302 #ifndef PLATFORM_WIN32
303         /* FIXME: libgc doesn't define this work win32 for some reason */
304         /* FIXME: No size info */
305         GC_remove_roots (addr, addr + sizeof (gpointer) + 1);
306 #endif
307 }
308
309 void
310 mono_gc_weak_link_add (void **link_addr, MonoObject *obj, gboolean track)
311 {
312         /* libgc requires that we use HIDE_POINTER... */
313         *link_addr = (void*)HIDE_POINTER (obj);
314         GC_GENERAL_REGISTER_DISAPPEARING_LINK (link_addr, obj);
315 }
316
317 void
318 mono_gc_weak_link_remove (void **link_addr)
319 {
320         GC_unregister_disappearing_link (link_addr);
321         *link_addr = NULL;
322 }
323
324 MonoObject*
325 mono_gc_weak_link_get (void **link_addr)
326 {
327         MonoObject *obj = REVEAL_POINTER (*link_addr);
328         if (obj == (MonoObject *) -1)
329                 return NULL;
330         return obj;
331 }
332
333 void*
334 mono_gc_make_descr_for_string (gsize *bitmap, int numbits)
335 {
336         return mono_gc_make_descr_from_bitmap (bitmap, numbits);
337 }
338
339 void*
340 mono_gc_make_descr_for_object (gsize *bitmap, int numbits, size_t obj_size)
341 {
342         return mono_gc_make_descr_from_bitmap (bitmap, numbits);
343 }
344
345 void*
346 mono_gc_make_descr_for_array (int vector, gsize *elem_bitmap, int numbits, size_t elem_size)
347 {
348         /* libgc has no usable support for arrays... */
349         return GC_NO_DESCRIPTOR;
350 }
351
352 void*
353 mono_gc_make_descr_from_bitmap (gsize *bitmap, int numbits)
354 {
355 #ifdef HAVE_GC_GCJ_MALLOC
356         /* It seems there are issues when the bitmap doesn't fit: play it safe */
357         if (numbits >= 30)
358                 return GC_NO_DESCRIPTOR;
359         else
360                 return (gpointer)GC_make_descriptor ((GC_bitmap)bitmap, numbits);
361 #else
362         return NULL;
363 #endif
364 }
365
366 void*
367 mono_gc_alloc_fixed (size_t size, void *descr)
368 {
369         /* To help track down typed allocation bugs */
370         /*
371         static int count;
372         count ++;
373         if (count == atoi (getenv ("COUNT2")))
374                 printf ("HIT!\n");
375         if (count > atoi (getenv ("COUNT2")))
376                 return GC_MALLOC (size);
377         */
378
379         if (descr)
380                 return GC_MALLOC_EXPLICITLY_TYPED (size, (GC_descr)descr);
381         else
382                 return GC_MALLOC (size);
383 }
384
385 void
386 mono_gc_free_fixed (void* addr)
387 {
388 }
389
390 int
391 mono_gc_invoke_finalizers (void)
392 {
393         /* There is a bug in GC_invoke_finalizer () in versions <= 6.2alpha4:
394          * the 'mem_freed' variable is not initialized when there are no
395          * objects to finalize, which leads to strange behavior later on.
396          * The check is necessary to work around that bug.
397          */
398         if (GC_should_invoke_finalizers ())
399                 return GC_invoke_finalizers ();
400         return 0;
401 }
402
403 gboolean
404 mono_gc_pending_finalizers (void)
405 {
406         return GC_should_invoke_finalizers ();
407 }
408
409 /*
410  * LOCKING: Assumes the domain_finalizers lock is held.
411  */
412 static void
413 add_weak_track_handle_internal (MonoDomain *domain, MonoObject *obj, guint32 gchandle)
414 {
415         GSList *refs;
416
417         if (!domain->track_resurrection_objects_hash)
418                 domain->track_resurrection_objects_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
419
420         refs = g_hash_table_lookup (domain->track_resurrection_objects_hash, obj);
421         refs = g_slist_prepend (refs, GUINT_TO_POINTER (gchandle));
422         g_hash_table_insert (domain->track_resurrection_objects_hash, obj, refs);
423 }
424
425 void
426 mono_gc_add_weak_track_handle (MonoObject *obj, guint32 handle)
427 {
428         MonoDomain *domain;
429
430         if (!obj)
431                 return;
432
433         domain = mono_object_get_domain (obj);
434
435         mono_domain_finalizers_lock (domain);
436
437         add_weak_track_handle_internal (domain, obj, handle);
438
439         g_hash_table_insert (domain->track_resurrection_handles_hash, GUINT_TO_POINTER (handle), obj);
440
441         mono_domain_finalizers_unlock (domain);
442 }
443
444 /*
445  * LOCKING: Assumes the domain_finalizers lock is held.
446  */
447 static void
448 remove_weak_track_handle_internal (MonoDomain *domain, MonoObject *obj, guint32 gchandle)
449 {
450         GSList *refs;
451
452         if (!domain->track_resurrection_objects_hash)
453                 return;
454
455         refs = g_hash_table_lookup (domain->track_resurrection_objects_hash, obj);
456         refs = g_slist_remove (refs, GUINT_TO_POINTER (gchandle));
457         g_hash_table_insert (domain->track_resurrection_objects_hash, obj, refs);
458 }
459
460 void
461 mono_gc_change_weak_track_handle (MonoObject *old_obj, MonoObject *obj, guint32 gchandle)
462 {
463         MonoDomain *domain = mono_domain_get ();
464
465         mono_domain_finalizers_lock (domain);
466
467         if (old_obj)
468                 remove_weak_track_handle_internal (domain, old_obj, gchandle);
469         if (obj)
470                 add_weak_track_handle_internal (domain, obj, gchandle);
471
472         mono_domain_finalizers_unlock (domain);
473 }
474
475 void
476 mono_gc_remove_weak_track_handle (guint32 gchandle)
477 {
478         MonoDomain *domain = mono_domain_get ();
479         MonoObject *obj;
480
481         /* Clean our entries in the two hashes in MonoDomain */
482
483         mono_domain_finalizers_lock (domain);
484
485         /* Get the original object this handle pointed to */
486         obj = g_hash_table_lookup (domain->track_resurrection_handles_hash, GUINT_TO_POINTER (gchandle));
487         if (obj) {
488                 g_hash_table_remove (domain->track_resurrection_handles_hash, GUINT_TO_POINTER (gchandle));
489
490                 remove_weak_track_handle_internal (domain, obj, gchandle);
491         }
492
493         mono_domain_finalizers_unlock (domain);
494 }
495
496 GSList*
497 mono_gc_remove_weak_track_object (MonoDomain *domain, MonoObject *obj)
498 {
499         GSList *refs = NULL;
500
501         if (domain->track_resurrection_objects_hash) {
502                 refs = g_hash_table_lookup (domain->track_resurrection_objects_hash, obj);
503
504                 if (refs)
505                         /*
506                          * Since we don't run finalizers again for resurrected objects,
507                          * no need to keep these around.
508                          */
509                         g_hash_table_remove (domain->track_resurrection_objects_hash, obj);
510         }
511
512         return refs;
513 }
514
515 void
516 mono_gc_wbarrier_set_field (MonoObject *obj, gpointer field_ptr, MonoObject* value)
517 {
518         *(void**)field_ptr = value;
519 }
520
521 void
522 mono_gc_wbarrier_set_arrayref (MonoArray *arr, gpointer slot_ptr, MonoObject* value)
523 {
524         *(void**)slot_ptr = value;
525 }
526
527 void
528 mono_gc_wbarrier_arrayref_copy (gpointer dest_ptr, gpointer src_ptr, int count)
529 {
530         memmove (dest_ptr, src_ptr, count * sizeof (gpointer));
531 }
532
533 void
534 mono_gc_wbarrier_generic_store (gpointer ptr, MonoObject* value)
535 {
536         *(void**)ptr = value;
537 }
538
539 void
540 mono_gc_wbarrier_generic_nostore (gpointer ptr)
541 {
542 }
543
544 void
545 mono_gc_wbarrier_value_copy (gpointer dest, gpointer src, int count, MonoClass *klass)
546 {
547         memmove (dest, src, count * mono_class_value_size (klass, NULL));
548 }
549
550 void
551 mono_gc_wbarrier_object_copy (MonoObject* obj, MonoObject *src)
552 {
553         /* do not copy the sync state */
554         memcpy ((char*)obj + sizeof (MonoObject), (char*)src + sizeof (MonoObject),
555                         mono_object_class (obj)->instance_size - sizeof (MonoObject));
556 }
557
558 void
559 mono_gc_clear_domain (MonoDomain *domain)
560 {
561 }
562
563 int
564 mono_gc_get_suspend_signal (void)
565 {
566         return GC_get_suspend_signal ();
567 }
568
569 #if defined(USE_INCLUDED_LIBGC) && defined(USE_COMPILER_TLS) && defined(__linux__) && (defined(__i386__) || defined(__x86_64__))
570 extern __thread MONO_TLS_FAST void* GC_thread_tls;
571 #include "metadata-internals.h"
572
573 static int
574 shift_amount (int v)
575 {
576         int i = 0;
577         while (!(v & (1 << i)))
578                 i++;
579         return i;
580 }
581
582 enum {
583         ATYPE_FREEPTR,
584         ATYPE_FREEPTR_FOR_BOX,
585         ATYPE_NORMAL,
586         ATYPE_GCJ,
587         ATYPE_STRING,
588         ATYPE_NUM
589 };
590
591 static MonoMethod*
592 create_allocator (int atype, int offset)
593 {
594         int index_var, bytes_var, my_fl_var, my_entry_var;
595         guint32 no_freelist_branch, not_small_enough_branch = 0;
596         guint32 size_overflow_branch = 0;
597         MonoMethodBuilder *mb;
598         MonoMethod *res;
599         MonoMethodSignature *csig;
600
601         if (atype == ATYPE_STRING) {
602                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
603                 csig->ret = &mono_defaults.string_class->byval_arg;
604                 csig->params [0] = &mono_defaults.int_class->byval_arg;
605                 csig->params [1] = &mono_defaults.int32_class->byval_arg;
606         } else {
607                 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
608                 csig->ret = &mono_defaults.object_class->byval_arg;
609                 csig->params [0] = &mono_defaults.int_class->byval_arg;
610         }
611
612         mb = mono_mb_new (mono_defaults.object_class, "Alloc", MONO_WRAPPER_ALLOC);
613         bytes_var = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
614         if (atype == ATYPE_STRING) {
615                 /* a string alloator method takes the args: (vtable, len) */
616                 /* bytes = (sizeof (MonoString) + ((len + 1) * 2)); */
617                 mono_mb_emit_ldarg (mb, 1);
618                 mono_mb_emit_icon (mb, 1);
619                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
620                 mono_mb_emit_icon (mb, 1);
621                 mono_mb_emit_byte (mb, MONO_CEE_SHL);
622                 // sizeof (MonoString) might include padding
623                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoString, chars));
624                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
625                 mono_mb_emit_stloc (mb, bytes_var);
626         } else {
627                 /* bytes = vtable->klass->instance_size */
628                 mono_mb_emit_ldarg (mb, 0);
629                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoVTable, klass));
630                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
631                 mono_mb_emit_byte (mb, MONO_CEE_LDIND_I);
632                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoClass, instance_size));
633                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
634                 /* FIXME: assert instance_size stays a 4 byte integer */
635                 mono_mb_emit_byte (mb, MONO_CEE_LDIND_U4);
636                 mono_mb_emit_stloc (mb, bytes_var);
637         }
638
639         /* this is needed for strings/arrays only as the other big types are never allocated with this method */
640         if (atype == ATYPE_STRING) {
641                 /* check for size */
642                 /* if (!SMALL_ENOUGH (bytes)) jump slow_path;*/
643                 mono_mb_emit_ldloc (mb, bytes_var);
644                 mono_mb_emit_icon (mb, (NFREELISTS-1) * GRANULARITY);
645                 not_small_enough_branch = mono_mb_emit_short_branch (mb, MONO_CEE_BGT_UN_S);
646                 /* check for overflow */
647                 mono_mb_emit_ldloc (mb, bytes_var);
648                 mono_mb_emit_icon (mb, sizeof (MonoString));
649                 size_overflow_branch = mono_mb_emit_short_branch (mb, MONO_CEE_BLE_UN_S);
650         }
651
652         /* int index = INDEX_FROM_BYTES(bytes); */
653         index_var = mono_mb_add_local (mb, &mono_defaults.int32_class->byval_arg);
654         
655         mono_mb_emit_ldloc (mb, bytes_var);
656         mono_mb_emit_icon (mb, GRANULARITY - 1);
657         mono_mb_emit_byte (mb, MONO_CEE_ADD);
658         mono_mb_emit_icon (mb, shift_amount (GRANULARITY));
659         mono_mb_emit_byte (mb, MONO_CEE_SHR_UN);
660         mono_mb_emit_icon (mb, shift_amount (sizeof (gpointer)));
661         mono_mb_emit_byte (mb, MONO_CEE_SHL);
662         /* index var is already adjusted into bytes */
663         mono_mb_emit_stloc (mb, index_var);
664
665         my_fl_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
666         my_entry_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
667         /* my_fl = ((GC_thread)tsd) -> ptrfree_freelists + index; */
668         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
669         mono_mb_emit_byte (mb, 0x0D); /* CEE_MONO_TLS */
670         mono_mb_emit_i4 (mb, offset);
671         if (atype == ATYPE_FREEPTR || atype == ATYPE_FREEPTR_FOR_BOX || atype == ATYPE_STRING)
672                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (struct GC_Thread_Rep, ptrfree_freelists));
673         else if (atype == ATYPE_NORMAL)
674                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (struct GC_Thread_Rep, normal_freelists));
675         else if (atype == ATYPE_GCJ)
676                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (struct GC_Thread_Rep, gcj_freelists));
677         else
678                 g_assert_not_reached ();
679         mono_mb_emit_byte (mb, MONO_CEE_ADD);
680         mono_mb_emit_ldloc (mb, index_var);
681         mono_mb_emit_byte (mb, MONO_CEE_ADD);
682         mono_mb_emit_stloc (mb, my_fl_var);
683
684         /* my_entry = *my_fl; */
685         mono_mb_emit_ldloc (mb, my_fl_var);
686         mono_mb_emit_byte (mb, MONO_CEE_LDIND_I);
687         mono_mb_emit_stloc (mb, my_entry_var);
688
689         /* if (EXPECT((word)my_entry >= HBLKSIZE, 1)) { */
690         mono_mb_emit_ldloc (mb, my_entry_var);
691         mono_mb_emit_icon (mb, HBLKSIZE);
692         no_freelist_branch = mono_mb_emit_short_branch (mb, MONO_CEE_BLT_UN_S);
693
694         /* ptr_t next = obj_link(my_entry); *my_fl = next; */
695         mono_mb_emit_ldloc (mb, my_fl_var);
696         mono_mb_emit_ldloc (mb, my_entry_var);
697         mono_mb_emit_byte (mb, MONO_CEE_LDIND_I);
698         mono_mb_emit_byte (mb, MONO_CEE_STIND_I);
699
700         /* set the vtable and clear the words in the object */
701         mono_mb_emit_ldloc (mb, my_entry_var);
702         mono_mb_emit_ldarg (mb, 0);
703         mono_mb_emit_byte (mb, MONO_CEE_STIND_I);
704
705         if (atype == ATYPE_FREEPTR) {
706                 int start_var, end_var, start_loop;
707                 /* end = my_entry + bytes; start = my_entry + sizeof (gpointer);
708                  */
709                 start_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
710                 end_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
711                 mono_mb_emit_ldloc (mb, my_entry_var);
712                 mono_mb_emit_ldloc (mb, bytes_var);
713                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
714                 mono_mb_emit_stloc (mb, end_var);
715                 mono_mb_emit_ldloc (mb, my_entry_var);
716                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoObject, synchronisation));
717                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
718                 mono_mb_emit_stloc (mb, start_var);
719                 /*
720                  * do {
721                  *      *start++ = NULL;
722                  * } while (start < end);
723                  */
724                 start_loop = mono_mb_get_label (mb);
725                 mono_mb_emit_ldloc (mb, start_var);
726                 mono_mb_emit_icon (mb, 0);
727                 mono_mb_emit_byte (mb, MONO_CEE_STIND_I);
728                 mono_mb_emit_ldloc (mb, start_var);
729                 mono_mb_emit_icon (mb, sizeof (gpointer));
730                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
731                 mono_mb_emit_stloc (mb, start_var);
732
733                 mono_mb_emit_ldloc (mb, start_var);
734                 mono_mb_emit_ldloc (mb, end_var);
735                 mono_mb_emit_byte (mb, MONO_CEE_BLT_UN_S);
736                 mono_mb_emit_byte (mb, start_loop - (mono_mb_get_label (mb) + 1));
737         } else if (atype == ATYPE_FREEPTR_FOR_BOX || atype == ATYPE_STRING) {
738                 /* need to clear just the sync pointer */
739                 mono_mb_emit_ldloc (mb, my_entry_var);
740                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoObject, synchronisation));
741                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
742                 mono_mb_emit_icon (mb, 0);
743                 mono_mb_emit_byte (mb, MONO_CEE_STIND_I);
744         }
745
746         if (atype == ATYPE_STRING) {
747                 /* need to set length and clear the last char */
748                 /* s->length = len; */
749                 mono_mb_emit_ldloc (mb, my_entry_var);
750                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoString, length));
751                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
752                 mono_mb_emit_ldarg (mb, 1);
753                 mono_mb_emit_byte (mb, MONO_CEE_STIND_I4);
754                 /* s->chars [len] = 0; */
755                 mono_mb_emit_ldloc (mb, my_entry_var);
756                 mono_mb_emit_ldloc (mb, bytes_var);
757                 mono_mb_emit_icon (mb, 2);
758                 mono_mb_emit_byte (mb, MONO_CEE_SUB);
759                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
760                 mono_mb_emit_icon (mb, 0);
761                 mono_mb_emit_byte (mb, MONO_CEE_STIND_I2);
762         }
763
764         /* return my_entry; */
765         mono_mb_emit_ldloc (mb, my_entry_var);
766         mono_mb_emit_byte (mb, MONO_CEE_RET);
767         
768         mono_mb_patch_short_branch (mb, no_freelist_branch);
769         if (not_small_enough_branch > 0)
770                 mono_mb_patch_short_branch (mb, not_small_enough_branch);
771         if (size_overflow_branch > 0)
772                 mono_mb_patch_short_branch (mb, size_overflow_branch);
773         /* the slow path: we just call back into the runtime */
774         if (atype == ATYPE_STRING) {
775                 mono_mb_emit_ldarg (mb, 1);
776                 mono_mb_emit_icall (mb, mono_string_alloc);
777         } else {
778                 mono_mb_emit_ldarg (mb, 0);
779                 mono_mb_emit_icall (mb, mono_object_new_specific);
780         }
781
782         mono_mb_emit_byte (mb, MONO_CEE_RET);
783
784         res = mono_mb_create_method (mb, csig, 8);
785         mono_mb_free (mb);
786         mono_method_get_header (res)->init_locals = FALSE;
787         return res;
788 }
789
790 static MonoMethod* alloc_method_cache [ATYPE_NUM];
791
792 /*
793  * If possible, generate a managed method that can quickly allocate objects in class
794  * @klass. The method will typically have an thread-local inline allocation sequence.
795  * The signature of the called method is:
796  *      object allocate (MonoVTable *vtable)
797  * Some of the logic here is similar to mono_class_get_allocation_ftn () i object.c,
798  * keep in sync.
799  * The thread local alloc logic is taken from libgc/pthread_support.c.
800  */
801
802 MonoMethod*
803 mono_gc_get_managed_allocator (MonoVTable *vtable, gboolean for_box)
804 {
805         int offset = -1;
806         int atype;
807         MonoClass *klass = vtable->klass;
808         MONO_THREAD_VAR_OFFSET (GC_thread_tls, offset);
809
810         /*g_print ("thread tls: %d\n", offset);*/
811         if (offset == -1)
812                 return NULL;
813         if (!SMALL_ENOUGH (klass->instance_size))
814                 return NULL;
815         if (klass->has_finalize || klass->marshalbyref || (mono_profiler_get_events () & MONO_PROFILE_ALLOCATIONS))
816                 return NULL;
817         if (klass->rank)
818                 return NULL;
819         if (klass->byval_arg.type == MONO_TYPE_STRING) {
820                 atype = ATYPE_STRING;
821         } else if (!klass->has_references) {
822                 if (for_box)
823                         atype = ATYPE_FREEPTR_FOR_BOX;
824                 else
825                         atype = ATYPE_FREEPTR;
826         } else {
827                 return NULL;
828                 /*
829                  * disabled because we currently do a runtime choice anyway, to
830                  * deal with multiple appdomains.
831                 if (vtable->gc_descr != GC_NO_DESCRIPTOR)
832                         atype = ATYPE_GCJ;
833                 else
834                         atype = ATYPE_NORMAL;
835                 */
836         }
837         return mono_gc_get_managed_allocator_by_type (atype);
838 }
839
840 MonoMethod*
841 mono_gc_get_managed_array_allocator (MonoVTable *vtable, int rank)
842 {
843         return NULL;
844 }
845
846 /**
847  * mono_gc_get_managed_allocator_id:
848  *
849  *   Return a type for the managed allocator method MANAGED_ALLOC which can later be passed
850  * to mono_gc_get_managed_allocator_by_type () to get back this allocator method. This can be
851  * used by the AOT code to encode references to managed allocator methods.
852  */
853 int
854 mono_gc_get_managed_allocator_type (MonoMethod *managed_alloc)
855 {
856         int i;
857
858         mono_loader_lock ();
859         for (i = 0; i < ATYPE_NUM; ++i) {
860                 if (alloc_method_cache [i] == managed_alloc) {
861                         mono_loader_unlock ();
862                         return i;
863                 }
864         }
865         mono_loader_unlock ();
866
867         return -1;
868 }
869
870 /**
871  * mono_gc_get_managed_allocator_by_type:
872  *
873  *   Return a managed allocator method corresponding to allocator type ATYPE.
874  */
875 MonoMethod*
876 mono_gc_get_managed_allocator_by_type (int atype)
877 {
878         int offset = -1;
879         MonoMethod *res;
880         MONO_THREAD_VAR_OFFSET (GC_thread_tls, offset);
881
882         mono_loader_lock ();
883         res = alloc_method_cache [atype];
884         if (!res)
885                 res = alloc_method_cache [atype] = create_allocator (atype, offset);
886         mono_loader_unlock ();
887         return res;
888 }
889
890 guint32
891 mono_gc_get_managed_allocator_types (void)
892 {
893         return ATYPE_NUM;
894 }
895
896 #else
897
898 MonoMethod*
899 mono_gc_get_managed_allocator (MonoVTable *vtable, gboolean for_box)
900 {
901         return NULL;
902 }
903
904 MonoMethod*
905 mono_gc_get_managed_array_allocator (MonoVTable *vtable, int rank)
906 {
907         return NULL;
908 }
909
910 int
911 mono_gc_get_managed_allocator_type (MonoMethod *managed_alloc)
912 {
913         return -1;
914 }
915
916 MonoMethod*
917 mono_gc_get_managed_allocator_by_type (int atype)
918 {
919         return NULL;
920 }
921
922 guint32
923 mono_gc_get_managed_allocator_types (void)
924 {
925         return 0;
926 }
927
928 #endif
929
930 #endif /* no Boehm GC */
931