524c58eb96d5d0a7dd098befb390bef5aae3df67
[cparser] / ast2firm.c
1 #include <config.h>
2
3 #include <assert.h>
4 #include <string.h>
5 #include <stdbool.h>
6
7 #include <libfirm/firm.h>
8 #include <libfirm/adt/obst.h>
9
10 #include "ast2firm.h"
11
12 #include "adt/error.h"
13 #include "adt/array.h"
14 #include "token_t.h"
15 #include "type_t.h"
16 #include "ast_t.h"
17 #include "parser.h"
18 #include "diagnostic.h"
19 #include "lang_features.h"
20 #include "types.h"
21 #include "driver/firm_opt.h"
22 #include "driver/firm_cmdline.h"
23
24 #define MAGIC_DEFAULT_PN_NUMBER     (long) -314159265
25
26 static ir_type *ir_type_const_char;
27 static ir_type *ir_type_wchar_t;
28 static ir_type *ir_type_void;
29 static ir_type *ir_type_int;
30
31 static type_t *type_const_char;
32
33 static int       next_value_number_function;
34 static ir_node  *continue_label;
35 static ir_node  *break_label;
36 static ir_node  *current_switch_cond;
37 static bool      saw_default_label;
38 static ir_node **imature_blocks;
39
40 static const declaration_t *current_function_decl;
41 static ir_node             *current_function_name;
42
43 static struct obstack asm_obst;
44
45 typedef enum declaration_kind_t {
46         DECLARATION_KIND_UNKNOWN,
47         DECLARATION_KIND_FUNCTION,
48         DECLARATION_KIND_VARIABLE_LENGTH_ARRAY,
49         DECLARATION_KIND_GLOBAL_VARIABLE,
50         DECLARATION_KIND_LOCAL_VARIABLE,
51         DECLARATION_KIND_LOCAL_VARIABLE_ENTITY,
52         DECLARATION_KIND_COMPOUND_MEMBER,
53         DECLARATION_KIND_LABEL_BLOCK,
54         DECLARATION_KIND_ENUM_ENTRY
55 } declaration_kind_t;
56
57 static ir_type *get_ir_type(type_t *type);
58 static int count_decls_in_stmts(const statement_t *stmt);
59
60 ir_node *uninitialized_local_var(ir_graph *irg, ir_mode *mode, int pos)
61 {
62         const declaration_t *declaration = get_irg_loc_description(irg, pos);
63
64         warningf(declaration->source_position,
65                  "variable '%#T' might be used uninitialized",
66                  declaration->type, declaration->symbol);
67         return new_r_Unknown(irg, mode);
68 }
69
70 unsigned dbg_snprint(char *buf, unsigned len, const dbg_info *dbg)
71 {
72         const source_position_t *pos = (const source_position_t*) dbg;
73         if(pos == NULL)
74                 return 0;
75         return (unsigned) snprintf(buf, len, "%s:%u", pos->input_name,
76                                    pos->linenr);
77 }
78
79 const char *dbg_retrieve(const dbg_info *dbg, unsigned *line)
80 {
81         const source_position_t *pos = (const source_position_t*) dbg;
82         if(pos == NULL)
83                 return NULL;
84         if(line != NULL)
85                 *line = pos->linenr;
86         return pos->input_name;
87 }
88
89 static dbg_info *get_dbg_info(const source_position_t *pos)
90 {
91         return (dbg_info*) pos;
92 }
93
94 static unsigned unique_id = 0;
95
96 static ident *unique_ident(const char *tag)
97 {
98         char buf[256];
99
100         snprintf(buf, sizeof(buf), "%s.%u", tag, unique_id);
101         unique_id++;
102         return new_id_from_str(buf);
103 }
104
105 /**
106  * Return the signed integer mode of size bytes.
107  *
108  * @param size   the size
109  */
110 static ir_mode *get_smode(unsigned size)
111 {
112         static ir_mode *s_modes[16 + 1] = {0, };
113         ir_mode *res;
114
115         if (size <= 0 || size > 16)
116                 return NULL;
117
118         res = s_modes[size];
119         if (res == NULL) {
120                 unsigned bits;
121         char name[32];
122
123         bits = size * 8;
124         snprintf(name, sizeof(name), "i%u", bits);
125         res = new_ir_mode(name, irms_int_number, bits, 1, irma_twos_complement,
126                                         bits <= machine_size ? machine_size : bits );
127
128                 s_modes[size] = res;
129         }
130         return res;
131 }
132
133 /**
134  * Return the unsigned integer mode of size bytes.
135  *
136  * @param size  the size
137  */
138 static ir_mode *get_umode(unsigned size)
139 {
140         static ir_mode *u_modes[16 + 1] = {0, };
141         ir_mode *res;
142
143         if (size <= 0 || size > 16)
144                 return NULL;
145
146         res = u_modes[size];
147         if (res == NULL) {
148                 unsigned bits;
149                 char name[32];
150
151                 bits = size * 8;
152                 snprintf(name, sizeof(name), "u%u", bits);
153                 res = new_ir_mode(name, irms_int_number, bits, 0, irma_twos_complement,
154                                                 bits <= machine_size ? machine_size : bits );
155
156                 u_modes[size] = res;
157         }
158         return res;
159 }
160
161 /**
162  * Return the pointer mode of size bytes.
163  *
164  * @param size  the size
165  */
166 static ir_mode *get_ptrmode(unsigned size, char *name)
167 {
168         static ir_mode *p_modes[16 + 1] = {0, };
169         ir_mode *res;
170
171         if (size <= 0 || size > 16)
172                 return NULL;
173
174         res = p_modes[size];
175         if (res == NULL) {
176                 unsigned bits;
177                 char buf[32];
178
179                 bits = size * 8;
180                 if (name == NULL) {
181                         snprintf(buf, sizeof(buf), "p%u", bits);
182                         name = buf;
183                 }
184                 res = new_ir_mode(name, irms_reference, bits, 0, irma_twos_complement,
185                                                 bits <= machine_size ? machine_size : bits);
186
187                 p_modes[size] = res;
188
189                 set_reference_mode_signed_eq(res, get_smode(size));
190                 set_reference_mode_unsigned_eq(res, get_umode(size));
191         }
192         return res;
193 }
194
195 static ir_mode *_atomic_modes[ATOMIC_TYPE_LAST];
196
197 static ir_mode *mode_int, *mode_uint;
198
199 static ir_node *expression_to_firm(const expression_t *expression);
200 static inline ir_mode *get_ir_mode(type_t *type);
201
202 /**
203  * Initialises the atomic modes depending on the machine size.
204  */
205 static void init_atomic_modes(void) {
206         unsigned int_size   = machine_size < 32 ? 2 : 4;
207         unsigned long_size  = machine_size < 64 ? 4 : 8;
208         unsigned llong_size = machine_size < 32 ? 4 : 8;
209
210         /* firm has no real void... */
211         _atomic_modes[ATOMIC_TYPE_VOID]        = mode_T;
212         _atomic_modes[ATOMIC_TYPE_CHAR]        = char_is_signed ? get_smode(1) : get_umode(1);
213         _atomic_modes[ATOMIC_TYPE_SCHAR]       = get_smode(1);
214         _atomic_modes[ATOMIC_TYPE_UCHAR]       = get_umode(1);
215         _atomic_modes[ATOMIC_TYPE_SHORT]       = get_smode(2);
216         _atomic_modes[ATOMIC_TYPE_USHORT]      = get_umode(2);
217         _atomic_modes[ATOMIC_TYPE_INT]         = get_smode(int_size);
218         _atomic_modes[ATOMIC_TYPE_UINT]        = get_umode(int_size);
219         _atomic_modes[ATOMIC_TYPE_LONG]        = get_smode(long_size);
220         _atomic_modes[ATOMIC_TYPE_ULONG]       = get_umode(long_size);
221         _atomic_modes[ATOMIC_TYPE_LONGLONG]    = get_smode(llong_size);
222         _atomic_modes[ATOMIC_TYPE_ULONGLONG]   = get_umode(llong_size);
223         _atomic_modes[ATOMIC_TYPE_FLOAT]       = mode_F;
224         _atomic_modes[ATOMIC_TYPE_DOUBLE]      = mode_D;
225         _atomic_modes[ATOMIC_TYPE_LONG_DOUBLE] = mode_E;
226         _atomic_modes[ATOMIC_TYPE_BOOL]        = get_umode(int_size);
227
228 #ifdef PROVIDE_COMPLEX
229         _atomic_modes[ATOMIC_TYPE_BOOL]                  = _atomic_modes[ATOMIC_TYPE_INT];
230         _atomic_modes[ATOMIC_TYPE_FLOAT_IMAGINARY]       = _atomic_modes[ATOMIC_TYPE_FLOAT];
231         _atomic_modes[ATOMIC_TYPE_DOUBLE_IMAGINARY]      = _atomic_modes[ATOMIC_TYPE_DOUBLE];
232         _atomic_modes[ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY] = _atomic_modes[ATOMIC_TYPE_LONG_DOUBLE];
233 #endif
234
235         /* Hmm, pointers should be machine size */
236         set_modeP_data(get_ptrmode(machine_size >> 3, NULL));
237         set_modeP_code(get_ptrmode(machine_size >> 3, NULL));
238
239         mode_int  = _atomic_modes[ATOMIC_TYPE_INT];
240         mode_uint = _atomic_modes[ATOMIC_TYPE_UINT];
241 }
242
243 static ir_mode *get_atomic_mode(const atomic_type_t* atomic_type)
244 {
245         ir_mode *res = NULL;
246         if ((unsigned)atomic_type->akind < (unsigned)ATOMIC_TYPE_LAST)
247                 res = _atomic_modes[(unsigned)atomic_type->akind];
248         if (res == NULL)
249                 panic("Encountered unknown atomic type");
250         return res;
251 }
252
253 static unsigned get_atomic_type_size(const atomic_type_t *type)
254 {
255         switch(type->akind) {
256         case ATOMIC_TYPE_CHAR:
257         case ATOMIC_TYPE_SCHAR:
258         case ATOMIC_TYPE_UCHAR:
259                 return 1;
260
261         case ATOMIC_TYPE_SHORT:
262         case ATOMIC_TYPE_USHORT:
263                 return 2;
264
265         case ATOMIC_TYPE_BOOL:
266         case ATOMIC_TYPE_INT:
267         case ATOMIC_TYPE_UINT:
268                 return machine_size >> 3;
269
270         case ATOMIC_TYPE_LONG:
271         case ATOMIC_TYPE_ULONG:
272                 return machine_size > 16 ? machine_size >> 3 : 4;
273
274         case ATOMIC_TYPE_LONGLONG:
275         case ATOMIC_TYPE_ULONGLONG:
276                 return machine_size > 16 ? 8 : 4;
277
278         case ATOMIC_TYPE_FLOAT:
279                 return 4;
280
281         case ATOMIC_TYPE_DOUBLE:
282                 return 8;
283
284         case ATOMIC_TYPE_LONG_DOUBLE:
285                 return 12;
286
287         case ATOMIC_TYPE_VOID:
288                 return 1;
289
290         case ATOMIC_TYPE_INVALID:
291         case ATOMIC_TYPE_LAST:
292                 break;
293         }
294         panic("Trying to determine size of invalid atomic type");
295 }
296
297 static unsigned get_compound_type_size(compound_type_t *type)
298 {
299         ir_type *irtype = get_ir_type((type_t*) type);
300         return get_type_size_bytes(irtype);
301 }
302
303 static unsigned get_array_type_size(array_type_t *type)
304 {
305         assert(!type->is_vla);
306         ir_type *irtype = get_ir_type((type_t*) type);
307         return get_type_size_bytes(irtype);
308 }
309
310
311 static unsigned get_type_size_const(type_t *type)
312 {
313         type = skip_typeref(type);
314
315         switch(type->kind) {
316         case TYPE_ERROR:
317                 panic("error type occured");
318         case TYPE_ATOMIC:
319                 return get_atomic_type_size(&type->atomic);
320         case TYPE_ENUM:
321                 return get_mode_size_bytes(mode_int);
322         case TYPE_COMPOUND_UNION:
323         case TYPE_COMPOUND_STRUCT:
324                 return get_compound_type_size(&type->compound);
325         case TYPE_FUNCTION:
326                 /* just a pointer to the function */
327                 return get_mode_size_bytes(mode_P_code);
328         case TYPE_POINTER:
329                 return get_mode_size_bytes(mode_P_data);
330         case TYPE_ARRAY:
331                 return get_array_type_size(&type->array);
332         case TYPE_BUILTIN:
333                 return get_type_size_const(type->builtin.real_type);
334         case TYPE_BITFIELD:
335                 panic("type size of bitfield request");
336         case TYPE_TYPEDEF:
337         case TYPE_TYPEOF:
338         case TYPE_INVALID:
339                 break;
340         }
341         panic("Trying to determine size of invalid type");
342 }
343
344 static ir_node *get_type_size(type_t *type)
345 {
346         type = skip_typeref(type);
347
348         if(is_type_array(type) && type->array.is_vla) {
349                 ir_node *size_node = type->array.size_node;
350                 if(size_node == NULL) {
351                         size_node = expression_to_firm(type->array.size_expression);
352                         assert(!is_Const(size_node));
353                         type->array.size_node = size_node;
354                 }
355
356                 ir_node *elem_size = get_type_size(type->array.element_type);
357                 ir_mode *mode      = get_irn_mode(size_node);
358                 ir_node *real_size = new_d_Mul(NULL, size_node, elem_size, mode);
359                 return real_size;
360         }
361
362         ir_mode *mode = get_ir_mode(type_size_t);
363         symconst_symbol sym;
364         sym.type_p = get_ir_type(type);
365         return new_SymConst(mode, sym, symconst_type_size);
366 }
367
368 static unsigned count_parameters(const function_type_t *function_type)
369 {
370         unsigned count = 0;
371
372         function_parameter_t *parameter = function_type->parameters;
373         for ( ; parameter != NULL; parameter = parameter->next) {
374                 ++count;
375         }
376
377         return count;
378 }
379
380
381 static ir_type *create_atomic_type(const atomic_type_t *type)
382 {
383         dbg_info *dbgi  = get_dbg_info(&type->type.source_position);
384         ir_mode *mode   = get_atomic_mode(type);
385         ident   *id     = get_mode_ident(mode);
386         ir_type *irtype = new_d_type_primitive(id, mode, dbgi);
387
388         /* TODO: this is x86 specific, we should fiddle this into
389          * lang_features.h somehow... */
390         if(type->akind == ATOMIC_TYPE_LONG_DOUBLE
391                         || type->akind == ATOMIC_TYPE_DOUBLE
392                         || type->akind == ATOMIC_TYPE_LONGLONG
393                         || type->akind == ATOMIC_TYPE_ULONGLONG) {
394                 set_type_alignment_bytes(irtype, 4);
395         }
396
397         return irtype;
398 }
399
400 static ir_type *create_method_type(const function_type_t *function_type)
401 {
402         type_t  *return_type  = function_type->return_type;
403
404         ident   *id           = unique_ident("functiontype");
405         int      n_parameters = count_parameters(function_type);
406         int      n_results    = return_type == type_void ? 0 : 1;
407         dbg_info *dbgi        = get_dbg_info(&function_type->type.source_position);
408         ir_type *irtype       = new_d_type_method(id, n_parameters, n_results, dbgi);
409
410         if(return_type != type_void) {
411                 ir_type *restype = get_ir_type(return_type);
412                 set_method_res_type(irtype, 0, restype);
413         }
414
415         function_parameter_t *parameter = function_type->parameters;
416         int                   n         = 0;
417         for( ; parameter != NULL; parameter = parameter->next) {
418                 ir_type *p_irtype = get_ir_type(parameter->type);
419                 set_method_param_type(irtype, n, p_irtype);
420                 ++n;
421         }
422
423         if(function_type->variadic || function_type->unspecified_parameters) {
424                 set_method_variadicity(irtype, variadicity_variadic);
425         }
426
427         return irtype;
428 }
429
430 static ir_type *create_pointer_type(pointer_type_t *type)
431 {
432         type_t  *points_to = type->points_to;
433         ir_type *ir_points_to;
434         /* Avoid endless recursion if the points_to type contains this poiner type
435          * again (might be a struct). We therefore first create a void* pointer
436          * and then set the real points_to type
437          */
438         dbg_info *dbgi   = get_dbg_info(&type->type.source_position);
439         ir_type *ir_type = new_d_type_pointer(unique_ident("pointer"),
440                                             ir_type_void, mode_P_data, dbgi);
441         type->type.firm_type  = ir_type;
442
443         ir_points_to = get_ir_type(points_to);
444         set_pointer_points_to_type(ir_type, ir_points_to);
445
446         return ir_type;
447 }
448
449 static ir_type *create_array_type(array_type_t *type)
450 {
451         type_t  *element_type    = type->element_type;
452         ir_type *ir_element_type = get_ir_type(element_type);
453
454         ident    *id      = unique_ident("array");
455         dbg_info *dbgi    = get_dbg_info(&type->type.source_position);
456         ir_type  *ir_type = new_d_type_array(id, 1, ir_element_type, dbgi);
457
458         const int align = get_type_alignment_bytes(ir_element_type);
459         set_type_alignment_bytes(ir_type, align);
460
461         if(type->size_constant) {
462                 int n_elements = type->size;
463
464                 set_array_bounds_int(ir_type, 0, 0, n_elements);
465
466                 size_t elemsize = get_type_size_bytes(ir_element_type);
467                 if(elemsize % align > 0) {
468                         elemsize += align - (elemsize % align);
469                 }
470                 set_type_size_bytes(ir_type, n_elements * elemsize);
471         } else {
472                 set_array_lower_bound_int(ir_type, 0, 0);
473         }
474         set_type_state(ir_type, layout_fixed);
475
476         return ir_type;
477 }
478
479 /**
480  * Return the signed integer type of size bits.
481  *
482  * @param size   the size
483  */
484 static ir_type *get_signed_int_type_for_bit_size(ir_type *base_tp,
485                                                  unsigned size)
486 {
487         static ir_mode *s_modes[64 + 1] = {NULL, };
488         ir_type *res;
489         ir_mode *mode;
490
491         if (size <= 0 || size > 64)
492                 return NULL;
493
494         mode = s_modes[size];
495         if (mode == NULL) {
496                 char name[32];
497
498                 snprintf(name, sizeof(name), "bf_I%u", size);
499                 mode = new_ir_mode(name, irms_int_number, size, 1, irma_twos_complement,
500                                    size <= 32 ? 32 : size );
501                 s_modes[size] = mode;
502         }
503
504         char name[32];
505         snprintf(name, sizeof(name), "I%u", size);
506         ident *id = new_id_from_str(name);
507         dbg_info *dbgi = get_dbg_info(&builtin_source_position);
508         res = new_d_type_primitive(mangle_u(get_type_ident(base_tp), id), mode, dbgi);
509         set_primitive_base_type(res, base_tp);
510
511         return res;
512 }
513
514 /**
515  * Return the unsigned integer type of size bits.
516  *
517  * @param size   the size
518  */
519 static ir_type *get_unsigned_int_type_for_bit_size(ir_type *base_tp,
520                                                    unsigned size)
521 {
522         static ir_mode *u_modes[64 + 1] = {NULL, };
523         ir_type *res;
524         ir_mode *mode;
525
526         if (size <= 0 || size > 64)
527                 return NULL;
528
529         mode = u_modes[size];
530         if (mode == NULL) {
531                 char name[32];
532
533                 snprintf(name, sizeof(name), "bf_U%u", size);
534                 mode = new_ir_mode(name, irms_int_number, size, 0, irma_twos_complement,
535                                    size <= 32 ? 32 : size );
536                 u_modes[size] = mode;
537         }
538
539         char name[32];
540
541         snprintf(name, sizeof(name), "U%u", size);
542         ident *id = new_id_from_str(name);
543         dbg_info *dbgi = get_dbg_info(&builtin_source_position);
544         res = new_d_type_primitive(mangle_u(get_type_ident(base_tp), id), mode, dbgi);
545         set_primitive_base_type(res, base_tp);
546
547         return res;
548 }
549
550 static ir_type *create_bitfield_type(bitfield_type_t *const type)
551 {
552         type_t *base = skip_typeref(type->base);
553         assert(base->kind == TYPE_ATOMIC);
554         ir_type *irbase = get_ir_type(base);
555
556         unsigned size = fold_constant(type->size);
557
558         assert(!is_type_float(base));
559         if(is_type_signed(base)) {
560                 return get_signed_int_type_for_bit_size(irbase, size);
561         } else {
562                 return get_unsigned_int_type_for_bit_size(irbase, size);
563         }
564 }
565
566 #define INVALID_TYPE ((ir_type_ptr)-1)
567
568 static ir_type *create_union_type(compound_type_t *type, ir_type *irtype,
569                                   size_t *outer_offset, size_t *outer_align);
570
571 static ir_type *create_struct_type(compound_type_t *type, ir_type *irtype,
572                                    size_t *outer_offset, size_t *outer_align)
573 {
574         declaration_t *declaration = type->declaration;
575         if(declaration->v.irtype != NULL) {
576                 return declaration->v.irtype;
577         }
578
579         size_t align_all  = 1;
580         size_t offset     = 0;
581         size_t bit_offset = 0;
582         if(irtype == NULL) {
583                 symbol_t *symbol = declaration->symbol;
584                 ident    *id;
585                 if(symbol != NULL) {
586                         id = unique_ident(symbol->string);
587                 } else {
588                         id = unique_ident("__anonymous_struct");
589                 }
590                 dbg_info *dbgi  = get_dbg_info(&type->type.source_position);
591
592                 irtype = new_d_type_struct(id, dbgi);
593
594                 declaration->v.irtype = irtype;
595                 type->type.firm_type  = irtype;
596         } else {
597                 offset    = *outer_offset;
598                 align_all = *outer_align;
599         }
600
601         declaration_t *entry = declaration->scope.declarations;
602         for( ; entry != NULL; entry = entry->next) {
603                 if(entry->namespc != NAMESPACE_NORMAL)
604                         continue;
605
606                 symbol_t *symbol     = entry->symbol;
607                 type_t   *entry_type = skip_typeref(entry->type);
608                 dbg_info *dbgi       = get_dbg_info(&entry->source_position);
609                 ident    *ident;
610                 if(symbol != NULL) {
611                         ident = new_id_from_str(symbol->string);
612                 } else {
613                         if(entry_type->kind == TYPE_COMPOUND_STRUCT) {
614                                 create_struct_type(&entry_type->compound, irtype, &offset,
615                                                    &align_all);
616                                 continue;
617                         } else if(entry_type->kind == TYPE_COMPOUND_UNION) {
618                                 create_union_type(&entry_type->compound, irtype, &offset,
619                                                   &align_all);
620                                 continue;
621                         } else {
622                                 assert(entry_type->kind == TYPE_BITFIELD);
623                         }
624                         ident = unique_ident("anon");
625                 }
626
627                 ir_type *base_irtype;
628                 if(entry_type->kind == TYPE_BITFIELD) {
629                         base_irtype = get_ir_type(entry_type->bitfield.base);
630                 } else {
631                         base_irtype = get_ir_type(entry_type);
632                 }
633
634                 size_t entry_alignment = get_type_alignment_bytes(base_irtype);
635                 size_t misalign        = offset % entry_alignment;
636
637                 ir_type   *entry_irtype = get_ir_type(entry_type);
638                 ir_entity *entity = new_d_entity(irtype, ident, entry_irtype, dbgi);
639
640                 size_t base;
641                 size_t bits_remainder;
642                 if(entry_type->kind == TYPE_BITFIELD) {
643                         size_t size_bits      = fold_constant(entry_type->bitfield.size);
644                         size_t rest_size_bits = (entry_alignment - misalign)*8 - bit_offset;
645
646                         if(size_bits > rest_size_bits) {
647                                 /* start a new bucket */
648                                 offset     += entry_alignment - misalign;
649                                 bit_offset  = 0;
650
651                                 base           = offset;
652                                 bits_remainder = 0;
653                         } else {
654                                 /* put into current bucket */
655                                 base           = offset - misalign;
656                                 bits_remainder = misalign * 8 + bit_offset;
657                         }
658
659                         offset     += size_bits / 8;
660                         bit_offset  = bit_offset + (size_bits % 8);
661                 } else {
662                         size_t entry_size = get_type_size_bytes(base_irtype);
663                         if(misalign > 0 || bit_offset > 0)
664                                 offset += entry_alignment - misalign;
665
666                         base           = offset;
667                         bits_remainder = 0;
668                         offset        += entry_size;
669                         bit_offset     = 0;
670                 }
671
672                 if(entry_alignment > align_all) {
673                         if(entry_alignment % align_all != 0) {
674                                 panic("uneven alignments not supported yet");
675                         }
676                         align_all = entry_alignment;
677                 }
678
679                 set_entity_offset(entity, base);
680                 set_entity_offset_bits_remainder(entity,
681                                                  (unsigned char) bits_remainder);
682                 //add_struct_member(irtype, entity);
683                 entry->declaration_kind = DECLARATION_KIND_COMPOUND_MEMBER;
684                 assert(entry->v.entity == NULL);
685                 entry->v.entity         = entity;
686         }
687
688         size_t misalign = offset % align_all;
689         if(misalign > 0 || bit_offset > 0) {
690                 offset += align_all - misalign;
691         }
692
693         if(outer_offset != NULL) {
694                 *outer_offset = offset;
695                 *outer_align  = align_all;
696         } else {
697                 set_type_alignment_bytes(irtype, align_all);
698                 set_type_size_bytes(irtype, offset);
699                 set_type_state(irtype, layout_fixed);
700         }
701
702         return irtype;
703 }
704
705 static ir_type *create_union_type(compound_type_t *type, ir_type *irtype,
706                                   size_t *outer_offset, size_t *outer_align)
707 {
708         declaration_t *declaration = type->declaration;
709         if(declaration->v.irtype != NULL) {
710                 return declaration->v.irtype;
711         }
712
713         size_t align_all = 1;
714         size_t offset    = 0;
715         size_t size      = 0;
716
717         if(irtype == NULL) {
718                 symbol_t      *symbol      = declaration->symbol;
719                 ident         *id;
720                 if(symbol != NULL) {
721                         id = unique_ident(symbol->string);
722                 } else {
723                         id = unique_ident("__anonymous_union");
724                 }
725                 dbg_info *dbgi = get_dbg_info(&type->type.source_position);
726
727                 irtype = new_d_type_union(id, dbgi);
728
729                 declaration->v.irtype = irtype;
730                 type->type.firm_type  = irtype;
731         } else {
732                 offset    = *outer_offset;
733                 align_all = *outer_align;
734         }
735
736         type->type.firm_type = irtype;
737
738         declaration_t *entry = declaration->scope.declarations;
739         for( ; entry != NULL; entry = entry->next) {
740                 if(entry->namespc != NAMESPACE_NORMAL)
741                         continue;
742
743                 symbol_t *symbol        = entry->symbol;
744                 type_t   *entry_type    = skip_typeref(entry->type);
745                 ir_type  *entry_ir_type = get_ir_type(entry_type);
746
747                 ident *ident;
748                 if(symbol != NULL) {
749                         ident = new_id_from_str(entry->symbol->string);
750                 } else {
751                         size_t offs = offset;
752                         if(entry_type->kind == TYPE_COMPOUND_STRUCT) {
753                                 create_struct_type(&entry_type->compound, irtype, &offs,
754                                                    &align_all);
755                                 continue;
756                         } else if(entry_type->kind == TYPE_COMPOUND_UNION) {
757                                 create_union_type(&entry_type->compound, irtype, &offs,
758                                                   &align_all);
759                                 continue;
760                         } else {
761                                 panic("anonymous union member must be struct or union");
762                         }
763                         size_t entry_size = offs - offset;
764                         if(entry_size > size) {
765                                 size = entry_size;
766                         }
767                         ident = unique_ident("anon");
768                 }
769
770                 size_t entry_size      = get_type_size_bytes(entry_ir_type);
771                 size_t entry_alignment = get_type_alignment_bytes(entry_ir_type);
772
773                 dbg_info  *const dbgi   = get_dbg_info(&entry->source_position);
774                 ir_entity *const entity = new_d_entity(irtype, ident, entry_ir_type,
775                                                        dbgi);
776                 //add_union_member(irtype, entity);
777                 set_entity_offset(entity, 0);
778                 entry->declaration_kind = DECLARATION_KIND_COMPOUND_MEMBER;
779                 assert(entry->v.entity == NULL);
780                 entry->v.entity         = entity;
781
782                 if(entry_size > size) {
783                         size = entry_size;
784                 }
785                 if(entry_alignment > align_all) {
786                         if(entry_alignment % align_all != 0) {
787                                 panic("Uneven alignments not supported yet");
788                         }
789                         align_all = entry_alignment;
790                 }
791         }
792
793         if(outer_offset != NULL) {
794                 assert(*outer_offset == offset);
795
796                 size_t misalign = offset % align_all;
797                 if (misalign != 0)
798                         size += align_all - misalign;
799                 *outer_offset += size;
800
801                 if(align_all > *outer_align) {
802                         if(align_all % *outer_align != 0) {
803                                 panic("uneven alignments not supported yet");
804                         }
805                         *outer_align = align_all;
806                 }
807         } else {
808                 set_type_alignment_bytes(irtype, align_all);
809                 set_type_size_bytes(irtype, size);
810                 set_type_state(irtype, layout_fixed);
811                 declaration->v.irtype = irtype;
812         }
813
814         return irtype;
815 }
816
817 static ir_type *create_enum_type(enum_type_t *const type)
818 {
819         type->type.firm_type = ir_type_int;
820
821         ir_mode *const mode    = mode_int;
822         tarval  *const one     = get_mode_one(mode);
823         tarval  *      tv_next = get_tarval_null(mode);
824
825         declaration_t *declaration = type->declaration->next;
826         for (; declaration != NULL; declaration = declaration->next) {
827                 if (declaration->storage_class != STORAGE_CLASS_ENUM_ENTRY)
828                         break;
829
830                 declaration->declaration_kind = DECLARATION_KIND_ENUM_ENTRY;
831
832                 expression_t *const init = declaration->init.enum_value;
833                 if (init != NULL) {
834                         ir_node *const cnst = expression_to_firm(init);
835                         if (!is_Const(cnst)) {
836                                 panic("couldn't fold constant");
837                         }
838                         tv_next = get_Const_tarval(cnst);
839                 }
840                 declaration->v.enum_val = tv_next;
841                 tv_next = tarval_add(tv_next, one);
842         }
843
844         return ir_type_int;
845 }
846
847 static ir_type *get_ir_type(type_t *type)
848 {
849         assert(type != NULL);
850
851         type = skip_typeref(type);
852
853         if(type->base.firm_type != NULL) {
854                 assert(type->base.firm_type != INVALID_TYPE);
855                 return type->base.firm_type;
856         }
857
858         ir_type *firm_type = NULL;
859         switch(type->kind) {
860         case TYPE_ERROR:
861                 panic("error type occured");
862         case TYPE_ATOMIC:
863                 firm_type = create_atomic_type(&type->atomic);
864                 break;
865         case TYPE_FUNCTION:
866                 firm_type = create_method_type(&type->function);
867                 break;
868         case TYPE_POINTER:
869                 firm_type = create_pointer_type(&type->pointer);
870                 break;
871         case TYPE_ARRAY:
872                 firm_type = create_array_type(&type->array);
873                 break;
874         case TYPE_COMPOUND_STRUCT:
875                 firm_type = create_struct_type(&type->compound, NULL, NULL, NULL);
876                 break;
877         case TYPE_COMPOUND_UNION:
878                 firm_type = create_union_type(&type->compound, NULL, NULL, NULL);
879                 break;
880         case TYPE_ENUM:
881                 firm_type = create_enum_type(&type->enumt);
882                 break;
883         case TYPE_BUILTIN:
884                 firm_type = get_ir_type(type->builtin.real_type);
885                 break;
886         case TYPE_BITFIELD:
887                 firm_type = create_bitfield_type(&type->bitfield);
888                 break;
889
890         case TYPE_TYPEOF:
891         case TYPE_TYPEDEF:
892         case TYPE_INVALID:
893                 break;
894         }
895         if(firm_type == NULL)
896                 panic("unknown type found");
897
898         type->base.firm_type = firm_type;
899         return firm_type;
900 }
901
902 static inline ir_mode *get_ir_mode(type_t *type)
903 {
904         ir_type *irtype = get_ir_type(type);
905
906         /* firm doesn't report a mode for arrays somehow... */
907         if(is_Array_type(irtype)) {
908                 return mode_P_data;
909         }
910
911         ir_mode *mode = get_type_mode(irtype);
912         assert(mode != NULL);
913         return mode;
914 }
915
916 static ident *predef_idents[rts_max];
917
918 /** Names of the runtime functions. */
919 static const struct {
920         int        id;           /**< the rts id */
921         int        n_res;        /**< number of return values */
922         const char *name;        /**< the name of the rts function */
923         int        n_params;     /**< number of parameters */
924         unsigned   flags;        /**< language flags */
925 } rts_data[] = {
926         { rts_debugbreak, 0, "__debugbreak", 0, _MS },
927         { rts_abort,      0, "abort",        0, _C89 },
928         { rts_abs,        1, "abs",          1, _C89 },
929         { rts_labs,       1, "labs",         1, _C89 },
930         { rts_llabs,      1, "llabs",        1, _C99 },
931         { rts_imaxabs,    1, "imaxabs",      1, _C99 },
932
933         { rts_fabs,       1, "fabs",         1, _C89 },
934         { rts_sqrt,       1, "sqrt",         1, _C89 },
935         { rts_cbrt,       1, "cbrt",         1, _C99 },
936         { rts_exp,        1, "exp",          1, _C89 },
937         { rts_exp2,       1, "exp2",         1, _C89 },
938         { rts_exp10,      1, "exp10",        1, _GNUC },
939         { rts_log,        1, "log",          1, _C89 },
940         { rts_log2,       1, "log2",         1, _C89 },
941         { rts_log10,      1, "log10",        1, _C89 },
942         { rts_pow,        1, "pow",          2, _C89 },
943         { rts_sin,        1, "sin",          1, _C89 },
944         { rts_cos,        1, "cos",          1, _C89 },
945         { rts_tan,        1, "tan",          1, _C89 },
946         { rts_asin,       1, "asin",         1, _C89 },
947         { rts_acos,       1, "acos",         1, _C89 },
948         { rts_atan,       1, "atan",         1, _C89 },
949         { rts_sinh,       1, "sinh",         1, _C89 },
950         { rts_cosh,       1, "cosh",         1, _C89 },
951         { rts_tanh,       1, "tanh",         1, _C89 },
952
953         { rts_fabsf,      1, "fabsf",        1, _C99 },
954         { rts_sqrtf,      1, "sqrtf",        1, _C99 },
955         { rts_cbrtf,      1, "cbrtf",        1, _C99 },
956         { rts_expf,       1, "expf",         1, _C99 },
957         { rts_exp2f,      1, "exp2f",        1, _C99 },
958         { rts_exp10f,     1, "exp10f",       1, _GNUC },
959         { rts_logf,       1, "logf",         1, _C99 },
960         { rts_log2f,      1, "log2f",        1, _C99 },
961         { rts_log10f,     1, "log10f",       1, _C99 },
962         { rts_powf,       1, "powf",         2, _C99 },
963         { rts_sinf,       1, "sinf",         1, _C99 },
964         { rts_cosf,       1, "cosf",         1, _C99 },
965         { rts_tanf,       1, "tanf",         1, _C99 },
966         { rts_asinf,      1, "asinf",        1, _C99 },
967         { rts_acosf,      1, "acosf",        1, _C99 },
968         { rts_atanf,      1, "atanf",        1, _C99 },
969         { rts_sinhf,      1, "sinhf",        1, _C99 },
970         { rts_coshf,      1, "coshf",        1, _C99 },
971         { rts_tanhf,      1, "tanhf",        1, _C99 },
972
973         { rts_fabsl,      1, "fabsl",        1, _C99 },
974         { rts_sqrtl,      1, "sqrtl",        1, _C99 },
975         { rts_cbrtl,      1, "cbrtl",        1, _C99 },
976         { rts_expl,       1, "expl",         1, _C99 },
977         { rts_exp2l,      1, "exp2l",        1, _C99 },
978         { rts_exp10l,     1, "exp10l",       1, _GNUC },
979         { rts_logl,       1, "logl",         1, _C99 },
980         { rts_log2l,      1, "log2l",        1, _C99 },
981         { rts_log10l,     1, "log10l",       1, _C99 },
982         { rts_powl,       1, "powl",         2, _C99 },
983         { rts_sinl,       1, "sinl",         1, _C99 },
984         { rts_cosl,       1, "cosl",         1, _C99 },
985         { rts_tanl,       1, "tanl",         1, _C99 },
986         { rts_asinl,      1, "asinl",        1, _C99 },
987         { rts_acosl,      1, "acosl",        1, _C99 },
988         { rts_atanl,      1, "atanl",        1, _C99 },
989         { rts_sinhl,      1, "sinhl",        1, _C99 },
990         { rts_coshl,      1, "coshl",        1, _C99 },
991         { rts_tanhl,      1, "tanhl",        1, _C99 },
992
993         { rts_memcpy,     1, "memcpy",       3, _C89 },  /* HMM, man say its C99 */
994         { rts_memset,     1, "memset",       3, _C89 },  /* HMM, man say its C99 */
995         { rts_strcmp,     1, "strcmp",       2, _C89 },
996         { rts_strncmp,    1, "strncmp",      3, _C89 }
997 };
998
999 static ir_entity* get_function_entity(declaration_t *declaration)
1000 {
1001         if(declaration->declaration_kind == DECLARATION_KIND_FUNCTION)
1002                 return declaration->v.entity;
1003         assert(declaration->declaration_kind == DECLARATION_KIND_UNKNOWN);
1004
1005         symbol_t *symbol = declaration->symbol;
1006         ident    *id     = new_id_from_str(symbol->string);
1007
1008         ir_type  *global_type    = get_glob_type();
1009         ir_type  *ir_type_method = get_ir_type(declaration->type);
1010         assert(is_Method_type(ir_type_method));
1011
1012         dbg_info  *const dbgi   = get_dbg_info(&declaration->source_position);
1013         ir_entity *const entity = new_d_entity(global_type, id, ir_type_method, dbgi);
1014         set_entity_ld_ident(entity, id);
1015         if(declaration->storage_class == STORAGE_CLASS_STATIC
1016                         || declaration->is_inline) {
1017                 set_entity_visibility(entity, visibility_local);
1018         } else if(declaration->init.statement != NULL) {
1019                 set_entity_visibility(entity, visibility_external_visible);
1020         } else {
1021                 set_entity_visibility(entity, visibility_external_allocated);
1022
1023                 /* We should check for file scope here, but as long as we compile C only
1024                    this is not needed. */
1025                 int    n_params = get_method_n_params(ir_type_method);
1026                 int    n_res    = get_method_n_ress(ir_type_method);
1027                 int    i;
1028
1029                 if (n_params == 0 && n_res == 0 && id == predef_idents[rts_abort]) {
1030                         /* found abort(), store for later */
1031                         //abort_ent = ent;
1032                         //abort_tp  = ftype;
1033                 } else {
1034                         if (! firm_opt.freestanding) {
1035                                 /* check for a known runtime function */
1036                                 for (i = 0; i < rts_max; ++i) {
1037                                         /* ignore those rts functions not necessary needed for current mode */
1038                                         if ((c_mode & rts_data[i].flags) == 0)
1039                                                 continue;
1040                                         if (n_params == rts_data[i].n_params && n_res == rts_data[i].n_res &&
1041                                                 id == predef_idents[rts_data[i].id])
1042                                                 rts_entities[rts_data[i].id] = entity;
1043                                 }
1044                         }
1045                 }
1046         }
1047         set_entity_allocation(entity, allocation_static);
1048
1049         declaration->declaration_kind = DECLARATION_KIND_FUNCTION;
1050         declaration->v.entity         = entity;
1051
1052         return entity;
1053 }
1054
1055 static ir_node *const_to_firm(const const_expression_t *cnst)
1056 {
1057         dbg_info *dbgi = get_dbg_info(&cnst->base.source_position);
1058         ir_mode  *mode = get_ir_mode(cnst->base.type);
1059
1060         char    buf[128];
1061         tarval *tv;
1062         size_t  len;
1063         if(mode_is_float(mode)) {
1064                 tv = new_tarval_from_double(cnst->v.float_value, mode);
1065         } else {
1066                 if(mode_is_signed(mode)) {
1067                         len = snprintf(buf, sizeof(buf), "%lld", cnst->v.int_value);
1068                 } else {
1069                         len = snprintf(buf, sizeof(buf), "%llu",
1070                                        (unsigned long long) cnst->v.int_value);
1071                 }
1072                 tv = new_tarval_from_str(buf, len, mode);
1073         }
1074
1075         return new_d_Const(dbgi, mode, tv);
1076 }
1077
1078 static ir_node *char_const_to_firm(const const_expression_t *cnst)
1079 {
1080         dbg_info *dbgi = get_dbg_info(&cnst->base.source_position);
1081         ir_mode  *mode = get_ir_mode(cnst->base.type);
1082
1083         long long int v = 0;
1084         for (size_t i = 0; i < cnst->v.chars.size; ++i) {
1085                 v = (v << 8) | ((unsigned char)cnst->v.chars.begin[i]);
1086         }
1087         char    buf[128];
1088         size_t  len = snprintf(buf, sizeof(buf), "%lld", v);
1089         tarval *tv = new_tarval_from_str(buf, len, mode);
1090
1091         return new_d_Const(dbgi, mode, tv);
1092 }
1093
1094 static ir_node *create_symconst(dbg_info *dbgi, ir_mode *mode,
1095                                 ir_entity *entity)
1096 {
1097         assert(entity != NULL);
1098         union symconst_symbol sym;
1099         sym.entity_p = entity;
1100         return new_d_SymConst(dbgi, mode, sym, symconst_addr_ent);
1101 }
1102
1103 static ir_node *string_to_firm(const source_position_t *const src_pos,
1104                                const char *const id_prefix,
1105                                const string_t *const value)
1106 {
1107         ir_type  *const global_type = get_glob_type();
1108         dbg_info *const dbgi        = get_dbg_info(src_pos);
1109         ir_type  *const type        = new_d_type_array(unique_ident("strtype"), 1,
1110                                                        ir_type_const_char, dbgi);
1111
1112         ident     *const id     = unique_ident(id_prefix);
1113         ir_entity *const entity = new_d_entity(global_type, id, type, dbgi);
1114         set_entity_ld_ident(entity, id);
1115         set_entity_variability(entity, variability_constant);
1116         set_entity_allocation(entity, allocation_static);
1117
1118         ir_type *const elem_type = ir_type_const_char;
1119         ir_mode *const mode      = get_type_mode(elem_type);
1120
1121         const char* const string = value->begin;
1122         const size_t      slen   = value->size;
1123
1124         set_array_lower_bound_int(type, 0, 0);
1125         set_array_upper_bound_int(type, 0, slen);
1126         set_type_size_bytes(type, slen);
1127         set_type_state(type, layout_fixed);
1128
1129         tarval **const tvs = xmalloc(slen * sizeof(tvs[0]));
1130         for(size_t i = 0; i < slen; ++i) {
1131                 tvs[i] = new_tarval_from_long(string[i], mode);
1132         }
1133
1134         set_array_entity_values(entity, tvs, slen);
1135         free(tvs);
1136
1137         return create_symconst(dbgi, mode_P_data, entity);
1138 }
1139
1140 static ir_node *string_literal_to_firm(
1141                 const string_literal_expression_t* literal)
1142 {
1143         return string_to_firm(&literal->base.source_position, "Lstr",
1144                               &literal->value);
1145 }
1146
1147 static ir_node *wide_string_literal_to_firm(
1148         const wide_string_literal_expression_t* const literal)
1149 {
1150         ir_type *const global_type = get_glob_type();
1151         ir_type *const elem_type   = ir_type_wchar_t;
1152         dbg_info *const dbgi       = get_dbg_info(&literal->base.source_position);
1153         ir_type *const type        = new_d_type_array(unique_ident("strtype"), 1,
1154                                                     elem_type, dbgi);
1155
1156         ident     *const id     = unique_ident("Lstr");
1157         ir_entity *const entity = new_d_entity(global_type, id, type, dbgi);
1158         set_entity_ld_ident(entity, id);
1159         set_entity_variability(entity, variability_constant);
1160         set_entity_allocation(entity, allocation_static);
1161
1162         ir_mode *const mode      = get_type_mode(elem_type);
1163
1164         const wchar_rep_t *const string = literal->value.begin;
1165         const size_t             slen   = literal->value.size;
1166
1167         set_array_lower_bound_int(type, 0, 0);
1168         set_array_upper_bound_int(type, 0, slen);
1169         set_type_size_bytes(type, slen);
1170         set_type_state(type, layout_fixed);
1171
1172         tarval **const tvs = xmalloc(slen * sizeof(tvs[0]));
1173         for(size_t i = 0; i < slen; ++i) {
1174                 tvs[i] = new_tarval_from_long(string[i], mode);
1175         }
1176
1177         set_array_entity_values(entity, tvs, slen);
1178         free(tvs);
1179
1180         return create_symconst(dbgi, mode_P_data, entity);
1181 }
1182
1183 static ir_node *deref_address(ir_type *const irtype, ir_node *const addr,
1184                               dbg_info *const dbgi)
1185 {
1186         if (is_compound_type(irtype) ||
1187                         is_Method_type(irtype)   ||
1188                         is_Array_type(irtype)) {
1189                 return addr;
1190         }
1191
1192         ir_mode *const mode     = get_type_mode(irtype);
1193         ir_node *const memory   = get_store();
1194         ir_node *const load     = new_d_Load(dbgi, memory, addr, mode);
1195         ir_node *const load_mem = new_d_Proj(dbgi, load, mode_M, pn_Load_M);
1196         ir_node *const load_res = new_d_Proj(dbgi, load, mode,   pn_Load_res);
1197         set_store(load_mem);
1198         return load_res;
1199 }
1200
1201 static ir_node *do_strict_conv(dbg_info *dbgi, ir_node *node)
1202 {
1203         ir_mode *mode = get_irn_mode(node);
1204
1205         if(!(get_irg_fp_model(current_ir_graph) & fp_explicit_rounding))
1206                 return node;
1207         if(!mode_is_float(mode))
1208                 return node;
1209
1210         /* check if there is already a Conv */
1211         if (get_irn_op(node) == op_Conv) {
1212                 /* convert it into a strict Conv */
1213                 set_Conv_strict(node, 1);
1214                 return node;
1215         }
1216
1217         /* otherwise create a new one */
1218         return new_d_strictConv(dbgi, node, mode);
1219 }
1220
1221 static ir_node *get_global_var_address(dbg_info *const dbgi,
1222                                        const declaration_t *const decl)
1223 {
1224         assert(decl->declaration_kind == DECLARATION_KIND_GLOBAL_VARIABLE);
1225
1226         ir_entity *const entity = decl->v.entity;
1227         switch ((storage_class_tag_t)decl->storage_class) {
1228                 case STORAGE_CLASS_THREAD:
1229                 case STORAGE_CLASS_THREAD_EXTERN:
1230                 case STORAGE_CLASS_THREAD_STATIC: {
1231                         ir_node *const no_mem = new_NoMem();
1232                         ir_node *const tls    = get_irg_tls(current_ir_graph);
1233                         return new_d_simpleSel(dbgi, no_mem, tls, entity);
1234                 }
1235
1236                 default:
1237                         return create_symconst(dbgi, mode_P_data, entity);
1238         }
1239 }
1240
1241 /* Returns the correct base address depending on whether it is a parameter or a
1242  * normal local variable */
1243 static ir_node *get_local_frame(ir_entity *const ent)
1244 {
1245         ir_graph      *const irg   = current_ir_graph;
1246         const ir_type *const owner = get_entity_owner(ent);
1247         if (owner == get_irg_frame_type(irg)) {
1248                 return get_irg_frame(irg);
1249         } else {
1250                 assert(owner == get_method_value_param_type(get_entity_type(get_irg_entity(irg))));
1251                 return get_irg_value_param_base(irg);
1252         }
1253 }
1254
1255 static ir_node *reference_expression_to_firm(const reference_expression_t *ref)
1256 {
1257         dbg_info      *dbgi        = get_dbg_info(&ref->base.source_position);
1258         declaration_t *declaration = ref->declaration;
1259         type_t        *type        = skip_typeref(declaration->type);
1260
1261         switch((declaration_kind_t) declaration->declaration_kind) {
1262         case DECLARATION_KIND_UNKNOWN:
1263                 if (declaration->storage_class != STORAGE_CLASS_ENUM_ENTRY) {
1264                         break;
1265                 }
1266                 get_ir_type(type);
1267                 /* FALLTHROUGH */
1268
1269         case DECLARATION_KIND_ENUM_ENTRY: {
1270                 ir_mode *const mode = get_ir_mode(type);
1271                 return new_Const(mode, declaration->v.enum_val);
1272         }
1273
1274         case DECLARATION_KIND_LOCAL_VARIABLE: {
1275                 ir_mode *const mode = get_ir_mode(type);
1276                 return get_value(declaration->v.value_number, mode);
1277         }
1278         case DECLARATION_KIND_FUNCTION: {
1279                 ir_mode *const mode = get_ir_mode(type);
1280                 return create_symconst(dbgi, mode, declaration->v.entity);
1281         }
1282         case DECLARATION_KIND_GLOBAL_VARIABLE: {
1283                 ir_node *const addr   = get_global_var_address(dbgi, declaration);
1284                 ir_type *const irtype = get_entity_type(declaration->v.entity);
1285                 return deref_address(irtype, addr, dbgi);
1286         }
1287
1288         case DECLARATION_KIND_LOCAL_VARIABLE_ENTITY: {
1289                 ir_entity *entity = declaration->v.entity;
1290                 ir_node   *frame  = get_local_frame(entity);
1291                 ir_node   *sel    = new_d_simpleSel(dbgi, new_NoMem(), frame, entity);
1292                 ir_type   *irtype = get_entity_type(entity);
1293                 return deref_address(irtype, sel, dbgi);
1294         }
1295
1296         case DECLARATION_KIND_VARIABLE_LENGTH_ARRAY:
1297                 return declaration->v.vla_base;
1298
1299         case DECLARATION_KIND_COMPOUND_MEMBER:
1300         case DECLARATION_KIND_LABEL_BLOCK:
1301                 panic("not implemented reference type");
1302         }
1303
1304         panic("reference to declaration with unknown type found");
1305 }
1306
1307 static ir_node *reference_addr(const reference_expression_t *ref)
1308 {
1309         dbg_info      *dbgi        = get_dbg_info(&ref->base.source_position);
1310         declaration_t *declaration = ref->declaration;
1311
1312         switch((declaration_kind_t) declaration->declaration_kind) {
1313         case DECLARATION_KIND_UNKNOWN:
1314                 break;
1315         case DECLARATION_KIND_LOCAL_VARIABLE:
1316                 panic("local variable without entity has no address");
1317         case DECLARATION_KIND_FUNCTION: {
1318                 type_t *const  type = skip_typeref(ref->base.type);
1319                 ir_mode *const mode = get_ir_mode(type);
1320                 return create_symconst(dbgi, mode, declaration->v.entity);
1321         }
1322         case DECLARATION_KIND_GLOBAL_VARIABLE: {
1323                 ir_node *const addr = get_global_var_address(dbgi, declaration);
1324                 return addr;
1325         }
1326         case DECLARATION_KIND_LOCAL_VARIABLE_ENTITY: {
1327                 ir_entity *entity = declaration->v.entity;
1328                 ir_node   *frame  = get_local_frame(entity);
1329                 ir_node   *sel    = new_d_simpleSel(dbgi, new_NoMem(), frame, entity);
1330
1331                 return sel;
1332         }
1333
1334         case DECLARATION_KIND_VARIABLE_LENGTH_ARRAY:
1335                 return declaration->v.vla_base;
1336
1337         case DECLARATION_KIND_ENUM_ENTRY:
1338                 panic("trying to reference enum entry");
1339
1340         case DECLARATION_KIND_COMPOUND_MEMBER:
1341         case DECLARATION_KIND_LABEL_BLOCK:
1342                 panic("not implemented reference type");
1343         }
1344
1345         panic("reference to declaration with unknown type found");
1346 }
1347
1348 static ir_node *process_builtin_call(const call_expression_t *call)
1349 {
1350         dbg_info *dbgi = get_dbg_info(&call->base.source_position);
1351
1352         assert(call->function->kind == EXPR_BUILTIN_SYMBOL);
1353         builtin_symbol_expression_t *builtin = &call->function->builtin_symbol;
1354
1355         type_t *type = skip_typeref(builtin->base.type);
1356         assert(is_type_pointer(type));
1357
1358         type_t   *function_type = skip_typeref(type->pointer.points_to);
1359         symbol_t *symbol        = builtin->symbol;
1360
1361         switch(symbol->ID) {
1362         case T___builtin_alloca: {
1363                 if(call->arguments == NULL || call->arguments->next != NULL) {
1364                         panic("invalid number of parameters on __builtin_alloca");
1365                 }
1366                 expression_t *argument = call->arguments->expression;
1367                 ir_node      *size     = expression_to_firm(argument);
1368
1369                 ir_node *store  = get_store();
1370                 ir_node *alloca = new_d_Alloc(dbgi, store, size, firm_unknown_type,
1371                                               stack_alloc);
1372                 ir_node *proj_m = new_Proj(alloca, mode_M, pn_Alloc_M);
1373                 set_store(proj_m);
1374                 ir_node *res    = new_Proj(alloca, mode_P_data, pn_Alloc_res);
1375
1376                 return res;
1377         }
1378         case T___builtin_nan:
1379         case T___builtin_nanf:
1380         case T___builtin_nand: {
1381                 /* Ignore string for now... */
1382                 assert(is_type_function(function_type));
1383                 ir_mode *mode = get_ir_mode(function_type->function.return_type);
1384                 tarval  *tv   = get_mode_NAN(mode);
1385                 ir_node *res  = new_d_Const(dbgi, mode, tv);
1386                 return res;
1387         }
1388         case T___builtin_va_end:
1389                 return NULL;
1390         default:
1391                 panic("Unsupported builtin found\n");
1392         }
1393 }
1394
1395 static ir_node *call_expression_to_firm(const call_expression_t *call)
1396 {
1397         assert(get_cur_block() != NULL);
1398
1399         expression_t *function = call->function;
1400         if(function->kind == EXPR_BUILTIN_SYMBOL) {
1401                 return process_builtin_call(call);
1402         }
1403         ir_node *callee = expression_to_firm(function);
1404
1405         type_t *type = skip_typeref(function->base.type);
1406         assert(is_type_pointer(type));
1407         pointer_type_t *pointer_type = &type->pointer;
1408         type_t         *points_to    = skip_typeref(pointer_type->points_to);
1409         assert(is_type_function(points_to));
1410         function_type_t *function_type = &points_to->function;
1411
1412         int              n_parameters = 0;
1413         call_argument_t *argument     = call->arguments;
1414         for( ; argument != NULL; argument = argument->next) {
1415                 ++n_parameters;
1416         }
1417
1418         dbg_info *dbgi  = get_dbg_info(&call->base.source_position);
1419
1420         ir_type *ir_method_type  = get_ir_type((type_t*) function_type);
1421         ir_type *new_method_type = NULL;
1422         if(function_type->variadic || function_type->unspecified_parameters) {
1423                 /* we need to construct a new method type matching the call
1424                  * arguments... */
1425                 int n_res       = get_method_n_ress(ir_method_type);
1426                 dbg_info *dbgi  = get_dbg_info(&call->base.source_position);
1427                 new_method_type = new_d_type_method(unique_ident("calltype"),
1428                                                   n_parameters, n_res, dbgi);
1429                 set_method_calling_convention(new_method_type,
1430                                get_method_calling_convention(ir_method_type));
1431                 set_method_additional_properties(new_method_type,
1432                                get_method_additional_properties(ir_method_type));
1433
1434                 for(int i = 0; i < n_res; ++i) {
1435                         set_method_res_type(new_method_type, i,
1436                                             get_method_res_type(ir_method_type, i));
1437                 }
1438         }
1439         ir_node *in[n_parameters];
1440
1441         argument = call->arguments;
1442         int n = 0;
1443         for( ; argument != NULL; argument = argument->next) {
1444                 expression_t *expression = argument->expression;
1445                 ir_node      *arg_node   = expression_to_firm(expression);
1446
1447                 arg_node = do_strict_conv(dbgi, arg_node);
1448
1449                 in[n] = arg_node;
1450                 if(new_method_type != NULL) {
1451                         ir_type *irtype = get_ir_type(expression->base.type);
1452                         set_method_param_type(new_method_type, n, irtype);
1453                 }
1454
1455                 n++;
1456         }
1457         assert(n == n_parameters);
1458
1459         if(new_method_type != NULL)
1460                 ir_method_type = new_method_type;
1461
1462         ir_node  *store = get_store();
1463         ir_node  *node  = new_d_Call(dbgi, store, callee, n_parameters, in,
1464                                      ir_method_type);
1465         ir_node  *mem   = new_d_Proj(dbgi, node, mode_M, pn_Call_M_regular);
1466         set_store(mem);
1467
1468         type_t  *return_type = skip_typeref(function_type->return_type);
1469         ir_node *result      = NULL;
1470
1471         if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
1472                 ir_mode *mode;
1473                 if(is_type_scalar(return_type)) {
1474                         mode = get_ir_mode(return_type);
1475                 } else {
1476                         mode = mode_P_data;
1477                 }
1478                 ir_node *resproj = new_d_Proj(dbgi, node, mode_T, pn_Call_T_result);
1479                 result           = new_d_Proj(dbgi, resproj, mode, 0);
1480         }
1481
1482         return result;
1483 }
1484
1485 static void statement_to_firm(statement_t *statement);
1486 static ir_node *compound_statement_to_firm(compound_statement_t *compound);
1487
1488 static ir_node *expression_to_addr(const expression_t *expression);
1489 static void create_condition_evaluation(const expression_t *expression,
1490                                         ir_node *true_block,
1491                                         ir_node *false_block);
1492
1493 static void assign_value(dbg_info *dbgi, ir_node *addr, type_t *type,
1494                          ir_node *value)
1495 {
1496         value = do_strict_conv(dbgi, value);
1497
1498         ir_node *memory = get_store();
1499
1500         if(is_type_scalar(type)) {
1501                 ir_node  *store     = new_d_Store(dbgi, memory, addr, value);
1502                 ir_node  *store_mem = new_d_Proj(dbgi, store, mode_M, pn_Store_M);
1503                 set_store(store_mem);
1504         } else {
1505                 ir_type *irtype    = get_ir_type(type);
1506                 ir_node *copyb     = new_d_CopyB(dbgi, memory, addr, value, irtype);
1507                 ir_node *copyb_mem = new_Proj(copyb, mode_M, pn_CopyB_M_regular);
1508                 set_store(copyb_mem);
1509         }
1510 }
1511
1512 static tarval *create_bitfield_mask(ir_mode *mode, int offset, int size)
1513 {
1514         tarval *all_one   = get_mode_all_one(mode);
1515         int     mode_size = get_mode_size_bits(mode);
1516
1517         assert(offset >= 0 && size >= 0);
1518         assert(offset + size <= mode_size);
1519         if(size == mode_size) {
1520                 return all_one;
1521         }
1522
1523         long    shiftr    = get_mode_size_bits(mode) - size;
1524         long    shiftl    = offset;
1525         tarval *tv_shiftr = new_tarval_from_long(shiftr, mode_uint);
1526         tarval *tv_shiftl = new_tarval_from_long(shiftl, mode_uint);
1527         tarval *mask0     = tarval_shr(all_one, tv_shiftr);
1528         tarval *mask1     = tarval_shl(mask0, tv_shiftl);
1529
1530         return mask1;
1531 }
1532
1533 static void bitfield_store_to_firm(const unary_expression_t *expression,
1534                                    ir_node *value)
1535 {
1536         expression_t *select = expression->value;
1537         assert(select->kind == EXPR_SELECT);
1538         type_t       *type   = select->base.type;
1539         assert(type->kind == TYPE_BITFIELD);
1540         ir_mode      *mode   = get_ir_mode(type->bitfield.base);
1541         ir_node      *addr   = expression_to_addr(select);
1542
1543         assert(get_irn_mode(value) == mode);
1544
1545         dbg_info *dbgi = get_dbg_info(&expression->base.source_position);
1546
1547         /* kill upper bits of value and shift to right position */
1548         ir_entity *entity       = select->select.compound_entry->v.entity;
1549         int        bitoffset    = get_entity_offset_bits_remainder(entity);
1550         ir_type   *entity_type  = get_entity_type(entity);
1551         int        bitsize      = get_mode_size_bits(get_type_mode(entity_type));
1552
1553         tarval  *mask            = create_bitfield_mask(mode, 0, bitsize);
1554         ir_node *mask_node       = new_d_Const(dbgi, mode, mask);
1555         ir_node *value_masked    = new_d_And(dbgi, value, mask_node, mode);
1556         tarval  *shiftl          = new_tarval_from_long(bitoffset, mode_uint);
1557         ir_node *shiftcount      = new_d_Const(dbgi, mode_uint, shiftl);
1558         ir_node *value_maskshift = new_d_Shl(dbgi, value_masked, shiftcount, mode);
1559
1560         /* load current value */
1561         ir_node  *mem             = get_store();
1562         ir_node  *load            = new_d_Load(dbgi, mem, addr, mode);
1563         ir_node  *load_mem        = new_d_Proj(dbgi, load, mode_M, pn_Load_M);
1564         ir_node  *load_res        = new_d_Proj(dbgi, load, mode, pn_Load_res);
1565         tarval   *shift_mask      = create_bitfield_mask(mode, bitoffset, bitsize);
1566         tarval   *inv_mask        = tarval_not(shift_mask);
1567         ir_node  *inv_mask_node   = new_d_Const(dbgi, mode, inv_mask);
1568         ir_node  *load_res_masked = new_d_And(dbgi, load_res, inv_mask_node, mode);
1569
1570         /* construct new value and store */
1571         ir_node *new_val   = new_d_Or(dbgi, load_res_masked, value_maskshift, mode);
1572         ir_node *store     = new_d_Store(dbgi, load_mem, addr, new_val);
1573         ir_node *store_mem = new_d_Proj(dbgi, store, mode_M, pn_Store_M);
1574         set_store(store_mem);
1575 }
1576
1577 static void set_value_for_expression(const expression_t *expression,
1578                                      ir_node *value)
1579 {
1580         dbg_info *dbgi = get_dbg_info(&expression->base.source_position);
1581         value          = do_strict_conv(dbgi, value);
1582
1583         if(expression->kind == EXPR_REFERENCE) {
1584                 const reference_expression_t *ref = &expression->reference;
1585
1586                 declaration_t *declaration = ref->declaration;
1587                 assert(declaration->declaration_kind != DECLARATION_KIND_UNKNOWN);
1588                 if(declaration->declaration_kind == DECLARATION_KIND_LOCAL_VARIABLE) {
1589                         set_value(declaration->v.value_number, value);
1590                         return;
1591                 }
1592         }
1593
1594         if(expression->kind == EXPR_UNARY_BITFIELD_EXTRACT) {
1595                 bitfield_store_to_firm(&expression->unary, value);
1596                 return;
1597         }
1598
1599         ir_node *addr = expression_to_addr(expression);
1600         type_t  *type = skip_typeref(expression->base.type);
1601         assign_value(dbgi, addr, type, value);
1602 }
1603
1604 static ir_node *create_conv(dbg_info *dbgi, ir_node *value, ir_mode *dest_mode)
1605 {
1606         ir_mode *value_mode = get_irn_mode(value);
1607
1608         if (value_mode == dest_mode || is_Bad(value))
1609                 return value;
1610
1611         if(dest_mode == mode_b) {
1612                 ir_node *zero = new_Const(value_mode, get_mode_null(value_mode));
1613                 ir_node *cmp  = new_d_Cmp(dbgi, value, zero);
1614                 ir_node *proj = new_d_Proj(dbgi, cmp, mode_b, pn_Cmp_Lg);
1615                 return proj;
1616         }
1617
1618         return new_d_Conv(dbgi, value, dest_mode);
1619 }
1620
1621 static ir_node *create_incdec(const unary_expression_t *expression)
1622 {
1623         dbg_info     *dbgi  = get_dbg_info(&expression->base.source_position);
1624         type_t       *type  = skip_typeref(expression->base.type);
1625         ir_mode      *mode  = get_ir_mode(type);
1626         expression_t *value = expression->value;
1627
1628         ir_node *value_node = expression_to_firm(value);
1629
1630         ir_node *offset;
1631         if(is_type_pointer(type)) {
1632                 pointer_type_t *pointer_type = &type->pointer;
1633                 offset                       = get_type_size(pointer_type->points_to);
1634         } else {
1635                 assert(is_type_arithmetic(type));
1636                 offset = new_Const(mode, get_mode_one(mode));
1637         }
1638
1639         switch(expression->base.kind) {
1640         case EXPR_UNARY_POSTFIX_INCREMENT: {
1641                 ir_node *new_value = new_d_Add(dbgi, value_node, offset, mode);
1642                 set_value_for_expression(value, new_value);
1643                 return value_node;
1644         }
1645         case EXPR_UNARY_POSTFIX_DECREMENT: {
1646                 ir_node *new_value = new_d_Sub(dbgi, value_node, offset, mode);
1647                 set_value_for_expression(value, new_value);
1648                 return value_node;
1649         }
1650         case EXPR_UNARY_PREFIX_INCREMENT: {
1651                 ir_node *new_value = new_d_Add(dbgi, value_node, offset, mode);
1652                 set_value_for_expression(value, new_value);
1653                 return new_value;
1654         }
1655         case EXPR_UNARY_PREFIX_DECREMENT: {
1656                 ir_node *new_value = new_d_Sub(dbgi, value_node, offset, mode);
1657                 set_value_for_expression(value, new_value);
1658                 return new_value;
1659         }
1660         default:
1661                 panic("no incdec expr in create_incdec");
1662                 return NULL;
1663         }
1664 }
1665
1666 static bool is_local_variable(expression_t *expression)
1667 {
1668         if (expression->kind != EXPR_REFERENCE)
1669                 return false;
1670         reference_expression_t *ref_expr    = &expression->reference;
1671         declaration_t          *declaration = ref_expr->declaration;
1672         return declaration->declaration_kind == DECLARATION_KIND_LOCAL_VARIABLE;
1673 }
1674
1675 static pn_Cmp get_pnc(const expression_kind_t kind, type_t *const type)
1676 {
1677         switch(kind) {
1678         case EXPR_BINARY_EQUAL:         return pn_Cmp_Eq;
1679         case EXPR_BINARY_ISLESSGREATER: return pn_Cmp_Lg;
1680         case EXPR_BINARY_NOTEQUAL:
1681                 return is_type_float(skip_typeref(type)) ? pn_Cmp_Ne : pn_Cmp_Lg;
1682         case EXPR_BINARY_ISLESS:
1683         case EXPR_BINARY_LESS:          return pn_Cmp_Lt;
1684         case EXPR_BINARY_ISLESSEQUAL:
1685         case EXPR_BINARY_LESSEQUAL:     return pn_Cmp_Le;
1686         case EXPR_BINARY_ISGREATER:
1687         case EXPR_BINARY_GREATER:       return pn_Cmp_Gt;
1688         case EXPR_BINARY_ISGREATEREQUAL:
1689         case EXPR_BINARY_GREATEREQUAL:  return pn_Cmp_Ge;
1690         case EXPR_BINARY_ISUNORDERED:   return pn_Cmp_Uo;
1691
1692         default:
1693                 break;
1694         }
1695         panic("trying to get pn_Cmp from non-comparison binexpr type");
1696 }
1697
1698 /**
1699  * Handle the assume optimizer hint: check if a Confirm
1700  * node can be created.
1701  *
1702  * @param dbi    debug info
1703  * @param expr   the IL assume expression
1704  *
1705  * we support here only some simple cases:
1706  *  - var rel const
1707  *  - const rel val
1708  *  - var rel var
1709  */
1710 static ir_node *handle_assume_compare(dbg_info *dbi,
1711                                       const binary_expression_t *expression)
1712 {
1713         expression_t  *op1 = expression->left;
1714         expression_t  *op2 = expression->right;
1715         declaration_t *var2, *var = NULL;
1716         ir_node       *res = NULL;
1717         pn_Cmp         cmp_val;
1718
1719         cmp_val = get_pnc(expression->base.kind, op1->base.type);
1720
1721         if (is_local_variable(op1) && is_local_variable(op2)) {
1722         var  = op1->reference.declaration;
1723             var2 = op2->reference.declaration;
1724
1725                 type_t  *const type = skip_typeref(var->type);
1726                 ir_mode *const mode = get_ir_mode(type);
1727
1728                 ir_node *const irn1 = get_value(var->v.value_number, mode);
1729                 ir_node *const irn2 = get_value(var2->v.value_number, mode);
1730
1731                 res = new_d_Confirm(dbi, irn2, irn1, get_inversed_pnc(cmp_val));
1732                 set_value(var2->v.value_number, res);
1733
1734                 res = new_d_Confirm(dbi, irn1, irn2, cmp_val);
1735                 set_value(var->v.value_number, res);
1736
1737                 return res;
1738         }
1739
1740         expression_t *con;
1741         if (is_local_variable(op1) && is_constant_expression(op2)) {
1742                 var = op1->reference.declaration;
1743                 con = op2;
1744         } else if (is_constant_expression(op1) && is_local_variable(op2)) {
1745                 cmp_val = get_inversed_pnc(cmp_val);
1746                 var = op2->reference.declaration;
1747                 con = op1;
1748         }
1749
1750         if (var != NULL) {
1751                 type_t  *const type = skip_typeref(var->type);
1752                 ir_mode *const mode = get_ir_mode(type);
1753
1754                 res = get_value(var->v.value_number, mode);
1755                 res = new_d_Confirm(dbi, res, expression_to_firm(con), cmp_val);
1756                 set_value(var->v.value_number, res);
1757         }
1758         return res;
1759 }
1760
1761 /**
1762  * Handle the assume optimizer hint.
1763  *
1764  * @param dbi    debug info
1765  * @param expr   the IL assume expression
1766  */
1767 static ir_node *handle_assume(dbg_info *dbi, const expression_t *expression) {
1768         switch(expression->kind) {
1769         case EXPR_BINARY_EQUAL:
1770         case EXPR_BINARY_NOTEQUAL:
1771         case EXPR_BINARY_LESS:
1772         case EXPR_BINARY_LESSEQUAL:
1773         case EXPR_BINARY_GREATER:
1774         case EXPR_BINARY_GREATEREQUAL:
1775                 return handle_assume_compare(dbi, &expression->binary);
1776         default:
1777                 return NULL;
1778         }
1779 }
1780
1781 static ir_node *bitfield_extract_to_firm(const unary_expression_t *expression)
1782 {
1783         expression_t *select = expression->value;
1784         assert(select->kind == EXPR_SELECT);
1785
1786         type_t   *type     = select->base.type;
1787         assert(type->kind == TYPE_BITFIELD);
1788         ir_mode  *mode     = get_ir_mode(type->bitfield.base);
1789         dbg_info *dbgi     = get_dbg_info(&expression->base.source_position);
1790         ir_node  *addr     = expression_to_addr(select);
1791         ir_node  *mem      = get_store();
1792         ir_node  *load     = new_d_Load(dbgi, mem, addr, mode);
1793         ir_node  *load_mem = new_d_Proj(dbgi, load, mode_M, pn_Load_M);
1794         ir_node  *load_res = new_d_Proj(dbgi, load, mode, pn_Load_res);
1795
1796         load_res           = create_conv(dbgi, load_res, mode_int);
1797
1798         set_store(load_mem);
1799
1800         /* kill upper bits */
1801         ir_entity *entity       = select->select.compound_entry->v.entity;
1802         int        bitoffset    = get_entity_offset_bits_remainder(entity);
1803         ir_type   *entity_type  = get_entity_type(entity);
1804         int        bitsize      = get_mode_size_bits(get_type_mode(entity_type));
1805         long       shift_bitsl  = machine_size - bitoffset - bitsize;
1806         assert(shift_bitsl >= 0);
1807         tarval    *tvl          = new_tarval_from_long(shift_bitsl, mode_uint);
1808         ir_node   *countl       = new_d_Const(dbgi, mode_uint, tvl);
1809         ir_node   *shiftl       = new_d_Shl(dbgi, load_res, countl, mode_int);
1810
1811         long       shift_bitsr  = bitoffset + shift_bitsl;
1812         assert(shift_bitsr <= (long) machine_size);
1813         tarval    *tvr          = new_tarval_from_long(shift_bitsr, mode_uint);
1814         ir_node   *countr       = new_d_Const(dbgi, mode_uint, tvr);
1815         ir_node   *shiftr;
1816         if(mode_is_signed(mode)) {
1817                 shiftr = new_d_Shrs(dbgi, shiftl, countr, mode_int);
1818         } else {
1819                 shiftr = new_d_Shr(dbgi, shiftl, countr, mode_int);
1820         }
1821
1822         return create_conv(dbgi, shiftr, mode);
1823 }
1824
1825 static ir_node *unary_expression_to_firm(const unary_expression_t *expression)
1826 {
1827         dbg_info *dbgi = get_dbg_info(&expression->base.source_position);
1828         type_t   *type = skip_typeref(expression->base.type);
1829
1830         if(expression->base.kind == EXPR_UNARY_TAKE_ADDRESS)
1831                 return expression_to_addr(expression->value);
1832
1833         const expression_t *value = expression->value;
1834
1835         switch(expression->base.kind) {
1836         case EXPR_UNARY_NEGATE: {
1837                 ir_node *value_node = expression_to_firm(value);
1838                 ir_mode *mode = get_ir_mode(type);
1839                 return new_d_Minus(dbgi, value_node, mode);
1840         }
1841         case EXPR_UNARY_PLUS:
1842                 return expression_to_firm(value);
1843         case EXPR_UNARY_BITWISE_NEGATE: {
1844                 ir_node *value_node = expression_to_firm(value);
1845                 ir_mode *mode = get_ir_mode(type);
1846                 return new_d_Not(dbgi, value_node, mode);
1847         }
1848         case EXPR_UNARY_NOT: {
1849                 ir_node *value_node = expression_to_firm(value);
1850                 ir_mode *mode = get_ir_mode(type);
1851                 if(get_irn_mode(value_node) != mode_b) {
1852                         value_node = create_conv(dbgi, value_node, mode_b);
1853                 }
1854                 value_node = new_d_Not(dbgi, value_node, mode_b);
1855                 if(mode != mode_b) {
1856                         value_node = create_conv(dbgi, value_node, mode);
1857                 }
1858                 return value_node;
1859         }
1860         case EXPR_UNARY_DEREFERENCE: {
1861                 ir_node *value_node = expression_to_firm(value);
1862                 type_t  *value_type = skip_typeref(value->base.type);
1863                 ir_type *irtype     = get_ir_type(value_type);
1864                 assert(is_Pointer_type(irtype));
1865                 ir_type *points_to  = get_pointer_points_to_type(irtype);
1866                 return deref_address(points_to, value_node, dbgi);
1867         }
1868         case EXPR_UNARY_POSTFIX_INCREMENT:
1869         case EXPR_UNARY_POSTFIX_DECREMENT:
1870         case EXPR_UNARY_PREFIX_INCREMENT:
1871         case EXPR_UNARY_PREFIX_DECREMENT:
1872                 return create_incdec(expression);
1873         case EXPR_UNARY_CAST: {
1874                 ir_node *value_node = expression_to_firm(value);
1875                 if(is_type_scalar(type)) {
1876                         ir_mode *mode = get_ir_mode(type);
1877                         ir_node *node = create_conv(dbgi, value_node, mode);
1878                         node = do_strict_conv(dbgi, node);
1879                         return node;
1880                 } else {
1881                         return value_node;
1882                 }
1883         }
1884         case EXPR_UNARY_CAST_IMPLICIT: {
1885                 ir_node *value_node = expression_to_firm(value);
1886                 if(is_type_scalar(type)) {
1887                         ir_mode *mode = get_ir_mode(type);
1888                         return create_conv(dbgi, value_node, mode);
1889                 } else {
1890                         return value_node;
1891                 }
1892         }
1893         case EXPR_UNARY_ASSUME:
1894                 if(firm_opt.confirm)
1895                         return handle_assume(dbgi, value);
1896                 else
1897                         return NULL;
1898         case EXPR_UNARY_BITFIELD_EXTRACT:
1899                 return bitfield_extract_to_firm(expression);
1900
1901         default:
1902                 break;
1903         }
1904         panic("invalid UNEXPR type found");
1905 }
1906
1907 static ir_node *produce_condition_result(const expression_t *expression,
1908                                          dbg_info *dbgi)
1909 {
1910         ir_mode *mode      = get_ir_mode(expression->base.type);
1911         ir_node *cur_block = get_cur_block();
1912
1913         ir_node *one_block = new_immBlock();
1914         ir_node *one       = new_Const(mode, get_mode_one(mode));
1915         ir_node *jmp_one   = new_d_Jmp(dbgi);
1916
1917         ir_node *zero_block = new_immBlock();
1918         ir_node *zero       = new_Const(mode, get_mode_null(mode));
1919         ir_node *jmp_zero   = new_d_Jmp(dbgi);
1920
1921         set_cur_block(cur_block);
1922         create_condition_evaluation(expression, one_block, zero_block);
1923         mature_immBlock(one_block);
1924         mature_immBlock(zero_block);
1925
1926         ir_node *common_block = new_immBlock();
1927         add_immBlock_pred(common_block, jmp_one);
1928         add_immBlock_pred(common_block, jmp_zero);
1929         mature_immBlock(common_block);
1930
1931         ir_node *in[2] = { one, zero };
1932         ir_node *val   = new_d_Phi(dbgi, 2, in, mode);
1933
1934         return val;
1935 }
1936
1937 static ir_node *create_lazy_op(const binary_expression_t *expression)
1938 {
1939         dbg_info *dbgi = get_dbg_info(&expression->base.source_position);
1940         type_t   *type = expression->base.type;
1941         ir_mode  *mode = get_ir_mode(type);
1942
1943         if(is_constant_expression(expression->left)) {
1944                 long val = fold_constant(expression->left);
1945                 expression_kind_t ekind = expression->base.kind;
1946                 if((ekind == EXPR_BINARY_LOGICAL_AND && val != 0)
1947                                 || (ekind == EXPR_BINARY_LOGICAL_OR && val == 0)) {
1948                         return expression_to_firm(expression->right);
1949                 } else {
1950                         assert((ekind == EXPR_BINARY_LOGICAL_AND && val == 0)
1951                                         || (ekind == EXPR_BINARY_LOGICAL_OR && val != 0));
1952                         return new_Const(mode, get_mode_one(mode));
1953                 }
1954         }
1955
1956         return produce_condition_result((const expression_t*) expression, dbgi);
1957 }
1958
1959 typedef ir_node * (*create_arithmetic_func)(dbg_info *dbgi, ir_node *left,
1960                                             ir_node *right, ir_mode *mode);
1961
1962 static ir_node *create_arithmetic_binop(const binary_expression_t *expression,
1963                                         create_arithmetic_func func)
1964 {
1965         dbg_info *dbgi  = get_dbg_info(&expression->base.source_position);
1966         ir_node  *left  = expression_to_firm(expression->left);
1967         ir_node  *right = expression_to_firm(expression->right);
1968         type_t   *type  = expression->right->base.type;
1969         /* be careful with the modes, because in arithmetic assign nodes only
1970          * the right operand has the mode of the arithmetic already */
1971         ir_mode  *mode  = get_ir_mode(type);
1972         left            = create_conv(dbgi, left, mode);
1973         ir_node  *res   = func(dbgi, left, right, mode);
1974
1975         return res;
1976 }
1977
1978 static ir_node *pointer_arithmetic(ir_node  *const pointer,
1979                                    ir_node  *      integer,
1980                                    type_t   *const type,
1981                                    dbg_info *const dbgi,
1982                                    const create_arithmetic_func func)
1983 {
1984         pointer_type_t *const pointer_type = &type->pointer;
1985         type_t         *const points_to    = pointer_type->points_to;
1986         const unsigned        elem_size    = get_type_size_const(points_to);
1987
1988         assert(elem_size >= 1);
1989         if (elem_size > 1) {
1990                 integer             = create_conv(dbgi, integer, mode_int);
1991                 ir_node *const cnst = new_Const_long(mode_int, (long)elem_size);
1992                 ir_node *const mul  = new_d_Mul(dbgi, integer, cnst, mode_int);
1993                 integer = mul;
1994         }
1995
1996         ir_mode *const mode = get_ir_mode(type);
1997         return func(dbgi, pointer, integer, mode);
1998 }
1999
2000 static ir_node *create_arithmetic_assign_binop(
2001                 const binary_expression_t *expression, create_arithmetic_func func)
2002 {
2003         dbg_info *const dbgi = get_dbg_info(&expression->base.source_position);
2004         type_t   *const type = skip_typeref(expression->base.type);
2005         ir_node  *value;
2006
2007         if (is_type_pointer(type)) {
2008                 ir_node *const pointer = expression_to_firm(expression->left);
2009                 ir_node *      integer = expression_to_firm(expression->right);
2010                 value = pointer_arithmetic(pointer, integer, type, dbgi, func);
2011         } else {
2012                 value = create_arithmetic_binop(expression, func);
2013         }
2014
2015         ir_mode *const mode = get_ir_mode(type);
2016         value = create_conv(dbgi, value, mode);
2017         set_value_for_expression(expression->left, value);
2018
2019         return value;
2020 }
2021
2022 static ir_node *create_add(const binary_expression_t *expression)
2023 {
2024         dbg_info *dbgi  = get_dbg_info(&expression->base.source_position);
2025         ir_node  *left  = expression_to_firm(expression->left);
2026         ir_node  *right = expression_to_firm(expression->right);
2027         type_t   *type  = expression->base.type;
2028
2029         expression_t *expr_left  = expression->left;
2030         expression_t *expr_right = expression->right;
2031         type_t       *type_left  = skip_typeref(expr_left->base.type);
2032         type_t       *type_right = skip_typeref(expr_right->base.type);
2033
2034         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
2035                 ir_mode *const mode = get_ir_mode(type);
2036                 return new_d_Add(dbgi, left, right, mode);
2037         }
2038
2039         if (is_type_pointer(type_left)) {
2040                 return pointer_arithmetic(left, right, type, dbgi, new_d_Add);
2041         } else {
2042                 assert(is_type_pointer(type_right));
2043                 return pointer_arithmetic(right, left, type, dbgi, new_d_Add);
2044         }
2045 }
2046
2047 static ir_node *create_sub(const binary_expression_t *expression)
2048 {
2049         dbg_info *const dbgi  = get_dbg_info(&expression->base.source_position);
2050         expression_t *const expr_left  = expression->left;
2051         expression_t *const expr_right = expression->right;
2052         ir_node      *const left       = expression_to_firm(expr_left);
2053         ir_node      *const right      = expression_to_firm(expr_right);
2054         type_t       *const type       = expression->base.type;
2055         type_t       *const type_left  = skip_typeref(expr_left->base.type);
2056         type_t       *const type_right = skip_typeref(expr_right->base.type);
2057
2058         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
2059                 ir_mode *const mode = get_ir_mode(type);
2060                 return new_d_Sub(dbgi, left, right, mode);
2061         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
2062                 const pointer_type_t *const ptr_type = &type_left->pointer;
2063
2064                 ir_node *const elem_size = get_type_size(ptr_type->points_to);
2065                 ir_mode *const mode      = get_ir_mode(type);
2066                 ir_node *const sub       = new_d_Sub(dbgi, left, right, mode);
2067                 ir_node *const no_mem    = new_NoMem();
2068                 ir_node *const div       = new_d_Div(dbgi, no_mem, sub, elem_size, mode,
2069                                                      op_pin_state_floats);
2070                 return new_d_Proj(dbgi, div, mode, pn_Div_res);
2071         }
2072
2073         assert(is_type_pointer(type_left));
2074         return pointer_arithmetic(left, right, type_left, dbgi, new_d_Sub);
2075 }
2076
2077 static ir_node *create_shift(const binary_expression_t *expression)
2078 {
2079         dbg_info *dbgi  = get_dbg_info(&expression->base.source_position);
2080         ir_node  *left  = expression_to_firm(expression->left);
2081         ir_node  *right = expression_to_firm(expression->right);
2082         type_t   *type  = expression->base.type;
2083         ir_mode  *mode  = get_ir_mode(type);
2084
2085         /* firm always wants the shift count to be unsigned */
2086         right = create_conv(dbgi, right, mode_uint);
2087
2088         ir_node *res;
2089
2090         switch(expression->base.kind) {
2091         case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2092         case EXPR_BINARY_SHIFTLEFT:
2093                 res = new_d_Shl(dbgi, left, right, mode);
2094                 break;
2095         case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2096         case EXPR_BINARY_SHIFTRIGHT: {
2097                  expression_t *expr_left = expression->left;
2098                  type_t       *type_left = skip_typeref(expr_left->base.type);
2099
2100                  if(is_type_signed(type_left)) {
2101                         res = new_d_Shrs(dbgi, left, right, mode);
2102                  } else {
2103                          res = new_d_Shr(dbgi, left, right, mode);
2104                  }
2105                  break;
2106         }
2107         default:
2108                 panic("create shift op called for non-shift op");
2109         }
2110
2111         return res;
2112 }
2113
2114
2115 static ir_node *create_divmod(const binary_expression_t *expression)
2116 {
2117         dbg_info *dbgi  = get_dbg_info(&expression->base.source_position);
2118         ir_node  *left  = expression_to_firm(expression->left);
2119         ir_node  *right = expression_to_firm(expression->right);
2120         ir_node  *pin   = new_Pin(new_NoMem());
2121         /* be careful with the modes, because in arithmetic assign nodes only
2122          * the right operand has the mode of the arithmetic already */
2123         type_t   *type  = expression->right->base.type;
2124         ir_mode  *mode  = get_ir_mode(type);
2125         left            = create_conv(dbgi, left, mode);
2126         ir_node  *op;
2127         ir_node  *res;
2128
2129         switch (expression->base.kind) {
2130         case EXPR_BINARY_DIV:
2131         case EXPR_BINARY_DIV_ASSIGN:
2132                 if(mode_is_float(mode)) {
2133                         op  = new_d_Quot(dbgi, pin, left, right, mode, op_pin_state_floats);
2134                         res = new_d_Proj(dbgi, op, mode, pn_Quot_res);
2135                 } else {
2136                         op  = new_d_Div(dbgi, pin, left, right, mode, op_pin_state_floats);
2137                         res = new_d_Proj(dbgi, op, mode, pn_Div_res);
2138                 }
2139                 break;
2140
2141         case EXPR_BINARY_MOD:
2142         case EXPR_BINARY_MOD_ASSIGN:
2143                 assert(!mode_is_float(mode));
2144                 op  = new_d_Mod(dbgi, pin, left, right, mode, op_pin_state_floats);
2145                 res = new_d_Proj(dbgi, op, mode, pn_Mod_res);
2146                 break;
2147
2148         default: panic("unexpected binary expression type in create_divmod()");
2149         }
2150
2151         return res;
2152 }
2153
2154 static ir_node *create_arithmetic_assign_divmod(
2155                 const binary_expression_t *expression)
2156 {
2157         ir_node  *      value = create_divmod(expression);
2158         dbg_info *const dbgi  = get_dbg_info(&expression->base.source_position);
2159         type_t   *const type  = expression->base.type;
2160         ir_mode  *const mode  = get_ir_mode(type);
2161
2162         assert(type->kind != TYPE_POINTER);
2163
2164         value = create_conv(dbgi, value, mode);
2165         set_value_for_expression(expression->left, value);
2166
2167         return value;
2168 }
2169
2170 static ir_node *create_arithmetic_assign_shift(
2171                 const binary_expression_t *expression)
2172 {
2173         ir_node  *      value = create_shift(expression);
2174         dbg_info *const dbgi  = get_dbg_info(&expression->base.source_position);
2175         type_t   *const type  = expression->base.type;
2176         ir_mode  *const mode  = get_ir_mode(type);
2177
2178         value = create_conv(dbgi, value, mode);
2179         set_value_for_expression(expression->left, value);
2180
2181         return value;
2182 }
2183
2184 static ir_node *binary_expression_to_firm(const binary_expression_t *expression)
2185 {
2186         expression_kind_t kind = expression->base.kind;
2187
2188         switch(kind) {
2189         case EXPR_BINARY_EQUAL:
2190         case EXPR_BINARY_NOTEQUAL:
2191         case EXPR_BINARY_LESS:
2192         case EXPR_BINARY_LESSEQUAL:
2193         case EXPR_BINARY_GREATER:
2194         case EXPR_BINARY_GREATEREQUAL:
2195         case EXPR_BINARY_ISGREATER:
2196         case EXPR_BINARY_ISGREATEREQUAL:
2197         case EXPR_BINARY_ISLESS:
2198         case EXPR_BINARY_ISLESSEQUAL:
2199         case EXPR_BINARY_ISLESSGREATER:
2200         case EXPR_BINARY_ISUNORDERED: {
2201                 dbg_info *dbgi = get_dbg_info(&expression->base.source_position);
2202                 ir_node *left  = expression_to_firm(expression->left);
2203                 ir_node *right = expression_to_firm(expression->right);
2204                 ir_node *cmp   = new_d_Cmp(dbgi, left, right);
2205                 long     pnc   = get_pnc(kind, expression->left->base.type);
2206                 ir_node *proj  = new_d_Proj(dbgi, cmp, mode_b, pnc);
2207                 return proj;
2208         }
2209         case EXPR_BINARY_ASSIGN: {
2210                 ir_node *right = expression_to_firm(expression->right);
2211                 set_value_for_expression(expression->left, right);
2212
2213                 return right;
2214         }
2215         case EXPR_BINARY_ADD:
2216                 return create_add(expression);
2217         case EXPR_BINARY_SUB:
2218                 return create_sub(expression);
2219         case EXPR_BINARY_MUL:
2220                 return create_arithmetic_binop(expression, new_d_Mul);
2221         case EXPR_BINARY_BITWISE_AND:
2222                 return create_arithmetic_binop(expression, new_d_And);
2223         case EXPR_BINARY_BITWISE_OR:
2224                 return create_arithmetic_binop(expression, new_d_Or);
2225         case EXPR_BINARY_BITWISE_XOR:
2226                 return create_arithmetic_binop(expression, new_d_Eor);
2227         case EXPR_BINARY_SHIFTLEFT:
2228         case EXPR_BINARY_SHIFTRIGHT:
2229                 return create_shift(expression);
2230         case EXPR_BINARY_DIV:
2231         case EXPR_BINARY_MOD:
2232                 return create_divmod(expression);
2233         case EXPR_BINARY_LOGICAL_AND:
2234         case EXPR_BINARY_LOGICAL_OR:
2235                 return create_lazy_op(expression);
2236         case EXPR_BINARY_COMMA:
2237                 expression_to_firm(expression->left);
2238                 return expression_to_firm(expression->right);
2239         case EXPR_BINARY_ADD_ASSIGN:
2240                 return create_arithmetic_assign_binop(expression, new_d_Add);
2241         case EXPR_BINARY_SUB_ASSIGN:
2242                 return create_arithmetic_assign_binop(expression, new_d_Sub);
2243         case EXPR_BINARY_MUL_ASSIGN:
2244                 return create_arithmetic_assign_binop(expression, new_d_Mul);
2245         case EXPR_BINARY_MOD_ASSIGN:
2246         case EXPR_BINARY_DIV_ASSIGN:
2247                 return create_arithmetic_assign_divmod(expression);
2248         case EXPR_BINARY_BITWISE_AND_ASSIGN:
2249                 return create_arithmetic_assign_binop(expression, new_d_And);
2250         case EXPR_BINARY_BITWISE_OR_ASSIGN:
2251                 return create_arithmetic_assign_binop(expression, new_d_Or);
2252         case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2253                 return create_arithmetic_assign_binop(expression, new_d_Eor);
2254         case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2255         case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2256                 return create_arithmetic_assign_shift(expression);
2257         case EXPR_BINARY_BUILTIN_EXPECT:
2258                 return expression_to_firm(expression->left);
2259         default:
2260                 panic("TODO binexpr type");
2261         }
2262 }
2263
2264 static ir_node *array_access_addr(const array_access_expression_t *expression)
2265 {
2266         dbg_info *dbgi      = get_dbg_info(&expression->base.source_position);
2267         ir_node  *base_addr = expression_to_firm(expression->array_ref);
2268         ir_node  *offset    = expression_to_firm(expression->index);
2269         offset              = create_conv(dbgi, offset, mode_uint);
2270
2271         type_t *ref_type = skip_typeref(expression->array_ref->base.type);
2272         assert(is_type_pointer(ref_type));
2273         pointer_type_t *pointer_type = &ref_type->pointer;
2274
2275         ir_node *elem_size_const = get_type_size(pointer_type->points_to);
2276         ir_node *real_offset     = new_d_Mul(dbgi, offset, elem_size_const,
2277                                              mode_uint);
2278         ir_node *result          = new_d_Add(dbgi, base_addr, real_offset, mode_P_data);
2279
2280         return result;
2281 }
2282
2283 static ir_node *array_access_to_firm(
2284                 const array_access_expression_t *expression)
2285 {
2286         dbg_info *dbgi   = get_dbg_info(&expression->base.source_position);
2287         ir_node  *addr   = array_access_addr(expression);
2288         type_t   *type   = revert_automatic_type_conversion(
2289                         (const expression_t*) expression);
2290         type             = skip_typeref(type);
2291         ir_type  *irtype = get_ir_type(type);
2292
2293         return deref_address(irtype, addr, dbgi);
2294 }
2295
2296 static long get_offsetof_offset(const offsetof_expression_t *expression)
2297 {
2298         type_t *orig_type = expression->type;
2299         long    offset    = 0;
2300
2301         designator_t *designator = expression->designator;
2302         for( ; designator != NULL; designator = designator->next) {
2303                 type_t *type = skip_typeref(orig_type);
2304                 /* be sure the type is constructed */
2305                 (void) get_ir_type(type);
2306
2307                 if(designator->symbol != NULL) {
2308                         assert(is_type_compound(type));
2309                         symbol_t *symbol = designator->symbol;
2310
2311                         declaration_t *declaration = type->compound.declaration;
2312                         declaration_t *iter        = declaration->scope.declarations;
2313                         for( ; iter != NULL; iter = iter->next) {
2314                                 if(iter->symbol == symbol) {
2315                                         break;
2316                                 }
2317                         }
2318                         assert(iter != NULL);
2319
2320                         assert(iter->declaration_kind == DECLARATION_KIND_COMPOUND_MEMBER);
2321                         offset += get_entity_offset(iter->v.entity);
2322
2323                         orig_type = iter->type;
2324                 } else {
2325                         expression_t *array_index = designator->array_index;
2326                         assert(designator->array_index != NULL);
2327                         assert(is_type_array(type));
2328                         assert(is_type_valid(array_index->base.type));
2329
2330                         long index         = fold_constant(array_index);
2331                         ir_type *arr_type  = get_ir_type(type);
2332                         ir_type *elem_type = get_array_element_type(arr_type);
2333                         long     elem_size = get_type_size_bytes(elem_type);
2334
2335                         offset += index * elem_size;
2336
2337                         orig_type = type->array.element_type;
2338                 }
2339         }
2340
2341         return offset;
2342 }
2343
2344 static ir_node *offsetof_to_firm(const offsetof_expression_t *expression)
2345 {
2346         ir_mode  *mode   = get_ir_mode(expression->base.type);
2347         long      offset = get_offsetof_offset(expression);
2348         tarval   *tv     = new_tarval_from_long(offset, mode);
2349         dbg_info *dbgi   = get_dbg_info(&expression->base.source_position);
2350
2351         return new_d_Const(dbgi, mode, tv);
2352 }
2353
2354 static void create_local_initializer(initializer_t *initializer, dbg_info *dbgi,
2355                                      ir_entity *entity, type_t *type);
2356
2357 static ir_node *compound_literal_to_firm(
2358                 const compound_literal_expression_t *expression)
2359 {
2360         type_t *type = expression->type;
2361
2362         /* create an entity on the stack */
2363         ir_type *frame_type = get_irg_frame_type(current_ir_graph);
2364
2365         ident     *const id     = unique_ident("CompLit");
2366         ir_type   *const irtype = get_ir_type(type);
2367         dbg_info  *const dbgi   = get_dbg_info(&expression->base.source_position);
2368         ir_entity *const entity = new_d_entity(frame_type, id, irtype, dbgi);
2369         set_entity_ld_ident(entity, id);
2370
2371         set_entity_variability(entity, variability_uninitialized);
2372
2373         /* create initialisation code */
2374         initializer_t *initializer = expression->initializer;
2375         create_local_initializer(initializer, dbgi, entity, type);
2376
2377         /* create a sel for the compound literal address */
2378         ir_node *frame = get_local_frame(entity);
2379         ir_node *sel   = new_d_simpleSel(dbgi, new_NoMem(), frame, entity);
2380         return sel;
2381 }
2382
2383 /**
2384  * Transform a sizeof expression into Firm code.
2385  */
2386 static ir_node *sizeof_to_firm(const typeprop_expression_t *expression)
2387 {
2388         type_t *type = expression->type;
2389         if(type == NULL) {
2390                 type = expression->tp_expression->base.type;
2391                 assert(type != NULL);
2392         }
2393
2394         type = skip_typeref(type);
2395         /* ยง 6.5.3.4 (2) if the type is a VLA, evaluate the expression. */
2396         if(is_type_array(type) && type->array.is_vla
2397                         && expression->tp_expression != NULL) {
2398                 expression_to_firm(expression->tp_expression);
2399         }
2400
2401         return get_type_size(type);
2402 }
2403
2404 /**
2405  * Transform an alignof expression into Firm code.
2406  */
2407 static ir_node *alignof_to_firm(const typeprop_expression_t *expression)
2408 {
2409         type_t *type = expression->type;
2410         if(type == NULL) {
2411                 /* beware: if expression is a variable reference, return the
2412                    alignment of the variable. */
2413                 const expression_t *tp_expression = expression->tp_expression;
2414                 const declaration_t *declaration = expr_is_variable(tp_expression);
2415                 if (declaration != NULL) {
2416                         /* TODO: get the alignment of this variable. */
2417                 }
2418                 type = tp_expression->base.type;
2419                 assert(type != NULL);
2420         }
2421
2422         ir_mode *const mode = get_ir_mode(expression->base.type);
2423         symconst_symbol sym;
2424         sym.type_p = get_ir_type(type);
2425         return new_SymConst(mode, sym, symconst_type_align);
2426 }
2427
2428 static void init_ir_types(void);
2429 long fold_constant(const expression_t *expression)
2430 {
2431         init_ir_types();
2432
2433         assert(is_constant_expression(expression));
2434
2435         ir_graph *old_current_ir_graph = current_ir_graph;
2436         if(current_ir_graph == NULL) {
2437                 current_ir_graph = get_const_code_irg();
2438         }
2439
2440         ir_node *cnst = expression_to_firm(expression);
2441         current_ir_graph = old_current_ir_graph;
2442
2443         if(!is_Const(cnst)) {
2444                 panic("couldn't fold constant\n");
2445         }
2446
2447         tarval *tv = get_Const_tarval(cnst);
2448         if(!tarval_is_long(tv)) {
2449                 panic("result of constant folding is not integer\n");
2450         }
2451
2452         return get_tarval_long(tv);
2453 }
2454
2455 static ir_node *conditional_to_firm(const conditional_expression_t *expression)
2456 {
2457         dbg_info *const dbgi = get_dbg_info(&expression->base.source_position);
2458
2459         /* first try to fold a constant condition */
2460         if(is_constant_expression(expression->condition)) {
2461                 long val = fold_constant(expression->condition);
2462                 if(val) {
2463                         return expression_to_firm(expression->true_expression);
2464                 } else {
2465                         return expression_to_firm(expression->false_expression);
2466                 }
2467         }
2468
2469         ir_node *cur_block   = get_cur_block();
2470
2471         /* create the true block */
2472         ir_node *true_block  = new_immBlock();
2473
2474         ir_node *true_val = expression_to_firm(expression->true_expression);
2475         ir_node *true_jmp = new_Jmp();
2476
2477         /* create the false block */
2478         ir_node *false_block = new_immBlock();
2479
2480         ir_node *false_val = expression_to_firm(expression->false_expression);
2481         ir_node *false_jmp = new_Jmp();
2482
2483         /* create the condition evaluation */
2484         set_cur_block(cur_block);
2485         create_condition_evaluation(expression->condition, true_block, false_block);
2486         mature_immBlock(true_block);
2487         mature_immBlock(false_block);
2488
2489         /* create the common block */
2490         ir_node *common_block = new_immBlock();
2491         add_immBlock_pred(common_block, true_jmp);
2492         add_immBlock_pred(common_block, false_jmp);
2493         mature_immBlock(common_block);
2494
2495         /* TODO improve static semantics, so either both or no values are NULL */
2496         if (true_val == NULL || false_val == NULL)
2497                 return NULL;
2498
2499         ir_node *in[2] = { true_val, false_val };
2500         ir_mode *mode  = get_irn_mode(true_val);
2501         assert(get_irn_mode(false_val) == mode);
2502         ir_node *val   = new_d_Phi(dbgi, 2, in, mode);
2503
2504         return val;
2505 }
2506
2507 static ir_node *select_addr(const select_expression_t *expression)
2508 {
2509         dbg_info *dbgi = get_dbg_info(&expression->base.source_position);
2510
2511         ir_node *compound_addr = expression_to_firm(expression->compound);
2512
2513         declaration_t *entry = expression->compound_entry;
2514         assert(entry->declaration_kind == DECLARATION_KIND_COMPOUND_MEMBER);
2515         ir_entity     *entity = entry->v.entity;
2516
2517         assert(entity != NULL);
2518
2519         ir_node *sel = new_d_simpleSel(dbgi, new_NoMem(), compound_addr, entity);
2520
2521         return sel;
2522 }
2523
2524 static ir_node *select_to_firm(const select_expression_t *expression)
2525 {
2526         dbg_info *dbgi   = get_dbg_info(&expression->base.source_position);
2527         ir_node  *addr   = select_addr(expression);
2528         type_t   *type   = revert_automatic_type_conversion(
2529                         (const expression_t*) expression);
2530         type             = skip_typeref(type);
2531         ir_type  *irtype = get_ir_type(type);
2532
2533         return deref_address(irtype, addr, dbgi);
2534 }
2535
2536 /* Values returned by __builtin_classify_type. */
2537 typedef enum gcc_type_class
2538 {
2539         no_type_class = -1,
2540         void_type_class,
2541         integer_type_class,
2542         char_type_class,
2543         enumeral_type_class,
2544         boolean_type_class,
2545         pointer_type_class,
2546         reference_type_class,
2547         offset_type_class,
2548         real_type_class,
2549         complex_type_class,
2550         function_type_class,
2551         method_type_class,
2552         record_type_class,
2553         union_type_class,
2554         array_type_class,
2555         string_type_class,
2556         set_type_class,
2557         file_type_class,
2558         lang_type_class
2559 } gcc_type_class;
2560
2561 static ir_node *classify_type_to_firm(const classify_type_expression_t *const expr)
2562 {
2563         const type_t *const type = expr->type_expression->base.type;
2564
2565         gcc_type_class tc;
2566         switch (type->kind)
2567         {
2568                 case TYPE_ATOMIC: {
2569                         const atomic_type_t *const atomic_type = &type->atomic;
2570                         switch (atomic_type->akind) {
2571                                 /* should not be reached */
2572                                 case ATOMIC_TYPE_INVALID:
2573                                         tc = no_type_class;
2574                                         break;
2575
2576                                 /* gcc cannot do that */
2577                                 case ATOMIC_TYPE_VOID:
2578                                         tc = void_type_class;
2579                                         break;
2580
2581                                 case ATOMIC_TYPE_CHAR:      /* gcc handles this as integer */
2582                                 case ATOMIC_TYPE_SCHAR:     /* gcc handles this as integer */
2583                                 case ATOMIC_TYPE_UCHAR:     /* gcc handles this as integer */
2584                                 case ATOMIC_TYPE_SHORT:
2585                                 case ATOMIC_TYPE_USHORT:
2586                                 case ATOMIC_TYPE_INT:
2587                                 case ATOMIC_TYPE_UINT:
2588                                 case ATOMIC_TYPE_LONG:
2589                                 case ATOMIC_TYPE_ULONG:
2590                                 case ATOMIC_TYPE_LONGLONG:
2591                                 case ATOMIC_TYPE_ULONGLONG:
2592                                 case ATOMIC_TYPE_BOOL:      /* gcc handles this as integer */
2593                                         tc = integer_type_class;
2594                                         break;
2595
2596                                 case ATOMIC_TYPE_FLOAT:
2597                                 case ATOMIC_TYPE_DOUBLE:
2598                                 case ATOMIC_TYPE_LONG_DOUBLE:
2599                                         tc = real_type_class;
2600                                         break;
2601
2602 #ifdef PROVIDE_COMPLEX
2603                                 case ATOMIC_TYPE_FLOAT_COMPLEX:
2604                                 case ATOMIC_TYPE_DOUBLE_COMPLEX:
2605                                 case ATOMIC_TYPE_LONG_DOUBLE_COMPLEX:
2606                                         tc = complex_type_class;
2607                                         break;
2608                                 case ATOMIC_TYPE_FLOAT_IMAGINARY:
2609                                 case ATOMIC_TYPE_DOUBLE_IMAGINARY:
2610                                 case ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY:
2611                                         tc = complex_type_class;
2612                                         break;
2613 #endif
2614
2615                                 default:
2616                                         panic("Unimplemented case in classify_type_to_firm().");
2617                         }
2618                         break;
2619                 }
2620
2621                 case TYPE_ARRAY:           /* gcc handles this as pointer */
2622                 case TYPE_FUNCTION:        /* gcc handles this as pointer */
2623                 case TYPE_POINTER:         tc = pointer_type_class; break;
2624                 case TYPE_COMPOUND_STRUCT: tc = record_type_class;  break;
2625                 case TYPE_COMPOUND_UNION:  tc = union_type_class;   break;
2626
2627                 /* gcc handles this as integer */
2628                 case TYPE_ENUM:            tc = integer_type_class; break;
2629
2630                 default:
2631                         panic("Unimplemented case in classify_type_to_firm().");
2632         }
2633
2634         dbg_info *const dbgi = get_dbg_info(&expr->base.source_position);
2635         ir_mode  *const mode = mode_int;
2636         tarval   *const tv   = new_tarval_from_long(tc, mode);
2637         return new_d_Const(dbgi, mode, tv);
2638 }
2639
2640 static ir_node *function_name_to_firm(
2641                 const string_literal_expression_t *const expr)
2642 {
2643         if (current_function_name == NULL) {
2644                 const source_position_t *const src_pos = &expr->base.source_position;
2645                 const char *const name = current_function_decl->symbol->string;
2646                 const string_t string = { name, strlen(name) + 1 };
2647                 current_function_name = string_to_firm(src_pos, "__func__", &string);
2648         }
2649
2650         return current_function_name;
2651 }
2652
2653 static ir_node *statement_expression_to_firm(const statement_expression_t *expr)
2654 {
2655         statement_t *statement = expr->statement;
2656
2657         assert(statement->kind == STATEMENT_COMPOUND);
2658         return compound_statement_to_firm(&statement->compound);
2659 }
2660
2661 static ir_node *va_start_expression_to_firm(
2662         const va_start_expression_t *const expr)
2663 {
2664         ir_type   *const method_type = get_ir_type(current_function_decl->type);
2665         int        const n           = get_method_n_params(method_type) - 1;
2666         ir_entity *const parm_ent    = get_method_value_param_ent(method_type, n);
2667         ir_node   *const arg_base    = get_irg_value_param_base(current_ir_graph);
2668         dbg_info  *const dbgi        = get_dbg_info(&expr->base.source_position);
2669         ir_node   *const no_mem      = new_NoMem();
2670         ir_node   *const arg_sel     =
2671                 new_d_simpleSel(dbgi, no_mem, arg_base, parm_ent);
2672
2673         ir_node   *const cnst        = get_type_size(expr->parameter->type);
2674         ir_node   *const add         = new_d_Add(dbgi, arg_sel, cnst, mode_P_data);
2675         set_value_for_expression(expr->ap, add);
2676
2677         return NULL;
2678 }
2679
2680 static ir_node *va_arg_expression_to_firm(const va_arg_expression_t *const expr)
2681 {
2682         ir_type  *const irtype = get_ir_type(expr->base.type);
2683         ir_node  *const ap     = expression_to_firm(expr->ap);
2684         dbg_info *const dbgi   = get_dbg_info(&expr->base.source_position);
2685         ir_node  *const res    = deref_address(irtype, ap, dbgi);
2686
2687         ir_node  *const cnst      = get_type_size(expr->base.type);
2688         ir_node  *const add       = new_d_Add(dbgi, ap, cnst, mode_P_data);
2689         set_value_for_expression(expr->ap, add);
2690
2691         return res;
2692 }
2693
2694 static ir_node *dereference_addr(const unary_expression_t *const expression)
2695 {
2696         assert(expression->base.kind == EXPR_UNARY_DEREFERENCE);
2697         return expression_to_firm(expression->value);
2698 }
2699
2700 static ir_node *expression_to_addr(const expression_t *expression)
2701 {
2702         switch(expression->kind) {
2703         case EXPR_REFERENCE:
2704                 return reference_addr(&expression->reference);
2705         case EXPR_ARRAY_ACCESS:
2706                 return array_access_addr(&expression->array_access);
2707         case EXPR_SELECT:
2708                 return select_addr(&expression->select);
2709         case EXPR_CALL:
2710                 return call_expression_to_firm(&expression->call);
2711         case EXPR_UNARY_DEREFERENCE: {
2712                 return dereference_addr(&expression->unary);
2713         }
2714         default:
2715                 break;
2716         }
2717         panic("trying to get address of non-lvalue");
2718 }
2719
2720 static ir_node *builtin_constant_to_firm(
2721                 const builtin_constant_expression_t *expression)
2722 {
2723         ir_mode *mode = get_ir_mode(expression->base.type);
2724         long     v;
2725
2726         if (is_constant_expression(expression->value)) {
2727                 v = 1;
2728         } else {
2729                 v = 0;
2730         }
2731         return new_Const_long(mode, v);
2732 }
2733
2734 static ir_node *builtin_prefetch_to_firm(
2735                 const builtin_prefetch_expression_t *expression)
2736 {
2737         ir_node *adr = expression_to_firm(expression->adr);
2738         /* no Firm support for prefetch yet */
2739         (void) adr;
2740         return NULL;
2741 }
2742
2743 static ir_node *_expression_to_firm(const expression_t *expression)
2744 {
2745         switch(expression->kind) {
2746         case EXPR_CHAR_CONST:
2747                 return char_const_to_firm(&expression->conste);
2748         case EXPR_CONST:
2749                 return const_to_firm(&expression->conste);
2750         case EXPR_STRING_LITERAL:
2751                 return string_literal_to_firm(&expression->string);
2752         case EXPR_WIDE_STRING_LITERAL:
2753                 return wide_string_literal_to_firm(&expression->wide_string);
2754         case EXPR_REFERENCE:
2755                 return reference_expression_to_firm(&expression->reference);
2756         case EXPR_CALL:
2757                 return call_expression_to_firm(&expression->call);
2758         EXPR_UNARY_CASES
2759                 return unary_expression_to_firm(&expression->unary);
2760         EXPR_BINARY_CASES
2761                 return binary_expression_to_firm(&expression->binary);
2762         case EXPR_ARRAY_ACCESS:
2763                 return array_access_to_firm(&expression->array_access);
2764         case EXPR_SIZEOF:
2765                 return sizeof_to_firm(&expression->typeprop);
2766         case EXPR_ALIGNOF:
2767                 return alignof_to_firm(&expression->typeprop);
2768         case EXPR_CONDITIONAL:
2769                 return conditional_to_firm(&expression->conditional);
2770         case EXPR_SELECT:
2771                 return select_to_firm(&expression->select);
2772         case EXPR_CLASSIFY_TYPE:
2773                 return classify_type_to_firm(&expression->classify_type);
2774         case EXPR_FUNCTION:
2775         case EXPR_PRETTY_FUNCTION:
2776                 return function_name_to_firm(&expression->string);
2777         case EXPR_STATEMENT:
2778                 return statement_expression_to_firm(&expression->statement);
2779         case EXPR_VA_START:
2780                 return va_start_expression_to_firm(&expression->va_starte);
2781         case EXPR_VA_ARG:
2782                 return va_arg_expression_to_firm(&expression->va_arge);
2783         case EXPR_BUILTIN_SYMBOL:
2784                 panic("unimplemented expression found");
2785         case EXPR_BUILTIN_CONSTANT_P:
2786                 return builtin_constant_to_firm(&expression->builtin_constant);
2787         case EXPR_BUILTIN_PREFETCH:
2788                 return builtin_prefetch_to_firm(&expression->builtin_prefetch);
2789         case EXPR_OFFSETOF:
2790                 return offsetof_to_firm(&expression->offsetofe);
2791         case EXPR_COMPOUND_LITERAL:
2792                 return compound_literal_to_firm(&expression->compound_literal);
2793
2794         case EXPR_UNKNOWN:
2795         case EXPR_INVALID:
2796                 break;
2797         }
2798         panic("invalid expression found");
2799 }
2800
2801 static ir_node *expression_to_firm(const expression_t *expression)
2802 {
2803         ir_node *res = _expression_to_firm(expression);
2804
2805         if(res != NULL && get_irn_mode(res) == mode_b) {
2806                 ir_mode *mode = get_ir_mode(expression->base.type);
2807                 if(is_Const(res)) {
2808                         if(is_Const_null(res)) {
2809                                 return new_Const_long(mode, 0);
2810                         } else {
2811                                 assert(is_Const_one(res));
2812                                 return new_Const_long(mode, 1);
2813                         }
2814                 }
2815
2816                 dbg_info *dbgi        = get_dbg_info(&expression->base.source_position);
2817                 return produce_condition_result(expression, dbgi);
2818         }
2819
2820         return res;
2821 }
2822
2823 static ir_node *expression_to_modeb(const expression_t *expression)
2824 {
2825         ir_node *res = _expression_to_firm(expression);
2826         res          = create_conv(NULL, res, mode_b);
2827
2828         return res;
2829 }
2830
2831 /**
2832  * create a short-circuit expression evaluation that tries to construct
2833  * efficient control flow structures for &&, || and ! expressions
2834  */
2835 static void create_condition_evaluation(const expression_t *expression,
2836                                         ir_node *true_block,
2837                                         ir_node *false_block)
2838 {
2839         switch(expression->kind) {
2840         case EXPR_UNARY_NOT: {
2841                 const unary_expression_t *unary_expression = &expression->unary;
2842                 create_condition_evaluation(unary_expression->value, false_block,
2843                                             true_block);
2844                 return;
2845         }
2846         case EXPR_BINARY_LOGICAL_AND: {
2847                 const binary_expression_t *binary_expression = &expression->binary;
2848
2849                 ir_node *cur_block   = get_cur_block();
2850                 ir_node *extra_block = new_immBlock();
2851                 set_cur_block(cur_block);
2852                 create_condition_evaluation(binary_expression->left, extra_block,
2853                                             false_block);
2854                 mature_immBlock(extra_block);
2855                 set_cur_block(extra_block);
2856                 create_condition_evaluation(binary_expression->right, true_block,
2857                                             false_block);
2858                 return;
2859         }
2860         case EXPR_BINARY_LOGICAL_OR: {
2861                 const binary_expression_t *binary_expression = &expression->binary;
2862
2863                 ir_node *cur_block   = get_cur_block();
2864                 ir_node *extra_block = new_immBlock();
2865                 set_cur_block(cur_block);
2866                 create_condition_evaluation(binary_expression->left, true_block,
2867                                             extra_block);
2868                 mature_immBlock(extra_block);
2869                 set_cur_block(extra_block);
2870                 create_condition_evaluation(binary_expression->right, true_block,
2871                                             false_block);
2872                 return;
2873         }
2874         default:
2875                 break;
2876         }
2877
2878         dbg_info *dbgi       = get_dbg_info(&expression->base.source_position);
2879         ir_node  *condition  = expression_to_modeb(expression);
2880         ir_node  *cond       = new_d_Cond(dbgi, condition);
2881         ir_node  *true_proj  = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true);
2882         ir_node  *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false);
2883
2884         /* set branch prediction info based on __builtin_expect */
2885         if(expression->kind == EXPR_BINARY_BUILTIN_EXPECT) {
2886                 long               cnst = fold_constant(expression->binary.right);
2887                 cond_jmp_predicate pred;
2888
2889                 if(cnst == 0) {
2890                         pred = COND_JMP_PRED_FALSE;
2891                 } else {
2892                         pred = COND_JMP_PRED_TRUE;
2893                 }
2894                 set_Cond_jmp_pred(cond, pred);
2895         }
2896
2897         add_immBlock_pred(true_block, true_proj);
2898         add_immBlock_pred(false_block, false_proj);
2899
2900         set_cur_block(NULL);
2901 }
2902
2903
2904
2905 static void create_declaration_entity(declaration_t *declaration,
2906                                       declaration_kind_t declaration_kind,
2907                                       ir_type *parent_type)
2908 {
2909         ident     *const id     = new_id_from_str(declaration->symbol->string);
2910         ir_type   *const irtype = get_ir_type(declaration->type);
2911         dbg_info  *const dbgi   = get_dbg_info(&declaration->source_position);
2912         ir_entity *const entity = new_d_entity(parent_type, id, irtype, dbgi);
2913         set_entity_ld_ident(entity, id);
2914
2915         declaration->declaration_kind = (unsigned char) declaration_kind;
2916         declaration->v.entity         = entity;
2917         set_entity_variability(entity, variability_uninitialized);
2918         if(parent_type == get_tls_type())
2919                 set_entity_allocation(entity, allocation_automatic);
2920         else if(declaration_kind == DECLARATION_KIND_GLOBAL_VARIABLE)
2921                 set_entity_allocation(entity, allocation_static);
2922         /* TODO: visibility? */
2923 }
2924
2925
2926 typedef struct type_path_entry_t type_path_entry_t;
2927 struct type_path_entry_t {
2928         type_t           *type;
2929         ir_initializer_t *initializer;
2930         size_t            index;
2931         declaration_t    *compound_entry;
2932 };
2933
2934 typedef struct type_path_t type_path_t;
2935 struct type_path_t {
2936         type_path_entry_t *path;
2937         type_t            *top_type;
2938         bool               invalid;
2939 };
2940
2941 static __attribute__((unused)) void debug_print_type_path(const type_path_t *path)
2942 {
2943         size_t len = ARR_LEN(path->path);
2944
2945         for(size_t i = 0; i < len; ++i) {
2946                 const type_path_entry_t *entry = & path->path[i];
2947
2948                 type_t *type = skip_typeref(entry->type);
2949                 if(is_type_compound(type)) {
2950                         fprintf(stderr, ".%s", entry->compound_entry->symbol->string);
2951                 } else if(is_type_array(type)) {
2952                         fprintf(stderr, "[%u]", entry->index);
2953                 } else {
2954                         fprintf(stderr, "-INVALID-");
2955                 }
2956         }
2957         fprintf(stderr, "  (");
2958         print_type(path->top_type);
2959         fprintf(stderr, ")");
2960 }
2961
2962 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2963 {
2964         size_t len = ARR_LEN(path->path);
2965         assert(len > 0);
2966         return & path->path[len-1];
2967 }
2968
2969 static type_path_entry_t *append_to_type_path(type_path_t *path)
2970 {
2971         size_t len = ARR_LEN(path->path);
2972         ARR_RESIZE(type_path_entry_t, path->path, len+1);
2973
2974         type_path_entry_t *result = & path->path[len];
2975         memset(result, 0, sizeof(result[0]));
2976         return result;
2977 }
2978
2979 static size_t get_compound_size(const compound_type_t *type)
2980 {
2981         declaration_t *declaration = type->declaration;
2982         declaration_t *member      = declaration->scope.declarations;
2983         size_t         size        = 0;
2984         for( ; member != NULL; member = member->next) {
2985                 ++size;
2986         }
2987         /* TODO: cache results? */
2988
2989         return size;
2990 }
2991
2992 static ir_initializer_t *get_initializer_entry(type_path_t *path)
2993 {
2994         type_t *orig_top_type = path->top_type;
2995         type_t *top_type      = skip_typeref(orig_top_type);
2996
2997         assert(is_type_compound(top_type) || is_type_array(top_type));
2998
2999         if(ARR_LEN(path->path) == 0) {
3000                 return NULL;
3001         } else {
3002                 type_path_entry_t *top         = get_type_path_top(path);
3003                 ir_initializer_t  *initializer = top->initializer;
3004                 return get_initializer_compound_value(initializer, top->index);
3005         }
3006 }
3007
3008 static void descend_into_subtype(type_path_t *path)
3009 {
3010         type_t *orig_top_type = path->top_type;
3011         type_t *top_type      = skip_typeref(orig_top_type);
3012
3013         assert(is_type_compound(top_type) || is_type_array(top_type));
3014
3015         ir_initializer_t *initializer = get_initializer_entry(path);
3016
3017         type_path_entry_t *top = append_to_type_path(path);
3018         top->type              = top_type;
3019
3020         size_t len;
3021
3022         if(is_type_compound(top_type)) {
3023                 declaration_t *declaration = top_type->compound.declaration;
3024                 declaration_t *entry       = declaration->scope.declarations;
3025
3026                 top->compound_entry = entry;
3027                 top->index          = 0;
3028                 path->top_type      = entry->type;
3029                 len                 = get_compound_size(&top_type->compound);
3030         } else {
3031                 assert(is_type_array(top_type));
3032                 assert(top_type->array.size > 0);
3033
3034                 top->index     = 0;
3035                 path->top_type = top_type->array.element_type;
3036                 len            = top_type->array.size;
3037         }
3038         if(initializer == NULL
3039                         || get_initializer_kind(initializer) == IR_INITIALIZER_NULL) {
3040                 initializer = create_initializer_compound(len);
3041                 /* we have to set the entry at the 2nd latest path entry... */
3042                 size_t path_len = ARR_LEN(path->path);
3043                 assert(path_len >= 1);
3044                 if(path_len > 1) {
3045                         type_path_entry_t *entry        = & path->path[path_len-2];
3046                         ir_initializer_t  *tinitializer = entry->initializer;
3047                         set_initializer_compound_value(tinitializer, entry->index,
3048                                                        initializer);
3049                 }
3050         }
3051         top->initializer = initializer;
3052 }
3053
3054 static void ascend_from_subtype(type_path_t *path)
3055 {
3056         type_path_entry_t *top = get_type_path_top(path);
3057
3058         path->top_type = top->type;
3059
3060         size_t len = ARR_LEN(path->path);
3061         ARR_RESIZE(type_path_entry_t, path->path, len-1);
3062 }
3063
3064 static void walk_designator(type_path_t *path, const designator_t *designator)
3065 {
3066         /* designators start at current object type */
3067         ARR_RESIZE(type_path_entry_t, path->path, 1);
3068
3069         for( ; designator != NULL; designator = designator->next) {
3070                 type_path_entry_t *top         = get_type_path_top(path);
3071                 type_t            *orig_type   = top->type;
3072                 type_t            *type        = skip_typeref(orig_type);
3073
3074                 if(designator->symbol != NULL) {
3075                         assert(is_type_compound(type));
3076                         size_t    index  = 0;
3077                         symbol_t *symbol = designator->symbol;
3078
3079                         declaration_t *declaration = type->compound.declaration;
3080                         declaration_t *iter        = declaration->scope.declarations;
3081                         for( ; iter != NULL; iter = iter->next, ++index) {
3082                                 if(iter->symbol == symbol) {
3083                                         break;
3084                                 }
3085                         }
3086                         assert(iter != NULL);
3087
3088                         top->type           = orig_type;
3089                         top->compound_entry = iter;
3090                         top->index          = index;
3091                         orig_type           = iter->type;
3092                 } else {
3093                         expression_t *array_index = designator->array_index;
3094                         assert(designator->array_index != NULL);
3095                         assert(is_type_array(type));
3096                         assert(is_type_valid(array_index->base.type));
3097
3098                         long index = fold_constant(array_index);
3099                         assert(index >= 0);
3100 #ifndef NDEBUG
3101                         if(type->array.size_constant == 1) {
3102                                 long array_size = type->array.size;
3103                                 assert(index < array_size);
3104                         }
3105 #endif
3106
3107                         top->type  = orig_type;
3108                         top->index = (size_t) index;
3109                         orig_type  = type->array.element_type;
3110                 }
3111                 path->top_type = orig_type;
3112
3113                 if(designator->next != NULL) {
3114                         descend_into_subtype(path);
3115                 }
3116         }
3117
3118         path->invalid  = false;
3119 }
3120
3121 static void advance_current_object(type_path_t *path)
3122 {
3123         if(path->invalid) {
3124                 /* TODO: handle this... */
3125                 panic("invalid initializer in ast2firm (excessive elements)");
3126                 return;
3127         }
3128
3129         type_path_entry_t *top = get_type_path_top(path);
3130
3131         type_t *type = skip_typeref(top->type);
3132         if(is_type_union(type)) {
3133                 top->compound_entry = NULL;
3134         } else if(is_type_struct(type)) {
3135                 declaration_t *entry = top->compound_entry;
3136
3137                 top->index++;
3138                 entry               = entry->next;
3139                 top->compound_entry = entry;
3140                 if(entry != NULL) {
3141                         path->top_type = entry->type;
3142                         return;
3143                 }
3144         } else {
3145                 assert(is_type_array(type));
3146
3147                 top->index++;
3148                 if(!type->array.size_constant || top->index < type->array.size) {
3149                         return;
3150                 }
3151         }
3152
3153         /* we're past the last member of the current sub-aggregate, try if we
3154          * can ascend in the type hierarchy and continue with another subobject */
3155         size_t len = ARR_LEN(path->path);
3156
3157         if(len > 1) {
3158                 ascend_from_subtype(path);
3159                 advance_current_object(path);
3160         } else {
3161                 path->invalid = true;
3162         }
3163 }
3164
3165
3166 static ir_initializer_t *create_ir_initializer(
3167                 const initializer_t *initializer, type_t *type);
3168
3169 static ir_initializer_t *create_ir_initializer_value(
3170                 const initializer_value_t *initializer)
3171 {
3172         ir_node *value = expression_to_firm(initializer->value);
3173         return create_initializer_const(value);
3174 }
3175
3176 static ir_initializer_t *create_ir_initializer_list(
3177                 const initializer_list_t *initializer, type_t *type)
3178 {
3179         type_path_t path;
3180         memset(&path, 0, sizeof(path));
3181         path.top_type = type;
3182         path.path     = NEW_ARR_F(type_path_entry_t, 0);
3183
3184         descend_into_subtype(&path);
3185
3186         for(size_t i = 0; i < initializer->len; ++i) {
3187                 const initializer_t *sub_initializer = initializer->initializers[i];
3188
3189                 if(sub_initializer->kind == INITIALIZER_DESIGNATOR) {
3190                         walk_designator(&path, sub_initializer->designator.designator);
3191                         continue;
3192                 }
3193
3194                 if(sub_initializer->kind == INITIALIZER_VALUE) {
3195                         /* we might have to descend into types until we're at a scalar
3196                          * type */
3197                         while(true) {
3198                                 type_t *orig_top_type = path.top_type;
3199                                 type_t *top_type      = skip_typeref(orig_top_type);
3200
3201                                 if(is_type_scalar(top_type))
3202                                         break;
3203                                 descend_into_subtype(&path);
3204                         }
3205                 }
3206
3207                 ir_initializer_t *sub_irinitializer
3208                         = create_ir_initializer(sub_initializer, path.top_type);
3209
3210                 size_t path_len = ARR_LEN(path.path);
3211                 assert(path_len >= 1);
3212                 type_path_entry_t *entry        = & path.path[path_len-1];
3213                 ir_initializer_t  *tinitializer = entry->initializer;
3214                 set_initializer_compound_value(tinitializer, entry->index,
3215                                                sub_irinitializer);
3216
3217                 advance_current_object(&path);
3218         }
3219
3220         assert(ARR_LEN(path.path) >= 1);
3221         ir_initializer_t *result = path.path[0].initializer;
3222         DEL_ARR_F(path.path);
3223
3224         return result;
3225 }
3226
3227 static ir_initializer_t *create_ir_initializer_string(
3228                 const initializer_string_t *initializer, type_t *type)
3229 {
3230         size_t            string_len    = initializer->string.size;
3231         assert(type->kind == TYPE_ARRAY && type->array.size_constant);
3232         size_t            len           = type->array.size;
3233         ir_initializer_t *irinitializer = create_initializer_compound(len);
3234
3235         const char *string = initializer->string.begin;
3236         ir_mode    *mode   = get_type_mode(ir_type_const_char);
3237
3238         for(size_t i = 0; i < len; ++i) {
3239                 char c = 0;
3240                 if(i < string_len)
3241                         c = string[i];
3242
3243                 tarval           *tv = new_tarval_from_long(string[i], mode);
3244                 ir_initializer_t *char_initializer = create_initializer_tarval(tv);
3245
3246                 set_initializer_compound_value(irinitializer, i, char_initializer);
3247         }
3248
3249         return irinitializer;
3250 }
3251
3252 static ir_initializer_t *create_ir_initializer_wide_string(
3253                 const initializer_wide_string_t *initializer, type_t *type)
3254 {
3255         size_t            string_len    = initializer->string.size;
3256         assert(type->kind == TYPE_ARRAY && type->array.size_constant);
3257         size_t            len           = type->array.size;
3258         ir_initializer_t *irinitializer = create_initializer_compound(len);
3259
3260         const wchar_rep_t *string = initializer->string.begin;
3261         ir_mode           *mode   = get_type_mode(ir_type_wchar_t);
3262
3263         for(size_t i = 0; i < len; ++i) {
3264                 wchar_rep_t c = 0;
3265                 if(i < string_len) {
3266                         c = string[i];
3267                 }
3268                 tarval *tv = new_tarval_from_long(string[i], mode);
3269                 ir_initializer_t *char_initializer = create_initializer_tarval(tv);
3270
3271                 set_initializer_compound_value(irinitializer, i, char_initializer);
3272         }
3273
3274         return irinitializer;
3275 }
3276
3277 static ir_initializer_t *create_ir_initializer(
3278                 const initializer_t *initializer, type_t *type)
3279 {
3280         switch(initializer->kind) {
3281                 case INITIALIZER_STRING:
3282                         return create_ir_initializer_string(&initializer->string, type);
3283
3284                 case INITIALIZER_WIDE_STRING:
3285                         return create_ir_initializer_wide_string(&initializer->wide_string,
3286                                                                  type);
3287
3288                 case INITIALIZER_LIST:
3289                         return create_ir_initializer_list(&initializer->list, type);
3290
3291                 case INITIALIZER_VALUE:
3292                         return create_ir_initializer_value(&initializer->value);
3293
3294                 case INITIALIZER_DESIGNATOR:
3295                         panic("unexpected designator initializer found");
3296         }
3297         panic("unknown initializer");
3298 }
3299
3300 static void create_dynamic_initializer_sub(ir_initializer_t *initializer,
3301                 ir_type *type, dbg_info *dbgi, ir_node *base_addr)
3302 {
3303         switch(get_initializer_kind(initializer)) {
3304         case IR_INITIALIZER_NULL: {
3305                 ir_mode *mode = get_type_mode(type);
3306                 /* TODO: implement this for compound types... */
3307                 assert(type != NULL);
3308                 tarval  *zero = get_mode_null(mode);
3309                 ir_node *cnst = new_d_Const(dbgi, mode, zero);
3310
3311                 /* TODO: bitfields */
3312                 ir_node *mem    = get_store();
3313                 ir_node *store  = new_d_Store(dbgi, mem, base_addr, cnst);
3314                 ir_node *proj_m = new_Proj(store, mode_M, pn_Store_M);
3315                 set_store(proj_m);
3316                 return;
3317         }
3318         case IR_INITIALIZER_CONST: {
3319                 ir_node *node = get_initializer_const_value(initializer);
3320                 ir_mode *mode = get_irn_mode(node);
3321                 assert(get_type_mode(type) == mode);
3322
3323                 /* TODO: bitfields... */
3324                 ir_node *mem    = get_store();
3325                 ir_node *store  = new_d_Store(dbgi, mem, base_addr, node);
3326                 ir_node *proj_m = new_Proj(store, mode_M, pn_Store_M);
3327                 set_store(proj_m);
3328                 return;
3329         }
3330         case IR_INITIALIZER_TARVAL: {
3331                 tarval  *tv   = get_initializer_tarval_value(initializer);
3332                 ir_mode *mode = get_tarval_mode(tv);
3333                 ir_node *cnst = new_d_Const(dbgi, mode, tv);
3334                 assert(get_type_mode(type) == mode);
3335
3336                 /* TODO: bitfields... */
3337                 ir_node *mem    = get_store();
3338                 ir_node *store  = new_d_Store(dbgi, mem, base_addr, cnst);
3339                 ir_node *proj_m = new_Proj(store, mode_M, pn_Store_M);
3340                 set_store(proj_m);
3341                 return;
3342         }
3343         case IR_INITIALIZER_COMPOUND: {
3344                 assert(is_compound_type(type));
3345                 int n_members;
3346                 if(is_Array_type(type)) {
3347                         assert(has_array_upper_bound(type, 0));
3348                         n_members = get_array_upper_bound_int(type, 0);
3349                 } else {
3350                         n_members = get_compound_n_members(type);
3351                 }
3352
3353                 if(get_initializer_compound_n_entries(initializer)
3354                                 != (unsigned) n_members)
3355                         panic("initializer doesn't match compound type");
3356
3357                 for(int i = 0; i < n_members; ++i) {
3358                         ir_node *addr;
3359                         ir_type *irtype;
3360                         if(is_Array_type(type)) {
3361                                 ir_entity *entity   = get_array_element_entity(type);
3362                                 tarval    *index_tv = new_tarval_from_long(i, mode_uint);
3363                                 ir_node   *cnst     = new_d_Const(dbgi, mode_uint, index_tv);
3364                                 ir_node   *in[1]    = { cnst };
3365                                 irtype = get_array_element_type(type);
3366                                 addr   = new_d_Sel(dbgi, new_NoMem(), base_addr, 1, in, entity);
3367                         } else {
3368                                 ir_entity *member = get_compound_member(type, i);
3369
3370                                 irtype = get_entity_type(member);
3371                                 addr   = new_d_simpleSel(dbgi, new_NoMem(), base_addr, member);
3372                         }
3373
3374                         ir_initializer_t *sub_init
3375                                 = get_initializer_compound_value(initializer, i);
3376
3377                         create_dynamic_initializer_sub(sub_init, irtype, dbgi, addr);
3378                 }
3379                 return;
3380         }
3381         }
3382
3383         panic("invalid IR_INITIALIZER found");
3384 }
3385
3386 static void create_dynamic_initializer(ir_initializer_t *initializer,
3387                 dbg_info *dbgi, ir_entity *entity)
3388 {
3389         ir_node *frame     = get_local_frame(entity);
3390         ir_node *base_addr = new_d_simpleSel(dbgi, new_NoMem(), frame, entity);
3391         ir_type *type      = get_entity_type(entity);
3392
3393         create_dynamic_initializer_sub(initializer, type, dbgi, base_addr);
3394 }
3395
3396 static void create_local_initializer(initializer_t *initializer, dbg_info *dbgi,
3397                                      ir_entity *entity, type_t *type)
3398 {
3399         ir_node *memory = get_store();
3400         ir_node *nomem  = new_NoMem();
3401         ir_node *frame  = get_irg_frame(current_ir_graph);
3402         ir_node *addr   = new_d_simpleSel(dbgi, nomem, frame, entity);
3403
3404         if(initializer->kind == INITIALIZER_VALUE) {
3405                 initializer_value_t *initializer_value = &initializer->value;
3406
3407                 ir_node *value = expression_to_firm(initializer_value->value);
3408                 type = skip_typeref(type);
3409                 assign_value(dbgi, addr, type, value);
3410                 return;
3411         }
3412
3413         if(!is_constant_initializer(initializer)) {
3414                 ir_initializer_t *irinitializer
3415                         = create_ir_initializer(initializer, type);
3416
3417                 create_dynamic_initializer(irinitializer, dbgi, entity);
3418                 return;
3419         }
3420
3421         /* create the ir_initializer */
3422         ir_graph *const old_current_ir_graph = current_ir_graph;
3423         current_ir_graph = get_const_code_irg();
3424
3425         ir_initializer_t *irinitializer = create_ir_initializer(initializer, type);
3426
3427         assert(current_ir_graph == get_const_code_irg());
3428         current_ir_graph = old_current_ir_graph;
3429
3430         /* create a "template" entity which is copied to the entity on the stack */
3431         ident     *const id          = unique_ident("initializer");
3432         ir_type   *const irtype      = get_ir_type(type);
3433         ir_type   *const global_type = get_glob_type();
3434         ir_entity *const init_entity = new_d_entity(global_type, id, irtype, dbgi);
3435         set_entity_ld_ident(init_entity, id);
3436
3437         set_entity_variability(init_entity, variability_initialized);
3438         set_entity_visibility(init_entity, visibility_local);
3439         set_entity_allocation(init_entity, allocation_static);
3440
3441         set_entity_initializer(init_entity, irinitializer);
3442
3443         ir_node *const src_addr = create_symconst(dbgi, mode_P_data, init_entity);
3444         ir_node *const copyb    = new_d_CopyB(dbgi, memory, addr, src_addr, irtype);
3445
3446         ir_node *const copyb_mem = new_Proj(copyb, mode_M, pn_CopyB_M_regular);
3447         set_store(copyb_mem);
3448 }
3449
3450 static void create_initializer_local_variable_entity(declaration_t *declaration)
3451 {
3452         initializer_t *initializer = declaration->init.initializer;
3453         dbg_info      *dbgi        = get_dbg_info(&declaration->source_position);
3454         ir_entity     *entity      = declaration->v.entity;
3455         type_t        *type        = declaration->type;
3456         create_local_initializer(initializer, dbgi, entity, type);
3457 }
3458
3459 static void create_declaration_initializer(declaration_t *declaration)
3460 {
3461         initializer_t *initializer = declaration->init.initializer;
3462         if(initializer == NULL)
3463                 return;
3464
3465         declaration_kind_t declaration_kind
3466                 = (declaration_kind_t) declaration->declaration_kind;
3467         if(declaration_kind == DECLARATION_KIND_LOCAL_VARIABLE_ENTITY) {
3468                 create_initializer_local_variable_entity(declaration);
3469                 return;
3470         }
3471
3472         if(initializer->kind == INITIALIZER_VALUE) {
3473                 initializer_value_t *initializer_value = &initializer->value;
3474
3475                 ir_node *value = expression_to_firm(initializer_value->value);
3476
3477                 if(declaration_kind == DECLARATION_KIND_LOCAL_VARIABLE) {
3478                         set_value(declaration->v.value_number, value);
3479                 } else {
3480                         assert(declaration_kind == DECLARATION_KIND_GLOBAL_VARIABLE);
3481
3482                         ir_entity *entity = declaration->v.entity;
3483
3484                         set_entity_variability(entity, variability_initialized);
3485                         set_atomic_ent_value(entity, value);
3486                 }
3487         } else {
3488                 assert(declaration_kind == DECLARATION_KIND_LOCAL_VARIABLE_ENTITY
3489                                 || declaration_kind == DECLARATION_KIND_GLOBAL_VARIABLE);
3490
3491                 ir_entity        *entity        = declaration->v.entity;
3492                 ir_initializer_t *irinitializer
3493                         = create_ir_initializer(initializer, declaration->type);
3494
3495                 set_entity_variability(entity, variability_initialized);
3496                 set_entity_initializer(entity, irinitializer);
3497         }
3498 }
3499
3500 static void create_variable_length_array(declaration_t *declaration)
3501 {
3502         dbg_info *dbgi      = get_dbg_info(&declaration->source_position);
3503         type_t   *type      = declaration->type;
3504         ir_node  *mem       = get_store();
3505         ir_type  *el_type   = get_ir_type(type->array.element_type);
3506
3507         /* make sure size_node is calculated */
3508         get_type_size(type);
3509         ir_node  *elems = type->array.size_node;
3510         ir_node  *alloc = new_d_Alloc(dbgi, mem, elems, el_type, stack_alloc);
3511
3512         ir_node  *proj_m = new_d_Proj(dbgi, alloc, mode_M, pn_Alloc_M);
3513         ir_node  *addr   = new_d_Proj(dbgi, alloc, mode_P_data, pn_Alloc_res);
3514         set_store(proj_m);
3515
3516         /* initializers are not allowed for VLAs */
3517         assert(declaration->init.initializer == NULL);
3518
3519         declaration->declaration_kind = DECLARATION_KIND_VARIABLE_LENGTH_ARRAY;
3520         declaration->v.vla_base       = addr;
3521
3522         /* TODO: record VLA somewhere so we create the free node when we leave
3523          * it's scope */
3524 }
3525
3526 /**
3527  * Creates a Firm local variable from a declaration.
3528  */
3529 static void create_local_variable(declaration_t *declaration)
3530 {
3531         assert(declaration->declaration_kind == DECLARATION_KIND_UNKNOWN);
3532
3533         bool needs_entity = declaration->address_taken;
3534         type_t *type = skip_typeref(declaration->type);
3535
3536         /* is it a variable length array? */
3537         if(is_type_array(type) && !type->array.size_constant) {
3538                 create_variable_length_array(declaration);
3539                 return;
3540         } else if(is_type_array(type) || is_type_compound(type)) {
3541                 needs_entity = true;
3542         }
3543
3544         if(needs_entity) {
3545                 ir_type *frame_type = get_irg_frame_type(current_ir_graph);
3546                 create_declaration_entity(declaration,
3547                                           DECLARATION_KIND_LOCAL_VARIABLE_ENTITY,
3548                                           frame_type);
3549         } else {
3550                 declaration->declaration_kind = DECLARATION_KIND_LOCAL_VARIABLE;
3551                 declaration->v.value_number   = next_value_number_function;
3552                 set_irg_loc_description(current_ir_graph, next_value_number_function, declaration);
3553                 ++next_value_number_function;
3554         }
3555
3556         create_declaration_initializer(declaration);
3557 }
3558
3559 static void create_local_static_variable(declaration_t *declaration)
3560 {
3561         assert(declaration->declaration_kind == DECLARATION_KIND_UNKNOWN);
3562
3563         type_t    *const type        = skip_typeref(declaration->type);
3564         ir_type   *const global_type = get_glob_type();
3565         ident     *const id          = unique_ident(declaration->symbol->string);
3566         ir_type   *const irtype      = get_ir_type(type);
3567         dbg_info  *const dbgi        = get_dbg_info(&declaration->source_position);
3568         ir_entity *const entity      = new_d_entity(global_type, id, irtype, dbgi);
3569         set_entity_ld_ident(entity, id);
3570
3571         declaration->declaration_kind = DECLARATION_KIND_GLOBAL_VARIABLE;
3572         declaration->v.entity         = entity;
3573         set_entity_variability(entity, variability_uninitialized);
3574         set_entity_visibility(entity, visibility_local);
3575         set_entity_allocation(entity, allocation_static);
3576
3577         ir_graph *const old_current_ir_graph = current_ir_graph;
3578         current_ir_graph = get_const_code_irg();
3579
3580         create_declaration_initializer(declaration);
3581
3582         assert(current_ir_graph == get_const_code_irg());
3583         current_ir_graph = old_current_ir_graph;
3584 }
3585
3586
3587
3588 static void return_statement_to_firm(return_statement_t *statement)
3589 {
3590         if(get_cur_block() == NULL)
3591                 return;
3592
3593         dbg_info *dbgi        = get_dbg_info(&statement->base.source_position);
3594         ir_type  *func_irtype = get_ir_type(current_function_decl->type);
3595
3596
3597         ir_node *in[1];
3598         int      in_len;
3599         if(get_method_n_ress(func_irtype) > 0) {
3600                 ir_type *res_type = get_method_res_type(func_irtype, 0);
3601
3602                 if(statement->value != NULL) {
3603                         ir_node *node = expression_to_firm(statement->value);
3604                         node  = do_strict_conv(dbgi, node);
3605                         in[0] = node;
3606                 } else {
3607                         ir_mode *mode;
3608                         if(is_compound_type(res_type)) {
3609                                 mode = mode_P_data;
3610                         } else {
3611                                 mode = get_type_mode(res_type);
3612                         }
3613                         in[0] = new_Unknown(mode);
3614                 }
3615                 in_len = 1;
3616         } else {
3617                 /* build return_value for its side effects */
3618                 if(statement->value != NULL) {
3619                         expression_to_firm(statement->value);
3620                 }
3621                 in_len = 0;
3622         }
3623
3624         ir_node  *store = get_store();
3625         ir_node  *ret   = new_d_Return(dbgi, store, in_len, in);
3626
3627         ir_node *end_block = get_irg_end_block(current_ir_graph);
3628         add_immBlock_pred(end_block, ret);
3629
3630         set_cur_block(NULL);
3631 }
3632
3633 static ir_node *expression_statement_to_firm(expression_statement_t *statement)
3634 {
3635         if(get_cur_block() == NULL)
3636                 return NULL;
3637
3638         return expression_to_firm(statement->expression);
3639 }
3640
3641 static ir_node *compound_statement_to_firm(compound_statement_t *compound)
3642 {
3643         ir_node     *result    = NULL;
3644         statement_t *statement = compound->statements;
3645         for( ; statement != NULL; statement = statement->base.next) {
3646                 //context2firm(&statement->scope);
3647
3648                 if(statement->base.next == NULL
3649                                 && statement->kind == STATEMENT_EXPRESSION) {
3650                         result = expression_statement_to_firm(
3651                                         &statement->expression);
3652                         break;
3653                 }
3654                 statement_to_firm(statement);
3655         }
3656
3657         return result;
3658 }
3659
3660 static void create_global_variable(declaration_t *declaration)
3661 {
3662         ir_visibility  vis;
3663         ir_type       *var_type;
3664         switch ((storage_class_tag_t)declaration->storage_class) {
3665                 case STORAGE_CLASS_STATIC:
3666                         vis = visibility_local;
3667                         goto global_var;
3668
3669                 case STORAGE_CLASS_EXTERN:
3670                         vis = visibility_external_allocated;
3671                         goto global_var;
3672
3673                 case STORAGE_CLASS_NONE:
3674                         vis = visibility_external_visible;
3675                         goto global_var;
3676
3677                 case STORAGE_CLASS_THREAD:
3678                         vis = visibility_external_visible;
3679                         goto tls_var;
3680
3681                 case STORAGE_CLASS_THREAD_EXTERN:
3682                         vis = visibility_external_allocated;
3683                         goto tls_var;
3684
3685                 case STORAGE_CLASS_THREAD_STATIC:
3686                         vis = visibility_local;
3687                         goto tls_var;
3688
3689 tls_var:
3690                         var_type = get_tls_type();
3691                         goto create_var;
3692
3693 global_var:
3694                         var_type = get_glob_type();
3695                         goto create_var;
3696
3697 create_var:
3698                         create_declaration_entity(declaration,
3699                                                   DECLARATION_KIND_GLOBAL_VARIABLE,
3700                                                   var_type);
3701                         set_entity_visibility(declaration->v.entity, vis);
3702
3703                         return;
3704
3705                 case STORAGE_CLASS_TYPEDEF:
3706                 case STORAGE_CLASS_AUTO:
3707                 case STORAGE_CLASS_REGISTER:
3708                 case STORAGE_CLASS_ENUM_ENTRY:
3709                         break;
3710         }
3711         panic("Invalid storage class for global variable");
3712 }
3713
3714 static void create_local_declaration(declaration_t *declaration)
3715 {
3716         if(declaration->symbol == NULL)
3717                 return;
3718
3719         type_t *type = skip_typeref(declaration->type);
3720
3721         switch ((storage_class_tag_t) declaration->storage_class) {
3722         case STORAGE_CLASS_STATIC:
3723                 create_local_static_variable(declaration);
3724                 return;
3725         case STORAGE_CLASS_EXTERN:
3726                 create_global_variable(declaration);
3727                 create_declaration_initializer(declaration);
3728                 return;
3729         case STORAGE_CLASS_NONE:
3730         case STORAGE_CLASS_AUTO:
3731         case STORAGE_CLASS_REGISTER:
3732                 if(is_type_function(type)) {
3733                         if(declaration->init.statement != NULL) {
3734                                 panic("nested functions not supported yet");
3735                         } else {
3736                                 get_function_entity(declaration);
3737                         }
3738                 } else {
3739                         create_local_variable(declaration);
3740                 }
3741                 return;
3742         case STORAGE_CLASS_ENUM_ENTRY:
3743         case STORAGE_CLASS_TYPEDEF:
3744         case STORAGE_CLASS_THREAD:
3745         case STORAGE_CLASS_THREAD_EXTERN:
3746         case STORAGE_CLASS_THREAD_STATIC:
3747                 return;
3748         }
3749         panic("invalid storage class found");
3750 }
3751
3752 static void declaration_statement_to_firm(declaration_statement_t *statement)
3753 {
3754         declaration_t *declaration = statement->declarations_begin;
3755         declaration_t *end         = statement->declarations_end->next;
3756         for( ; declaration != end; declaration = declaration->next) {
3757                 if(declaration->namespc != NAMESPACE_NORMAL)
3758                         continue;
3759                 create_local_declaration(declaration);
3760         }
3761 }
3762
3763 static void if_statement_to_firm(if_statement_t *statement)
3764 {
3765         ir_node *cur_block = get_cur_block();
3766
3767         ir_node *fallthrough_block = new_immBlock();
3768
3769         /* the true (blocks) */
3770         ir_node *true_block;
3771         if (statement->true_statement != NULL) {
3772                 true_block = new_immBlock();
3773                 statement_to_firm(statement->true_statement);
3774                 if(get_cur_block() != NULL) {
3775                         ir_node *jmp = new_Jmp();
3776                         add_immBlock_pred(fallthrough_block, jmp);
3777                 }
3778         } else {
3779                 true_block = fallthrough_block;
3780         }
3781
3782         /* the false (blocks) */
3783         ir_node *false_block;
3784         if(statement->false_statement != NULL) {
3785                 false_block = new_immBlock();
3786
3787                 statement_to_firm(statement->false_statement);
3788                 if(get_cur_block() != NULL) {
3789                         ir_node *jmp = new_Jmp();
3790                         add_immBlock_pred(fallthrough_block, jmp);
3791                 }
3792         } else {
3793                 false_block = fallthrough_block;
3794         }
3795
3796         /* create the condition */
3797         if(cur_block != NULL) {
3798                 set_cur_block(cur_block);
3799                 create_condition_evaluation(statement->condition, true_block,
3800                                             false_block);
3801         }
3802
3803         mature_immBlock(true_block);
3804         if(false_block != fallthrough_block) {
3805                 mature_immBlock(false_block);
3806         }
3807         mature_immBlock(fallthrough_block);
3808
3809         set_cur_block(fallthrough_block);
3810 }
3811
3812 static void while_statement_to_firm(while_statement_t *statement)
3813 {
3814         ir_node *jmp = NULL;
3815         if(get_cur_block() != NULL) {
3816                 jmp = new_Jmp();
3817         }
3818
3819         /* create the header block */
3820         ir_node *header_block = new_immBlock();
3821         if(jmp != NULL) {
3822                 add_immBlock_pred(header_block, jmp);
3823         }
3824
3825         /* the false block */
3826         ir_node *false_block = new_immBlock();
3827
3828         /* the loop body */
3829         ir_node *body_block;
3830         if (statement->body != NULL) {
3831                 ir_node *old_continue_label = continue_label;
3832                 ir_node *old_break_label    = break_label;
3833                 continue_label              = header_block;
3834                 break_label                 = false_block;
3835
3836                 body_block = new_immBlock();
3837                 statement_to_firm(statement->body);
3838
3839                 assert(continue_label == header_block);
3840                 assert(break_label    == false_block);
3841                 continue_label = old_continue_label;
3842                 break_label    = old_break_label;
3843
3844                 if(get_cur_block() != NULL) {
3845                         jmp = new_Jmp();
3846                         add_immBlock_pred(header_block, jmp);
3847                 }
3848         } else {
3849                 body_block = header_block;
3850         }
3851
3852         /* create the condition */
3853         set_cur_block(header_block);
3854
3855         create_condition_evaluation(statement->condition, body_block, false_block);
3856         mature_immBlock(body_block);
3857         mature_immBlock(false_block);
3858         mature_immBlock(header_block);
3859
3860         set_cur_block(false_block);
3861 }
3862
3863 static void do_while_statement_to_firm(do_while_statement_t *statement)
3864 {
3865         ir_node *jmp = NULL;
3866         if(get_cur_block() != NULL) {
3867                 jmp = new_Jmp();
3868         }
3869
3870         /* create the header block */
3871         ir_node *header_block = new_immBlock();
3872
3873         /* the false block */
3874         ir_node *false_block = new_immBlock();
3875
3876         /* the loop body */
3877         ir_node *body_block = new_immBlock();
3878         if(jmp != NULL) {
3879                 add_immBlock_pred(body_block, jmp);
3880         }
3881
3882         if (statement->body != NULL) {
3883                 ir_node *old_continue_label = continue_label;
3884                 ir_node *old_break_label    = break_label;
3885                 continue_label              = header_block;
3886                 break_label                 = false_block;
3887
3888                 statement_to_firm(statement->body);
3889
3890                 assert(continue_label == header_block);
3891                 assert(break_label    == false_block);
3892                 continue_label = old_continue_label;
3893                 break_label    = old_break_label;
3894
3895                 if (get_cur_block() == NULL) {
3896                         mature_immBlock(header_block);
3897                         mature_immBlock(body_block);
3898                         mature_immBlock(false_block);
3899                         return;
3900                 }
3901         }
3902
3903         ir_node *body_jmp = new_Jmp();
3904         add_immBlock_pred(header_block, body_jmp);
3905         mature_immBlock(header_block);
3906
3907         /* create the condition */
3908         set_cur_block(header_block);
3909
3910         create_condition_evaluation(statement->condition, body_block, false_block);
3911         mature_immBlock(body_block);
3912         mature_immBlock(false_block);
3913         mature_immBlock(header_block);
3914
3915         set_cur_block(false_block);
3916 }
3917
3918 static void for_statement_to_firm(for_statement_t *statement)
3919 {
3920         ir_node *jmp = NULL;
3921         if (get_cur_block() != NULL) {
3922                 if(statement->initialisation != NULL) {
3923                         expression_to_firm(statement->initialisation);
3924                 }
3925
3926                 /* create declarations */
3927                 declaration_t *declaration = statement->scope.declarations;
3928                 for( ; declaration != NULL; declaration = declaration->next) {
3929                         create_local_declaration(declaration);
3930                 }
3931
3932                 jmp = new_Jmp();
3933         }
3934
3935
3936         /* create the step block */
3937         ir_node *const step_block = new_immBlock();
3938         if (statement->step != NULL) {
3939                 expression_to_firm(statement->step);
3940         }
3941         ir_node *const step_jmp = new_Jmp();
3942
3943         /* create the header block */
3944         ir_node *const header_block = new_immBlock();
3945         if (jmp != NULL) {
3946                 add_immBlock_pred(header_block, jmp);
3947         }
3948         add_immBlock_pred(header_block, step_jmp);
3949
3950         /* the false block */
3951         ir_node *const false_block = new_immBlock();
3952
3953         /* the loop body */
3954         ir_node * body_block;
3955         if (statement->body != NULL) {
3956                 ir_node *const old_continue_label = continue_label;
3957                 ir_node *const old_break_label    = break_label;
3958                 continue_label = step_block;
3959                 break_label    = false_block;
3960
3961                 body_block = new_immBlock();
3962                 statement_to_firm(statement->body);
3963
3964                 assert(continue_label == step_block);
3965                 assert(break_label    == false_block);
3966                 continue_label = old_continue_label;
3967                 break_label    = old_break_label;
3968
3969                 if (get_cur_block() != NULL) {
3970                         jmp = new_Jmp();
3971                         add_immBlock_pred(step_block, jmp);
3972                 }
3973         } else {
3974                 body_block = step_block;
3975         }
3976
3977         /* create the condition */
3978         set_cur_block(header_block);
3979         if (statement->condition != NULL) {
3980                 create_condition_evaluation(statement->condition, body_block,
3981                                             false_block);
3982         } else {
3983                 keep_alive(header_block);
3984                 jmp = new_Jmp();
3985                 add_immBlock_pred(body_block, jmp);
3986         }
3987
3988         mature_immBlock(body_block);
3989         mature_immBlock(false_block);
3990         mature_immBlock(step_block);
3991         mature_immBlock(header_block);
3992         mature_immBlock(false_block);
3993
3994         set_cur_block(false_block);
3995 }
3996
3997 static void create_jump_statement(const statement_t *statement,
3998                                   ir_node *target_block)
3999 {
4000         if(get_cur_block() == NULL)
4001                 return;
4002
4003         dbg_info *dbgi = get_dbg_info(&statement->base.source_position);
4004         ir_node  *jump = new_d_Jmp(dbgi);
4005         add_immBlock_pred(target_block, jump);
4006
4007         set_cur_block(NULL);
4008 }
4009
4010 static void switch_statement_to_firm(const switch_statement_t *statement)
4011 {
4012         dbg_info *dbgi = get_dbg_info(&statement->base.source_position);
4013
4014         ir_node *expression  = expression_to_firm(statement->expression);
4015         ir_node *cond        = new_d_Cond(dbgi, expression);
4016         ir_node *break_block = new_immBlock();
4017
4018         set_cur_block(NULL);
4019
4020         ir_node *const old_switch_cond       = current_switch_cond;
4021         ir_node *const old_break_label       = break_label;
4022         const bool     old_saw_default_label = saw_default_label;
4023         current_switch_cond                  = cond;
4024         break_label                          = break_block;
4025
4026         if (statement->body != NULL) {
4027                 statement_to_firm(statement->body);
4028         }
4029
4030         if(get_cur_block() != NULL) {
4031                 ir_node *jmp = new_Jmp();
4032                 add_immBlock_pred(break_block, jmp);
4033         }
4034
4035         if (!saw_default_label) {
4036                 set_cur_block(get_nodes_block(cond));
4037                 ir_node *const proj = new_d_defaultProj(dbgi, cond,
4038                                                         MAGIC_DEFAULT_PN_NUMBER);
4039                 add_immBlock_pred(break_block, proj);
4040         }
4041
4042         assert(current_switch_cond == cond);
4043         assert(break_label         == break_block);
4044         current_switch_cond = old_switch_cond;
4045         break_label         = old_break_label;
4046         saw_default_label   = old_saw_default_label;
4047
4048         mature_immBlock(break_block);
4049         set_cur_block(break_block);
4050 }
4051
4052 static void case_label_to_firm(const case_label_statement_t *statement)
4053 {
4054         dbg_info *dbgi = get_dbg_info(&statement->base.source_position);
4055
4056         ir_node *const fallthrough = (get_cur_block() == NULL ? NULL : new_Jmp());
4057
4058         /* let's create a node and hope firm constant folding creates a Const
4059          * node... */
4060         ir_node *proj;
4061         ir_node *old_block = get_nodes_block(current_switch_cond);
4062         ir_node *block     = new_immBlock();
4063
4064         set_cur_block(old_block);
4065         if(statement->expression != NULL) {
4066                 long start_pn = fold_constant(statement->expression);
4067                 long end_pn = start_pn;
4068                 if (statement->end_range != NULL) {
4069                         end_pn = fold_constant(statement->end_range);
4070                 }
4071                 assert(start_pn <= end_pn);
4072                 /* create jumps for all cases in the given range */
4073                 for (long pn = start_pn; pn <= end_pn; ++pn) {
4074                         if(pn == MAGIC_DEFAULT_PN_NUMBER) {
4075                                 /* oops someone detected our cheating... */
4076                                 panic("magic default pn used");
4077                         }
4078                         proj = new_d_Proj(dbgi, current_switch_cond, mode_X, pn);
4079                         add_immBlock_pred(block, proj);
4080                 }
4081         } else {
4082                 saw_default_label = true;
4083                 proj = new_d_defaultProj(dbgi, current_switch_cond,
4084                                          MAGIC_DEFAULT_PN_NUMBER);
4085
4086                 add_immBlock_pred(block, proj);
4087         }
4088
4089         if (fallthrough != NULL) {
4090                 add_immBlock_pred(block, fallthrough);
4091         }
4092         mature_immBlock(block);
4093         set_cur_block(block);
4094
4095         if(statement->statement != NULL) {
4096                 statement_to_firm(statement->statement);
4097         }
4098 }
4099
4100 static ir_node *get_label_block(declaration_t *label)
4101 {
4102         assert(label->namespc == NAMESPACE_LABEL);
4103
4104         if(label->declaration_kind == DECLARATION_KIND_LABEL_BLOCK) {
4105                 return label->v.block;
4106         }
4107         assert(label->declaration_kind == DECLARATION_KIND_UNKNOWN);
4108
4109         ir_node *old_cur_block = get_cur_block();
4110         ir_node *block         = new_immBlock();
4111         set_cur_block(old_cur_block);
4112
4113         label->declaration_kind = DECLARATION_KIND_LABEL_BLOCK;
4114         label->v.block          = block;
4115
4116         ARR_APP1(ir_node *, imature_blocks, block);
4117
4118         return block;
4119 }
4120
4121 static void label_to_firm(const label_statement_t *statement)
4122 {
4123         ir_node *block = get_label_block(statement->label);
4124
4125         if(get_cur_block() != NULL) {
4126                 ir_node *jmp = new_Jmp();
4127                 add_immBlock_pred(block, jmp);
4128         }
4129
4130         set_cur_block(block);
4131         keep_alive(block);
4132
4133         if(statement->statement != NULL) {
4134                 statement_to_firm(statement->statement);
4135         }
4136 }
4137
4138 static void goto_to_firm(const goto_statement_t *statement)
4139 {
4140         if(get_cur_block() == NULL)
4141                 return;
4142
4143         ir_node *block = get_label_block(statement->label);
4144         ir_node *jmp   = new_Jmp();
4145         add_immBlock_pred(block, jmp);
4146
4147         set_cur_block(NULL);
4148 }
4149
4150 typedef enum modifier_t {
4151         ASM_MODIFIER_WRITE_ONLY   = 1 << 0,
4152         ASM_MODIFIER_READ_WRITE   = 1 << 1,
4153         ASM_MODIFIER_COMMUTATIVE  = 1 << 2,
4154         ASM_MODIFIER_EARLYCLOBBER = 1 << 3,
4155 } modifier_t;
4156
4157 static void asm_statement_to_firm(const asm_statement_t *statement)
4158 {
4159         (void) statement;
4160         fprintf(stderr, "WARNING asm not implemented yet!\n");
4161 #if 0
4162         bool needs_memory = false;
4163
4164         size_t         n_clobbers = 0;
4165         asm_clobber_t *clobber    = statement->clobbers;
4166         for( ; clobber != NULL; clobber = clobber->next) {
4167                 if(strcmp(clobber->clobber, "memory") == 0) {
4168                         needs_memory = true;
4169                         continue;
4170                 }
4171
4172                 ident *id = new_id_from_str(clobber->clobber);
4173                 obstack_ptr_grow(&asm_obst, id);
4174                 ++n_clobbers;
4175         }
4176         assert(obstack_object_size(&asm_obst) == n_clobbers * sizeof(ident*));
4177         ident **clobbers = NULL;
4178         if(n_clobbers > 0) {
4179                 clobbers = obstack_finish(&asm_obst);
4180         }
4181
4182         /* find and count input and output constraints */
4183         asm_constraint_t *constraint = statement->inputs;
4184         for( ; constraint != NULL; constraint = constraint->next) {
4185                 int  modifiers      = 0;
4186                 bool supports_memop = false;
4187                 for(const char *c = constraint->constraints; *c != 0; ++c) {
4188                         /* TODO: improve error messages */
4189                         switch(*c) {
4190                         case '?':
4191                         case '!':
4192                                 panic("multiple alternative assembler constraints not "
4193                                       "supported");
4194                         case 'm':
4195                         case 'o':
4196                         case 'V':
4197                         case '<':
4198                         case '>':
4199                         case 'X':
4200                                 supports_memop = true;
4201                                 obstack_1grow(&asm_obst, *c);
4202                                 break;
4203                         case '=':
4204                                 if(modifiers & ASM_MODIFIER_READ_WRITE)
4205                                         panic("inconsistent register constraints");
4206                                 modifiers |= ASM_MODIFIER_WRITE_ONLY;
4207                                 break;
4208                         case '+':
4209                                 if(modifiers & ASM_MODIFIER_WRITE_ONLY)
4210                                         panic("inconsistent register constraints");
4211                                 modifiers |= ASM_MODIFIER_READ_WRITE;
4212                                 break;
4213                         case '&':
4214                                 modifiers |= ASM_MODIFIER_EARLYCLOBBER;
4215                                 panic("early clobber assembler constraint not supported yet");
4216                                 break;
4217                         case '%':
4218                                 modifiers |= ASM_MODIFIER_COMMUTATIVE;
4219                                 panic("commutative assembler constraint not supported yet");
4220                                 break;
4221                         case '#':
4222                                 /* skip register preferences stuff... */
4223                                 while(*c != 0 && *c != ',')
4224                                         ++c;
4225                                 break;
4226                         case '*':
4227                                 /* skip register preferences stuff... */
4228                                 ++c;
4229                                 break;
4230                         default:
4231                                 obstack_1grow(&asm_obst, *c);
4232                                 break;
4233                         }
4234                 }
4235                 obstack_1grow(&asm_obst, '\0');
4236                 const char *constraint_string = obstack_finish(&asm_obst);
4237
4238                 needs_memory |= supports_memop;
4239                 if(supports_memop) {
4240
4241                 }
4242         }
4243 #endif
4244 }
4245
4246 static void statement_to_firm(statement_t *statement)
4247 {
4248         switch(statement->kind) {
4249         case STATEMENT_INVALID:
4250                 panic("invalid statement found");
4251         case STATEMENT_COMPOUND:
4252                 compound_statement_to_firm(&statement->compound);
4253                 return;
4254         case STATEMENT_RETURN:
4255                 return_statement_to_firm(&statement->returns);
4256                 return;
4257         case STATEMENT_EXPRESSION:
4258                 expression_statement_to_firm(&statement->expression);
4259                 return;
4260         case STATEMENT_IF:
4261                 if_statement_to_firm(&statement->ifs);
4262                 return;
4263         case STATEMENT_WHILE:
4264                 while_statement_to_firm(&statement->whiles);
4265                 return;
4266         case STATEMENT_DO_WHILE:
4267                 do_while_statement_to_firm(&statement->do_while);
4268                 return;
4269         case STATEMENT_DECLARATION:
4270                 declaration_statement_to_firm(&statement->declaration);
4271                 return;
4272         case STATEMENT_BREAK:
4273                 create_jump_statement(statement, break_label);
4274                 return;
4275         case STATEMENT_CONTINUE:
4276                 create_jump_statement(statement, continue_label);
4277                 return;
4278         case STATEMENT_SWITCH:
4279                 switch_statement_to_firm(&statement->switchs);
4280                 return;
4281         case STATEMENT_CASE_LABEL:
4282                 case_label_to_firm(&statement->case_label);
4283                 return;
4284         case STATEMENT_FOR:
4285                 for_statement_to_firm(&statement->fors);
4286                 return;
4287         case STATEMENT_LABEL:
4288                 label_to_firm(&statement->label);
4289                 return;
4290         case STATEMENT_GOTO:
4291                 goto_to_firm(&statement->gotos);
4292                 return;
4293         case STATEMENT_ASM:
4294                 asm_statement_to_firm(&statement->asms);
4295                 return;
4296         }
4297         panic("Statement not implemented\n");
4298 }
4299
4300 static int count_decls_in_expression(const expression_t *expression);
4301
4302 static int count_local_declarations(const declaration_t *      decl,
4303                                     const declaration_t *const end)
4304 {
4305         int count = 0;
4306         for (; decl != end; decl = decl->next) {
4307                 if(decl->namespc != NAMESPACE_NORMAL)
4308                         continue;
4309                 const type_t *type = skip_typeref(decl->type);
4310                 if (!decl->address_taken && is_type_scalar(type))
4311                         ++count;
4312                 const initializer_t *initializer = decl->init.initializer;
4313                 /* FIXME: should walk initializer hierarchies... */
4314                 if(initializer != NULL && initializer->kind == INITIALIZER_VALUE) {
4315                         count += count_decls_in_expression(initializer->value.value);
4316                 }
4317         }
4318         return count;
4319 }
4320
4321 static int count_decls_in_expression(const expression_t *expression) {
4322         if(expression == NULL)
4323                 return 0;
4324
4325         switch(expression->base.kind) {
4326         case EXPR_STATEMENT:
4327                 return count_decls_in_stmts(expression->statement.statement);
4328         EXPR_BINARY_CASES {
4329                 int count_left  = count_decls_in_expression(expression->binary.left);
4330                 int count_right = count_decls_in_expression(expression->binary.right);
4331                 return count_left + count_right;
4332         }
4333         EXPR_UNARY_CASES
4334                 return count_decls_in_expression(expression->unary.value);
4335         case EXPR_CALL: {
4336                 int count = 0;
4337                 call_argument_t *argument = expression->call.arguments;
4338                 for( ; argument != NULL; argument = argument->next) {
4339                         count += count_decls_in_expression(argument->expression);
4340                 }
4341                 return count;
4342         }
4343
4344         default:
4345                 break;
4346         }
4347
4348         /* TODO FIXME: finish/fix that firm patch that allows dynamic value numbers
4349          * (or implement all the missing expressions here/implement a walker)
4350          */
4351
4352         return 0;
4353 }
4354
4355 static int count_decls_in_stmts(const statement_t *stmt)
4356 {
4357         int count = 0;
4358         for (; stmt != NULL; stmt = stmt->base.next) {
4359                 switch (stmt->kind) {
4360                         case STATEMENT_DECLARATION: {
4361                                 const declaration_statement_t *const decl_stmt = &stmt->declaration;
4362                                 count += count_local_declarations(decl_stmt->declarations_begin,
4363                                                                   decl_stmt->declarations_end->next);
4364                                 break;
4365                         }
4366
4367                         case STATEMENT_COMPOUND: {
4368                                 const compound_statement_t *const comp =
4369                                         &stmt->compound;
4370                                 count += count_decls_in_stmts(comp->statements);
4371                                 break;
4372                         }
4373
4374                         case STATEMENT_IF: {
4375                                 const if_statement_t *const if_stmt = &stmt->ifs;
4376                                 count += count_decls_in_expression(if_stmt->condition);
4377                                 count += count_decls_in_stmts(if_stmt->true_statement);
4378                                 count += count_decls_in_stmts(if_stmt->false_statement);
4379                                 break;
4380                         }
4381
4382                         case STATEMENT_SWITCH: {
4383                                 const switch_statement_t *const switch_stmt = &stmt->switchs;
4384                                 count += count_decls_in_expression(switch_stmt->expression);
4385                                 count += count_decls_in_stmts(switch_stmt->body);
4386                                 break;
4387                         }
4388
4389                         case STATEMENT_LABEL: {
4390                                 const label_statement_t *const label_stmt = &stmt->label;
4391                                 if(label_stmt->statement != NULL) {
4392                                         count += count_decls_in_stmts(label_stmt->statement);
4393                                 }
4394                                 break;
4395                         }
4396
4397                         case STATEMENT_WHILE: {
4398                                 const while_statement_t *const while_stmt = &stmt->whiles;
4399                                 count += count_decls_in_expression(while_stmt->condition);
4400                                 count += count_decls_in_stmts(while_stmt->body);
4401                                 break;
4402                         }
4403
4404                         case STATEMENT_DO_WHILE: {
4405                                 const do_while_statement_t *const do_while_stmt = &stmt->do_while;
4406                                 count += count_decls_in_expression(do_while_stmt->condition);
4407                                 count += count_decls_in_stmts(do_while_stmt->body);
4408                                 break;
4409                         }
4410
4411                         case STATEMENT_FOR: {
4412                                 const for_statement_t *const for_stmt = &stmt->fors;
4413                                 count += count_local_declarations(for_stmt->scope.declarations, NULL);
4414                                 count += count_decls_in_expression(for_stmt->initialisation);
4415                                 count += count_decls_in_expression(for_stmt->condition);
4416                                 count += count_decls_in_expression(for_stmt->step);
4417                                 count += count_decls_in_stmts(for_stmt->body);
4418                                 break;
4419                         }
4420
4421                         case STATEMENT_CASE_LABEL: {
4422                                 const case_label_statement_t *label = &stmt->case_label;
4423                                 count += count_decls_in_expression(label->expression);
4424                                 if(label->statement != NULL) {
4425                                         count += count_decls_in_stmts(label->statement);
4426                                 }
4427                                 break;
4428                         }
4429
4430                         case STATEMENT_ASM:
4431                         case STATEMENT_BREAK:
4432                         case STATEMENT_CONTINUE:
4433                                 break;
4434
4435                         case STATEMENT_EXPRESSION: {
4436                                 const expression_statement_t *expr_stmt = &stmt->expression;
4437                                 count += count_decls_in_expression(expr_stmt->expression);
4438                                 break;
4439                         }
4440
4441                         case STATEMENT_GOTO:
4442                         case STATEMENT_INVALID:
4443                                 break;
4444
4445                         case STATEMENT_RETURN: {
4446                                 const return_statement_t *ret_stmt = &stmt->returns;
4447                                 count += count_decls_in_expression(ret_stmt->value);
4448                                 break;
4449                         }
4450                 }
4451         }
4452         return count;
4453 }
4454
4455 static int get_function_n_local_vars(declaration_t *declaration)
4456 {
4457         int count = 0;
4458
4459         /* count parameters */
4460         count += count_local_declarations(declaration->scope.declarations, NULL);
4461
4462         /* count local variables declared in body */
4463         count += count_decls_in_stmts(declaration->init.statement);
4464
4465         return count;
4466 }
4467
4468 static void initialize_function_parameters(declaration_t *declaration)
4469 {
4470         ir_graph        *irg             = current_ir_graph;
4471         ir_node         *args            = get_irg_args(irg);
4472         ir_node         *start_block     = get_irg_start_block(irg);
4473         ir_type         *function_irtype = get_ir_type(declaration->type);
4474
4475         int            n         = 0;
4476         declaration_t *parameter = declaration->scope.declarations;
4477         for( ; parameter != NULL; parameter = parameter->next, ++n) {
4478                 assert(parameter->declaration_kind == DECLARATION_KIND_UNKNOWN);
4479                 type_t *type = skip_typeref(parameter->type);
4480
4481                 bool needs_entity = parameter->address_taken;
4482                 assert(!is_type_array(type));
4483                 if(is_type_compound(type)) {
4484                         needs_entity = true;
4485                 }
4486
4487                 if(needs_entity) {
4488                         ir_entity *entity = get_method_value_param_ent(function_irtype, n);
4489                         ident     *id     = new_id_from_str(parameter->symbol->string);
4490                         set_entity_ident(entity, id);
4491
4492                         parameter->declaration_kind
4493                                 = DECLARATION_KIND_LOCAL_VARIABLE_ENTITY;
4494                         parameter->v.entity = entity;
4495                         continue;
4496                 }
4497
4498                 ir_mode *mode = get_ir_mode(parameter->type);
4499                 long     pn   = n;
4500                 ir_node *proj = new_r_Proj(irg, start_block, args, mode, pn);
4501
4502                 parameter->declaration_kind = DECLARATION_KIND_LOCAL_VARIABLE;
4503                 parameter->v.value_number   = next_value_number_function;
4504                 set_irg_loc_description(current_ir_graph, next_value_number_function, parameter);
4505                 ++next_value_number_function;
4506
4507                 set_value(parameter->v.value_number, proj);
4508         }
4509 }
4510
4511 /**
4512  * Handle additional decl modifiers for IR-graphs
4513  *
4514  * @param irg            the IR-graph
4515  * @param dec_modifiers  additional modifiers
4516  */
4517 static void handle_decl_modifier_irg(ir_graph_ptr irg, decl_modifiers_t decl_modifiers)
4518 {
4519         if (decl_modifiers & DM_NORETURN) {
4520                 /* TRUE if the declaration includes the Microsoft
4521                    __declspec(noreturn) specifier. */
4522                 set_irg_additional_property(irg, mtp_property_noreturn);
4523         }
4524         if (decl_modifiers & DM_NOTHROW) {
4525                 /* TRUE if the declaration includes the Microsoft
4526                    __declspec(nothrow) specifier. */
4527                 set_irg_additional_property(irg, mtp_property_nothrow);
4528         }
4529         if (decl_modifiers & DM_NAKED) {
4530                 /* TRUE if the declaration includes the Microsoft
4531                    __declspec(naked) specifier. */
4532                 set_irg_additional_property(irg, mtp_property_naked);
4533         }
4534         if (decl_modifiers & DM_FORCEINLINE) {
4535                 /* TRUE if the declaration includes the
4536                    Microsoft __forceinline specifier. */
4537                 set_irg_inline_property(irg, irg_inline_forced);
4538         }
4539         if (decl_modifiers & DM_NOINLINE) {
4540                 /* TRUE if the declaration includes the Microsoft
4541                    __declspec(noinline) specifier. */
4542                 set_irg_inline_property(irg, irg_inline_forbidden);
4543         }
4544 }
4545
4546 static void create_function(declaration_t *declaration)
4547 {
4548         ir_entity *function_entity = get_function_entity(declaration);
4549
4550         if(declaration->init.statement == NULL)
4551                 return;
4552
4553         current_function_decl = declaration;
4554         current_function_name = NULL;
4555
4556         assert(imature_blocks == NULL);
4557         imature_blocks = NEW_ARR_F(ir_node*, 0);
4558
4559         int       n_local_vars = get_function_n_local_vars(declaration);
4560         ir_graph *irg          = new_ir_graph(function_entity, n_local_vars);
4561         ir_node  *first_block  = get_cur_block();
4562
4563         /* set inline flags */
4564         if (declaration->is_inline)
4565         set_irg_inline_property(irg, irg_inline_recomended);
4566     handle_decl_modifier_irg(irg, declaration->modifiers);
4567
4568         next_value_number_function = 0;
4569         initialize_function_parameters(declaration);
4570
4571         statement_to_firm(declaration->init.statement);
4572
4573         ir_node *end_block = get_irg_end_block(irg);
4574
4575         /* do we have a return statement yet? */
4576         if(get_cur_block() != NULL) {
4577                 type_t *type = skip_typeref(declaration->type);
4578                 assert(is_type_function(type));
4579                 const function_type_t *func_type   = &type->function;
4580                 const type_t          *return_type
4581                         = skip_typeref(func_type->return_type);
4582
4583                 ir_node *ret;
4584                 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
4585                         ret = new_Return(get_store(), 0, NULL);
4586                 } else {
4587                         ir_mode *mode;
4588                         if(is_type_scalar(return_type)) {
4589                                 mode = get_ir_mode(func_type->return_type);
4590                         } else {
4591                                 mode = mode_P_data;
4592                         }
4593
4594                         ir_node *in[1];
4595                         /* ยง5.1.2.2.3 main implicitly returns 0 */
4596                         if (strcmp(declaration->symbol->string, "main") == 0) {
4597                                 in[0] = new_Const(mode, get_mode_null(mode));
4598                         } else {
4599                                 in[0] = new_Unknown(mode);
4600                         }
4601                         ret = new_Return(get_store(), 1, in);
4602                 }
4603                 add_immBlock_pred(end_block, ret);
4604         }
4605
4606         for(int i = 0; i < ARR_LEN(imature_blocks); ++i) {
4607                 mature_immBlock(imature_blocks[i]);
4608         }
4609         DEL_ARR_F(imature_blocks);
4610         imature_blocks = NULL;
4611
4612         mature_immBlock(first_block);
4613         mature_immBlock(end_block);
4614
4615         irg_finalize_cons(irg);
4616
4617         /* finalize the frame type */
4618         ir_type *frame_type = get_irg_frame_type(irg);
4619         int      n          = get_compound_n_members(frame_type);
4620         int      align_all  = 4;
4621         int      offset     = 0;
4622         for(int i = 0; i < n; ++i) {
4623                 ir_entity *entity      = get_compound_member(frame_type, i);
4624                 ir_type   *entity_type = get_entity_type(entity);
4625
4626                 int align = get_type_alignment_bytes(entity_type);
4627                 if(align > align_all)
4628                         align_all = align;
4629                 int misalign = 0;
4630                 if(align > 0) {
4631                         misalign  = offset % align;
4632                         if(misalign > 0) {
4633                                 offset += align - misalign;
4634                         }
4635                 }
4636
4637                 set_entity_offset(entity, offset);
4638                 offset += get_type_size_bytes(entity_type);
4639         }
4640         set_type_size_bytes(frame_type, offset);
4641         set_type_alignment_bytes(frame_type, align_all);
4642
4643         irg_vrfy(irg);
4644 }
4645
4646 static void scope_to_firm(scope_t *scope)
4647 {
4648         /* first pass: create declarations */
4649         declaration_t *declaration = scope->declarations;
4650         for( ; declaration != NULL; declaration = declaration->next) {
4651                 if(declaration->namespc != NAMESPACE_NORMAL)
4652                         continue;
4653                 if(declaration->storage_class == STORAGE_CLASS_ENUM_ENTRY
4654                                 || declaration->storage_class == STORAGE_CLASS_TYPEDEF)
4655                         continue;
4656                 if(declaration->symbol == NULL)
4657                         continue;
4658
4659                 type_t *type = skip_typeref(declaration->type);
4660                 if(is_type_function(type)) {
4661                         get_function_entity(declaration);
4662                 } else {
4663                         create_global_variable(declaration);
4664                 }
4665         }
4666
4667         /* second pass: create code/initializers */
4668         declaration = scope->declarations;
4669         for( ; declaration != NULL; declaration = declaration->next) {
4670                 if(declaration->namespc != NAMESPACE_NORMAL)
4671                         continue;
4672                 if(declaration->storage_class == STORAGE_CLASS_ENUM_ENTRY
4673                                 || declaration->storage_class == STORAGE_CLASS_TYPEDEF)
4674                         continue;
4675                 if(declaration->symbol == NULL)
4676                         continue;
4677
4678                 type_t *type = declaration->type;
4679                 if(type->kind == TYPE_FUNCTION) {
4680                         create_function(declaration);
4681                 } else {
4682                         assert(declaration->declaration_kind
4683                                         == DECLARATION_KIND_GLOBAL_VARIABLE);
4684                         current_ir_graph = get_const_code_irg();
4685                         create_declaration_initializer(declaration);
4686                 }
4687         }
4688 }
4689
4690 void init_ast2firm(void)
4691 {
4692         obstack_init(&asm_obst);
4693         init_atomic_modes();
4694
4695         /* create idents for all known runtime functions */
4696         for (size_t i = 0; i < sizeof(rts_data) / sizeof(rts_data[0]); ++i) {
4697                 predef_idents[rts_data[i].id] = new_id_from_str(rts_data[i].name);
4698         }
4699 }
4700
4701 static void init_ir_types(void)
4702 {
4703         static int ir_types_initialized = 0;
4704         if(ir_types_initialized)
4705                 return;
4706         ir_types_initialized = 1;
4707
4708         type_const_char = make_atomic_type(ATOMIC_TYPE_CHAR, TYPE_QUALIFIER_CONST);
4709         type_void       = make_atomic_type(ATOMIC_TYPE_VOID, TYPE_QUALIFIER_NONE);
4710         type_int        = make_atomic_type(ATOMIC_TYPE_INT,  TYPE_QUALIFIER_NONE);
4711
4712         ir_type_int        = get_ir_type(type_int);
4713         ir_type_const_char = get_ir_type(type_const_char);
4714         ir_type_wchar_t    = get_ir_type(type_wchar_t);
4715         ir_type_void       = get_ir_type(type_int); /* we don't have a real void
4716                                                        type in firm */
4717
4718         type_void->base.firm_type = ir_type_void;
4719 }
4720
4721 void exit_ast2firm(void)
4722 {
4723         obstack_free(&asm_obst, NULL);
4724 }
4725
4726 void translation_unit_to_firm(translation_unit_t *unit)
4727 {
4728         /* just to be sure */
4729         continue_label      = NULL;
4730         break_label         = NULL;
4731         current_switch_cond = NULL;
4732
4733         init_ir_types();
4734
4735         scope_to_firm(&unit->scope);
4736 }