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