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