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