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