52a598bfcc47df3a20adad5b482d8396e59ef6df
[libfirm] / include / libfirm / adt / array.h
1 /*
2  * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief     Dynamic and flexible arrays for C.
23  * @author    Markus Armbruster, Michael Beck, Matthias Braun, Sebastian Hack
24  * @version   $Id$
25  */
26 #ifndef FIRM_ADT_ARRAY_H
27 #define FIRM_ADT_ARRAY_H
28
29 #include <assert.h>
30 #include <stddef.h>
31
32 #include "obst.h"
33 #include "fourcc.h"
34 #include "xmalloc.h"
35
36 /**
37  * Creates a flexible array.
38  *
39  * @param type     The element type of the new array.
40  * @param nelts    a size_t expression evaluating to the number of elements
41  *
42  * This macro creates a flexible array of a given type at runtime.
43  * The size of the array can be changed later.
44  *
45  * @return A pointer to the flexible array (can be used as a pointer to the
46  *         first element of this array).
47  */
48 #define NEW_ARR_F(type, nelts)                                          \
49   ((type *)ir_new_arr_f((nelts), sizeof(type) * (nelts)))
50
51 /**
52  * Creates a new flexible array with the same number of elements as a
53  * given one.
54  *
55  * @param type     The element type of the new array.
56  * @param arr      An array from which the number of elements will be taken
57  *
58  * This macro creates a flexible array of a given type at runtime.
59  * The size of the array can be changed later.
60  *
61  * @return A pointer to the flexible array (can be used as a pointer to the
62  *         first element of this array).
63  */
64 #define CLONE_ARR_F(type, arr)                  \
65   NEW_ARR_F(type, ARR_LEN((arr)))
66
67 /**
68  * Duplicates an array and returns the new flexible one.
69  *
70  * @param type     The element type of the new array.
71  * @param arr      An array from which the elements will be duplicated
72  *
73  * This macro creates a flexible array of a given type at runtime.
74  * The size of the array can be changed later.
75  *
76  * @return A pointer to the flexible array (can be used as a pointer to the
77  *         first element of this array).
78  */
79 #define DUP_ARR_F(type, arr)                                                    \
80   memcpy(CLONE_ARR_F(type, (arr)), (arr), sizeof(type) * ARR_LEN((arr)))
81
82 /**
83  * Delete a flexible array.
84  *
85  * @param arr    The flexible array.
86  */
87 #define DEL_ARR_F(arr) (ir_del_arr_f((void *)(arr)))
88
89 /**
90  * Creates a dynamic array on an obstack.
91  *
92  * @param type     The element type of the new array.
93  * @param obstack  A struct obstack * were the data will be allocated
94  * @param nelts    A size_t expression evaluating to the number of elements
95  *
96  * This macro creates a dynamic array of a given type at runtime.
97  * The size of the array cannot be changed later.
98  *
99  * @return A pointer to the dynamic array (can be used as a pointer to the
100  *         first element of this array).
101  */
102 #define NEW_ARR_D(type, obstack, nelts)                                 \
103   (  nelts                                                              \
104    ? (type *)ir_new_arr_d((obstack), (nelts), sizeof(type) * (nelts))   \
105    : (type *)arr_mt_descr.v.elts)
106
107 /**
108  * Creates a new dynamic array with the same number of elements as a
109  * given one.
110  *
111  * @param type     The element type of the new array.
112  * @param obstack  An struct obstack * were the data will be allocated
113  * @param arr      An array from which the number of elements will be taken
114  *
115  * This macro creates a dynamic array of a given type at runtime.
116  * The size of the array cannot be changed later.
117  *
118  * @return A pointer to the dynamic array (can be used as a pointer to the
119  *         first element of this array).
120  */
121 #define CLONE_ARR_D(type, obstack, arr)         \
122   NEW_ARR_D(type, (obstack), ARR_LEN((arr)))
123
124 /**
125  * Duplicates an array and returns the new dynamic one.
126  *
127  * @param type     The element type of the new array.
128  * @param obstack  An struct obstack * were the data will be allocated
129  * @param arr      An array from which the elements will be duplicated
130  *
131  * This macro creates a dynamic array of a given type at runtime.
132  * The size of the array cannot be changed later.
133  *
134  * @return A pointer to the dynamic array (can be used as a pointer to the
135  *         first element of this array).
136  */
137 #define DUP_ARR_D(type, obstack, arr)                                                   \
138   memcpy(CLONE_ARR_D(type, (obstack), (arr)), (arr), sizeof(type) * ARR_LEN ((arr)))
139
140 /**
141  * Returns the length of an array
142  *
143  * @param arr  a flexible, dynamic, automatic or static array.
144  */
145 #define ARR_LEN(arr) (ARR_VRFY((arr)), ARR_DESCR((arr))->nelts)
146
147 /**
148  * Resize a flexible array, allocate more data if needed but do NOT
149  * reduce.
150  *
151  * @param type     The element type of the array.
152  * @param arr      The array, which must be an lvalue.
153  * @param n        The new size of the array.
154  *
155  * @remark  This macro may change arr, so update all references!
156  */
157 #define ARR_RESIZE(type, arr, n)                                        \
158   ((arr) = ir_arr_resize((void *)(arr), (n), sizeof(type)))
159
160 /**
161  * Resize a flexible array, always reallocate data.
162  *
163  * @param type     The element type of the array.
164  * @param arr      The array, which must be an lvalue.
165  * @param n        The new size of the array.
166  *
167  * @remark  This macro may change arr, so update all references!
168  */
169 #define ARR_SETLEN(type, arr, n)                                        \
170   ((arr) = ir_arr_setlen((void *)(arr), (n), sizeof(type) * (n)))
171
172 /** Set a length smaller than the current length of the array.  Do not
173  *  resize. len must be <= ARR_LEN(arr). */
174 #define ARR_SHRINKLEN(arr,len)                                          \
175    (ARR_VRFY((arr)), assert(ARR_DESCR((arr))->nelts >= len),             \
176     ARR_DESCR((arr))->nelts = len)
177
178 /**
179  * Resize a flexible array by growing it by delta elements.
180  *
181  * @param type     The element type of the array.
182  * @param arr      The array, which must be an lvalue.
183  * @param delta    The delta number of elements.
184  *
185  * @remark  This macro may change arr, so update all references!
186  */
187 #define ARR_EXTEND(type, arr, delta)                    \
188   ARR_RESIZE(type, (arr), ARR_LEN((arr)) + (delta))
189
190 /**
191  * Resize a flexible array to hold n elements only if it is currently shorter
192  * than n.
193  *
194  * @param type     The element type of the array.
195  * @param arr      The array, which must be an lvalue.
196  * @param n        The new size of the array.
197  *
198  * @remark  This macro may change arr, so update all references!
199  */
200 #define ARR_EXTO(type, arr, n)                                          \
201   ((n) >= ARR_LEN((arr)) ? ARR_RESIZE(type, (arr), (n)+1) : (arr))
202
203 /**
204  * Append one element to a flexible array.
205  *
206  * @param type     The element type of the array.
207  * @param arr      The array, which must be an lvalue.
208  * @param elt      The new element, must be of type (type).
209  */
210 #define ARR_APP1(type, arr, elt)                                        \
211   (ARR_EXTEND(type, (arr), 1), (arr)[ARR_LEN((arr))-1] = (elt))
212
213 #ifdef NDEBUG
214 # define ARR_VRFY(arr)          ((void)0)
215 # define ARR_IDX_VRFY(arr, idx) ((void)0)
216 #else
217 # define ARR_VRFY(arr)          ir_verify_arr(arr)
218 # define ARR_IDX_VRFY(arr, idx)                         \
219     assert((0 <= (idx)) && ((idx) < ARR_LEN((arr))))
220 #endif
221
222 /** A type that has most constrained alignment.  */
223 typedef union {
224   long double d;
225   void *p;
226   long l;
227 } aligned_type;
228
229 /**
230  * Construct an array header.
231  */
232 #define ARR_STRUCT(type, rnelts)                    \
233   struct {                                          \
234         int magic;                                      \
235         size_t eltsize;                                 \
236     union {                                         \
237       struct obstack *obstack;  /* dynamic: allocated on this obstack */  \
238       int allocated;                    /* flexible: #slots allocated */          \
239     } u;                                            \
240     int nelts;                                      \
241     union {                                         \
242       type elts[(rnelts)];                          \
243       aligned_type align[1];                        \
244     } v;                                            \
245   }
246
247 /**
248  * The array descriptor header type.
249  */
250 typedef ARR_STRUCT(aligned_type, 1) ir_arr_descr;
251
252 extern ir_arr_descr arr_mt_descr;
253
254 void *ir_new_arr_f(int nelts, size_t elts_size);
255 void ir_del_arr_f(void *elts);
256 void *ir_new_arr_d(struct obstack *obstack, int nelts, size_t elts_size);
257 void *ir_arr_resize(void *elts, int nelts, size_t elts_size);
258 void *ir_arr_setlen(void *elts, int nelts, size_t elts_size);
259 void ir_verify_arr(const void *elts);
260
261 #define ARR_ELTS_OFFS offsetof(ir_arr_descr, v.elts)
262 #define ARR_DESCR(elts) ((ir_arr_descr *)(void *)((char *)(elts) - ARR_ELTS_OFFS))
263
264 /*
265  ____             _           _      _
266 / ___|  ___  _ __| |_ ___  __| |    / \   _ __ _ __ __ _ _   _ ___
267 \___ \ / _ \| '__| __/ _ \/ _` |   / _ \ | '__| '__/ _` | | | / __|
268  ___) | (_) | |  | ||  __/ (_| |  / ___ \| |  | | | (_| | |_| \__ \
269 |____/ \___/|_|   \__\___|\__,_| /_/   \_\_|  |_|  \__,_|\__, |___/
270                                                          |___/
271 */
272
273 typedef int (ir_arr_cmp_func_t)(const void *a, const void *b);
274
275 /**
276  * Do a binary search in an array.
277  * @param arr      The array.
278  * @param elm_size The size of an array element.
279  * @param cmp      A comparison function for two array elements (see qsort(3) for example).
280  * @param elm      A pointer to the element we are looking for.
281  * @return         This is somewhat tricky. Let <code>res</code> be the return value.
282  *                 If the return value is negative, then <code>elm</code> was not in the array
283  *                 but <code>-res - 1</code> gives the proper location where it should be inserted.
284  *                 If <code>res >= 0</code> then the element is in the array and <code>res</code>
285  *                 represents its index.
286  *                 That allows for testing membership and finding proper insertion indices.
287  * @note           The differences to bsearch(3) which does not give proper insert locations
288  *                 in the case that the element is not conatined in the array.
289  */
290 static inline int ir_arr_bsearch(const void *arr, size_t elm_size, ir_arr_cmp_func_t *cmp, const void *elm)
291 {
292         int hi = ARR_LEN(arr);
293         int lo = 0;
294
295         while(lo < hi) {
296                 int md     = lo + ((hi - lo) >> 1);
297                 int res    = cmp((char *) arr + md * elm_size, elm);
298                 if(res < 0)
299                         lo = md + 1;
300                 else if(res > 0)
301                         hi = md;
302                 else
303                         return md;
304         }
305
306         return -(lo + 1);
307 }
308
309 #define ARR_SET_INSERT(arr, cmp, elm) \
310 do { \
311         int idx = ir_arr_bsearch((arr), sizeof((arr)[0]), (cmp), (elm)); \
312         if (idx < 0) { \
313                 idx = -idx - 1; \
314                 memmove(&(arr)[idx+1], &(arr)[idx], sizeof((arr)[0]) * (ARR_DESCR((arr))->nelts - idx)); \
315                 (arr)[idx] = *(elm); \
316                 ++ARR_DESCR((arr))->nelts; \
317         } \
318 } while(0)
319
320 #define ARR_SET_INSERT_EXT(type, arr, cmp, elm) \
321 do { \
322         int idx = ir_arr_bsearch((arr), sizeof((arr)[0]), (cmp), (elm)); \
323         if (idx < 0) { \
324                 int len = ARR_LEN(arr); \
325                 idx = -idx - 1; \
326                 ARR_EXTO(type, arr, len + 1); \
327                 memmove(&(arr)[idx+1], &(arr)[idx], sizeof((arr)[0]) * (len - idx)); \
328                 (arr)[idx] = *(elm); \
329         } \
330 } while(0)
331
332 #define ARR_SET_REMOVE(arr, cmp, elm) \
333 do { \
334         int idx = ir_arr_bsearch((arr), sizeof((arr)[0]), (cmp), (elm)); \
335         if (idx >= 0) { \
336                 --ARR_DESCR((arr))->nelts; \
337                 memmove(&(arr)[idx], &(arr)[idx+1], sizeof((arr)[0]) * (ARR_DESCR((arr))->nelts - idx)); \
338         } \
339 } while(0)
340
341 /**
342  * Return the index of an element in an array set.
343  * To check for containment, use the expression:
344  *     (ARR_SET_GET_IDX(arr, cmp, elm) >= 0)
345  *
346  * @return The index or some value < 0 if the element was not in the set.
347  */
348 #define ARR_SET_GET_IDX(arr, cmp, elm) \
349         (ARR_VRFY((arr)), ir_arr_bsearch((arr), sizeof((arr)[0]), cmp, (elm)))
350
351 #ifdef __GNUC__
352 #define ARR_SET_GET(arr, cmp, elm) \
353         ({ int idx = ARR_SET_GET_IDX(arr, cmp, elm); idx >= 0 ? &(arr)[idx] : NULL; })
354 #else
355 #define ARR_SET_GET(arr, cmp, elm) \
356         (ARR_SET_GET_IDX(arr, cmp, elm) >= 0 ? &(arr)[ARR_SET_GET_IDX(arr, cmp, elm)] : NULL)
357 #endif
358
359
360 #define ARR_SET_CONTAINS(arr, cmp, elm) \
361         (ARR_SET_GET_IDX((arr), (cmp), (elm)) >= 0)
362
363 /**
364  * Reset the array set.
365  * This just initializes the size to zero but does not wipe out any element.
366  */
367 #define ARR_SET_CLEAR(arr) ARR_SHRINKLEN(arr, 0)
368
369 #endif /* FIRM_ADT_ARRAY_H */