the jit is now using a control flow graph
[mono.git] / mono / metadata / mempool.c
1 /*
2  * mempool.c: efficient memory allocation
3  *
4  * MonoMemPool is for fast allocation of memory. We free
5  * all memory when the pool is destroyed.
6  *
7  * Author:
8  *   Dietmar Maurer (dietmar@ximian.com)
9  *
10  * (C) 2001 Ximian, Inc.
11  */
12
13 #include <config.h>
14 #include <glib.h>
15
16 #include "jit.h"
17
18 /*
19  * MonoMemPool is for fast allocation of memory. We free
20  * all memory when the pool is destroyed.
21  */
22
23 #if SIZEOF_VOID_P > SIZEOF_LONG
24 #define MEM_ALIGN     SIZEOF_VOID_P
25 #else
26 #define MEM_ALIGN     SIZEOF_LONG
27 #endif
28
29 #define MONO_MEMPOOL_PAGESIZE 8192
30
31 struct _MonoMemPool {
32         MonoMemPool *next;
33         gint rest;
34         gpointer pos;
35 };
36
37 /**
38  * mono_mempool_new:
39  *
40  * Returns: a new memory pool.
41  */
42 MonoMemPool *
43 mono_mempool_new ()
44 {
45
46         MonoMemPool *pool = g_malloc (MONO_MEMPOOL_PAGESIZE);
47         pool->next = NULL;
48         pool->pos = (gpointer)pool + sizeof (MonoMemPool);
49         pool->rest = MONO_MEMPOOL_PAGESIZE - sizeof (MonoMemPool);
50         return pool;
51 }
52
53 /**
54  * mono_mempool_destroy:
55  * @pool: the momory pool to destroy
56  *
57  * Free all memory associated with this pool.
58  */
59 void
60 mono_mempool_destroy (MonoMemPool *pool)
61 {
62         MonoMemPool *p, *n;
63
64         p = pool;
65         while (p) {
66                 n = p->next;
67                 g_free (p);
68                 p = n;
69         }
70 }
71
72 /**
73  * mono_mempool_alloc:
74  * @pool: the momory pool to destroy
75  * @size: size of the momory block
76  *
77  * Allocates a new block of memory in @pool. @size must 
78  * be smaller than 256.
79  *
80  * Returns: the address of a newly allocated memory block.
81  */
82 gpointer
83 mono_mempool_alloc (MonoMemPool *pool, guint size)
84 {
85         gpointer rval;
86
87         g_assert (pool != NULL);
88
89         /* we should also handle large blocks */
90         g_assert (size < 4096);
91
92         size = (size + MEM_ALIGN - 1) & ~(MEM_ALIGN - 1);
93
94         if (pool->rest < size) {
95                 MonoMemPool *np = g_malloc (MONO_MEMPOOL_PAGESIZE);
96                 np->next = pool->next;
97                 pool->next = np;
98                 pool->pos = (gpointer)np + sizeof (MonoMemPool);
99                 pool->rest = MONO_MEMPOOL_PAGESIZE - sizeof (MonoMemPool);
100         }
101
102         rval = pool->pos;
103         pool->rest -= size;
104         pool->pos += size;
105
106         return rval;
107 }
108
109 /**
110  * mono_mempool_alloc0:
111  *
112  * same as mono_mempool_alloc, but fills memory with zero.
113  */
114 gpointer
115 mono_mempool_alloc0 (MonoMemPool *pool, guint size)
116 {
117         gpointer rval = mono_mempool_alloc (pool, size);
118         memset (rval, 0, size);
119         return rval;
120 }
121