Overwrites dequeued ref/value with default. Fixes 18421.
[mono.git] / mono / metadata / sgen-alloc.c
1 /*
2  * sgen-alloc.c: Object allocation routines + managed allocators
3  *
4  * Author:
5  *      Paolo Molaro (lupus@ximian.com)
6  *  Rodrigo Kumpera (kumpera@gmail.com)
7  *
8  * Copyright 2005-2011 Novell, Inc (http://www.novell.com)
9  * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
10  * Copyright 2011 Xamarin, Inc.
11  * Copyright (C) 2012 Xamarin Inc
12  *
13  * This library is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU Library General Public
15  * License 2.0 as published by the Free Software Foundation;
16  *
17  * This library is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Library General Public License for more details.
21  *
22  * You should have received a copy of the GNU Library General Public
23  * License 2.0 along with this library; if not, write to the Free
24  * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25  */
26
27 /*
28  * ######################################################################
29  * ########  Object allocation
30  * ######################################################################
31  * This section of code deals with allocating memory for objects.
32  * There are several ways:
33  * *) allocate large objects
34  * *) allocate normal objects
35  * *) fast lock-free allocation
36  * *) allocation of pinned objects
37  */
38
39 #include "config.h"
40 #ifdef HAVE_SGEN_GC
41
42 #include "metadata/sgen-gc.h"
43 #include "metadata/sgen-protocol.h"
44 #include "metadata/sgen-memory-governor.h"
45 #include "metadata/profiler-private.h"
46 #include "metadata/marshal.h"
47 #include "metadata/method-builder.h"
48 #include "utils/mono-memory-model.h"
49 #include "utils/mono-counters.h"
50
51 #define ALIGN_UP                SGEN_ALIGN_UP
52 #define ALLOC_ALIGN             SGEN_ALLOC_ALIGN
53 #define ALLOC_ALIGN_BITS        SGEN_ALLOC_ALIGN_BITS
54 #define MAX_SMALL_OBJ_SIZE      SGEN_MAX_SMALL_OBJ_SIZE
55 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
56
57 #define OPDEF(a,b,c,d,e,f,g,h,i,j) \
58         a = i,
59
60 enum {
61 #include "mono/cil/opcode.def"
62         CEE_LAST
63 };
64
65 #undef OPDEF
66
67 static gboolean use_managed_allocator = TRUE;
68
69 #ifdef HEAVY_STATISTICS
70 static long long stat_objects_alloced = 0;
71 static long long stat_bytes_alloced = 0;
72 static long long stat_bytes_alloced_los = 0;
73
74 #endif
75
76 /*
77  * Allocation is done from a Thread Local Allocation Buffer (TLAB). TLABs are allocated
78  * from nursery fragments.
79  * tlab_next is the pointer to the space inside the TLAB where the next object will 
80  * be allocated.
81  * tlab_temp_end is the pointer to the end of the temporary space reserved for
82  * the allocation: it allows us to set the scan starts at reasonable intervals.
83  * tlab_real_end points to the end of the TLAB.
84  */
85
86 /*
87  * FIXME: What is faster, a TLS variable pointing to a structure, or separate TLS 
88  * variables for next+temp_end ?
89  */
90 #ifdef HAVE_KW_THREAD
91 static __thread char *tlab_start;
92 static __thread char *tlab_next;
93 static __thread char *tlab_temp_end;
94 static __thread char *tlab_real_end;
95 /* Used by the managed allocator/wbarrier */
96 static __thread char **tlab_next_addr;
97 #endif
98
99 #ifdef HAVE_KW_THREAD
100 #define TLAB_START      tlab_start
101 #define TLAB_NEXT       tlab_next
102 #define TLAB_TEMP_END   tlab_temp_end
103 #define TLAB_REAL_END   tlab_real_end
104 #else
105 #define TLAB_START      (__thread_info__->tlab_start)
106 #define TLAB_NEXT       (__thread_info__->tlab_next)
107 #define TLAB_TEMP_END   (__thread_info__->tlab_temp_end)
108 #define TLAB_REAL_END   (__thread_info__->tlab_real_end)
109 #endif
110
111 static void*
112 alloc_degraded (MonoVTable *vtable, size_t size, gboolean for_mature)
113 {
114         static int last_major_gc_warned = -1;
115         static int num_degraded = 0;
116
117         void *p;
118
119         if (!for_mature) {
120                 if (last_major_gc_warned < stat_major_gcs) {
121                         ++num_degraded;
122                         if (num_degraded == 1 || num_degraded == 3)
123                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC, "Warning: Degraded allocation.  Consider increasing nursery-size if the warning persists.");
124                         else if (num_degraded == 10)
125                                 mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC, "Warning: Repeated degraded allocation.  Consider increasing nursery-size.");
126                         last_major_gc_warned = stat_major_gcs;
127                 }
128                 InterlockedExchangeAdd (&degraded_mode, size);
129                 sgen_ensure_free_space (size);
130         } else {
131                 if (sgen_need_major_collection (size))
132                         sgen_perform_collection (size, GENERATION_OLD, "mature allocation failure", !for_mature);
133         }
134
135
136         p = major_collector.alloc_degraded (vtable, size);
137
138         if (for_mature) {
139                 MONO_GC_MAJOR_OBJ_ALLOC_MATURE ((mword)p, size, vtable->klass->name_space, vtable->klass->name);
140         } else {
141                 binary_protocol_alloc_degraded (p, vtable, size);
142                 MONO_GC_MAJOR_OBJ_ALLOC_DEGRADED ((mword)p, size, vtable->klass->name_space, vtable->klass->name);
143         }
144
145         return p;
146 }
147
148 static void
149 zero_tlab_if_necessary (void *p, size_t size)
150 {
151         if (nursery_clear_policy == CLEAR_AT_TLAB_CREATION) {
152                 memset (p, 0, size);
153         } else {
154                 /*
155                  * This function is called for all allocations in
156                  * TLABs.  TLABs originate from fragments, which are
157                  * initialized to be faux arrays.  The remainder of
158                  * the fragments are zeroed out at initialization for
159                  * CLEAR_AT_GC, so here we just need to make sure that
160                  * the array header is zeroed.  Since we don't know
161                  * whether we're called for the start of a fragment or
162                  * for somewhere in between, we zero in any case, just
163                  * to make sure.
164                  */
165
166                 if (size >= sizeof (MonoArray))
167                         memset (p, 0, sizeof (MonoArray));
168                 else {
169                         static guint8 zeros [sizeof (MonoArray)];
170
171                         SGEN_ASSERT (0, !memcmp (p, zeros, size), "TLAB segment must be zeroed out.");
172                 }
173         }
174 }
175
176 /*
177  * Provide a variant that takes just the vtable for small fixed-size objects.
178  * The aligned size is already computed and stored in vt->gc_descr.
179  * Note: every SGEN_SCAN_START_SIZE or so we are given the chance to do some special
180  * processing. We can keep track of where objects start, for example,
181  * so when we scan the thread stacks for pinned objects, we can start
182  * a search for the pinned object in SGEN_SCAN_START_SIZE chunks.
183  */
184 static void*
185 mono_gc_alloc_obj_nolock (MonoVTable *vtable, size_t size)
186 {
187         /* FIXME: handle OOM */
188         void **p;
189         char *new_next;
190         TLAB_ACCESS_INIT;
191
192         HEAVY_STAT (++stat_objects_alloced);
193         if (size <= SGEN_MAX_SMALL_OBJ_SIZE)
194                 HEAVY_STAT (stat_bytes_alloced += size);
195         else
196                 HEAVY_STAT (stat_bytes_alloced_los += size);
197
198         size = ALIGN_UP (size);
199
200         g_assert (vtable->gc_descr);
201
202         if (G_UNLIKELY (has_per_allocation_action)) {
203                 static int alloc_count;
204                 int current_alloc = InterlockedIncrement (&alloc_count);
205
206                 if (collect_before_allocs) {
207                         if (((current_alloc % collect_before_allocs) == 0) && nursery_section) {
208                                 sgen_perform_collection (0, GENERATION_NURSERY, "collect-before-alloc-triggered", TRUE);
209                                 if (!degraded_mode && sgen_can_alloc_size (size) && size <= SGEN_MAX_SMALL_OBJ_SIZE) {
210                                         // FIXME:
211                                         g_assert_not_reached ();
212                                 }
213                         }
214                 } else if (verify_before_allocs) {
215                         if ((current_alloc % verify_before_allocs) == 0)
216                                 sgen_check_whole_heap_stw ();
217                 }
218         }
219
220         /*
221          * We must already have the lock here instead of after the
222          * fast path because we might be interrupted in the fast path
223          * (after confirming that new_next < TLAB_TEMP_END) by the GC,
224          * and we'll end up allocating an object in a fragment which
225          * no longer belongs to us.
226          *
227          * The managed allocator does not do this, but it's treated
228          * specially by the world-stopping code.
229          */
230
231         if (size > SGEN_MAX_SMALL_OBJ_SIZE) {
232                 p = sgen_los_alloc_large_inner (vtable, size);
233         } else {
234                 /* tlab_next and tlab_temp_end are TLS vars so accessing them might be expensive */
235
236                 p = (void**)TLAB_NEXT;
237                 /* FIXME: handle overflow */
238                 new_next = (char*)p + size;
239                 TLAB_NEXT = new_next;
240
241                 if (G_LIKELY (new_next < TLAB_TEMP_END)) {
242                         /* Fast path */
243
244                         /* 
245                          * FIXME: We might need a memory barrier here so the change to tlab_next is 
246                          * visible before the vtable store.
247                          */
248
249                         SGEN_LOG (6, "Allocated object %p, vtable: %p (%s), size: %zd", p, vtable, vtable->klass->name, size);
250                         binary_protocol_alloc (p , vtable, size);
251                         if (G_UNLIKELY (MONO_GC_NURSERY_OBJ_ALLOC_ENABLED ()))
252                                 MONO_GC_NURSERY_OBJ_ALLOC ((mword)p, size, vtable->klass->name_space, vtable->klass->name);
253                         g_assert (*p == NULL);
254                         mono_atomic_store_seq (p, vtable);
255
256                         return p;
257                 }
258
259                 /* Slow path */
260
261                 /* there are two cases: the object is too big or we run out of space in the TLAB */
262                 /* we also reach here when the thread does its first allocation after a minor 
263                  * collection, since the tlab_ variables are initialized to NULL.
264                  * there can be another case (from ORP), if we cooperate with the runtime a bit:
265                  * objects that need finalizers can have the high bit set in their size
266                  * so the above check fails and we can readily add the object to the queue.
267                  * This avoids taking again the GC lock when registering, but this is moot when
268                  * doing thread-local allocation, so it may not be a good idea.
269                  */
270                 if (TLAB_NEXT >= TLAB_REAL_END) {
271                         int available_in_tlab;
272                         /* 
273                          * Run out of space in the TLAB. When this happens, some amount of space
274                          * remains in the TLAB, but not enough to satisfy the current allocation
275                          * request. Currently, we retire the TLAB in all cases, later we could
276                          * keep it if the remaining space is above a treshold, and satisfy the
277                          * allocation directly from the nursery.
278                          */
279                         TLAB_NEXT -= size;
280                         /* when running in degraded mode, we continue allocing that way
281                          * for a while, to decrease the number of useless nursery collections.
282                          */
283                         if (degraded_mode && degraded_mode < DEFAULT_NURSERY_SIZE)
284                                 return alloc_degraded (vtable, size, FALSE);
285
286                         available_in_tlab = TLAB_REAL_END - TLAB_NEXT;
287                         if (size > tlab_size || available_in_tlab > SGEN_MAX_NURSERY_WASTE) {
288                                 /* Allocate directly from the nursery */
289                                 do {
290                                         p = sgen_nursery_alloc (size);
291                                         if (!p) {
292                                                 sgen_ensure_free_space (size);
293                                                 if (degraded_mode)
294                                                         return alloc_degraded (vtable, size, FALSE);
295                                                 else
296                                                         p = sgen_nursery_alloc (size);
297                                         }
298                                 } while (!p);
299                                 if (!p) {
300                                         // no space left
301                                         g_assert (0);
302                                 }
303
304                                 zero_tlab_if_necessary (p, size);
305                         } else {
306                                 size_t alloc_size = 0;
307                                 if (TLAB_START)
308                                         SGEN_LOG (3, "Retire TLAB: %p-%p [%ld]", TLAB_START, TLAB_REAL_END, (long)(TLAB_REAL_END - TLAB_NEXT - size));
309                                 sgen_nursery_retire_region (p, available_in_tlab);
310
311                                 do {
312                                         p = sgen_nursery_alloc_range (tlab_size, size, &alloc_size);
313                                         if (!p) {
314                                                 sgen_ensure_free_space (tlab_size);
315                                                 if (degraded_mode)
316                                                         return alloc_degraded (vtable, size, FALSE);
317                                                 else
318                                                         p = sgen_nursery_alloc_range (tlab_size, size, &alloc_size);
319                                         }
320                                 } while (!p);
321                                         
322                                 if (!p) {
323                                         // no space left
324                                         g_assert (0);
325                                 }
326
327                                 /* Allocate a new TLAB from the current nursery fragment */
328                                 TLAB_START = (char*)p;
329                                 TLAB_NEXT = TLAB_START;
330                                 TLAB_REAL_END = TLAB_START + alloc_size;
331                                 TLAB_TEMP_END = TLAB_START + MIN (SGEN_SCAN_START_SIZE, alloc_size);
332
333                                 zero_tlab_if_necessary (TLAB_START, alloc_size);
334
335                                 /* Allocate from the TLAB */
336                                 p = (void*)TLAB_NEXT;
337                                 TLAB_NEXT += size;
338                                 sgen_set_nursery_scan_start ((char*)p);
339                         }
340                 } else {
341                         /* Reached tlab_temp_end */
342
343                         /* record the scan start so we can find pinned objects more easily */
344                         sgen_set_nursery_scan_start ((char*)p);
345                         /* we just bump tlab_temp_end as well */
346                         TLAB_TEMP_END = MIN (TLAB_REAL_END, TLAB_NEXT + SGEN_SCAN_START_SIZE);
347                         SGEN_LOG (5, "Expanding local alloc: %p-%p", TLAB_NEXT, TLAB_TEMP_END);
348                 }
349         }
350
351         if (G_LIKELY (p)) {
352                 SGEN_LOG (6, "Allocated object %p, vtable: %p (%s), size: %zd", p, vtable, vtable->klass->name, size);
353                 binary_protocol_alloc (p, vtable, size);
354                 if (G_UNLIKELY (MONO_GC_MAJOR_OBJ_ALLOC_LARGE_ENABLED ()|| MONO_GC_NURSERY_OBJ_ALLOC_ENABLED ())) {
355                         if (size > SGEN_MAX_SMALL_OBJ_SIZE)
356                                 MONO_GC_MAJOR_OBJ_ALLOC_LARGE ((mword)p, size, vtable->klass->name_space, vtable->klass->name);
357                         else
358                                 MONO_GC_NURSERY_OBJ_ALLOC ((mword)p, size, vtable->klass->name_space, vtable->klass->name);
359                 }
360                 mono_atomic_store_seq (p, vtable);
361         }
362
363         return p;
364 }
365
366 static void*
367 mono_gc_try_alloc_obj_nolock (MonoVTable *vtable, size_t size)
368 {
369         void **p;
370         char *new_next;
371         TLAB_ACCESS_INIT;
372
373         size = ALIGN_UP (size);
374         SGEN_ASSERT (9, size >= sizeof (MonoObject), "Object too small");
375
376         g_assert (vtable->gc_descr);
377         if (size > SGEN_MAX_SMALL_OBJ_SIZE)
378                 return NULL;
379
380         if (G_UNLIKELY (size > tlab_size)) {
381                 /* Allocate directly from the nursery */
382                 p = sgen_nursery_alloc (size);
383                 if (!p)
384                         return NULL;
385                 sgen_set_nursery_scan_start ((char*)p);
386
387                 /*FIXME we should use weak memory ops here. Should help specially on x86. */
388                 zero_tlab_if_necessary (p, size);
389         } else {
390                 int available_in_tlab;
391                 char *real_end;
392                 /* tlab_next and tlab_temp_end are TLS vars so accessing them might be expensive */
393
394                 p = (void**)TLAB_NEXT;
395                 /* FIXME: handle overflow */
396                 new_next = (char*)p + size;
397
398                 real_end = TLAB_REAL_END;
399                 available_in_tlab = real_end - (char*)p;
400
401                 if (G_LIKELY (new_next < real_end)) {
402                         TLAB_NEXT = new_next;
403
404                         /* Second case, we overflowed temp end */
405                         if (G_UNLIKELY (new_next >= TLAB_TEMP_END)) {
406                                 sgen_set_nursery_scan_start (new_next);
407                                 /* we just bump tlab_temp_end as well */
408                                 TLAB_TEMP_END = MIN (TLAB_REAL_END, TLAB_NEXT + SGEN_SCAN_START_SIZE);
409                                 SGEN_LOG (5, "Expanding local alloc: %p-%p", TLAB_NEXT, TLAB_TEMP_END);
410                         }
411                 } else if (available_in_tlab > SGEN_MAX_NURSERY_WASTE) {
412                         /* Allocate directly from the nursery */
413                         p = sgen_nursery_alloc (size);
414                         if (!p)
415                                 return NULL;
416
417                         zero_tlab_if_necessary (p, size);
418                 } else {
419                         size_t alloc_size = 0;
420
421                         sgen_nursery_retire_region (p, available_in_tlab);
422                         new_next = sgen_nursery_alloc_range (tlab_size, size, &alloc_size);
423                         p = (void**)new_next;
424                         if (!p)
425                                 return NULL;
426
427                         TLAB_START = (char*)new_next;
428                         TLAB_NEXT = new_next + size;
429                         TLAB_REAL_END = new_next + alloc_size;
430                         TLAB_TEMP_END = new_next + MIN (SGEN_SCAN_START_SIZE, alloc_size);
431                         sgen_set_nursery_scan_start ((char*)p);
432
433                         zero_tlab_if_necessary (new_next, alloc_size);
434
435                         MONO_GC_NURSERY_TLAB_ALLOC ((mword)new_next, alloc_size);
436                 }
437         }
438
439         HEAVY_STAT (++stat_objects_alloced);
440         HEAVY_STAT (stat_bytes_alloced += size);
441
442         SGEN_LOG (6, "Allocated object %p, vtable: %p (%s), size: %zd", p, vtable, vtable->klass->name, size);
443         binary_protocol_alloc (p, vtable, size);
444         if (G_UNLIKELY (MONO_GC_NURSERY_OBJ_ALLOC_ENABLED ()))
445                 MONO_GC_NURSERY_OBJ_ALLOC ((mword)p, size, vtable->klass->name_space, vtable->klass->name);
446         g_assert (*p == NULL); /* FIXME disable this in non debug builds */
447
448         mono_atomic_store_seq (p, vtable);
449
450         return p;
451 }
452
453 void*
454 mono_gc_alloc_obj (MonoVTable *vtable, size_t size)
455 {
456         void *res;
457
458         if (!SGEN_CAN_ALIGN_UP (size))
459                 return NULL;
460
461 #ifndef DISABLE_CRITICAL_REGION
462         TLAB_ACCESS_INIT;
463
464         if (G_UNLIKELY (has_per_allocation_action)) {
465                 static int alloc_count;
466                 int current_alloc = InterlockedIncrement (&alloc_count);
467
468                 if (verify_before_allocs) {
469                         if ((current_alloc % verify_before_allocs) == 0)
470                                 sgen_check_whole_heap_stw ();
471                 }
472                 if (collect_before_allocs) {
473                         if (((current_alloc % collect_before_allocs) == 0) && nursery_section) {
474                                 LOCK_GC;
475                                 sgen_perform_collection (0, GENERATION_NURSERY, "collect-before-alloc-triggered", TRUE);
476                                 UNLOCK_GC;
477                         }
478                 }
479         }
480
481         ENTER_CRITICAL_REGION;
482         res = mono_gc_try_alloc_obj_nolock (vtable, size);
483         if (res) {
484                 EXIT_CRITICAL_REGION;
485                 return res;
486         }
487         EXIT_CRITICAL_REGION;
488 #endif
489         LOCK_GC;
490         res = mono_gc_alloc_obj_nolock (vtable, size);
491         UNLOCK_GC;
492         if (G_UNLIKELY (!res))
493                 return mono_gc_out_of_memory (size);
494         return res;
495 }
496
497 void*
498 mono_gc_alloc_vector (MonoVTable *vtable, size_t size, uintptr_t max_length)
499 {
500         MonoArray *arr;
501
502         if (!SGEN_CAN_ALIGN_UP (size))
503                 return NULL;
504
505 #ifndef DISABLE_CRITICAL_REGION
506         TLAB_ACCESS_INIT;
507         ENTER_CRITICAL_REGION;
508         arr = mono_gc_try_alloc_obj_nolock (vtable, size);
509         if (arr) {
510                 /*This doesn't require fencing since EXIT_CRITICAL_REGION already does it for us*/
511                 arr->max_length = max_length;
512                 EXIT_CRITICAL_REGION;
513                 return arr;
514         }
515         EXIT_CRITICAL_REGION;
516 #endif
517
518         LOCK_GC;
519
520         arr = mono_gc_alloc_obj_nolock (vtable, size);
521         if (G_UNLIKELY (!arr)) {
522                 UNLOCK_GC;
523                 return mono_gc_out_of_memory (size);
524         }
525
526         arr->max_length = max_length;
527
528         UNLOCK_GC;
529
530         return arr;
531 }
532
533 void*
534 mono_gc_alloc_array (MonoVTable *vtable, size_t size, uintptr_t max_length, uintptr_t bounds_size)
535 {
536         MonoArray *arr;
537         MonoArrayBounds *bounds;
538
539         if (!SGEN_CAN_ALIGN_UP (size))
540                 return NULL;
541
542 #ifndef DISABLE_CRITICAL_REGION
543         TLAB_ACCESS_INIT;
544         ENTER_CRITICAL_REGION;
545         arr = mono_gc_try_alloc_obj_nolock (vtable, size);
546         if (arr) {
547                 /*This doesn't require fencing since EXIT_CRITICAL_REGION already does it for us*/
548                 arr->max_length = max_length;
549
550                 bounds = (MonoArrayBounds*)((char*)arr + size - bounds_size);
551                 arr->bounds = bounds;
552                 EXIT_CRITICAL_REGION;
553                 return arr;
554         }
555         EXIT_CRITICAL_REGION;
556 #endif
557
558         LOCK_GC;
559
560         arr = mono_gc_alloc_obj_nolock (vtable, size);
561         if (G_UNLIKELY (!arr)) {
562                 UNLOCK_GC;
563                 return mono_gc_out_of_memory (size);
564         }
565
566         arr->max_length = max_length;
567
568         bounds = (MonoArrayBounds*)((char*)arr + size - bounds_size);
569         arr->bounds = bounds;
570
571         UNLOCK_GC;
572
573         return arr;
574 }
575
576 void*
577 mono_gc_alloc_string (MonoVTable *vtable, size_t size, gint32 len)
578 {
579         MonoString *str;
580
581         if (!SGEN_CAN_ALIGN_UP (size))
582                 return NULL;
583
584 #ifndef DISABLE_CRITICAL_REGION
585         TLAB_ACCESS_INIT;
586         ENTER_CRITICAL_REGION;
587         str = mono_gc_try_alloc_obj_nolock (vtable, size);
588         if (str) {
589                 /*This doesn't require fencing since EXIT_CRITICAL_REGION already does it for us*/
590                 str->length = len;
591                 EXIT_CRITICAL_REGION;
592                 return str;
593         }
594         EXIT_CRITICAL_REGION;
595 #endif
596
597         LOCK_GC;
598
599         str = mono_gc_alloc_obj_nolock (vtable, size);
600         if (G_UNLIKELY (!str)) {
601                 UNLOCK_GC;
602                 return mono_gc_out_of_memory (size);
603         }
604
605         str->length = len;
606
607         UNLOCK_GC;
608
609         return str;
610 }
611
612 /*
613  * To be used for interned strings and possibly MonoThread, reflection handles.
614  * We may want to explicitly free these objects.
615  */
616 void*
617 mono_gc_alloc_pinned_obj (MonoVTable *vtable, size_t size)
618 {
619         void **p;
620
621         if (!SGEN_CAN_ALIGN_UP (size))
622                 return NULL;
623         size = ALIGN_UP (size);
624
625         LOCK_GC;
626
627         if (size > SGEN_MAX_SMALL_OBJ_SIZE) {
628                 /* large objects are always pinned anyway */
629                 p = sgen_los_alloc_large_inner (vtable, size);
630         } else {
631                 SGEN_ASSERT (9, vtable->klass->inited, "class %s:%s is not initialized", vtable->klass->name_space, vtable->klass->name);
632                 p = major_collector.alloc_small_pinned_obj (vtable, size, SGEN_VTABLE_HAS_REFERENCES (vtable));
633         }
634         if (G_LIKELY (p)) {
635                 SGEN_LOG (6, "Allocated pinned object %p, vtable: %p (%s), size: %zd", p, vtable, vtable->klass->name, size);
636                 if (size > SGEN_MAX_SMALL_OBJ_SIZE)
637                         MONO_GC_MAJOR_OBJ_ALLOC_LARGE ((mword)p, size, vtable->klass->name_space, vtable->klass->name);
638                 else
639                         MONO_GC_MAJOR_OBJ_ALLOC_PINNED ((mword)p, size, vtable->klass->name_space, vtable->klass->name);
640                 binary_protocol_alloc_pinned (p, vtable, size);
641         }
642         UNLOCK_GC;
643         return p;
644 }
645
646 void*
647 mono_gc_alloc_mature (MonoVTable *vtable)
648 {
649         void **res;
650         size_t size = vtable->klass->instance_size;
651
652         if (!SGEN_CAN_ALIGN_UP (size))
653                 return NULL;
654         size = ALIGN_UP (size);
655
656         LOCK_GC;
657         res = alloc_degraded (vtable, size, TRUE);
658         UNLOCK_GC;
659         if (G_UNLIKELY (vtable->klass->has_finalize))
660                 mono_object_register_finalizer ((MonoObject*)res);
661
662         return res;
663 }
664
665 void*
666 mono_gc_alloc_fixed (size_t size, void *descr)
667 {
668         /* FIXME: do a single allocation */
669         void *res = calloc (1, size);
670         if (!res)
671                 return NULL;
672         if (!mono_gc_register_root (res, size, descr)) {
673                 free (res);
674                 res = NULL;
675         }
676         return res;
677 }
678
679 void
680 mono_gc_free_fixed (void* addr)
681 {
682         mono_gc_deregister_root (addr);
683         free (addr);
684 }
685
686 void
687 sgen_init_tlab_info (SgenThreadInfo* info)
688 {
689 #ifndef HAVE_KW_THREAD
690         SgenThreadInfo *__thread_info__ = info;
691 #endif
692
693         info->tlab_start_addr = &TLAB_START;
694         info->tlab_next_addr = &TLAB_NEXT;
695         info->tlab_temp_end_addr = &TLAB_TEMP_END;
696         info->tlab_real_end_addr = &TLAB_REAL_END;
697
698 #ifdef HAVE_KW_THREAD
699         tlab_next_addr = &tlab_next;
700 #endif
701 }
702
703 /*
704  * Clear the thread local TLAB variables for all threads.
705  */
706 void
707 sgen_clear_tlabs (void)
708 {
709         SgenThreadInfo *info;
710
711         FOREACH_THREAD (info) {
712                 /* A new TLAB will be allocated when the thread does its first allocation */
713                 *info->tlab_start_addr = NULL;
714                 *info->tlab_next_addr = NULL;
715                 *info->tlab_temp_end_addr = NULL;
716                 *info->tlab_real_end_addr = NULL;
717         } END_FOREACH_THREAD
718 }
719
720 static MonoMethod* alloc_method_cache [ATYPE_NUM];
721
722 #ifdef MANAGED_ALLOCATION
723 /* FIXME: Do this in the JIT, where specialized allocation sequences can be created
724  * for each class. This is currently not easy to do, as it is hard to generate basic 
725  * blocks + branches, but it is easy with the linear IL codebase.
726  *
727  * For this to work we'd need to solve the TLAB race, first.  Now we
728  * require the allocator to be in a few known methods to make sure
729  * that they are executed atomically via the restart mechanism.
730  */
731 static MonoMethod*
732 create_allocator (int atype)
733 {
734         int p_var, size_var;
735         guint32 slowpath_branch, max_size_branch;
736         MonoMethodBuilder *mb;
737         MonoMethod *res;
738         MonoMethodSignature *csig;
739         static gboolean registered = FALSE;
740         int tlab_next_addr_var, new_next_var;
741         int num_params, i;
742         const char *name = NULL;
743         AllocatorWrapperInfo *info;
744
745 #ifdef HAVE_KW_THREAD
746         int tlab_next_addr_offset = -1;
747         int tlab_temp_end_offset = -1;
748
749         MONO_THREAD_VAR_OFFSET (tlab_next_addr, tlab_next_addr_offset);
750         MONO_THREAD_VAR_OFFSET (tlab_temp_end, tlab_temp_end_offset);
751
752         mono_tls_key_set_offset (TLS_KEY_SGEN_TLAB_NEXT_ADDR, tlab_next_addr_offset);
753         mono_tls_key_set_offset (TLS_KEY_SGEN_TLAB_TEMP_END, tlab_temp_end_offset);
754
755         g_assert (tlab_next_addr_offset != -1);
756         g_assert (tlab_temp_end_offset != -1);
757 #endif
758
759         if (!registered) {
760                 mono_register_jit_icall (mono_gc_alloc_obj, "mono_gc_alloc_obj", mono_create_icall_signature ("object ptr int"), FALSE);
761                 mono_register_jit_icall (mono_gc_alloc_vector, "mono_gc_alloc_vector", mono_create_icall_signature ("object ptr int int"), FALSE);
762                 mono_register_jit_icall (mono_gc_alloc_string, "mono_gc_alloc_string", mono_create_icall_signature ("object ptr int int32"), FALSE);
763                 registered = TRUE;
764         }
765
766         if (atype == ATYPE_SMALL) {
767                 num_params = 1;
768                 name = "AllocSmall";
769         } else if (atype == ATYPE_NORMAL) {
770                 num_params = 1;
771                 name = "Alloc";
772         } else if (atype == ATYPE_VECTOR) {
773                 num_params = 2;
774                 name = "AllocVector";
775         } else if (atype == ATYPE_STRING) {
776                 num_params = 2;
777                 name = "AllocString";
778         } else {
779                 g_assert_not_reached ();
780         }
781
782         csig = mono_metadata_signature_alloc (mono_defaults.corlib, num_params);
783         if (atype == ATYPE_STRING) {
784                 csig->ret = &mono_defaults.string_class->byval_arg;
785                 csig->params [0] = &mono_defaults.int_class->byval_arg;
786                 csig->params [1] = &mono_defaults.int32_class->byval_arg;
787         } else {
788                 csig->ret = &mono_defaults.object_class->byval_arg;
789                 for (i = 0; i < num_params; ++i)
790                         csig->params [i] = &mono_defaults.int_class->byval_arg;
791         }
792
793         mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_ALLOC);
794
795 #ifndef DISABLE_JIT
796         size_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
797         if (atype == ATYPE_NORMAL || atype == ATYPE_SMALL) {
798                 /* size = vtable->klass->instance_size; */
799                 mono_mb_emit_ldarg (mb, 0);
800                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoVTable, klass));
801                 mono_mb_emit_byte (mb, CEE_ADD);
802                 mono_mb_emit_byte (mb, CEE_LDIND_I);
803                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoClass, instance_size));
804                 mono_mb_emit_byte (mb, CEE_ADD);
805                 /* FIXME: assert instance_size stays a 4 byte integer */
806                 mono_mb_emit_byte (mb, CEE_LDIND_U4);
807                 mono_mb_emit_byte (mb, CEE_CONV_I);
808                 mono_mb_emit_stloc (mb, size_var);
809         } else if (atype == ATYPE_VECTOR) {
810                 MonoExceptionClause *clause;
811                 int pos, pos_leave, pos_error;
812                 MonoClass *oom_exc_class;
813                 MonoMethod *ctor;
814
815                 /*
816                  * n > MONO_ARRAY_MAX_INDEX => OutOfMemoryException
817                  * n < 0                    => OverflowException
818                  *
819                  * We can do an unsigned comparison to catch both cases, then in the error
820                  * case compare signed to distinguish between them.
821                  */
822                 mono_mb_emit_ldarg (mb, 1);
823                 mono_mb_emit_icon (mb, MONO_ARRAY_MAX_INDEX);
824                 mono_mb_emit_byte (mb, CEE_CONV_U);
825                 pos = mono_mb_emit_short_branch (mb, CEE_BLE_UN_S);
826
827                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
828                 mono_mb_emit_byte (mb, CEE_MONO_NOT_TAKEN);
829                 mono_mb_emit_ldarg (mb, 1);
830                 mono_mb_emit_icon (mb, 0);
831                 pos_error = mono_mb_emit_short_branch (mb, CEE_BLT_S);
832                 mono_mb_emit_exception (mb, "OutOfMemoryException", NULL);
833                 mono_mb_patch_short_branch (mb, pos_error);
834                 mono_mb_emit_exception (mb, "OverflowException", NULL);
835
836                 mono_mb_patch_short_branch (mb, pos);
837
838                 clause = mono_image_alloc0 (mono_defaults.corlib, sizeof (MonoExceptionClause));
839                 clause->try_offset = mono_mb_get_label (mb);
840
841                 /* vtable->klass->sizes.element_size */
842                 mono_mb_emit_ldarg (mb, 0);
843                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoVTable, klass));
844                 mono_mb_emit_byte (mb, CEE_ADD);
845                 mono_mb_emit_byte (mb, CEE_LDIND_I);
846                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoClass, sizes.element_size));
847                 mono_mb_emit_byte (mb, CEE_ADD);
848                 mono_mb_emit_byte (mb, CEE_LDIND_U4);
849                 mono_mb_emit_byte (mb, CEE_CONV_I);
850
851                 /* * n */
852                 mono_mb_emit_ldarg (mb, 1);
853                 mono_mb_emit_byte (mb, CEE_MUL_OVF_UN);
854                 /* + sizeof (MonoArray) */
855                 mono_mb_emit_icon (mb, sizeof (MonoArray));
856                 mono_mb_emit_byte (mb, CEE_ADD_OVF_UN);
857                 mono_mb_emit_stloc (mb, size_var);
858
859                 pos_leave = mono_mb_emit_branch (mb, CEE_LEAVE);
860
861                 /* catch */
862                 clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
863                 clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
864                 clause->data.catch_class = mono_class_from_name (mono_defaults.corlib,
865                                 "System", "OverflowException");
866                 g_assert (clause->data.catch_class);
867                 clause->handler_offset = mono_mb_get_label (mb);
868
869                 oom_exc_class = mono_class_from_name (mono_defaults.corlib,
870                                 "System", "OutOfMemoryException");
871                 g_assert (oom_exc_class);
872                 ctor = mono_class_get_method_from_name (oom_exc_class, ".ctor", 0);
873                 g_assert (ctor);
874
875                 mono_mb_emit_byte (mb, CEE_POP);
876                 mono_mb_emit_op (mb, CEE_NEWOBJ, ctor);
877                 mono_mb_emit_byte (mb, CEE_THROW);
878
879                 clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
880                 mono_mb_set_clauses (mb, 1, clause);
881                 mono_mb_patch_branch (mb, pos_leave);
882                 /* end catch */
883         } else if (atype == ATYPE_STRING) {
884                 int pos;
885
886                 /*
887                  * a string allocator method takes the args: (vtable, len)
888                  *
889                  * bytes = sizeof (MonoString) + ((len + 1) * 2)
890                  *
891                  * condition:
892                  *
893                  * bytes <= INT32_MAX - (SGEN_ALLOC_ALIGN - 1)
894                  *
895                  * therefore:
896                  *
897                  * sizeof (MonoString) + ((len + 1) * 2) <= INT32_MAX - (SGEN_ALLOC_ALIGN - 1)
898                  * len <= (INT32_MAX - (SGEN_ALLOC_ALIGN - 1) - sizeof (MonoString)) / 2 - 1
899                  */
900                 mono_mb_emit_ldarg (mb, 1);
901                 mono_mb_emit_icon (mb, (INT32_MAX - (SGEN_ALLOC_ALIGN - 1) - sizeof (MonoString)) / 2 - 1);
902                 pos = mono_mb_emit_short_branch (mb, MONO_CEE_BLE_UN_S);
903
904                 mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
905                 mono_mb_emit_byte (mb, CEE_MONO_NOT_TAKEN);
906                 mono_mb_emit_exception (mb, "OutOfMemoryException", NULL);
907                 mono_mb_patch_short_branch (mb, pos);
908
909                 mono_mb_emit_ldarg (mb, 1);
910                 mono_mb_emit_icon (mb, 1);
911                 mono_mb_emit_byte (mb, MONO_CEE_SHL);
912                 //WE manually fold the above + 2 here
913                 mono_mb_emit_icon (mb, sizeof (MonoString) + 2);
914                 mono_mb_emit_byte (mb, CEE_ADD);
915                 mono_mb_emit_stloc (mb, size_var);
916         } else {
917                 g_assert_not_reached ();
918         }
919
920         /* size += ALLOC_ALIGN - 1; */
921         mono_mb_emit_ldloc (mb, size_var);
922         mono_mb_emit_icon (mb, ALLOC_ALIGN - 1);
923         mono_mb_emit_byte (mb, CEE_ADD);
924         /* size &= ~(ALLOC_ALIGN - 1); */
925         mono_mb_emit_icon (mb, ~(ALLOC_ALIGN - 1));
926         mono_mb_emit_byte (mb, CEE_AND);
927         mono_mb_emit_stloc (mb, size_var);
928
929         /* if (size > MAX_SMALL_OBJ_SIZE) goto slowpath */
930         if (atype != ATYPE_SMALL) {
931                 mono_mb_emit_ldloc (mb, size_var);
932                 mono_mb_emit_icon (mb, MAX_SMALL_OBJ_SIZE);
933                 max_size_branch = mono_mb_emit_short_branch (mb, MONO_CEE_BGT_UN_S);
934         }
935
936         /*
937          * We need to modify tlab_next, but the JIT only supports reading, so we read
938          * another tls var holding its address instead.
939          */
940
941         /* tlab_next_addr (local) = tlab_next_addr (TLS var) */
942         tlab_next_addr_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
943         EMIT_TLS_ACCESS (mb, tlab_next_addr, TLS_KEY_SGEN_TLAB_NEXT_ADDR);
944         mono_mb_emit_stloc (mb, tlab_next_addr_var);
945
946         /* p = (void**)tlab_next; */
947         p_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
948         mono_mb_emit_ldloc (mb, tlab_next_addr_var);
949         mono_mb_emit_byte (mb, CEE_LDIND_I);
950         mono_mb_emit_stloc (mb, p_var);
951         
952         /* new_next = (char*)p + size; */
953         new_next_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
954         mono_mb_emit_ldloc (mb, p_var);
955         mono_mb_emit_ldloc (mb, size_var);
956         mono_mb_emit_byte (mb, CEE_CONV_I);
957         mono_mb_emit_byte (mb, CEE_ADD);
958         mono_mb_emit_stloc (mb, new_next_var);
959
960         /* if (G_LIKELY (new_next < tlab_temp_end)) */
961         mono_mb_emit_ldloc (mb, new_next_var);
962         EMIT_TLS_ACCESS (mb, tlab_temp_end, TLS_KEY_SGEN_TLAB_TEMP_END);
963         slowpath_branch = mono_mb_emit_short_branch (mb, MONO_CEE_BLT_UN_S);
964
965         /* Slowpath */
966         if (atype != ATYPE_SMALL)
967                 mono_mb_patch_short_branch (mb, max_size_branch);
968
969         mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
970         mono_mb_emit_byte (mb, CEE_MONO_NOT_TAKEN);
971
972         /* FIXME: mono_gc_alloc_obj takes a 'size_t' as an argument, not an int32 */
973         mono_mb_emit_ldarg (mb, 0);
974         mono_mb_emit_ldloc (mb, size_var);
975         if (atype == ATYPE_NORMAL || atype == ATYPE_SMALL) {
976                 mono_mb_emit_icall (mb, mono_gc_alloc_obj);
977         } else if (atype == ATYPE_VECTOR) {
978                 mono_mb_emit_ldarg (mb, 1);
979                 mono_mb_emit_icall (mb, mono_gc_alloc_vector);
980         } else if (atype == ATYPE_STRING) {
981                 mono_mb_emit_ldarg (mb, 1);
982                 mono_mb_emit_icall (mb, mono_gc_alloc_string);
983         } else {
984                 g_assert_not_reached ();
985         }
986         mono_mb_emit_byte (mb, CEE_RET);
987
988         /* Fastpath */
989         mono_mb_patch_short_branch (mb, slowpath_branch);
990
991         /* FIXME: Memory barrier */
992
993         /* tlab_next = new_next */
994         mono_mb_emit_ldloc (mb, tlab_next_addr_var);
995         mono_mb_emit_ldloc (mb, new_next_var);
996         mono_mb_emit_byte (mb, CEE_STIND_I);
997
998         /*The tlab store must be visible before the the vtable store. This could be replaced with a DDS but doing it with IL would be tricky. */
999         mono_mb_emit_byte ((mb), MONO_CUSTOM_PREFIX);
1000         mono_mb_emit_op (mb, CEE_MONO_MEMORY_BARRIER, StoreStoreBarrier);
1001
1002         /* *p = vtable; */
1003         mono_mb_emit_ldloc (mb, p_var);
1004         mono_mb_emit_ldarg (mb, 0);
1005         mono_mb_emit_byte (mb, CEE_STIND_I);
1006
1007         if (atype == ATYPE_VECTOR) {
1008                 /* arr->max_length = max_length; */
1009                 mono_mb_emit_ldloc (mb, p_var);
1010                 mono_mb_emit_ldflda (mb, G_STRUCT_OFFSET (MonoArray, max_length));
1011                 mono_mb_emit_ldarg (mb, 1);
1012 #ifdef MONO_BIG_ARRAYS
1013                 mono_mb_emit_byte (mb, CEE_STIND_I);
1014 #else
1015                 mono_mb_emit_byte (mb, CEE_STIND_I4);
1016 #endif
1017         } else  if (atype == ATYPE_STRING) {
1018                 /* need to set length and clear the last char */
1019                 /* s->length = len; */
1020                 mono_mb_emit_ldloc (mb, p_var);
1021                 mono_mb_emit_icon (mb, G_STRUCT_OFFSET (MonoString, length));
1022                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
1023                 mono_mb_emit_ldarg (mb, 1);
1024                 mono_mb_emit_byte (mb, MONO_CEE_STIND_I4);
1025                 /* s->chars [len] = 0; */
1026                 mono_mb_emit_ldloc (mb, p_var);
1027                 mono_mb_emit_ldloc (mb, size_var);
1028                 mono_mb_emit_icon (mb, 2);
1029                 mono_mb_emit_byte (mb, MONO_CEE_SUB);
1030                 mono_mb_emit_byte (mb, MONO_CEE_ADD);
1031                 mono_mb_emit_icon (mb, 0);
1032                 mono_mb_emit_byte (mb, MONO_CEE_STIND_I2);
1033         }
1034
1035         /*
1036         We must make sure both vtable and max_length are globaly visible before returning to managed land.
1037         */
1038         mono_mb_emit_byte ((mb), MONO_CUSTOM_PREFIX);
1039         mono_mb_emit_op (mb, CEE_MONO_MEMORY_BARRIER, StoreStoreBarrier);
1040
1041         /* return p */
1042         mono_mb_emit_ldloc (mb, p_var);
1043         mono_mb_emit_byte (mb, CEE_RET);
1044 #endif
1045
1046         res = mono_mb_create_method (mb, csig, 8);
1047         mono_mb_free (mb);
1048         mono_method_get_header (res)->init_locals = FALSE;
1049
1050         info = mono_image_alloc0 (mono_defaults.corlib, sizeof (AllocatorWrapperInfo));
1051         info->gc_name = "sgen";
1052         info->alloc_type = atype;
1053         mono_marshal_set_wrapper_info (res, info);
1054
1055         return res;
1056 }
1057 #endif
1058
1059 /*
1060  * Generate an allocator method implementing the fast path of mono_gc_alloc_obj ().
1061  * The signature of the called method is:
1062  *      object allocate (MonoVTable *vtable)
1063  */
1064 MonoMethod*
1065 mono_gc_get_managed_allocator (MonoClass *klass, gboolean for_box)
1066 {
1067 #ifdef MANAGED_ALLOCATION
1068
1069 #ifdef HAVE_KW_THREAD
1070         int tlab_next_offset = -1;
1071         int tlab_temp_end_offset = -1;
1072         MONO_THREAD_VAR_OFFSET (tlab_next, tlab_next_offset);
1073         MONO_THREAD_VAR_OFFSET (tlab_temp_end, tlab_temp_end_offset);
1074
1075         if (tlab_next_offset == -1 || tlab_temp_end_offset == -1)
1076                 return NULL;
1077 #endif
1078         if (collect_before_allocs)
1079                 return NULL;
1080         if (!mono_runtime_has_tls_get ())
1081                 return NULL;
1082         if (klass->instance_size > tlab_size)
1083                 return NULL;
1084
1085         if (klass->has_finalize || mono_class_is_marshalbyref (klass) || (mono_profiler_get_events () & MONO_PROFILE_ALLOCATIONS))
1086                 return NULL;
1087         if (klass->rank)
1088                 return NULL;
1089         if (klass->byval_arg.type == MONO_TYPE_STRING)
1090                 return mono_gc_get_managed_allocator_by_type (ATYPE_STRING);
1091         /* Generic classes have dynamic field and can go above MAX_SMALL_OBJ_SIZE. */
1092         if (ALIGN_TO (klass->instance_size, ALLOC_ALIGN) < MAX_SMALL_OBJ_SIZE && !mono_class_is_open_constructed_type (&klass->byval_arg))
1093                 return mono_gc_get_managed_allocator_by_type (ATYPE_SMALL);
1094         else
1095                 return mono_gc_get_managed_allocator_by_type (ATYPE_NORMAL);
1096 #else
1097         return NULL;
1098 #endif
1099 }
1100
1101 MonoMethod*
1102 mono_gc_get_managed_array_allocator (MonoClass *klass)
1103 {
1104 #ifdef MANAGED_ALLOCATION
1105 #ifdef HAVE_KW_THREAD
1106         int tlab_next_offset = -1;
1107         int tlab_temp_end_offset = -1;
1108         MONO_THREAD_VAR_OFFSET (tlab_next, tlab_next_offset);
1109         MONO_THREAD_VAR_OFFSET (tlab_temp_end, tlab_temp_end_offset);
1110
1111         if (tlab_next_offset == -1 || tlab_temp_end_offset == -1)
1112                 return NULL;
1113 #endif
1114
1115         if (klass->rank != 1)
1116                 return NULL;
1117         if (!mono_runtime_has_tls_get ())
1118                 return NULL;
1119         if (mono_profiler_get_events () & MONO_PROFILE_ALLOCATIONS)
1120                 return NULL;
1121         if (has_per_allocation_action)
1122                 return NULL;
1123         g_assert (!mono_class_has_finalizer (klass) && !mono_class_is_marshalbyref (klass));
1124
1125         return mono_gc_get_managed_allocator_by_type (ATYPE_VECTOR);
1126 #else
1127         return NULL;
1128 #endif
1129 }
1130
1131 void
1132 sgen_set_use_managed_allocator (gboolean flag)
1133 {
1134         use_managed_allocator = flag;
1135 }
1136
1137 MonoMethod*
1138 mono_gc_get_managed_allocator_by_type (int atype)
1139 {
1140 #ifdef MANAGED_ALLOCATION
1141         MonoMethod *res;
1142
1143         if (!use_managed_allocator)
1144                 return NULL;
1145
1146         if (!mono_runtime_has_tls_get ())
1147                 return NULL;
1148
1149         res = alloc_method_cache [atype];
1150         if (res)
1151                 return res;
1152
1153         res = create_allocator (atype);
1154         LOCK_GC;
1155         if (alloc_method_cache [atype]) {
1156                 mono_free_method (res);
1157                 res = alloc_method_cache [atype];
1158         } else {
1159                 mono_memory_barrier ();
1160                 alloc_method_cache [atype] = res;
1161         }
1162         UNLOCK_GC;
1163
1164         return res;
1165 #else
1166         return NULL;
1167 #endif
1168 }
1169
1170 guint32
1171 mono_gc_get_managed_allocator_types (void)
1172 {
1173         return ATYPE_NUM;
1174 }
1175
1176 gboolean
1177 sgen_is_managed_allocator (MonoMethod *method)
1178 {
1179         int i;
1180
1181         for (i = 0; i < ATYPE_NUM; ++i)
1182                 if (method == alloc_method_cache [i])
1183                         return TRUE;
1184         return FALSE;
1185 }
1186
1187 gboolean
1188 sgen_has_managed_allocator (void)
1189 {
1190         int i;
1191
1192         for (i = 0; i < ATYPE_NUM; ++i)
1193                 if (alloc_method_cache [i])
1194                         return TRUE;
1195         return FALSE;
1196 }       
1197
1198 #ifdef HEAVY_STATISTICS
1199 void
1200 sgen_alloc_init_heavy_stats (void)
1201 {
1202         mono_counters_register ("# objects allocated", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_objects_alloced);     
1203         mono_counters_register ("bytes allocated", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_bytes_alloced);
1204         mono_counters_register ("bytes allocated in LOS", MONO_COUNTER_GC | MONO_COUNTER_LONG, &stat_bytes_alloced_los);
1205 }
1206 #endif
1207
1208 #endif /*HAVE_SGEN_GC*/