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