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