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