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