Simplify macro mumbo jumbo.
[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
1448                 if (entity->function.btk != bk_none) {
1449                         /* for gcc compatibility we have to produce (dummy) addresses for some
1450                          * builtins */
1451                         if (warning.other) {
1452                                 warningf(&ref->base.source_position,
1453                                         "taking address of builtin '%Y'", ref->entity->base.symbol);
1454                         }
1455
1456                         /* simply create a NULL pointer */
1457                         ir_mode  *mode = get_ir_mode_arithmetic(type_void_ptr);
1458                         ir_node  *res  = new_Const_long(mode, 0);
1459
1460                         return res;
1461                 }
1462                 return create_symconst(dbgi, mode, entity->function.entity);
1463         }
1464         case DECLARATION_KIND_INNER_FUNCTION: {
1465                 ir_mode *const mode = get_ir_mode_storage(type);
1466                 if (!entity->function.goto_to_outer && !entity->function.need_closure) {
1467                         /* inner function not using the closure */
1468                         return create_symconst(dbgi, mode, entity->function.entity);
1469                 } else {
1470                         /* TODO: need trampoline here */
1471                         panic("Trampoline code not implemented");
1472                         return create_symconst(dbgi, mode, entity->function.entity);
1473                 }
1474         }
1475         case DECLARATION_KIND_GLOBAL_VARIABLE: {
1476                 ir_node *const addr = get_global_var_address(dbgi, entity);
1477                 return deref_address(dbgi, entity->declaration.type, addr);
1478         }
1479
1480         case DECLARATION_KIND_LOCAL_VARIABLE_ENTITY: {
1481                 ir_entity *irentity = entity->variable.v.entity;
1482                 ir_node   *frame    = get_local_frame(irentity);
1483                 ir_node   *sel = new_d_simpleSel(dbgi, new_NoMem(), frame, irentity);
1484                 return deref_address(dbgi, entity->declaration.type, sel);
1485         }
1486         case DECLARATION_KIND_PARAMETER_ENTITY: {
1487                 ir_entity *irentity = entity->parameter.v.entity;
1488                 ir_node   *frame    = get_local_frame(irentity);
1489                 ir_node   *sel = new_d_simpleSel(dbgi, new_NoMem(), frame, irentity);
1490                 return deref_address(dbgi, entity->declaration.type, sel);
1491         }
1492
1493         case DECLARATION_KIND_VARIABLE_LENGTH_ARRAY:
1494                 return entity->variable.v.vla_base;
1495
1496         case DECLARATION_KIND_COMPOUND_MEMBER:
1497                 panic("not implemented reference type");
1498         }
1499
1500         panic("reference to declaration with unknown type found");
1501 }
1502
1503 static ir_node *reference_addr(const reference_expression_t *ref)
1504 {
1505         dbg_info *dbgi   = get_dbg_info(&ref->base.source_position);
1506         entity_t *entity = ref->entity;
1507         assert(is_declaration(entity));
1508
1509         switch((declaration_kind_t) entity->declaration.kind) {
1510         case DECLARATION_KIND_UNKNOWN:
1511                 break;
1512         case DECLARATION_KIND_PARAMETER:
1513         case DECLARATION_KIND_LOCAL_VARIABLE:
1514                 /* you can store to a local variable (so we don't panic but return NULL
1515                  * as an indicator for no real address) */
1516                 return NULL;
1517         case DECLARATION_KIND_GLOBAL_VARIABLE: {
1518                 ir_node *const addr = get_global_var_address(dbgi, entity);
1519                 return addr;
1520         }
1521         case DECLARATION_KIND_LOCAL_VARIABLE_ENTITY: {
1522                 ir_entity *irentity = entity->variable.v.entity;
1523                 ir_node   *frame    = get_local_frame(irentity);
1524                 ir_node   *sel = new_d_simpleSel(dbgi, new_NoMem(), frame, irentity);
1525
1526                 return sel;
1527         }
1528         case DECLARATION_KIND_PARAMETER_ENTITY: {
1529                 ir_entity *irentity = entity->parameter.v.entity;
1530                 ir_node   *frame    = get_local_frame(irentity);
1531                 ir_node   *sel = new_d_simpleSel(dbgi, new_NoMem(), frame, irentity);
1532
1533                 return sel;
1534         }
1535
1536         case DECLARATION_KIND_VARIABLE_LENGTH_ARRAY:
1537                 return entity->variable.v.vla_base;
1538
1539         case DECLARATION_KIND_FUNCTION: {
1540                 type_t  *const type = skip_typeref(entity->declaration.type);
1541                 ir_mode *const mode = get_ir_mode_storage(type);
1542                 return create_symconst(dbgi, mode, entity->function.entity);
1543         }
1544
1545         case DECLARATION_KIND_INNER_FUNCTION:
1546         case DECLARATION_KIND_COMPOUND_MEMBER:
1547                 panic("not implemented reference type");
1548         }
1549
1550         panic("reference to declaration with unknown type found");
1551 }
1552
1553 /**
1554  * Generate an unary builtin.
1555  *
1556  * @param kind           the builtin kind to generate
1557  * @param op             the operand
1558  * @param function_type  the function type for the GNU builtin routine
1559  * @param db             debug info
1560  */
1561 static ir_node *gen_unary_builtin(ir_builtin_kind kind, expression_t *op, type_t *function_type, dbg_info *db)
1562 {
1563         ir_node *in[1];
1564         in[0] = expression_to_firm(op);
1565
1566         ir_type *tp  = get_ir_type(function_type);
1567         ir_type *res = get_method_res_type(tp, 0);
1568         ir_node *irn = new_d_Builtin(db, get_irg_no_mem(current_ir_graph), kind, 1, in, tp);
1569         set_irn_pinned(irn, op_pin_state_floats);
1570         return new_Proj(irn, get_type_mode(res), pn_Builtin_1_result);
1571 }
1572
1573 /**
1574  * Generate a pinned unary builtin.
1575  *
1576  * @param kind           the builtin kind to generate
1577  * @param op             the operand
1578  * @param function_type  the function type for the GNU builtin routine
1579  * @param db             debug info
1580  */
1581 static ir_node *gen_unary_builtin_pinned(ir_builtin_kind kind, expression_t *op, type_t *function_type, dbg_info *db)
1582 {
1583         ir_node *in[1];
1584         in[0] = expression_to_firm(op);
1585
1586         ir_type *tp  = get_ir_type(function_type);
1587         ir_type *res = get_method_res_type(tp, 0);
1588         ir_node *mem = get_store();
1589         ir_node *irn = new_d_Builtin(db, mem, kind, 1, in, tp);
1590         set_store(new_Proj(irn, mode_M, pn_Builtin_M));
1591         return new_Proj(irn, get_type_mode(res), pn_Builtin_1_result);
1592 }
1593
1594
1595 /**
1596  * Generate an binary-void-return builtin.
1597  *
1598  * @param kind           the builtin kind to generate
1599  * @param op1            the first operand
1600  * @param op2            the second operand
1601  * @param function_type  the function type for the GNU builtin routine
1602  * @param db             debug info
1603  */
1604 static ir_node *gen_binary_builtin_mem(ir_builtin_kind kind, expression_t *op1, expression_t *op2,
1605                                                                            type_t *function_type, dbg_info *db)
1606 {
1607         ir_node *in[2];
1608         in[0] = expression_to_firm(op1);
1609         in[1] = expression_to_firm(op2);
1610
1611         ir_type *tp  = get_ir_type(function_type);
1612         ir_node *mem = get_store();
1613         ir_node *irn = new_d_Builtin(db, mem, kind, 2, in, tp);
1614         set_store(new_Proj(irn, mode_M, pn_Builtin_M));
1615         return NULL;
1616 }
1617
1618 /**
1619  * Transform calls to builtin functions.
1620  */
1621 static ir_node *process_builtin_call(const call_expression_t *call)
1622 {
1623         dbg_info *dbgi = get_dbg_info(&call->base.source_position);
1624
1625         assert(call->function->kind == EXPR_REFERENCE);
1626         reference_expression_t *builtin = &call->function->reference;
1627
1628         type_t *type = skip_typeref(builtin->base.type);
1629         assert(is_type_pointer(type));
1630
1631         type_t   *function_type = skip_typeref(type->pointer.points_to);
1632
1633         switch (builtin->entity->function.btk) {
1634         case bk_gnu_builtin_alloca: {
1635                 if (call->arguments == NULL || call->arguments->next != NULL) {
1636                         panic("invalid number of parameters on __builtin_alloca");
1637                 }
1638                 expression_t *argument = call->arguments->expression;
1639                 ir_node      *size     = expression_to_firm(argument);
1640
1641                 ir_node *store  = get_store();
1642                 ir_node *alloca = new_d_Alloc(dbgi, store, size, firm_unknown_type,
1643                                               stack_alloc);
1644                 ir_node *proj_m = new_Proj(alloca, mode_M, pn_Alloc_M);
1645                 set_store(proj_m);
1646                 ir_node *res    = new_Proj(alloca, mode_P_data, pn_Alloc_res);
1647
1648                 return res;
1649         }
1650
1651         case bk_gnu_builtin_huge_val:
1652         case bk_gnu_builtin_inf:
1653         case bk_gnu_builtin_inff:
1654         case bk_gnu_builtin_infl: {
1655                 type_t  *type = function_type->function.return_type;
1656                 ir_mode *mode = get_ir_mode_arithmetic(type);
1657                 tarval  *tv   = get_mode_infinite(mode);
1658                 ir_node *res  = new_d_Const(dbgi, tv);
1659                 return   res;
1660         }
1661         case bk_gnu_builtin_nan:
1662         case bk_gnu_builtin_nanf:
1663         case bk_gnu_builtin_nanl: {
1664                 /* Ignore string for now... */
1665                 assert(is_type_function(function_type));
1666                 type_t  *type = function_type->function.return_type;
1667                 ir_mode *mode = get_ir_mode_arithmetic(type);
1668                 tarval  *tv   = get_mode_NAN(mode);
1669                 ir_node *res  = new_d_Const(dbgi, tv);
1670                 return res;
1671         }
1672         case bk_gnu_builtin_expect: {
1673                 expression_t *argument = call->arguments->expression;
1674                 return _expression_to_firm(argument);
1675         }
1676         case bk_gnu_builtin_va_end:
1677                 /* evaluate the argument of va_end for its side effects */
1678                 _expression_to_firm(call->arguments->expression);
1679                 return NULL;
1680         case bk_gnu_builtin_frame_address: {
1681                 expression_t *const expression = call->arguments->expression;
1682                 long val = fold_constant(expression);
1683                 if (val == 0) {
1684                         /* the nice case */
1685                         return get_irg_frame(current_ir_graph);
1686                 } else {
1687                         /* get the argument */
1688                         ir_node *in[2];
1689
1690                         in[0] = expression_to_firm(expression);
1691                         in[1] = get_irg_frame(current_ir_graph);
1692                         ir_type *tp  = get_ir_type(function_type);
1693                         ir_node *irn = new_d_Builtin(dbgi, get_irg_no_mem(current_ir_graph), ir_bk_frame_addess, 2, in, tp);
1694                         return new_Proj(irn, mode_P_data, pn_Builtin_1_result);
1695                 }
1696         }
1697         case bk_gnu_builtin_return_address: {
1698                 expression_t *const expression = call->arguments->expression;
1699                 ir_node *in[2];
1700
1701                 in[0] = expression_to_firm(expression);
1702                 in[1] = get_irg_frame(current_ir_graph);
1703                 ir_type *tp  = get_ir_type(function_type);
1704                 ir_node *irn = new_d_Builtin(dbgi, get_irg_no_mem(current_ir_graph), ir_bk_return_address, 2, in, tp);
1705                 return new_Proj(irn, mode_P_data, pn_Builtin_1_result);
1706         }
1707         case bk_gnu_builtin_ffs:
1708                  return gen_unary_builtin(ir_bk_ffs,      call->arguments->expression, function_type, dbgi);
1709         case bk_gnu_builtin_clz:
1710                  return gen_unary_builtin(ir_bk_clz,      call->arguments->expression, function_type, dbgi);
1711         case bk_gnu_builtin_ctz:
1712                  return gen_unary_builtin(ir_bk_ctz,      call->arguments->expression, function_type, dbgi);
1713         case bk_gnu_builtin_popcount:
1714         case bk_ms__popcount:
1715                  return gen_unary_builtin(ir_bk_popcount, call->arguments->expression, function_type, dbgi);
1716         case bk_gnu_builtin_parity:
1717                  return gen_unary_builtin(ir_bk_parity,   call->arguments->expression, function_type, dbgi);
1718         case bk_gnu_builtin_prefetch: {
1719                 call_argument_t *const args = call->arguments;
1720                 expression_t *const addr    = args->expression;
1721                 ir_node *in[3];
1722
1723                 in[0] = _expression_to_firm(addr);
1724                 if (args->next != NULL) {
1725                         expression_t *const rw = args->next->expression;
1726
1727                         in[1] = _expression_to_firm(rw);
1728
1729                         if (args->next->next != NULL) {
1730                                 expression_t *const locality = args->next->next->expression;
1731
1732                                 in[2] = expression_to_firm(locality);
1733                         } else {
1734                                 in[2] = new_Const_long(mode_int, 3);
1735                         }
1736                 } else {
1737                         in[1] = new_Const_long(mode_int, 0);
1738                         in[2] = new_Const_long(mode_int, 3);
1739                 }
1740                 ir_type *tp  = get_ir_type(function_type);
1741                 ir_node *irn = new_d_Builtin(dbgi, get_store(), ir_bk_prefetch, 3, in, tp);
1742                 set_store(new_Proj(irn, mode_M, pn_Builtin_M));
1743                 return NULL;
1744         }
1745         case bk_gnu_builtin_trap:
1746         case bk_ms__ud2:
1747         {
1748                 ir_type *tp  = get_ir_type(function_type);
1749                 ir_node *irn = new_d_Builtin(dbgi, get_store(), ir_bk_trap, 0, NULL, tp);
1750                 set_store(new_Proj(irn, mode_M, pn_Builtin_M));
1751                 return NULL;
1752         }
1753         case bk_ms__debugbreak: {
1754                 ir_type *tp  = get_ir_type(function_type);
1755                 ir_node *irn = new_d_Builtin(dbgi, get_store(), ir_bk_debugbreak, 0, NULL, tp);
1756                 set_store(new_Proj(irn, mode_M, pn_Builtin_M));
1757                 return NULL;
1758         }
1759         case bk_ms_ReturnAddress: {
1760                 ir_node *in[2];
1761
1762                 in[0] = new_Const_long(mode_int, 0);
1763                 in[1] = get_irg_frame(current_ir_graph);
1764                 ir_type *tp  = get_ir_type(function_type);
1765                 ir_node *irn = new_d_Builtin(dbgi, get_irg_no_mem(current_ir_graph), ir_bk_return_address, 2, in, tp);
1766                 return new_Proj(irn, mode_P_data, pn_Builtin_1_result);
1767         }
1768         case bk_ms_rotl:
1769         case bk_ms_rotl64: {
1770                 ir_node *val  = expression_to_firm(call->arguments->expression);
1771                 ir_node *shf  = expression_to_firm(call->arguments->next->expression);
1772                 ir_mode *mode = get_irn_mode(val);
1773                 return new_d_Rotl(dbgi, val, create_conv(dbgi, shf, mode_uint), mode);
1774         }
1775         case bk_ms_rotr:
1776         case bk_ms_rotr64: {
1777                 ir_node *val  = expression_to_firm(call->arguments->expression);
1778                 ir_node *shf  = expression_to_firm(call->arguments->next->expression);
1779                 ir_mode *mode = get_irn_mode(val);
1780                 ir_node *c    = new_Const_long(mode_uint, get_mode_size_bits(mode));
1781                 ir_node *sub  = new_d_Sub(dbgi, c, create_conv(dbgi, shf, mode_uint), mode_uint);
1782                 return new_d_Rotl(dbgi, val, sub, mode);
1783         }
1784         case bk_ms_byteswap_ushort:
1785         case bk_ms_byteswap_ulong:
1786         case bk_ms_byteswap_uint64:
1787                 return gen_unary_builtin(ir_bk_bswap, call->arguments->expression, function_type, dbgi);
1788         case bk_ms__inbyte:
1789         case bk_ms__inword:
1790         case bk_ms__indword:
1791                 return gen_unary_builtin_pinned(ir_bk_inport, call->arguments->expression, function_type, dbgi);
1792         case bk_ms__outbyte:
1793         case bk_ms__outword:
1794         case bk_ms__outdword:
1795                 return gen_binary_builtin_mem(ir_bk_outport, call->arguments->expression,
1796                         call->arguments->next->expression, function_type, dbgi);
1797         default:
1798                 panic("unsupported builtin found");
1799         }
1800 }
1801
1802 /**
1803  * Transform a call expression.
1804  * Handles some special cases, like alloca() calls, which must be resolved
1805  * BEFORE the inlines runs. Inlining routines calling alloca() is dangerous,
1806  * 176.gcc for instance might allocate 2GB instead of 256 MB if alloca is not
1807  * handled right...
1808  */
1809 static ir_node *call_expression_to_firm(const call_expression_t *const call)
1810 {
1811         dbg_info *const dbgi = get_dbg_info(&call->base.source_position);
1812         assert(get_cur_block() != NULL);
1813
1814         expression_t *function = call->function;
1815         if (function->kind == EXPR_REFERENCE) {
1816                 const reference_expression_t *ref    = &function->reference;
1817                 entity_t                     *entity = ref->entity;
1818
1819                 if (ref->entity->kind == ENTITY_FUNCTION &&
1820                     ref->entity->function.btk != bk_none) {
1821                         return process_builtin_call(call);
1822                 }
1823
1824                 if (entity->kind == ENTITY_FUNCTION
1825                                 && entity->function.entity == rts_entities[rts_alloca]) {
1826                         /* handle alloca() call */
1827                         expression_t *argument = call->arguments->expression;
1828                         ir_node      *size     = expression_to_firm(argument);
1829                         ir_mode      *mode     = get_ir_mode_arithmetic(type_size_t);
1830
1831                         size = create_conv(dbgi, size, mode);
1832
1833                         ir_node  *store  = get_store();
1834                         ir_node  *alloca = new_d_Alloc(dbgi, store, size, firm_unknown_type,
1835                                                        stack_alloc);
1836                         ir_node  *proj_m = new_Proj(alloca, mode_M, pn_Alloc_M);
1837                         set_store(proj_m);
1838                         ir_node  *res    = new_Proj(alloca, mode_P_data, pn_Alloc_res);
1839
1840                         return res;
1841                 }
1842         }
1843         ir_node *callee = expression_to_firm(function);
1844
1845         type_t *type = skip_typeref(function->base.type);
1846         assert(is_type_pointer(type));
1847         pointer_type_t *pointer_type = &type->pointer;
1848         type_t         *points_to    = skip_typeref(pointer_type->points_to);
1849         assert(is_type_function(points_to));
1850         function_type_t *function_type = &points_to->function;
1851
1852         int      n_parameters = 0;
1853         ir_type *ir_method_type  = get_ir_type((type_t*) function_type);
1854         ir_type *new_method_type = NULL;
1855         if (function_type->variadic || function_type->unspecified_parameters) {
1856                 const call_argument_t *argument = call->arguments;
1857                 for ( ; argument != NULL; argument = argument->next) {
1858                         ++n_parameters;
1859                 }
1860
1861                 /* we need to construct a new method type matching the call
1862                  * arguments... */
1863                 int n_res       = get_method_n_ress(ir_method_type);
1864                 new_method_type = new_d_type_method(id_unique("calltype.%u"),
1865                                                     n_parameters, n_res, dbgi);
1866                 set_method_calling_convention(new_method_type,
1867                                get_method_calling_convention(ir_method_type));
1868                 set_method_additional_properties(new_method_type,
1869                                get_method_additional_properties(ir_method_type));
1870                 set_method_variadicity(new_method_type,
1871                                        get_method_variadicity(ir_method_type));
1872
1873                 for (int i = 0; i < n_res; ++i) {
1874                         set_method_res_type(new_method_type, i,
1875                                             get_method_res_type(ir_method_type, i));
1876                 }
1877                 argument = call->arguments;
1878                 for (int i = 0; i < n_parameters; ++i, argument = argument->next) {
1879                         expression_t *expression = argument->expression;
1880                         ir_type      *irtype     = get_ir_type(expression->base.type);
1881                         set_method_param_type(new_method_type, i, irtype);
1882                 }
1883                 ir_method_type = new_method_type;
1884         } else {
1885                 n_parameters = get_method_n_params(ir_method_type);
1886         }
1887
1888         ir_node *in[n_parameters];
1889
1890         const call_argument_t *argument = call->arguments;
1891         for (int n = 0; n < n_parameters; ++n) {
1892                 expression_t *expression = argument->expression;
1893                 ir_node      *arg_node   = expression_to_firm(expression);
1894
1895                 type_t  *type = skip_typeref(expression->base.type);
1896                 if (!is_type_compound(type)) {
1897                         ir_mode *mode = get_ir_mode_storage(expression->base.type);
1898                         arg_node      = create_conv(dbgi, arg_node, mode);
1899                         arg_node      = do_strict_conv(dbgi, arg_node);
1900                 }
1901
1902                 in[n] = arg_node;
1903
1904                 argument = argument->next;
1905         }
1906
1907         ir_node  *store = get_store();
1908         ir_node  *node  = new_d_Call(dbgi, store, callee, n_parameters, in,
1909                                      ir_method_type);
1910         ir_node  *mem   = new_d_Proj(dbgi, node, mode_M, pn_Call_M_regular);
1911         set_store(mem);
1912
1913         type_t  *return_type = skip_typeref(function_type->return_type);
1914         ir_node *result      = NULL;
1915
1916         if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
1917                 ir_node *resproj = new_d_Proj(dbgi, node, mode_T, pn_Call_T_result);
1918
1919                 if (is_type_scalar(return_type)) {
1920                         ir_mode *mode       = get_ir_mode_storage(return_type);
1921                         result              = new_d_Proj(dbgi, resproj, mode, 0);
1922                         ir_mode *mode_arith = get_ir_mode_arithmetic(return_type);
1923                         result              = create_conv(NULL, result, mode_arith);
1924                 } else {
1925                         ir_mode *mode = mode_P_data;
1926                         result        = new_d_Proj(dbgi, resproj, mode, 0);
1927                 }
1928         }
1929
1930         if (function->kind == EXPR_REFERENCE &&
1931             function->reference.entity->declaration.modifiers & DM_NORETURN) {
1932                 /* A dead end:  Keep the Call and the Block.  Also place all further
1933                  * nodes into a new and unreachable block. */
1934                 keep_alive(node);
1935                 keep_alive(get_cur_block());
1936                 new_Block(0, NULL);
1937         }
1938
1939         return result;
1940 }
1941
1942 static void statement_to_firm(statement_t *statement);
1943 static ir_node *compound_statement_to_firm(compound_statement_t *compound);
1944
1945 static ir_node *expression_to_addr(const expression_t *expression);
1946 static ir_node *create_condition_evaluation(const expression_t *expression,
1947                                             ir_node *true_block,
1948                                             ir_node *false_block);
1949
1950 static void assign_value(dbg_info *dbgi, ir_node *addr, type_t *type,
1951                          ir_node *value)
1952 {
1953         if (!is_type_compound(type)) {
1954                 ir_mode *mode = get_ir_mode_storage(type);
1955                 value         = create_conv(dbgi, value, mode);
1956                 value         = do_strict_conv(dbgi, value);
1957         }
1958
1959         ir_node *memory = get_store();
1960
1961         if (is_type_scalar(type)) {
1962                 ir_cons_flags flags = type->base.qualifiers & TYPE_QUALIFIER_VOLATILE
1963                                       ? cons_volatile : cons_none;
1964                 ir_node  *store     = new_d_Store(dbgi, memory, addr, value, flags);
1965                 ir_node  *store_mem = new_d_Proj(dbgi, store, mode_M, pn_Store_M);
1966                 set_store(store_mem);
1967         } else {
1968                 ir_type *irtype    = get_ir_type(type);
1969                 ir_node *copyb     = new_d_CopyB(dbgi, memory, addr, value, irtype);
1970                 ir_node *copyb_mem = new_Proj(copyb, mode_M, pn_CopyB_M_regular);
1971                 set_store(copyb_mem);
1972         }
1973 }
1974
1975 static tarval *create_bitfield_mask(ir_mode *mode, int offset, int size)
1976 {
1977         tarval *all_one   = get_mode_all_one(mode);
1978         int     mode_size = get_mode_size_bits(mode);
1979
1980         assert(offset >= 0);
1981         assert(size   >= 0);
1982         assert(offset + size <= mode_size);
1983         if (size == mode_size) {
1984                 return all_one;
1985         }
1986
1987         long    shiftr    = get_mode_size_bits(mode) - size;
1988         long    shiftl    = offset;
1989         tarval *tv_shiftr = new_tarval_from_long(shiftr, mode_uint);
1990         tarval *tv_shiftl = new_tarval_from_long(shiftl, mode_uint);
1991         tarval *mask0     = tarval_shr(all_one, tv_shiftr);
1992         tarval *mask1     = tarval_shl(mask0, tv_shiftl);
1993
1994         return mask1;
1995 }
1996
1997 static ir_node *bitfield_store_to_firm(dbg_info *dbgi,
1998                 ir_entity *entity, ir_node *addr, ir_node *value, bool set_volatile)
1999 {
2000         ir_type *entity_type = get_entity_type(entity);
2001         ir_type *base_type   = get_primitive_base_type(entity_type);
2002         assert(base_type != NULL);
2003         ir_mode *mode        = get_type_mode(base_type);
2004
2005         value = create_conv(dbgi, value, mode);
2006
2007         /* kill upper bits of value and shift to right position */
2008         int      bitoffset    = get_entity_offset_bits_remainder(entity);
2009         int      bitsize      = get_mode_size_bits(get_type_mode(entity_type));
2010
2011         tarval  *mask            = create_bitfield_mask(mode, 0, bitsize);
2012         ir_node *mask_node       = new_d_Const(dbgi, mask);
2013         ir_node *value_masked    = new_d_And(dbgi, value, mask_node, mode);
2014         tarval  *shiftl          = new_tarval_from_long(bitoffset, mode_uint);
2015         ir_node *shiftcount      = new_d_Const(dbgi, shiftl);
2016         ir_node *value_maskshift = new_d_Shl(dbgi, value_masked, shiftcount, mode);
2017
2018         /* load current value */
2019         ir_node  *mem             = get_store();
2020         ir_node  *load            = new_d_Load(dbgi, mem, addr, mode,
2021                                         set_volatile ? cons_volatile : cons_none);
2022         ir_node  *load_mem        = new_d_Proj(dbgi, load, mode_M, pn_Load_M);
2023         ir_node  *load_res        = new_d_Proj(dbgi, load, mode, pn_Load_res);
2024         tarval   *shift_mask      = create_bitfield_mask(mode, bitoffset, bitsize);
2025         tarval   *inv_mask        = tarval_not(shift_mask);
2026         ir_node  *inv_mask_node   = new_d_Const(dbgi, inv_mask);
2027         ir_node  *load_res_masked = new_d_And(dbgi, load_res, inv_mask_node, mode);
2028
2029         /* construct new value and store */
2030         ir_node *new_val   = new_d_Or(dbgi, load_res_masked, value_maskshift, mode);
2031         ir_node *store     = new_d_Store(dbgi, load_mem, addr, new_val,
2032                                          set_volatile ? cons_volatile : cons_none);
2033         ir_node *store_mem = new_d_Proj(dbgi, store, mode_M, pn_Store_M);
2034         set_store(store_mem);
2035
2036         return value_masked;
2037 }
2038
2039 static ir_node *bitfield_extract_to_firm(const select_expression_t *expression,
2040                 ir_node *addr)
2041 {
2042         dbg_info *dbgi     = get_dbg_info(&expression->base.source_position);
2043         type_t   *type     = expression->base.type;
2044         ir_mode  *mode     = get_ir_mode_storage(type);
2045         ir_node  *mem      = get_store();
2046         ir_node  *load     = new_d_Load(dbgi, mem, addr, mode, cons_none);
2047         ir_node  *load_mem = new_d_Proj(dbgi, load, mode_M, pn_Load_M);
2048         ir_node  *load_res = new_d_Proj(dbgi, load, mode, pn_Load_res);
2049
2050         load_res           = create_conv(dbgi, load_res, mode_int);
2051
2052         set_store(load_mem);
2053
2054         /* kill upper bits */
2055         assert(expression->compound_entry->kind == ENTITY_COMPOUND_MEMBER);
2056         ir_entity *entity       = expression->compound_entry->compound_member.entity;
2057         int        bitoffset    = get_entity_offset_bits_remainder(entity);
2058         ir_type   *entity_type  = get_entity_type(entity);
2059         int        bitsize      = get_mode_size_bits(get_type_mode(entity_type));
2060         long       shift_bitsl  = machine_size - bitoffset - bitsize;
2061         assert(shift_bitsl >= 0);
2062         tarval    *tvl          = new_tarval_from_long(shift_bitsl, mode_uint);
2063         ir_node   *countl       = new_d_Const(dbgi, tvl);
2064         ir_node   *shiftl       = new_d_Shl(dbgi, load_res, countl, mode_int);
2065
2066         long       shift_bitsr  = bitoffset + shift_bitsl;
2067         assert(shift_bitsr <= (long) machine_size);
2068         tarval    *tvr          = new_tarval_from_long(shift_bitsr, mode_uint);
2069         ir_node   *countr       = new_d_Const(dbgi, tvr);
2070         ir_node   *shiftr;
2071         if (mode_is_signed(mode)) {
2072                 shiftr = new_d_Shrs(dbgi, shiftl, countr, mode_int);
2073         } else {
2074                 shiftr = new_d_Shr(dbgi, shiftl, countr, mode_int);
2075         }
2076
2077         return create_conv(dbgi, shiftr, mode);
2078 }
2079
2080 /* make sure the selected compound type is constructed */
2081 static void construct_select_compound(const select_expression_t *expression)
2082 {
2083         type_t *type = skip_typeref(expression->compound->base.type);
2084         if (is_type_pointer(type)) {
2085                 type = type->pointer.points_to;
2086         }
2087         (void) get_ir_type(type);
2088 }
2089
2090 static ir_node *set_value_for_expression_addr(const expression_t *expression,
2091                                               ir_node *value, ir_node *addr)
2092 {
2093         dbg_info *dbgi = get_dbg_info(&expression->base.source_position);
2094         type_t   *type = skip_typeref(expression->base.type);
2095
2096         if (!is_type_compound(type)) {
2097                 ir_mode  *mode = get_ir_mode_storage(type);
2098                 value          = create_conv(dbgi, value, mode);
2099                 value          = do_strict_conv(dbgi, value);
2100         }
2101
2102         if (expression->kind == EXPR_REFERENCE) {
2103                 const reference_expression_t *ref = &expression->reference;
2104
2105                 entity_t *entity = ref->entity;
2106                 assert(is_declaration(entity));
2107                 assert(entity->declaration.kind != DECLARATION_KIND_UNKNOWN);
2108                 if (entity->declaration.kind == DECLARATION_KIND_LOCAL_VARIABLE) {
2109                         set_value(entity->variable.v.value_number, value);
2110                         return value;
2111                 } else if (entity->declaration.kind == DECLARATION_KIND_PARAMETER) {
2112                         set_value(entity->parameter.v.value_number, value);
2113                         return value;
2114                 }
2115         }
2116
2117         if (addr == NULL)
2118                 addr = expression_to_addr(expression);
2119         assert(addr != NULL);
2120
2121         if (expression->kind == EXPR_SELECT) {
2122                 const select_expression_t *select = &expression->select;
2123
2124                 construct_select_compound(select);
2125
2126                 entity_t *entity = select->compound_entry;
2127                 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
2128                 if (entity->declaration.type->kind == TYPE_BITFIELD) {
2129                         ir_entity *irentity = entity->compound_member.entity;
2130                         bool       set_volatile
2131                                 = select->base.type->base.qualifiers & TYPE_QUALIFIER_VOLATILE;
2132                         value = bitfield_store_to_firm(dbgi, irentity, addr, value,
2133                                                        set_volatile);
2134                         return value;
2135                 }
2136         }
2137
2138         assign_value(dbgi, addr, type, value);
2139         return value;
2140 }
2141
2142 static void set_value_for_expression(const expression_t *expression,
2143                                      ir_node *value)
2144 {
2145         set_value_for_expression_addr(expression, value, NULL);
2146 }
2147
2148 static ir_node *get_value_from_lvalue(const expression_t *expression,
2149                                       ir_node *addr)
2150 {
2151         if (expression->kind == EXPR_REFERENCE) {
2152                 const reference_expression_t *ref = &expression->reference;
2153
2154                 entity_t *entity = ref->entity;
2155                 assert(entity->kind == ENTITY_VARIABLE
2156                                 || entity->kind == ENTITY_PARAMETER);
2157                 assert(entity->declaration.kind != DECLARATION_KIND_UNKNOWN);
2158                 int value_number;
2159                 if (entity->declaration.kind == DECLARATION_KIND_LOCAL_VARIABLE) {
2160                         value_number = entity->variable.v.value_number;
2161                         assert(addr == NULL);
2162                         type_t  *type = skip_typeref(expression->base.type);
2163                         ir_mode *mode = get_ir_mode_storage(type);
2164                         ir_node *res  = get_value(value_number, mode);
2165                         return create_conv(NULL, res, get_ir_mode_arithmetic(type));
2166                 } else if (entity->declaration.kind == DECLARATION_KIND_PARAMETER) {
2167                         value_number = entity->parameter.v.value_number;
2168                         assert(addr == NULL);
2169                         type_t  *type = skip_typeref(expression->base.type);
2170                         ir_mode *mode = get_ir_mode_storage(type);
2171                         ir_node *res  = get_value(value_number, mode);
2172                         return create_conv(NULL, res, get_ir_mode_arithmetic(type));
2173                 }
2174         }
2175
2176         assert(addr != NULL);
2177         dbg_info *dbgi = get_dbg_info(&expression->base.source_position);
2178
2179         ir_node *value;
2180         if (expression->kind == EXPR_SELECT &&
2181             expression->select.compound_entry->declaration.type->kind == TYPE_BITFIELD){
2182             construct_select_compound(&expression->select);
2183                 value = bitfield_extract_to_firm(&expression->select, addr);
2184         } else {
2185                 value = deref_address(dbgi, expression->base.type, addr);
2186         }
2187
2188         return value;
2189 }
2190
2191
2192 static ir_node *create_incdec(const unary_expression_t *expression)
2193 {
2194         dbg_info *const     dbgi = get_dbg_info(&expression->base.source_position);
2195         const expression_t *value_expr = expression->value;
2196         ir_node            *addr       = expression_to_addr(value_expr);
2197         ir_node            *value      = get_value_from_lvalue(value_expr, addr);
2198
2199         type_t  *type = skip_typeref(expression->base.type);
2200         ir_mode *mode = get_ir_mode_arithmetic(expression->base.type);
2201
2202         ir_node *offset;
2203         if (is_type_pointer(type)) {
2204                 pointer_type_t *pointer_type = &type->pointer;
2205                 offset                       = get_type_size(pointer_type->points_to);
2206         } else {
2207                 assert(is_type_arithmetic(type));
2208                 offset = new_Const(get_mode_one(mode));
2209         }
2210
2211         ir_node *result;
2212         ir_node *store_value;
2213         switch(expression->base.kind) {
2214         case EXPR_UNARY_POSTFIX_INCREMENT:
2215                 result      = value;
2216                 store_value = new_d_Add(dbgi, value, offset, mode);
2217                 break;
2218         case EXPR_UNARY_POSTFIX_DECREMENT:
2219                 result      = value;
2220                 store_value = new_d_Sub(dbgi, value, offset, mode);
2221                 break;
2222         case EXPR_UNARY_PREFIX_INCREMENT:
2223                 result      = new_d_Add(dbgi, value, offset, mode);
2224                 store_value = result;
2225                 break;
2226         case EXPR_UNARY_PREFIX_DECREMENT:
2227                 result      = new_d_Sub(dbgi, value, offset, mode);
2228                 store_value = result;
2229                 break;
2230         default:
2231                 panic("no incdec expr in create_incdec");
2232         }
2233
2234         set_value_for_expression_addr(value_expr, store_value, addr);
2235
2236         return result;
2237 }
2238
2239 static bool is_local_variable(expression_t *expression)
2240 {
2241         if (expression->kind != EXPR_REFERENCE)
2242                 return false;
2243         reference_expression_t *ref_expr = &expression->reference;
2244         entity_t               *entity   = ref_expr->entity;
2245         if (entity->kind != ENTITY_VARIABLE)
2246                 return false;
2247         assert(entity->declaration.kind != DECLARATION_KIND_UNKNOWN);
2248         return entity->declaration.kind == DECLARATION_KIND_LOCAL_VARIABLE;
2249 }
2250
2251 static pn_Cmp get_pnc(const expression_kind_t kind, type_t *const type)
2252 {
2253         switch(kind) {
2254         case EXPR_BINARY_EQUAL:         return pn_Cmp_Eq;
2255         case EXPR_BINARY_ISLESSGREATER: return pn_Cmp_Lg;
2256         case EXPR_BINARY_NOTEQUAL:
2257                 return is_type_float(skip_typeref(type)) ? pn_Cmp_Ne : pn_Cmp_Lg;
2258         case EXPR_BINARY_ISLESS:
2259         case EXPR_BINARY_LESS:          return pn_Cmp_Lt;
2260         case EXPR_BINARY_ISLESSEQUAL:
2261         case EXPR_BINARY_LESSEQUAL:     return pn_Cmp_Le;
2262         case EXPR_BINARY_ISGREATER:
2263         case EXPR_BINARY_GREATER:       return pn_Cmp_Gt;
2264         case EXPR_BINARY_ISGREATEREQUAL:
2265         case EXPR_BINARY_GREATEREQUAL:  return pn_Cmp_Ge;
2266         case EXPR_BINARY_ISUNORDERED:   return pn_Cmp_Uo;
2267
2268         default:
2269                 break;
2270         }
2271         panic("trying to get pn_Cmp from non-comparison binexpr type");
2272 }
2273
2274 /**
2275  * Handle the assume optimizer hint: check if a Confirm
2276  * node can be created.
2277  *
2278  * @param dbi    debug info
2279  * @param expr   the IL assume expression
2280  *
2281  * we support here only some simple cases:
2282  *  - var rel const
2283  *  - const rel val
2284  *  - var rel var
2285  */
2286 static ir_node *handle_assume_compare(dbg_info *dbi,
2287                                       const binary_expression_t *expression)
2288 {
2289         expression_t *op1 = expression->left;
2290         expression_t *op2 = expression->right;
2291         entity_t     *var2, *var = NULL;
2292         ir_node      *res = NULL;
2293         pn_Cmp        cmp_val;
2294
2295         cmp_val = get_pnc(expression->base.kind, op1->base.type);
2296
2297         if (is_local_variable(op1) && is_local_variable(op2)) {
2298         var  = op1->reference.entity;
2299             var2 = op2->reference.entity;
2300
2301                 type_t  *const type = skip_typeref(var->declaration.type);
2302                 ir_mode *const mode = get_ir_mode_storage(type);
2303
2304                 ir_node *const irn1 = get_value(var->variable.v.value_number, mode);
2305                 ir_node *const irn2 = get_value(var2->variable.v.value_number, mode);
2306
2307                 res = new_d_Confirm(dbi, irn2, irn1, get_inversed_pnc(cmp_val));
2308                 set_value(var2->variable.v.value_number, res);
2309
2310                 res = new_d_Confirm(dbi, irn1, irn2, cmp_val);
2311                 set_value(var->variable.v.value_number, res);
2312
2313                 return res;
2314         }
2315
2316         expression_t *con;
2317         if (is_local_variable(op1) && is_constant_expression(op2)) {
2318                 var = op1->reference.entity;
2319                 con = op2;
2320         } else if (is_constant_expression(op1) && is_local_variable(op2)) {
2321                 cmp_val = get_inversed_pnc(cmp_val);
2322                 var = op2->reference.entity;
2323                 con = op1;
2324         }
2325
2326         if (var != NULL) {
2327                 type_t  *const type = skip_typeref(var->declaration.type);
2328                 ir_mode *const mode = get_ir_mode_storage(type);
2329
2330                 res = get_value(var->variable.v.value_number, mode);
2331                 res = new_d_Confirm(dbi, res, expression_to_firm(con), cmp_val);
2332                 set_value(var->variable.v.value_number, res);
2333         }
2334         return res;
2335 }
2336
2337 /**
2338  * Handle the assume optimizer hint.
2339  *
2340  * @param dbi    debug info
2341  * @param expr   the IL assume expression
2342  */
2343 static ir_node *handle_assume(dbg_info *dbi, const expression_t *expression)
2344 {
2345         switch(expression->kind) {
2346         case EXPR_BINARY_EQUAL:
2347         case EXPR_BINARY_NOTEQUAL:
2348         case EXPR_BINARY_LESS:
2349         case EXPR_BINARY_LESSEQUAL:
2350         case EXPR_BINARY_GREATER:
2351         case EXPR_BINARY_GREATEREQUAL:
2352                 return handle_assume_compare(dbi, &expression->binary);
2353         default:
2354                 return NULL;
2355         }
2356 }
2357
2358 static ir_node *unary_expression_to_firm(const unary_expression_t *expression)
2359 {
2360         dbg_info *dbgi = get_dbg_info(&expression->base.source_position);
2361         type_t   *type = skip_typeref(expression->base.type);
2362
2363         if (expression->base.kind == EXPR_UNARY_TAKE_ADDRESS)
2364                 return expression_to_addr(expression->value);
2365
2366         const expression_t *value = expression->value;
2367
2368         switch(expression->base.kind) {
2369         case EXPR_UNARY_NEGATE: {
2370                 ir_node *value_node = expression_to_firm(value);
2371                 ir_mode *mode       = get_ir_mode_arithmetic(type);
2372                 return new_d_Minus(dbgi, value_node, mode);
2373         }
2374         case EXPR_UNARY_PLUS:
2375                 return expression_to_firm(value);
2376         case EXPR_UNARY_BITWISE_NEGATE: {
2377                 ir_node *value_node = expression_to_firm(value);
2378                 ir_mode *mode       = get_ir_mode_arithmetic(type);
2379                 return new_d_Not(dbgi, value_node, mode);
2380         }
2381         case EXPR_UNARY_NOT: {
2382                 ir_node *value_node = _expression_to_firm(value);
2383                 value_node          = create_conv(dbgi, value_node, mode_b);
2384                 ir_node *res        = new_d_Not(dbgi, value_node, mode_b);
2385                 return res;
2386         }
2387         case EXPR_UNARY_DEREFERENCE: {
2388                 ir_node *value_node = expression_to_firm(value);
2389                 type_t  *value_type = skip_typeref(value->base.type);
2390                 assert(is_type_pointer(value_type));
2391                 type_t  *points_to  = value_type->pointer.points_to;
2392                 return deref_address(dbgi, points_to, value_node);
2393         }
2394         case EXPR_UNARY_POSTFIX_INCREMENT:
2395         case EXPR_UNARY_POSTFIX_DECREMENT:
2396         case EXPR_UNARY_PREFIX_INCREMENT:
2397         case EXPR_UNARY_PREFIX_DECREMENT:
2398                 return create_incdec(expression);
2399         case EXPR_UNARY_CAST: {
2400                 ir_node *value_node = expression_to_firm(value);
2401                 if (is_type_scalar(type)) {
2402                         ir_mode *mode       = get_ir_mode_storage(type);
2403                         ir_node *node       = create_conv(dbgi, value_node, mode);
2404                         node                = do_strict_conv(dbgi, node);
2405                         ir_mode *mode_arith = get_ir_mode_arithmetic(type);
2406                         node                = create_conv(dbgi, node, mode_arith);
2407                         return node;
2408                 } else {
2409                         /* make sure firm type is constructed */
2410                         (void) get_ir_type(type);
2411                         return value_node;
2412                 }
2413         }
2414         case EXPR_UNARY_CAST_IMPLICIT: {
2415                 ir_node *value_node = expression_to_firm(value);
2416                 if (is_type_scalar(type)) {
2417                         ir_mode *mode       = get_ir_mode_storage(type);
2418                         ir_node *res        = create_conv(dbgi, value_node, mode);
2419                         ir_mode *mode_arith = get_ir_mode_arithmetic(type);
2420                         res                 = create_conv(dbgi, res, mode_arith);
2421                         return res;
2422                 } else {
2423                         return value_node;
2424                 }
2425         }
2426         case EXPR_UNARY_ASSUME:
2427                 if (firm_opt.confirm)
2428                         return handle_assume(dbgi, value);
2429                 else
2430                         return NULL;
2431
2432         default:
2433                 break;
2434         }
2435         panic("invalid UNEXPR type found");
2436 }
2437
2438 /**
2439  * produces a 0/1 depending of the value of a mode_b node
2440  */
2441 static ir_node *produce_condition_result(const expression_t *expression,
2442                                          ir_mode *mode, dbg_info *dbgi)
2443 {
2444         ir_node *cur_block = get_cur_block();
2445
2446         ir_node *one_block = new_immBlock();
2447         set_cur_block(one_block);
2448         ir_node *one       = new_Const(get_mode_one(mode));
2449         ir_node *jmp_one   = new_d_Jmp(dbgi);
2450
2451         ir_node *zero_block = new_immBlock();
2452         set_cur_block(zero_block);
2453         ir_node *zero       = new_Const(get_mode_null(mode));
2454         ir_node *jmp_zero   = new_d_Jmp(dbgi);
2455
2456         set_cur_block(cur_block);
2457         create_condition_evaluation(expression, one_block, zero_block);
2458         mature_immBlock(one_block);
2459         mature_immBlock(zero_block);
2460
2461         ir_node *in_cf[2] = { jmp_one, jmp_zero };
2462         new_Block(2, in_cf);
2463
2464         ir_node *in[2] = { one, zero };
2465         ir_node *val   = new_d_Phi(dbgi, 2, in, mode);
2466
2467         return val;
2468 }
2469
2470 static ir_node *adjust_for_pointer_arithmetic(dbg_info *dbgi,
2471                 ir_node *value, type_t *type)
2472 {
2473         ir_mode        *const mode         = get_ir_mode_arithmetic(type_ptrdiff_t);
2474         assert(is_type_pointer(type));
2475         pointer_type_t *const pointer_type = &type->pointer;
2476         type_t         *const points_to    = skip_typeref(pointer_type->points_to);
2477         ir_node        *      elem_size    = get_type_size(points_to);
2478         elem_size                          = create_conv(dbgi, elem_size, mode);
2479         value                              = create_conv(dbgi, value,     mode);
2480         ir_node        *const mul          = new_d_Mul(dbgi, value, elem_size, mode);
2481         return mul;
2482 }
2483
2484 static ir_node *create_op(dbg_info *dbgi, const binary_expression_t *expression,
2485                           ir_node *left, ir_node *right)
2486 {
2487         ir_mode  *mode;
2488         type_t   *type_left  = skip_typeref(expression->left->base.type);
2489         type_t   *type_right = skip_typeref(expression->right->base.type);
2490
2491         expression_kind_t kind = expression->base.kind;
2492
2493         switch (kind) {
2494         case EXPR_BINARY_SHIFTLEFT:
2495         case EXPR_BINARY_SHIFTRIGHT:
2496         case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2497         case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2498                 mode  = get_irn_mode(left);
2499                 right = create_conv(dbgi, right, mode_uint);
2500                 break;
2501
2502         case EXPR_BINARY_SUB:
2503                 if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
2504                         const pointer_type_t *const ptr_type = &type_left->pointer;
2505
2506                         mode = get_ir_mode_arithmetic(expression->base.type);
2507                         ir_node *const elem_size = get_type_size(ptr_type->points_to);
2508                         ir_node *const conv_size = new_d_Conv(dbgi, elem_size, mode);
2509                         ir_node *const sub       = new_d_Sub(dbgi, left, right, mode);
2510                         ir_node *const no_mem    = new_NoMem();
2511                         ir_node *const div       = new_d_DivRL(dbgi, no_mem, sub, conv_size,
2512                                                                                                    mode, op_pin_state_floats);
2513                         return new_d_Proj(dbgi, div, mode, pn_Div_res);
2514                 }
2515                 /* fallthrough */
2516         case EXPR_BINARY_SUB_ASSIGN:
2517                 if (is_type_pointer(type_left)) {
2518                         right = adjust_for_pointer_arithmetic(dbgi, right, type_left);
2519                         mode  = get_ir_mode_arithmetic(type_left);
2520                         break;
2521                 }
2522                 goto normal_node;
2523
2524         case EXPR_BINARY_ADD:
2525         case EXPR_BINARY_ADD_ASSIGN:
2526                 if (is_type_pointer(type_left)) {
2527                         right = adjust_for_pointer_arithmetic(dbgi, right, type_left);
2528                         mode  = get_ir_mode_arithmetic(type_left);
2529                         break;
2530                 } else if (is_type_pointer(type_right)) {
2531                         left  = adjust_for_pointer_arithmetic(dbgi, left, type_right);
2532                         mode  = get_ir_mode_arithmetic(type_right);
2533                         break;
2534                 }
2535                 goto normal_node;
2536
2537         default:
2538 normal_node:
2539                 mode = get_ir_mode_arithmetic(type_right);
2540                 left = create_conv(dbgi, left, mode);
2541                 break;
2542         }
2543
2544         switch (kind) {
2545         case EXPR_BINARY_ADD_ASSIGN:
2546         case EXPR_BINARY_ADD:
2547                 return new_d_Add(dbgi, left, right, mode);
2548         case EXPR_BINARY_SUB_ASSIGN:
2549         case EXPR_BINARY_SUB:
2550                 return new_d_Sub(dbgi, left, right, mode);
2551         case EXPR_BINARY_MUL_ASSIGN:
2552         case EXPR_BINARY_MUL:
2553                 return new_d_Mul(dbgi, left, right, mode);
2554         case EXPR_BINARY_BITWISE_AND:
2555         case EXPR_BINARY_BITWISE_AND_ASSIGN:
2556                 return new_d_And(dbgi, left, right, mode);
2557         case EXPR_BINARY_BITWISE_OR:
2558         case EXPR_BINARY_BITWISE_OR_ASSIGN:
2559                 return new_d_Or(dbgi, left, right, mode);
2560         case EXPR_BINARY_BITWISE_XOR:
2561         case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2562                 return new_d_Eor(dbgi, left, right, mode);
2563         case EXPR_BINARY_SHIFTLEFT:
2564         case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2565                 return new_d_Shl(dbgi, left, right, mode);
2566         case EXPR_BINARY_SHIFTRIGHT:
2567         case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2568                 if (mode_is_signed(mode)) {
2569                         return new_d_Shrs(dbgi, left, right, mode);
2570                 } else {
2571                         return new_d_Shr(dbgi, left, right, mode);
2572                 }
2573         case EXPR_BINARY_DIV:
2574         case EXPR_BINARY_DIV_ASSIGN: {
2575                 ir_node *pin = new_Pin(new_NoMem());
2576                 ir_node *op;
2577                 ir_node *res;
2578                 if (mode_is_float(mode)) {
2579                         op  = new_d_Quot(dbgi, pin, left, right, mode, op_pin_state_floats);
2580                         res = new_d_Proj(dbgi, op, mode, pn_Quot_res);
2581                 } else {
2582                         op  = new_d_Div(dbgi, pin, left, right, mode, op_pin_state_floats);
2583                         res = new_d_Proj(dbgi, op, mode, pn_Div_res);
2584                 }
2585                 return res;
2586         }
2587         case EXPR_BINARY_MOD:
2588         case EXPR_BINARY_MOD_ASSIGN: {
2589                 ir_node *pin = new_Pin(new_NoMem());
2590                 assert(!mode_is_float(mode));
2591                 ir_node *op  = new_d_Mod(dbgi, pin, left, right, mode,
2592                                          op_pin_state_floats);
2593                 ir_node *res = new_d_Proj(dbgi, op, mode, pn_Mod_res);
2594                 return res;
2595         }
2596         default:
2597                 panic("unexpected expression kind");
2598         }
2599 }
2600
2601 static ir_node *create_lazy_op(const binary_expression_t *expression)
2602 {
2603         dbg_info *dbgi = get_dbg_info(&expression->base.source_position);
2604         type_t   *type = skip_typeref(expression->base.type);
2605         ir_mode  *mode = get_ir_mode_arithmetic(type);
2606
2607         if (is_constant_expression(expression->left)) {
2608                 long val = fold_constant(expression->left);
2609                 expression_kind_t ekind = expression->base.kind;
2610                 assert(ekind == EXPR_BINARY_LOGICAL_AND || ekind == EXPR_BINARY_LOGICAL_OR);
2611                 if (ekind == EXPR_BINARY_LOGICAL_AND) {
2612                         if (val == 0) {
2613                                 return new_Const(get_mode_null(mode));
2614                         }
2615                 } else {
2616                         if (val != 0) {
2617                                 return new_Const(get_mode_one(mode));
2618                         }
2619                 }
2620
2621                 if (is_constant_expression(expression->right)) {
2622                         long const valr = fold_constant(expression->right);
2623                         return valr != 0 ?
2624                                 new_Const(get_mode_one(mode)) :
2625                                 new_Const(get_mode_null(mode));
2626                 }
2627
2628                 return produce_condition_result(expression->right, mode, dbgi);
2629         }
2630
2631         return produce_condition_result((const expression_t*) expression, mode,
2632                                         dbgi);
2633 }
2634
2635 typedef ir_node * (*create_arithmetic_func)(dbg_info *dbgi, ir_node *left,
2636                                             ir_node *right, ir_mode *mode);
2637
2638 static ir_node *create_assign_binop(const binary_expression_t *expression)
2639 {
2640         dbg_info *const     dbgi = get_dbg_info(&expression->base.source_position);
2641         const expression_t *left_expr = expression->left;
2642         type_t             *type      = skip_typeref(left_expr->base.type);
2643         ir_mode            *left_mode = get_ir_mode_storage(type);
2644         ir_node            *right     = expression_to_firm(expression->right);
2645         ir_node            *left_addr = expression_to_addr(left_expr);
2646         ir_node            *left      = get_value_from_lvalue(left_expr, left_addr);
2647         ir_node            *result    = create_op(dbgi, expression, left, right);
2648
2649         result = create_conv(dbgi, result, left_mode);
2650         result = do_strict_conv(dbgi, result);
2651
2652         result = set_value_for_expression_addr(left_expr, result, left_addr);
2653
2654         if (!is_type_compound(type)) {
2655                 ir_mode *mode_arithmetic = get_ir_mode_arithmetic(type);
2656                 result = create_conv(dbgi, result, mode_arithmetic);
2657         }
2658         return result;
2659 }
2660
2661 static ir_node *binary_expression_to_firm(const binary_expression_t *expression)
2662 {
2663         expression_kind_t kind = expression->base.kind;
2664
2665         switch(kind) {
2666         case EXPR_BINARY_EQUAL:
2667         case EXPR_BINARY_NOTEQUAL:
2668         case EXPR_BINARY_LESS:
2669         case EXPR_BINARY_LESSEQUAL:
2670         case EXPR_BINARY_GREATER:
2671         case EXPR_BINARY_GREATEREQUAL:
2672         case EXPR_BINARY_ISGREATER:
2673         case EXPR_BINARY_ISGREATEREQUAL:
2674         case EXPR_BINARY_ISLESS:
2675         case EXPR_BINARY_ISLESSEQUAL:
2676         case EXPR_BINARY_ISLESSGREATER:
2677         case EXPR_BINARY_ISUNORDERED: {
2678                 dbg_info *dbgi = get_dbg_info(&expression->base.source_position);
2679                 ir_node *left  = expression_to_firm(expression->left);
2680                 ir_node *right = expression_to_firm(expression->right);
2681                 ir_node *cmp   = new_d_Cmp(dbgi, left, right);
2682                 long     pnc   = get_pnc(kind, expression->left->base.type);
2683                 ir_node *proj  = new_d_Proj(dbgi, cmp, mode_b, pnc);
2684                 return proj;
2685         }
2686         case EXPR_BINARY_ASSIGN: {
2687                 ir_node *addr  = expression_to_addr(expression->left);
2688                 ir_node *right = expression_to_firm(expression->right);
2689                 ir_node *res
2690                         = set_value_for_expression_addr(expression->left, right, addr);
2691
2692                 type_t  *type            = skip_typeref(expression->base.type);
2693                 if (!is_type_compound(type)) {
2694                         ir_mode *mode_arithmetic = get_ir_mode_arithmetic(type);
2695                         res                      = create_conv(NULL, res, mode_arithmetic);
2696                 }
2697                 return res;
2698         }
2699         case EXPR_BINARY_ADD:
2700         case EXPR_BINARY_SUB:
2701         case EXPR_BINARY_MUL:
2702         case EXPR_BINARY_DIV:
2703         case EXPR_BINARY_MOD:
2704         case EXPR_BINARY_BITWISE_AND:
2705         case EXPR_BINARY_BITWISE_OR:
2706         case EXPR_BINARY_BITWISE_XOR:
2707         case EXPR_BINARY_SHIFTLEFT:
2708         case EXPR_BINARY_SHIFTRIGHT:
2709         {
2710                 dbg_info *dbgi  = get_dbg_info(&expression->base.source_position);
2711                 ir_node  *left  = expression_to_firm(expression->left);
2712                 ir_node  *right = expression_to_firm(expression->right);
2713                 return create_op(dbgi, expression, left, right);
2714         }
2715         case EXPR_BINARY_LOGICAL_AND:
2716         case EXPR_BINARY_LOGICAL_OR:
2717                 return create_lazy_op(expression);
2718         case EXPR_BINARY_COMMA:
2719                 /* create side effects of left side */
2720                 (void) expression_to_firm(expression->left);
2721                 return _expression_to_firm(expression->right);
2722
2723         case EXPR_BINARY_ADD_ASSIGN:
2724         case EXPR_BINARY_SUB_ASSIGN:
2725         case EXPR_BINARY_MUL_ASSIGN:
2726         case EXPR_BINARY_MOD_ASSIGN:
2727         case EXPR_BINARY_DIV_ASSIGN:
2728         case EXPR_BINARY_BITWISE_AND_ASSIGN:
2729         case EXPR_BINARY_BITWISE_OR_ASSIGN:
2730         case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2731         case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2732         case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2733                 return create_assign_binop(expression);
2734         default:
2735                 panic("TODO binexpr type");
2736         }
2737 }
2738
2739 static ir_node *array_access_addr(const array_access_expression_t *expression)
2740 {
2741         dbg_info *dbgi        = get_dbg_info(&expression->base.source_position);
2742         ir_node  *base_addr   = expression_to_firm(expression->array_ref);
2743         ir_node  *offset      = expression_to_firm(expression->index);
2744         type_t   *ref_type    = skip_typeref(expression->array_ref->base.type);
2745         ir_node  *real_offset = adjust_for_pointer_arithmetic(dbgi, offset, ref_type);
2746         ir_node  *result      = new_d_Add(dbgi, base_addr, real_offset, mode_P_data);
2747
2748         return result;
2749 }
2750
2751 static ir_node *array_access_to_firm(
2752                 const array_access_expression_t *expression)
2753 {
2754         dbg_info *dbgi   = get_dbg_info(&expression->base.source_position);
2755         ir_node  *addr   = array_access_addr(expression);
2756         type_t   *type   = revert_automatic_type_conversion(
2757                         (const expression_t*) expression);
2758         type             = skip_typeref(type);
2759
2760         return deref_address(dbgi, type, addr);
2761 }
2762
2763 static long get_offsetof_offset(const offsetof_expression_t *expression)
2764 {
2765         type_t *orig_type = expression->type;
2766         long    offset    = 0;
2767
2768         designator_t *designator = expression->designator;
2769         for ( ; designator != NULL; designator = designator->next) {
2770                 type_t *type = skip_typeref(orig_type);
2771                 /* be sure the type is constructed */
2772                 (void) get_ir_type(type);
2773
2774                 if (designator->symbol != NULL) {
2775                         assert(is_type_compound(type));
2776                         symbol_t *symbol = designator->symbol;
2777
2778                         compound_t *compound = type->compound.compound;
2779                         entity_t   *iter     = compound->members.entities;
2780                         for ( ; iter != NULL; iter = iter->base.next) {
2781                                 if (iter->base.symbol == symbol) {
2782                                         break;
2783                                 }
2784                         }
2785                         assert(iter != NULL);
2786
2787                         assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2788                         assert(iter->declaration.kind == DECLARATION_KIND_COMPOUND_MEMBER);
2789                         offset += get_entity_offset(iter->compound_member.entity);
2790
2791                         orig_type = iter->declaration.type;
2792                 } else {
2793                         expression_t *array_index = designator->array_index;
2794                         assert(designator->array_index != NULL);
2795                         assert(is_type_array(type));
2796
2797                         long index         = fold_constant(array_index);
2798                         ir_type *arr_type  = get_ir_type(type);
2799                         ir_type *elem_type = get_array_element_type(arr_type);
2800                         long     elem_size = get_type_size_bytes(elem_type);
2801
2802                         offset += index * elem_size;
2803
2804                         orig_type = type->array.element_type;
2805                 }
2806         }
2807
2808         return offset;
2809 }
2810
2811 static ir_node *offsetof_to_firm(const offsetof_expression_t *expression)
2812 {
2813         ir_mode  *mode   = get_ir_mode_arithmetic(expression->base.type);
2814         long      offset = get_offsetof_offset(expression);
2815         tarval   *tv     = new_tarval_from_long(offset, mode);
2816         dbg_info *dbgi   = get_dbg_info(&expression->base.source_position);
2817
2818         return new_d_Const(dbgi, tv);
2819 }
2820
2821 static void create_local_initializer(initializer_t *initializer, dbg_info *dbgi,
2822                                      ir_entity *entity, type_t *type);
2823
2824 static ir_node *compound_literal_to_firm(
2825                 const compound_literal_expression_t *expression)
2826 {
2827         type_t *type = expression->type;
2828
2829         /* create an entity on the stack */
2830         ir_type *frame_type = get_irg_frame_type(current_ir_graph);
2831
2832         ident     *const id     = id_unique("CompLit.%u");
2833         ir_type   *const irtype = get_ir_type(type);
2834         dbg_info  *const dbgi   = get_dbg_info(&expression->base.source_position);
2835         ir_entity *const entity = new_d_entity(frame_type, id, irtype, dbgi);
2836         set_entity_ld_ident(entity, id);
2837
2838         set_entity_variability(entity, variability_uninitialized);
2839
2840         /* create initialisation code */
2841         initializer_t *initializer = expression->initializer;
2842         create_local_initializer(initializer, dbgi, entity, type);
2843
2844         /* create a sel for the compound literal address */
2845         ir_node *frame = get_local_frame(entity);
2846         ir_node *sel   = new_d_simpleSel(dbgi, new_NoMem(), frame, entity);
2847         return sel;
2848 }
2849
2850 /**
2851  * Transform a sizeof expression into Firm code.
2852  */
2853 static ir_node *sizeof_to_firm(const typeprop_expression_t *expression)
2854 {
2855         type_t *type = expression->type;
2856         if (type == NULL) {
2857                 type = expression->tp_expression->base.type;
2858                 assert(type != NULL);
2859         }
2860
2861         type = skip_typeref(type);
2862         /* ยง6.5.3.4:2 if the type is a VLA, evaluate the expression. */
2863         if (is_type_array(type) && type->array.is_vla
2864                         && expression->tp_expression != NULL) {
2865                 expression_to_firm(expression->tp_expression);
2866         }
2867
2868         return get_type_size(type);
2869 }
2870
2871 static entity_t *get_expression_entity(const expression_t *expression)
2872 {
2873         if (expression->kind != EXPR_REFERENCE)
2874                 return NULL;
2875
2876         return expression->reference.entity;
2877 }
2878
2879 /**
2880  * Transform an alignof expression into Firm code.
2881  */
2882 static ir_node *alignof_to_firm(const typeprop_expression_t *expression)
2883 {
2884         ir_entity *irentity = NULL;
2885
2886         const expression_t *tp_expression = expression->tp_expression;
2887         if (tp_expression != NULL) {
2888                 entity_t *entity = get_expression_entity(tp_expression);
2889                 if (entity != NULL && is_declaration(entity)) {
2890                         switch (entity->declaration.kind) {
2891                         case DECLARATION_KIND_UNKNOWN:
2892                                 panic("unknown entity reference found");
2893                         case DECLARATION_KIND_COMPOUND_MEMBER:
2894                                 irentity = entity->compound_member.entity;
2895                                 break;
2896                         case DECLARATION_KIND_GLOBAL_VARIABLE:
2897                         case DECLARATION_KIND_LOCAL_VARIABLE_ENTITY:
2898                                 irentity = entity->variable.v.entity;
2899                                 break;
2900                         case DECLARATION_KIND_PARAMETER_ENTITY:
2901                                 irentity = entity->parameter.v.entity;
2902                                 break;
2903                         case DECLARATION_KIND_FUNCTION:
2904                         case DECLARATION_KIND_INNER_FUNCTION:
2905                                 irentity = entity->function.entity;
2906                                 break;
2907                         case DECLARATION_KIND_PARAMETER:
2908                         case DECLARATION_KIND_LOCAL_VARIABLE:
2909                         case DECLARATION_KIND_VARIABLE_LENGTH_ARRAY:
2910                                 break;
2911                         }
2912                 }
2913         }
2914
2915         ir_type *irtype;
2916         if (irentity != NULL) {
2917                 irtype = get_entity_type(irentity);
2918         } else {
2919                 type_t *type = expression->type;
2920                 irtype = get_ir_type(type);
2921         }
2922
2923         ir_mode *const mode = get_ir_mode_arithmetic(expression->base.type);
2924         symconst_symbol sym;
2925         sym.type_p = irtype;
2926         return new_SymConst(mode, sym, symconst_type_align);
2927 }
2928
2929 static void init_ir_types(void);
2930
2931 long fold_constant(const expression_t *expression)
2932 {
2933         assert(is_type_valid(skip_typeref(expression->base.type)));
2934
2935         bool constant_folding_old = constant_folding;
2936         constant_folding = true;
2937
2938         init_ir_types();
2939
2940         assert(is_constant_expression(expression));
2941
2942         ir_graph *old_current_ir_graph = current_ir_graph;
2943         current_ir_graph = get_const_code_irg();
2944
2945         ir_node *cnst = expression_to_firm(expression);
2946         current_ir_graph = old_current_ir_graph;
2947
2948         if (!is_Const(cnst)) {
2949                 panic("couldn't fold constant");
2950         }
2951
2952         tarval *tv = get_Const_tarval(cnst);
2953         if (!tarval_is_long(tv)) {
2954                 panic("result of constant folding is not integer");
2955         }
2956
2957         constant_folding = constant_folding_old;
2958
2959         return get_tarval_long(tv);
2960 }
2961
2962 static ir_node *conditional_to_firm(const conditional_expression_t *expression)
2963 {
2964         dbg_info *const dbgi = get_dbg_info(&expression->base.source_position);
2965
2966         /* first try to fold a constant condition */
2967         if (is_constant_expression(expression->condition)) {
2968                 long val = fold_constant(expression->condition);
2969                 if (val) {
2970                         expression_t *true_expression = expression->true_expression;
2971                         if (true_expression == NULL)
2972                                 true_expression = expression->condition;
2973                         return expression_to_firm(true_expression);
2974                 } else {
2975                         return expression_to_firm(expression->false_expression);
2976                 }
2977         }
2978
2979         ir_node *cur_block   = get_cur_block();
2980
2981         /* create the true block */
2982         ir_node *true_block  = new_immBlock();
2983         set_cur_block(true_block);
2984
2985         ir_node *true_val = expression->true_expression != NULL ?
2986                 expression_to_firm(expression->true_expression) : NULL;
2987         ir_node *true_jmp = new_Jmp();
2988
2989         /* create the false block */
2990         ir_node *false_block = new_immBlock();
2991         set_cur_block(false_block);
2992
2993         ir_node *false_val = expression_to_firm(expression->false_expression);
2994         ir_node *false_jmp = new_Jmp();
2995
2996         /* create the condition evaluation */
2997         set_cur_block(cur_block);
2998         ir_node *const cond_expr = create_condition_evaluation(expression->condition, true_block, false_block);
2999         if (expression->true_expression == NULL) {
3000                 if (cond_expr != NULL && get_irn_mode(cond_expr) != mode_b) {
3001                         true_val = cond_expr;
3002                 } else {
3003                         /* Condition ended with a short circuit (&&, ||, !) operation or a
3004                          * comparison.  Generate a "1" as value for the true branch. */
3005                         true_val = new_Const(get_mode_one(mode_Is));
3006                 }
3007         }
3008         mature_immBlock(true_block);
3009         mature_immBlock(false_block);
3010
3011         /* create the common block */
3012         ir_node *in_cf[2] = { true_jmp, false_jmp };
3013         new_Block(2, in_cf);
3014
3015         /* TODO improve static semantics, so either both or no values are NULL */
3016         if (true_val == NULL || false_val == NULL)
3017                 return NULL;
3018
3019         ir_node *in[2] = { true_val, false_val };
3020         ir_mode *mode  = get_irn_mode(true_val);
3021         assert(get_irn_mode(false_val) == mode);
3022         ir_node *val   = new_d_Phi(dbgi, 2, in, mode);
3023
3024         return val;
3025 }
3026
3027 /**
3028  * Returns an IR-node representing the address of a field.
3029  */
3030 static ir_node *select_addr(const select_expression_t *expression)
3031 {
3032         dbg_info *dbgi = get_dbg_info(&expression->base.source_position);
3033
3034         construct_select_compound(expression);
3035
3036         ir_node *compound_addr = expression_to_firm(expression->compound);
3037
3038         entity_t *entry = expression->compound_entry;
3039         assert(entry->kind == ENTITY_COMPOUND_MEMBER);
3040         assert(entry->declaration.kind == DECLARATION_KIND_COMPOUND_MEMBER);
3041
3042         if (constant_folding) {
3043                 ir_mode *mode = get_irn_mode(compound_addr);
3044                 /* FIXME: here, we need an integer mode with the same number of bits as mode */
3045                 ir_node *ofs  = new_Const_long(mode_uint, entry->compound_member.offset);
3046                 return new_d_Add(dbgi, compound_addr, ofs, mode);
3047         } else {
3048                 ir_entity *irentity = entry->compound_member.entity;
3049                 assert(irentity != NULL);
3050                 return new_d_simpleSel(dbgi, new_NoMem(), compound_addr, irentity);
3051         }
3052 }
3053
3054 static ir_node *select_to_firm(const select_expression_t *expression)
3055 {
3056         dbg_info *dbgi = get_dbg_info(&expression->base.source_position);
3057         ir_node  *addr = select_addr(expression);
3058         type_t   *type = revert_automatic_type_conversion(
3059                         (const expression_t*) expression);
3060         type           = skip_typeref(type);
3061
3062         entity_t *entry      = expression->compound_entry;
3063         assert(entry->kind == ENTITY_COMPOUND_MEMBER);
3064         type_t   *entry_type = skip_typeref(entry->declaration.type);
3065
3066         if (entry_type->kind == TYPE_BITFIELD) {
3067                 return bitfield_extract_to_firm(expression, addr);
3068         }
3069
3070         return deref_address(dbgi, type, addr);
3071 }
3072
3073 /* Values returned by __builtin_classify_type. */
3074 typedef enum gcc_type_class
3075 {
3076         no_type_class = -1,
3077         void_type_class,
3078         integer_type_class,
3079         char_type_class,
3080         enumeral_type_class,
3081         boolean_type_class,
3082         pointer_type_class,
3083         reference_type_class,
3084         offset_type_class,
3085         real_type_class,
3086         complex_type_class,
3087         function_type_class,
3088         method_type_class,
3089         record_type_class,
3090         union_type_class,
3091         array_type_class,
3092         string_type_class,
3093         set_type_class,
3094         file_type_class,
3095         lang_type_class
3096 } gcc_type_class;
3097
3098 static ir_node *classify_type_to_firm(const classify_type_expression_t *const expr)
3099 {
3100         type_t *type = expr->type_expression->base.type;
3101
3102         /* FIXME gcc returns different values depending on whether compiling C or C++
3103          * e.g. int x[10] is pointer_type_class in C, but array_type_class in C++ */
3104         gcc_type_class tc;
3105         for (;;) {
3106                 type = skip_typeref(type);
3107                 switch (type->kind) {
3108                         case TYPE_ATOMIC: {
3109                                 const atomic_type_t *const atomic_type = &type->atomic;
3110                                 switch (atomic_type->akind) {
3111                                         /* should not be reached */
3112                                         case ATOMIC_TYPE_INVALID:
3113                                                 tc = no_type_class;
3114                                                 goto make_const;
3115
3116                                         /* gcc cannot do that */
3117                                         case ATOMIC_TYPE_VOID:
3118                                                 tc = void_type_class;
3119                                                 goto make_const;
3120
3121                                         case ATOMIC_TYPE_WCHAR_T:   /* gcc handles this as integer */
3122                                         case ATOMIC_TYPE_CHAR:      /* gcc handles this as integer */
3123                                         case ATOMIC_TYPE_SCHAR:     /* gcc handles this as integer */
3124                                         case ATOMIC_TYPE_UCHAR:     /* gcc handles this as integer */
3125                                         case ATOMIC_TYPE_SHORT:
3126                                         case ATOMIC_TYPE_USHORT:
3127                                         case ATOMIC_TYPE_INT:
3128                                         case ATOMIC_TYPE_UINT:
3129                                         case ATOMIC_TYPE_LONG:
3130                                         case ATOMIC_TYPE_ULONG:
3131                                         case ATOMIC_TYPE_LONGLONG:
3132                                         case ATOMIC_TYPE_ULONGLONG:
3133                                         case ATOMIC_TYPE_BOOL:      /* gcc handles this as integer */
3134                                                 tc = integer_type_class;
3135                                                 goto make_const;
3136
3137                                         case ATOMIC_TYPE_FLOAT:
3138                                         case ATOMIC_TYPE_DOUBLE:
3139                                         case ATOMIC_TYPE_LONG_DOUBLE:
3140                                                 tc = real_type_class;
3141                                                 goto make_const;
3142                                 }
3143                                 panic("Unexpected atomic type in classify_type_to_firm().");
3144                         }
3145
3146                         case TYPE_COMPLEX:         tc = complex_type_class; goto make_const;
3147                         case TYPE_IMAGINARY:       tc = complex_type_class; goto make_const;
3148                         case TYPE_BITFIELD:        tc = integer_type_class; goto make_const;
3149                         case TYPE_ARRAY:           /* gcc handles this as pointer */
3150                         case TYPE_FUNCTION:        /* gcc handles this as pointer */
3151                         case TYPE_POINTER:         tc = pointer_type_class; goto make_const;
3152                         case TYPE_COMPOUND_STRUCT: tc = record_type_class;  goto make_const;
3153                         case TYPE_COMPOUND_UNION:  tc = union_type_class;   goto make_const;
3154
3155                         /* gcc handles this as integer */
3156                         case TYPE_ENUM:            tc = integer_type_class; goto make_const;
3157
3158                         /* gcc classifies the referenced type */
3159                         case TYPE_REFERENCE: type = type->reference.refers_to; continue;
3160
3161                         case TYPE_BUILTIN:
3162                         /* typedef/typeof should be skipped already */
3163                         case TYPE_TYPEDEF:
3164                         case TYPE_TYPEOF:
3165                         case TYPE_INVALID:
3166                         case TYPE_ERROR:
3167                                 break;
3168                 }
3169                 panic("unexpected TYPE classify_type_to_firm().");
3170         }
3171
3172 make_const:;
3173         dbg_info *const dbgi = get_dbg_info(&expr->base.source_position);
3174         tarval   *const tv   = new_tarval_from_long(tc, mode_int);
3175         return new_d_Const(dbgi, tv);
3176 }
3177
3178 static ir_node *function_name_to_firm(
3179                 const funcname_expression_t *const expr)
3180 {
3181         switch(expr->kind) {
3182         case FUNCNAME_FUNCTION:
3183         case FUNCNAME_PRETTY_FUNCTION:
3184         case FUNCNAME_FUNCDNAME:
3185                 if (current_function_name == NULL) {
3186                         const source_position_t *const src_pos = &expr->base.source_position;
3187                         const char    *name  = current_function_entity->base.symbol->string;
3188                         const string_t string = { name, strlen(name) + 1 };
3189                         current_function_name = string_to_firm(src_pos, "__func__.%u", &string);
3190                 }
3191                 return current_function_name;
3192         case FUNCNAME_FUNCSIG:
3193                 if (current_funcsig == NULL) {
3194                         const source_position_t *const src_pos = &expr->base.source_position;
3195                         ir_entity *ent = get_irg_entity(current_ir_graph);
3196                         const char *const name = get_entity_ld_name(ent);
3197                         const string_t string = { name, strlen(name) + 1 };
3198                         current_funcsig = string_to_firm(src_pos, "__FUNCSIG__.%u", &string);
3199                 }
3200                 return current_funcsig;
3201         }
3202         panic("Unsupported function name");
3203 }
3204
3205 static ir_node *statement_expression_to_firm(const statement_expression_t *expr)
3206 {
3207         statement_t *statement = expr->statement;
3208
3209         assert(statement->kind == STATEMENT_COMPOUND);
3210         return compound_statement_to_firm(&statement->compound);
3211 }
3212
3213 static ir_node *va_start_expression_to_firm(
3214         const va_start_expression_t *const expr)
3215 {
3216         type_t    *const type        = current_function_entity->declaration.type;
3217         ir_type   *const method_type = get_ir_type(type);
3218         int        const n           = get_method_n_params(method_type) - 1;
3219         ir_entity *const parm_ent    = get_method_value_param_ent(method_type, n);
3220         ir_node   *const arg_base    = get_irg_value_param_base(current_ir_graph);
3221         dbg_info  *const dbgi        = get_dbg_info(&expr->base.source_position);
3222         ir_node   *const no_mem      = new_NoMem();
3223         ir_node   *const arg_sel     =
3224                 new_d_simpleSel(dbgi, no_mem, arg_base, parm_ent);
3225
3226         ir_node   *const cnst        = get_type_size(expr->parameter->base.type);
3227         ir_node   *const add         = new_d_Add(dbgi, arg_sel, cnst, mode_P_data);
3228         set_value_for_expression(expr->ap, add);
3229
3230         return NULL;
3231 }
3232
3233 static ir_node *va_arg_expression_to_firm(const va_arg_expression_t *const expr)
3234 {
3235         type_t       *const type    = expr->base.type;
3236         expression_t *const ap_expr = expr->ap;
3237         ir_node      *const ap_addr = expression_to_addr(ap_expr);
3238         ir_node      *const ap      = get_value_from_lvalue(ap_expr, ap_addr);
3239         dbg_info     *const dbgi    = get_dbg_info(&expr->base.source_position);
3240         ir_node      *const res     = deref_address(dbgi, type, ap);
3241
3242         ir_node      *const cnst    = get_type_size(expr->base.type);
3243         ir_node      *const add     = new_d_Add(dbgi, ap, cnst, mode_P_data);
3244
3245         set_value_for_expression_addr(ap_expr, add, ap_addr);
3246
3247         return res;
3248 }
3249
3250 static ir_node *dereference_addr(const unary_expression_t *const expression)
3251 {
3252         assert(expression->base.kind == EXPR_UNARY_DEREFERENCE);
3253         return expression_to_firm(expression->value);
3254 }
3255
3256 /**
3257  * Returns a IR-node representing an lvalue of the given expression.
3258  */
3259 static ir_node *expression_to_addr(const expression_t *expression)
3260 {
3261         switch(expression->kind) {
3262         case EXPR_ARRAY_ACCESS:
3263                 return array_access_addr(&expression->array_access);
3264         case EXPR_CALL:
3265                 return call_expression_to_firm(&expression->call);
3266         case EXPR_COMPOUND_LITERAL:
3267                 return compound_literal_to_firm(&expression->compound_literal);
3268         case EXPR_REFERENCE:
3269                 return reference_addr(&expression->reference);
3270         case EXPR_SELECT:
3271                 return select_addr(&expression->select);
3272         case EXPR_UNARY_DEREFERENCE:
3273                 return dereference_addr(&expression->unary);
3274         default:
3275                 break;
3276         }
3277         panic("trying to get address of non-lvalue");
3278 }
3279
3280 static ir_node *builtin_constant_to_firm(
3281                 const builtin_constant_expression_t *expression)
3282 {
3283         ir_mode *mode = get_ir_mode_arithmetic(expression->base.type);
3284         long     v;
3285
3286         if (is_constant_expression(expression->value)) {
3287                 v = 1;
3288         } else {
3289                 v = 0;
3290         }
3291         return new_Const_long(mode, v);
3292 }
3293
3294 static ir_node *builtin_types_compatible_to_firm(
3295                 const builtin_types_compatible_expression_t *expression)
3296 {
3297         type_t  *const left  = get_unqualified_type(skip_typeref(expression->left));
3298         type_t  *const right = get_unqualified_type(skip_typeref(expression->right));
3299         long     const value = types_compatible(left, right) ? 1 : 0;
3300         ir_mode *const mode  = get_ir_mode_arithmetic(expression->base.type);
3301         return new_Const_long(mode, value);
3302 }
3303
3304 static ir_node *get_label_block(label_t *label)
3305 {
3306         if (label->block != NULL)
3307                 return label->block;
3308
3309         /* beware: might be called from create initializer with current_ir_graph
3310          * set to const_code_irg. */
3311         ir_graph *rem    = current_ir_graph;
3312         current_ir_graph = current_function;
3313
3314         ir_node *block = new_immBlock();
3315
3316         label->block = block;
3317
3318         ARR_APP1(label_t *, all_labels, label);
3319
3320         current_ir_graph = rem;
3321         return block;
3322 }
3323
3324 /**
3325  * Pointer to a label.  This is used for the
3326  * GNU address-of-label extension.
3327  */
3328 static ir_node *label_address_to_firm(
3329                 const label_address_expression_t *label)
3330 {
3331         ir_node    *block = get_label_block(label->label);
3332         ir_label_t  nr    = get_Block_label(block);
3333
3334         if (nr == 0) {
3335                 nr = get_irp_next_label_nr();
3336                 set_Block_label(block, nr);
3337         }
3338         symconst_symbol value;
3339         value.label = nr;
3340         return new_SymConst(mode_P_code, value, symconst_label);
3341 }
3342
3343 /**
3344  * creates firm nodes for an expression. The difference between this function
3345  * and expression_to_firm is, that this version might produce mode_b nodes
3346  * instead of mode_Is.
3347  */
3348 static ir_node *_expression_to_firm(const expression_t *expression)
3349 {
3350 #ifndef NDEBUG
3351         if (!constant_folding) {
3352                 assert(!expression->base.transformed);
3353                 ((expression_t*) expression)->base.transformed = true;
3354         }
3355 #endif
3356
3357         switch (expression->kind) {
3358         case EXPR_CHARACTER_CONSTANT:
3359                 return character_constant_to_firm(&expression->conste);
3360         case EXPR_WIDE_CHARACTER_CONSTANT:
3361                 return wide_character_constant_to_firm(&expression->conste);
3362         case EXPR_CONST:
3363                 return const_to_firm(&expression->conste);
3364         case EXPR_STRING_LITERAL:
3365                 return string_literal_to_firm(&expression->string);
3366         case EXPR_WIDE_STRING_LITERAL:
3367                 return wide_string_literal_to_firm(&expression->wide_string);
3368         case EXPR_REFERENCE:
3369                 return reference_expression_to_firm(&expression->reference);
3370         case EXPR_REFERENCE_ENUM_VALUE:
3371                 return reference_expression_enum_value_to_firm(&expression->reference);
3372         case EXPR_CALL:
3373                 return call_expression_to_firm(&expression->call);
3374         EXPR_UNARY_CASES
3375                 return unary_expression_to_firm(&expression->unary);
3376         EXPR_BINARY_CASES
3377                 return binary_expression_to_firm(&expression->binary);
3378         case EXPR_ARRAY_ACCESS:
3379                 return array_access_to_firm(&expression->array_access);
3380         case EXPR_SIZEOF:
3381                 return sizeof_to_firm(&expression->typeprop);
3382         case EXPR_ALIGNOF:
3383                 return alignof_to_firm(&expression->typeprop);
3384         case EXPR_CONDITIONAL:
3385                 return conditional_to_firm(&expression->conditional);
3386         case EXPR_SELECT:
3387                 return select_to_firm(&expression->select);
3388         case EXPR_CLASSIFY_TYPE:
3389                 return classify_type_to_firm(&expression->classify_type);
3390         case EXPR_FUNCNAME:
3391                 return function_name_to_firm(&expression->funcname);
3392         case EXPR_STATEMENT:
3393                 return statement_expression_to_firm(&expression->statement);
3394         case EXPR_VA_START:
3395                 return va_start_expression_to_firm(&expression->va_starte);
3396         case EXPR_VA_ARG:
3397                 return va_arg_expression_to_firm(&expression->va_arge);
3398         case EXPR_BUILTIN_CONSTANT_P:
3399                 return builtin_constant_to_firm(&expression->builtin_constant);
3400         case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
3401                 return builtin_types_compatible_to_firm(&expression->builtin_types_compatible);
3402         case EXPR_OFFSETOF:
3403                 return offsetof_to_firm(&expression->offsetofe);
3404         case EXPR_COMPOUND_LITERAL:
3405                 return compound_literal_to_firm(&expression->compound_literal);
3406         case EXPR_LABEL_ADDRESS:
3407                 return label_address_to_firm(&expression->label_address);
3408
3409         case EXPR_UNKNOWN:
3410         case EXPR_INVALID:
3411                 break;
3412         }
3413         panic("invalid expression found");
3414 }
3415
3416 /**
3417  * Check if a given expression is a GNU __builtin_expect() call.
3418  */
3419 static bool is_builtin_expect(const expression_t *expression)
3420 {
3421         if (expression->kind != EXPR_CALL)
3422                 return false;
3423
3424         expression_t *function = expression->call.function;
3425         if (function->kind != EXPR_REFERENCE)
3426                 return false;
3427         reference_expression_t *ref = &function->reference;
3428         if (ref->entity->kind         != ENTITY_FUNCTION ||
3429             ref->entity->function.btk != bk_gnu_builtin_expect)
3430                 return false;
3431
3432         return true;
3433 }
3434
3435 static bool produces_mode_b(const expression_t *expression)
3436 {
3437         switch (expression->kind) {
3438         case EXPR_BINARY_EQUAL:
3439         case EXPR_BINARY_NOTEQUAL:
3440         case EXPR_BINARY_LESS:
3441         case EXPR_BINARY_LESSEQUAL:
3442         case EXPR_BINARY_GREATER:
3443         case EXPR_BINARY_GREATEREQUAL:
3444         case EXPR_BINARY_ISGREATER:
3445         case EXPR_BINARY_ISGREATEREQUAL:
3446         case EXPR_BINARY_ISLESS:
3447         case EXPR_BINARY_ISLESSEQUAL:
3448         case EXPR_BINARY_ISLESSGREATER:
3449         case EXPR_BINARY_ISUNORDERED:
3450         case EXPR_UNARY_NOT:
3451                 return true;
3452
3453         case EXPR_CALL:
3454                 if (is_builtin_expect(expression)) {
3455                         expression_t *argument = expression->call.arguments->expression;
3456                         return produces_mode_b(argument);
3457                 }
3458                 return false;
3459         case EXPR_BINARY_COMMA:
3460                 return produces_mode_b(expression->binary.right);
3461
3462         default:
3463                 return false;
3464         }
3465 }
3466
3467 static ir_node *expression_to_firm(const expression_t *expression)
3468 {
3469         if (!produces_mode_b(expression)) {
3470                 ir_node *res = _expression_to_firm(expression);
3471                 assert(res == NULL || get_irn_mode(res) != mode_b);
3472                 return res;
3473         }
3474
3475         if (is_constant_expression(expression)) {
3476                 ir_node *res  = _expression_to_firm(expression);
3477                 ir_mode *mode = get_ir_mode_arithmetic(expression->base.type);
3478                 assert(is_Const(res));
3479                 if (is_Const_null(res)) {
3480                         return new_Const_long(mode, 0);
3481                 } else {
3482                         return new_Const_long(mode, 1);
3483                 }
3484         }
3485
3486         /* we have to produce a 0/1 from the mode_b expression */
3487         dbg_info *dbgi = get_dbg_info(&expression->base.source_position);
3488         ir_mode  *mode = get_ir_mode_arithmetic(expression->base.type);
3489         return produce_condition_result(expression, mode, dbgi);
3490 }
3491
3492 /**
3493  * create a short-circuit expression evaluation that tries to construct
3494  * efficient control flow structures for &&, || and ! expressions
3495  */
3496 static ir_node *create_condition_evaluation(const expression_t *expression,
3497                                             ir_node *true_block,
3498                                             ir_node *false_block)
3499 {
3500         switch(expression->kind) {
3501         case EXPR_UNARY_NOT: {
3502                 const unary_expression_t *unary_expression = &expression->unary;
3503                 create_condition_evaluation(unary_expression->value, false_block,
3504                                             true_block);
3505                 return NULL;
3506         }
3507         case EXPR_BINARY_LOGICAL_AND: {
3508                 const binary_expression_t *binary_expression = &expression->binary;
3509
3510                 ir_node *extra_block = new_immBlock();
3511                 create_condition_evaluation(binary_expression->left, extra_block,
3512                                             false_block);
3513                 mature_immBlock(extra_block);
3514                 set_cur_block(extra_block);
3515                 create_condition_evaluation(binary_expression->right, true_block,
3516                                             false_block);
3517                 return NULL;
3518         }
3519         case EXPR_BINARY_LOGICAL_OR: {
3520                 const binary_expression_t *binary_expression = &expression->binary;
3521
3522                 ir_node *extra_block = new_immBlock();
3523                 create_condition_evaluation(binary_expression->left, true_block,
3524                                             extra_block);
3525                 mature_immBlock(extra_block);
3526                 set_cur_block(extra_block);
3527                 create_condition_evaluation(binary_expression->right, true_block,
3528                                             false_block);
3529                 return NULL;
3530         }
3531         default:
3532                 break;
3533         }
3534
3535         dbg_info *dbgi       = get_dbg_info(&expression->base.source_position);
3536         ir_node  *cond_expr  = _expression_to_firm(expression);
3537         ir_node  *condition  = create_conv(dbgi, cond_expr, mode_b);
3538         ir_node  *cond       = new_d_Cond(dbgi, condition);
3539         ir_node  *true_proj  = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true);
3540         ir_node  *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false);
3541
3542         /* set branch prediction info based on __builtin_expect */
3543         if (is_builtin_expect(expression) && is_Cond(cond)) {
3544                 call_argument_t *argument = expression->call.arguments->next;
3545                 if (is_constant_expression(argument->expression)) {
3546                         long               cnst = fold_constant(argument->expression);
3547                         cond_jmp_predicate pred;
3548
3549                         if (cnst == 0) {
3550                                 pred = COND_JMP_PRED_FALSE;
3551                         } else {
3552                                 pred = COND_JMP_PRED_TRUE;
3553                         }
3554                         set_Cond_jmp_pred(cond, pred);
3555                 }
3556         }
3557
3558         add_immBlock_pred(true_block, true_proj);
3559         add_immBlock_pred(false_block, false_proj);
3560
3561         set_cur_block(NULL);
3562         return cond_expr;
3563 }
3564
3565
3566 static void create_variable_entity(entity_t *variable,
3567                                    declaration_kind_t declaration_kind,
3568                                    ir_type *parent_type)
3569 {
3570         assert(variable->kind == ENTITY_VARIABLE);
3571         type_t    *type = skip_typeref(variable->declaration.type);
3572         type            = get_aligned_type(type, variable->variable.alignment);
3573
3574         ident     *const id       = new_id_from_str(variable->base.symbol->string);
3575         ir_type   *const irtype   = get_ir_type(type);
3576         dbg_info  *const dbgi     = get_dbg_info(&variable->base.source_position);
3577
3578         ir_entity *const irentity = new_d_entity(parent_type, id, irtype, dbgi);
3579
3580         handle_gnu_attributes_ent(irentity, variable);
3581
3582         variable->declaration.kind  = (unsigned char) declaration_kind;
3583         variable->variable.v.entity = irentity;
3584         set_entity_variability(irentity, variability_uninitialized);
3585         set_entity_ld_ident(irentity, create_ld_ident(variable));
3586
3587         if (parent_type == get_tls_type())
3588                 set_entity_allocation(irentity, allocation_automatic);
3589         else if (declaration_kind == DECLARATION_KIND_GLOBAL_VARIABLE)
3590                 set_entity_allocation(irentity, allocation_static);
3591
3592         if (type->base.qualifiers & TYPE_QUALIFIER_VOLATILE) {
3593                 set_entity_volatility(irentity, volatility_is_volatile);
3594         }
3595 }
3596
3597
3598 typedef struct type_path_entry_t type_path_entry_t;
3599 struct type_path_entry_t {
3600         type_t           *type;
3601         ir_initializer_t *initializer;
3602         size_t            index;
3603         entity_t         *compound_entry;
3604 };
3605
3606 typedef struct type_path_t type_path_t;
3607 struct type_path_t {
3608         type_path_entry_t *path;
3609         type_t            *top_type;
3610         bool               invalid;
3611 };
3612
3613 static __attribute__((unused)) void debug_print_type_path(const type_path_t *path)
3614 {
3615         size_t len = ARR_LEN(path->path);
3616
3617         for (size_t i = 0; i < len; ++i) {
3618                 const type_path_entry_t *entry = & path->path[i];
3619
3620                 type_t *type = skip_typeref(entry->type);
3621                 if (is_type_compound(type)) {
3622                         fprintf(stderr, ".%s", entry->compound_entry->base.symbol->string);
3623                 } else if (is_type_array(type)) {
3624                         fprintf(stderr, "[%u]", (unsigned) entry->index);
3625                 } else {
3626                         fprintf(stderr, "-INVALID-");
3627                 }
3628         }
3629         fprintf(stderr, "  (");
3630         print_type(path->top_type);
3631         fprintf(stderr, ")");
3632 }
3633
3634 static type_path_entry_t *get_type_path_top(const type_path_t *path)
3635 {
3636         size_t len = ARR_LEN(path->path);
3637         assert(len > 0);
3638         return & path->path[len-1];
3639 }
3640
3641 static type_path_entry_t *append_to_type_path(type_path_t *path)
3642 {
3643         size_t len = ARR_LEN(path->path);
3644         ARR_RESIZE(type_path_entry_t, path->path, len+1);
3645
3646         type_path_entry_t *result = & path->path[len];
3647         memset(result, 0, sizeof(result[0]));
3648         return result;
3649 }
3650
3651 static size_t get_compound_member_count(const compound_type_t *type)
3652 {
3653         compound_t *compound  = type->compound;
3654         size_t      n_members = 0;
3655         entity_t   *member    = compound->members.entities;
3656         for ( ; member != NULL; member = member->base.next) {
3657                 ++n_members;
3658         }
3659
3660         return n_members;
3661 }
3662
3663 static ir_initializer_t *get_initializer_entry(type_path_t *path)
3664 {
3665         type_t *orig_top_type = path->top_type;
3666         type_t *top_type      = skip_typeref(orig_top_type);
3667
3668         assert(is_type_compound(top_type) || is_type_array(top_type));
3669
3670         if (ARR_LEN(path->path) == 0) {
3671                 return NULL;
3672         } else {
3673                 type_path_entry_t *top         = get_type_path_top(path);
3674                 ir_initializer_t  *initializer = top->initializer;
3675                 return get_initializer_compound_value(initializer, top->index);
3676         }
3677 }
3678
3679 static void descend_into_subtype(type_path_t *path)
3680 {
3681         type_t *orig_top_type = path->top_type;
3682         type_t *top_type      = skip_typeref(orig_top_type);
3683
3684         assert(is_type_compound(top_type) || is_type_array(top_type));
3685
3686         ir_initializer_t *initializer = get_initializer_entry(path);
3687
3688         type_path_entry_t *top = append_to_type_path(path);
3689         top->type              = top_type;
3690
3691         size_t len;
3692
3693         if (is_type_compound(top_type)) {
3694                 compound_t *compound = top_type->compound.compound;
3695                 entity_t   *entry    = compound->members.entities;
3696
3697                 top->compound_entry = entry;
3698                 top->index          = 0;
3699                 len                 = get_compound_member_count(&top_type->compound);
3700                 if (entry != NULL) {
3701                         assert(entry->kind == ENTITY_COMPOUND_MEMBER);
3702                         path->top_type = entry->declaration.type;
3703                 }
3704         } else {
3705                 assert(is_type_array(top_type));
3706                 assert(top_type->array.size > 0);
3707
3708                 top->index     = 0;
3709                 path->top_type = top_type->array.element_type;
3710                 len            = top_type->array.size;
3711         }
3712         if (initializer == NULL
3713                         || get_initializer_kind(initializer) == IR_INITIALIZER_NULL) {
3714                 initializer = create_initializer_compound(len);
3715                 /* we have to set the entry at the 2nd latest path entry... */
3716                 size_t path_len = ARR_LEN(path->path);
3717                 assert(path_len >= 1);
3718                 if (path_len > 1) {
3719                         type_path_entry_t *entry        = & path->path[path_len-2];
3720                         ir_initializer_t  *tinitializer = entry->initializer;
3721                         set_initializer_compound_value(tinitializer, entry->index,
3722                                                        initializer);
3723                 }
3724         }
3725         top->initializer = initializer;
3726 }
3727
3728 static void ascend_from_subtype(type_path_t *path)
3729 {
3730         type_path_entry_t *top = get_type_path_top(path);
3731
3732         path->top_type = top->type;
3733
3734         size_t len = ARR_LEN(path->path);
3735         ARR_RESIZE(type_path_entry_t, path->path, len-1);
3736 }
3737
3738 static void walk_designator(type_path_t *path, const designator_t *designator)
3739 {
3740         /* designators start at current object type */
3741         ARR_RESIZE(type_path_entry_t, path->path, 1);
3742
3743         for ( ; designator != NULL; designator = designator->next) {
3744                 type_path_entry_t *top         = get_type_path_top(path);
3745                 type_t            *orig_type   = top->type;
3746                 type_t            *type        = skip_typeref(orig_type);
3747
3748                 if (designator->symbol != NULL) {
3749                         assert(is_type_compound(type));
3750                         size_t    index  = 0;
3751                         symbol_t *symbol = designator->symbol;
3752
3753                         compound_t *compound = type->compound.compound;
3754                         entity_t   *iter     = compound->members.entities;
3755                         for ( ; iter != NULL; iter = iter->base.next, ++index) {
3756                                 if (iter->base.symbol == symbol) {
3757                                         assert(iter->kind == ENTITY_COMPOUND_MEMBER);
3758                                         break;
3759                                 }
3760                         }
3761                         assert(iter != NULL);
3762
3763                         top->type           = orig_type;
3764                         top->compound_entry = iter;
3765                         top->index          = index;
3766                         orig_type           = iter->declaration.type;
3767                 } else {
3768                         expression_t *array_index = designator->array_index;
3769                         assert(designator->array_index != NULL);
3770                         assert(is_type_array(type));
3771
3772                         long index = fold_constant(array_index);
3773                         assert(index >= 0);
3774 #ifndef NDEBUG
3775                         if (type->array.size_constant) {
3776                                 long array_size = type->array.size;
3777                                 assert(index < array_size);
3778                         }
3779 #endif
3780
3781                         top->type  = orig_type;
3782                         top->index = (size_t) index;
3783                         orig_type  = type->array.element_type;
3784                 }
3785                 path->top_type = orig_type;
3786
3787                 if (designator->next != NULL) {
3788                         descend_into_subtype(path);
3789                 }
3790         }
3791
3792         path->invalid  = false;
3793 }
3794
3795 static void advance_current_object(type_path_t *path)
3796 {
3797         if (path->invalid) {
3798                 /* TODO: handle this... */
3799                 panic("invalid initializer in ast2firm (excessive elements)");
3800         }
3801
3802         type_path_entry_t *top = get_type_path_top(path);
3803
3804         type_t *type = skip_typeref(top->type);
3805         if (is_type_union(type)) {
3806                 top->compound_entry = NULL;
3807         } else if (is_type_struct(type)) {
3808                 entity_t *entry = top->compound_entry;
3809
3810                 top->index++;
3811                 entry               = entry->base.next;
3812                 top->compound_entry = entry;
3813                 if (entry != NULL) {
3814                         assert(entry->kind == ENTITY_COMPOUND_MEMBER);
3815                         path->top_type = entry->declaration.type;
3816                         return;
3817                 }
3818         } else {
3819                 assert(is_type_array(type));
3820
3821                 top->index++;
3822                 if (!type->array.size_constant || top->index < type->array.size) {
3823                         return;
3824                 }
3825         }
3826
3827         /* we're past the last member of the current sub-aggregate, try if we
3828          * can ascend in the type hierarchy and continue with another subobject */
3829         size_t len = ARR_LEN(path->path);
3830
3831         if (len > 1) {
3832                 ascend_from_subtype(path);
3833                 advance_current_object(path);
3834         } else {
3835                 path->invalid = true;
3836         }
3837 }
3838
3839
3840 static ir_initializer_t *create_ir_initializer(
3841                 const initializer_t *initializer, type_t *type);
3842
3843 static ir_initializer_t *create_ir_initializer_value(
3844                 const initializer_value_t *initializer)
3845 {
3846         if (is_type_compound(initializer->value->base.type)) {
3847                 panic("initializer creation for compounds not implemented yet");
3848         }
3849         ir_node *value = expression_to_firm(initializer->value);
3850         type_t  *type  = initializer->value->base.type;
3851         ir_mode *mode  = get_ir_mode_storage(type);
3852         value          = create_conv(NULL, value, mode);
3853         return create_initializer_const(value);
3854 }
3855
3856 /** test wether type can be initialized by a string constant */
3857 static bool is_string_type(type_t *type)
3858 {
3859         type_t *inner;
3860         if (is_type_pointer(type)) {
3861                 inner = skip_typeref(type->pointer.points_to);
3862         } else if(is_type_array(type)) {
3863                 inner = skip_typeref(type->array.element_type);
3864         } else {
3865                 return false;
3866         }
3867
3868         return is_type_integer(inner);
3869 }
3870
3871 static ir_initializer_t *create_ir_initializer_list(
3872                 const initializer_list_t *initializer, type_t *type)
3873 {
3874         type_path_t path;
3875         memset(&path, 0, sizeof(path));
3876         path.top_type = type;
3877         path.path     = NEW_ARR_F(type_path_entry_t, 0);
3878
3879         descend_into_subtype(&path);
3880
3881         for (size_t i = 0; i < initializer->len; ++i) {
3882                 const initializer_t *sub_initializer = initializer->initializers[i];
3883
3884                 if (sub_initializer->kind == INITIALIZER_DESIGNATOR) {
3885                         walk_designator(&path, sub_initializer->designator.designator);
3886                         continue;
3887                 }
3888
3889                 if (sub_initializer->kind == INITIALIZER_VALUE) {
3890                         /* we might have to descend into types until we're at a scalar
3891                          * type */
3892                         while(true) {
3893                                 type_t *orig_top_type = path.top_type;
3894                                 type_t *top_type      = skip_typeref(orig_top_type);
3895
3896                                 if (is_type_scalar(top_type))
3897                                         break;
3898                                 descend_into_subtype(&path);
3899                         }
3900                 } else if (sub_initializer->kind == INITIALIZER_STRING
3901                                 || sub_initializer->kind == INITIALIZER_WIDE_STRING) {
3902                         /* we might have to descend into types until we're at a scalar
3903                          * type */
3904                         while (true) {
3905                                 type_t *orig_top_type = path.top_type;
3906                                 type_t *top_type      = skip_typeref(orig_top_type);
3907
3908                                 if (is_string_type(top_type))
3909                                         break;
3910                                 descend_into_subtype(&path);
3911                         }
3912                 }
3913
3914                 ir_initializer_t *sub_irinitializer
3915                         = create_ir_initializer(sub_initializer, path.top_type);
3916
3917                 size_t path_len = ARR_LEN(path.path);
3918                 assert(path_len >= 1);
3919                 type_path_entry_t *entry        = & path.path[path_len-1];
3920                 ir_initializer_t  *tinitializer = entry->initializer;
3921                 set_initializer_compound_value(tinitializer, entry->index,
3922                                                sub_irinitializer);
3923
3924                 advance_current_object(&path);
3925         }
3926
3927         assert(ARR_LEN(path.path) >= 1);
3928         ir_initializer_t *result = path.path[0].initializer;
3929         DEL_ARR_F(path.path);
3930
3931         return result;
3932 }
3933
3934 static ir_initializer_t *create_ir_initializer_string(
3935                 const initializer_string_t *initializer, type_t *type)
3936 {
3937         type = skip_typeref(type);
3938
3939         size_t            string_len    = initializer->string.size;
3940         assert(type->kind == TYPE_ARRAY);
3941         assert(type->array.size_constant);
3942         size_t            len           = type->array.size;
3943         ir_initializer_t *irinitializer = create_initializer_compound(len);
3944
3945         const char *string = initializer->string.begin;
3946         ir_mode    *mode   = get_ir_mode_storage(type->array.element_type);
3947
3948         for (size_t i = 0; i < len; ++i) {
3949                 char c = 0;
3950                 if (i < string_len)
3951                         c = string[i];
3952
3953                 tarval           *tv = new_tarval_from_long(c, mode);
3954                 ir_initializer_t *char_initializer = create_initializer_tarval(tv);
3955
3956                 set_initializer_compound_value(irinitializer, i, char_initializer);
3957         }
3958
3959         return irinitializer;
3960 }
3961
3962 static ir_initializer_t *create_ir_initializer_wide_string(
3963                 const initializer_wide_string_t *initializer, type_t *type)
3964 {
3965         size_t            string_len    = initializer->string.size;
3966         assert(type->kind == TYPE_ARRAY);
3967         assert(type->array.size_constant);
3968         size_t            len           = type->array.size;
3969         ir_initializer_t *irinitializer = create_initializer_compound(len);
3970
3971         const wchar_rep_t *string = initializer->string.begin;
3972         ir_mode           *mode   = get_type_mode(ir_type_wchar_t);
3973
3974         for (size_t i = 0; i < len; ++i) {
3975                 wchar_rep_t c = 0;
3976                 if (i < string_len) {
3977                         c = string[i];
3978                 }
3979                 tarval *tv = new_tarval_from_long(c, mode);
3980                 ir_initializer_t *char_initializer = create_initializer_tarval(tv);
3981
3982                 set_initializer_compound_value(irinitializer, i, char_initializer);
3983         }
3984
3985         return irinitializer;
3986 }
3987
3988 static ir_initializer_t *create_ir_initializer(
3989                 const initializer_t *initializer, type_t *type)
3990 {
3991         switch(initializer->kind) {
3992                 case INITIALIZER_STRING:
3993                         return create_ir_initializer_string(&initializer->string, type);
3994
3995                 case INITIALIZER_WIDE_STRING:
3996                         return create_ir_initializer_wide_string(&initializer->wide_string,
3997                                                                  type);
3998
3999                 case INITIALIZER_LIST:
4000                         return create_ir_initializer_list(&initializer->list, type);
4001
4002                 case INITIALIZER_VALUE:
4003                         return create_ir_initializer_value(&initializer->value);
4004
4005                 case INITIALIZER_DESIGNATOR:
4006                         panic("unexpected designator initializer found");
4007         }
4008         panic("unknown initializer");
4009 }
4010
4011 static void create_dynamic_null_initializer(ir_type *type, dbg_info *dbgi,
4012                 ir_node *base_addr)
4013 {
4014         if (is_atomic_type(type)) {
4015                 ir_mode *mode = get_type_mode(type);
4016                 tarval  *zero = get_mode_null(mode);
4017                 ir_node *cnst = new_d_Const(dbgi, zero);
4018
4019                 /* TODO: bitfields */
4020                 ir_node *mem    = get_store();
4021                 ir_node *store  = new_d_Store(dbgi, mem, base_addr, cnst, cons_none);
4022                 ir_node *proj_m = new_Proj(store, mode_M, pn_Store_M);
4023                 set_store(proj_m);
4024         } else {
4025                 assert(is_compound_type(type));
4026
4027                 int n_members;
4028                 if (is_Array_type(type)) {
4029                         assert(has_array_upper_bound(type, 0));
4030                         n_members = get_array_upper_bound_int(type, 0);
4031                 } else {
4032                         n_members = get_compound_n_members(type);
4033                 }
4034
4035                 for (int i = 0; i < n_members; ++i) {
4036                         ir_node *addr;
4037                         ir_type *irtype;
4038                         if (is_Array_type(type)) {
4039                                 ir_entity *entity   = get_array_element_entity(type);
4040                                 tarval    *index_tv = new_tarval_from_long(i, mode_uint);
4041                                 ir_node   *cnst     = new_d_Const(dbgi, index_tv);
4042                                 ir_node   *in[1]    = { cnst };
4043                                 irtype = get_array_element_type(type);
4044                                 addr   = new_d_Sel(dbgi, new_NoMem(), base_addr, 1, in, entity);
4045                         } else {
4046                                 ir_entity *member = get_compound_member(type, i);
4047
4048                                 irtype = get_entity_type(member);
4049                                 addr   = new_d_simpleSel(dbgi, new_NoMem(), base_addr, member);
4050                         }
4051
4052                         create_dynamic_null_initializer(irtype, dbgi, addr);
4053                 }
4054         }
4055 }
4056
4057 static void create_dynamic_initializer_sub(ir_initializer_t *initializer,
4058                 ir_entity *entity, ir_type *type, dbg_info *dbgi, ir_node *base_addr)
4059 {
4060         switch(get_initializer_kind(initializer)) {
4061         case IR_INITIALIZER_NULL: {
4062                 create_dynamic_null_initializer(type, dbgi, base_addr);
4063                 return;
4064         }
4065         case IR_INITIALIZER_CONST: {
4066                 ir_node *node     = get_initializer_const_value(initializer);
4067                 ir_mode *mode     = get_irn_mode(node);
4068                 ir_type *ent_type = get_entity_type(entity);
4069
4070                 /* is it a bitfield type? */
4071                 if (is_Primitive_type(ent_type) &&
4072                                 get_primitive_base_type(ent_type) != NULL) {
4073                         bitfield_store_to_firm(dbgi, entity, base_addr, node, false);
4074                         return;
4075                 }
4076
4077                 assert(get_type_mode(type) == mode);
4078                 ir_node *mem    = get_store();
4079                 ir_node *store  = new_d_Store(dbgi, mem, base_addr, node, cons_none);
4080                 ir_node *proj_m = new_Proj(store, mode_M, pn_Store_M);
4081                 set_store(proj_m);
4082                 return;
4083         }
4084         case IR_INITIALIZER_TARVAL: {
4085                 tarval  *tv       = get_initializer_tarval_value(initializer);
4086                 ir_mode *mode     = get_tarval_mode(tv);
4087                 ir_node *cnst     = new_d_Const(dbgi, tv);
4088                 ir_type *ent_type = get_entity_type(entity);
4089
4090                 /* is it a bitfield type? */
4091                 if (is_Primitive_type(ent_type) &&
4092                                 get_primitive_base_type(ent_type) != NULL) {
4093                         bitfield_store_to_firm(dbgi, entity, base_addr, cnst, false);
4094                         return;
4095                 }
4096
4097                 assert(get_type_mode(type) == mode);
4098                 ir_node *mem    = get_store();
4099                 ir_node *store  = new_d_Store(dbgi, mem, base_addr, cnst, cons_none);
4100                 ir_node *proj_m = new_Proj(store, mode_M, pn_Store_M);
4101                 set_store(proj_m);
4102                 return;
4103         }
4104         case IR_INITIALIZER_COMPOUND: {
4105                 assert(is_compound_type(type));
4106                 int n_members;
4107                 if (is_Array_type(type)) {
4108                         assert(has_array_upper_bound(type, 0));
4109                         n_members = get_array_upper_bound_int(type, 0);
4110                 } else {
4111                         n_members = get_compound_n_members(type);
4112                 }
4113
4114                 if (get_initializer_compound_n_entries(initializer)
4115                                 != (unsigned) n_members)
4116                         panic("initializer doesn't match compound type");
4117
4118                 for (int i = 0; i < n_members; ++i) {
4119                         ir_node   *addr;
4120                         ir_type   *irtype;
4121                         ir_entity *sub_entity;
4122                         if (is_Array_type(type)) {
4123                                 tarval    *index_tv = new_tarval_from_long(i, mode_uint);
4124                                 ir_node   *cnst     = new_d_Const(dbgi, index_tv);
4125                                 ir_node   *in[1]    = { cnst };
4126                                 irtype     = get_array_element_type(type);
4127                                 sub_entity = get_array_element_entity(type);
4128                                 addr       = new_d_Sel(dbgi, new_NoMem(), base_addr, 1, in,
4129                                                        sub_entity);
4130                         } else {
4131                                 sub_entity = get_compound_member(type, i);
4132                                 irtype     = get_entity_type(sub_entity);
4133                                 addr       = new_d_simpleSel(dbgi, new_NoMem(), base_addr,
4134                                                              sub_entity);
4135                         }
4136
4137                         ir_initializer_t *sub_init
4138                                 = get_initializer_compound_value(initializer, i);
4139
4140                         create_dynamic_initializer_sub(sub_init, sub_entity, irtype, dbgi,
4141                                                        addr);
4142                 }
4143                 return;
4144         }
4145         }
4146
4147         panic("invalid IR_INITIALIZER found");
4148 }
4149
4150 static void create_dynamic_initializer(ir_initializer_t *initializer,
4151                 dbg_info *dbgi, ir_entity *entity)
4152 {
4153         ir_node *frame     = get_local_frame(entity);
4154         ir_node *base_addr = new_d_simpleSel(dbgi, new_NoMem(), frame, entity);
4155         ir_type *type      = get_entity_type(entity);
4156
4157         create_dynamic_initializer_sub(initializer, entity, type, dbgi, base_addr);
4158 }
4159
4160 static void create_local_initializer(initializer_t *initializer, dbg_info *dbgi,
4161                                      ir_entity *entity, type_t *type)
4162 {
4163         ir_node *memory = get_store();
4164         ir_node *nomem  = new_NoMem();
4165         ir_node *frame  = get_irg_frame(current_ir_graph);
4166         ir_node *addr   = new_d_simpleSel(dbgi, nomem, frame, entity);
4167
4168         if (initializer->kind == INITIALIZER_VALUE) {
4169                 initializer_value_t *initializer_value = &initializer->value;
4170
4171                 ir_node *value = expression_to_firm(initializer_value->value);
4172                 type = skip_typeref(type);
4173                 assign_value(dbgi, addr, type, value);
4174                 return;
4175         }
4176
4177         if (!is_constant_initializer(initializer)) {
4178                 ir_initializer_t *irinitializer
4179                         = create_ir_initializer(initializer, type);
4180
4181                 create_dynamic_initializer(irinitializer, dbgi, entity);
4182                 return;
4183         }
4184
4185         /* create the ir_initializer */
4186         ir_graph *const old_current_ir_graph = current_ir_graph;
4187         current_ir_graph = get_const_code_irg();
4188
4189         ir_initializer_t *irinitializer = create_ir_initializer(initializer, type);
4190
4191         assert(current_ir_graph == get_const_code_irg());
4192         current_ir_graph = old_current_ir_graph;
4193
4194         /* create a "template" entity which is copied to the entity on the stack */
4195         ident     *const id          = id_unique("initializer.%u");
4196         ir_type   *const irtype      = get_ir_type(type);
4197         ir_type   *const global_type = get_glob_type();
4198         ir_entity *const init_entity = new_d_entity(global_type, id, irtype, dbgi);
4199         set_entity_ld_ident(init_entity, id);
4200
4201         set_entity_variability(init_entity, variability_initialized);
4202         set_entity_visibility(init_entity, visibility_local);
4203         set_entity_allocation(init_entity, allocation_static);
4204
4205         set_entity_initializer(init_entity, irinitializer);
4206
4207         ir_node *const src_addr = create_symconst(dbgi, mode_P_data, init_entity);
4208         ir_node *const copyb    = new_d_CopyB(dbgi, memory, addr, src_addr, irtype);
4209
4210         ir_node *const copyb_mem = new_Proj(copyb, mode_M, pn_CopyB_M_regular);
4211         set_store(copyb_mem);
4212 }
4213
4214 static void create_initializer_local_variable_entity(entity_t *entity)
4215 {
4216         assert(entity->kind == ENTITY_VARIABLE);
4217         initializer_t *initializer = entity->variable.initializer;
4218         dbg_info      *dbgi        = get_dbg_info(&entity->base.source_position);
4219         ir_entity     *irentity    = entity->variable.v.entity;
4220         type_t        *type        = entity->declaration.type;
4221
4222         type = get_aligned_type(type, entity->variable.alignment);
4223         create_local_initializer(initializer, dbgi, irentity, type);
4224 }
4225
4226 static void create_variable_initializer(entity_t *entity)
4227 {
4228         assert(entity->kind == ENTITY_VARIABLE);
4229         initializer_t *initializer = entity->variable.initializer;
4230         if (initializer == NULL)
4231                 return;
4232
4233         declaration_kind_t declaration_kind
4234                 = (declaration_kind_t) entity->declaration.kind;
4235         if (declaration_kind == DECLARATION_KIND_LOCAL_VARIABLE_ENTITY) {
4236                 create_initializer_local_variable_entity(entity);
4237                 return;
4238         }
4239
4240         type_t            *type = entity->declaration.type;
4241         type_qualifiers_t  tq   = get_type_qualifier(type, true);
4242
4243         if (initializer->kind == INITIALIZER_VALUE) {
4244                 initializer_value_t *initializer_value = &initializer->value;
4245                 dbg_info            *dbgi = get_dbg_info(&entity->base.source_position);
4246
4247                 ir_node *value = expression_to_firm(initializer_value->value);
4248
4249                 type_t  *type = initializer_value->value->base.type;
4250                 ir_mode *mode = get_ir_mode_storage(type);
4251                 value = create_conv(dbgi, value, mode);
4252                 value = do_strict_conv(dbgi, value);
4253
4254                 if (declaration_kind == DECLARATION_KIND_LOCAL_VARIABLE) {
4255                         set_value(entity->variable.v.value_number, value);
4256                 } else {
4257                         assert(declaration_kind == DECLARATION_KIND_GLOBAL_VARIABLE);
4258
4259                         ir_entity *irentity = entity->variable.v.entity;
4260
4261                         if (tq & TYPE_QUALIFIER_CONST) {
4262                                 set_entity_variability(irentity, variability_constant);
4263                         } else {
4264                                 set_entity_variability(irentity, variability_initialized);
4265                         }
4266                         set_atomic_ent_value(irentity, value);
4267                 }
4268         } else {
4269                 assert(declaration_kind == DECLARATION_KIND_LOCAL_VARIABLE_ENTITY ||
4270                        declaration_kind == DECLARATION_KIND_GLOBAL_VARIABLE);
4271
4272                 ir_entity        *irentity        = entity->variable.v.entity;
4273                 ir_initializer_t *irinitializer
4274                         = create_ir_initializer(initializer, type);
4275
4276                 if (tq & TYPE_QUALIFIER_CONST) {
4277                         set_entity_variability(irentity, variability_constant);
4278                 } else {
4279                         set_entity_variability(irentity, variability_initialized);
4280                 }
4281                 set_entity_initializer(irentity, irinitializer);
4282         }
4283 }
4284
4285 static void create_variable_length_array(entity_t *entity)
4286 {
4287         assert(entity->kind == ENTITY_VARIABLE);
4288         assert(entity->variable.initializer == NULL);
4289
4290         entity->declaration.kind    = DECLARATION_KIND_VARIABLE_LENGTH_ARRAY;
4291         entity->variable.v.vla_base = NULL;
4292
4293         /* TODO: record VLA somewhere so we create the free node when we leave
4294          * it's scope */
4295 }
4296
4297 static void allocate_variable_length_array(entity_t *entity)
4298 {
4299         assert(entity->kind == ENTITY_VARIABLE);
4300         assert(entity->variable.initializer == NULL);
4301         assert(get_cur_block() != NULL);
4302
4303         dbg_info *dbgi      = get_dbg_info(&entity->base.source_position);
4304         type_t   *type      = entity->declaration.type;
4305         ir_type  *el_type   = get_ir_type(type->array.element_type);
4306
4307         /* make sure size_node is calculated */
4308         get_type_size(type);
4309         ir_node  *elems = type->array.size_node;
4310         ir_node  *mem   = get_store();
4311         ir_node  *alloc = new_d_Alloc(dbgi, mem, elems, el_type, stack_alloc);
4312
4313         ir_node  *proj_m = new_d_Proj(dbgi, alloc, mode_M, pn_Alloc_M);
4314         ir_node  *addr   = new_d_Proj(dbgi, alloc, mode_P_data, pn_Alloc_res);
4315         set_store(proj_m);
4316
4317         assert(entity->declaration.kind == DECLARATION_KIND_VARIABLE_LENGTH_ARRAY);
4318         entity->variable.v.vla_base = addr;
4319 }
4320
4321 /**
4322  * Creates a Firm local variable from a declaration.
4323  */
4324 static void create_local_variable(entity_t *entity)
4325 {
4326         assert(entity->kind == ENTITY_VARIABLE);
4327         assert(entity->declaration.kind == DECLARATION_KIND_UNKNOWN);
4328
4329         bool needs_entity = entity->variable.address_taken;
4330         type_t *type = skip_typeref(entity->declaration.type);
4331
4332         /* is it a variable length array? */
4333         if (is_type_array(type) && !type->array.size_constant) {
4334                 create_variable_length_array(entity);
4335                 return;
4336         } else if (is_type_array(type) || is_type_compound(type)) {
4337                 needs_entity = true;
4338         } else if (type->base.qualifiers & TYPE_QUALIFIER_VOLATILE) {
4339                 needs_entity = true;
4340         }
4341
4342         if (needs_entity) {
4343                 ir_type *frame_type = get_irg_frame_type(current_ir_graph);
4344                 create_variable_entity(entity,
4345                                        DECLARATION_KIND_LOCAL_VARIABLE_ENTITY,
4346                                        frame_type);
4347         } else {
4348                 entity->declaration.kind        = DECLARATION_KIND_LOCAL_VARIABLE;
4349                 entity->variable.v.value_number = next_value_number_function;
4350                 set_irg_loc_description(current_ir_graph, next_value_number_function,
4351                                         entity);
4352                 ++next_value_number_function;
4353         }
4354 }
4355
4356 static void create_local_static_variable(entity_t *entity)
4357 {
4358         assert(entity->kind == ENTITY_VARIABLE);
4359         assert(entity->declaration.kind == DECLARATION_KIND_UNKNOWN);
4360
4361         type_t    *type = skip_typeref(entity->declaration.type);
4362         type            = get_aligned_type(type, entity->variable.alignment);
4363
4364         ir_type   *const var_type = entity->variable.thread_local ?
4365                 get_tls_type() : get_glob_type();
4366         ir_type   *const irtype   = get_ir_type(type);
4367         dbg_info  *const dbgi     = get_dbg_info(&entity->base.source_position);
4368
4369         size_t l = strlen(entity->base.symbol->string);
4370         char   buf[l + sizeof(".%u")];
4371         snprintf(buf, sizeof(buf), "%s.%%u", entity->base.symbol->string);
4372         ident     *const id = id_unique(buf);
4373
4374         ir_entity *const irentity = new_d_entity(var_type, id, irtype, dbgi);
4375
4376         if (type->base.qualifiers & TYPE_QUALIFIER_VOLATILE) {
4377                 set_entity_volatility(irentity, volatility_is_volatile);
4378         }
4379
4380         entity->declaration.kind  = DECLARATION_KIND_GLOBAL_VARIABLE;
4381         entity->variable.v.entity = irentity;
4382
4383         set_entity_ld_ident(irentity, id);
4384         set_entity_variability(irentity, variability_uninitialized);
4385         set_entity_visibility(irentity, visibility_local);
4386         set_entity_allocation(irentity, entity->variable.thread_local ?
4387                 allocation_automatic : allocation_static);
4388
4389         ir_graph *const old_current_ir_graph = current_ir_graph;
4390         current_ir_graph = get_const_code_irg();
4391
4392         create_variable_initializer(entity);
4393
4394         assert(current_ir_graph == get_const_code_irg());
4395         current_ir_graph = old_current_ir_graph;
4396 }
4397
4398
4399
4400 static void return_statement_to_firm(return_statement_t *statement)
4401 {
4402         if (get_cur_block() == NULL)
4403                 return;
4404
4405         dbg_info *dbgi        = get_dbg_info(&statement->base.source_position);
4406         type_t   *type        = current_function_entity->declaration.type;
4407         ir_type  *func_irtype = get_ir_type(type);
4408
4409
4410         ir_node *in[1];
4411         int      in_len;
4412         if (get_method_n_ress(func_irtype) > 0) {
4413                 ir_type *res_type = get_method_res_type(func_irtype, 0);
4414
4415                 if (statement->value != NULL) {
4416                         ir_node *node = expression_to_firm(statement->value);
4417                         if (!is_compound_type(res_type)) {
4418                                 type_t  *type = statement->value->base.type;
4419                                 ir_mode *mode = get_ir_mode_storage(type);
4420                                 node          = create_conv(dbgi, node, mode);
4421                                 node          = do_strict_conv(dbgi, node);
4422                         }
4423                         in[0] = node;
4424                 } else {
4425                         ir_mode *mode;
4426                         if (is_compound_type(res_type)) {
4427                                 mode = mode_P_data;
4428                         } else {
4429                                 mode = get_type_mode(res_type);
4430                         }
4431                         in[0] = new_Unknown(mode);
4432                 }
4433                 in_len = 1;
4434         } else {
4435                 /* build return_value for its side effects */
4436                 if (statement->value != NULL) {
4437                         expression_to_firm(statement->value);
4438                 }
4439                 in_len = 0;
4440         }
4441
4442         ir_node  *store = get_store();
4443         ir_node  *ret   = new_d_Return(dbgi, store, in_len, in);
4444
4445         ir_node *end_block = get_irg_end_block(current_ir_graph);
4446         add_immBlock_pred(end_block, ret);
4447
4448         set_cur_block(NULL);
4449 }
4450
4451 static ir_node *expression_statement_to_firm(expression_statement_t *statement)
4452 {
4453         if (get_cur_block() == NULL)
4454                 return NULL;
4455
4456         return expression_to_firm(statement->expression);
4457 }
4458
4459 static ir_node *compound_statement_to_firm(compound_statement_t *compound)
4460 {
4461         entity_t *entity = compound->scope.entities;
4462         for ( ; entity != NULL; entity = entity->base.next) {
4463                 if (!is_declaration(entity))
4464                         continue;
4465
4466                 create_local_declaration(entity);
4467         }
4468
4469         ir_node     *result    = NULL;
4470         statement_t *statement = compound->statements;
4471         for ( ; statement != NULL; statement = statement->base.next) {
4472                 if (statement->base.next == NULL
4473                                 && statement->kind == STATEMENT_EXPRESSION) {
4474                         result = expression_statement_to_firm(
4475                                         &statement->expression);
4476                         break;
4477                 }
4478                 statement_to_firm(statement);
4479         }
4480
4481         return result;
4482 }
4483
4484 static void create_global_variable(entity_t *entity)
4485 {
4486         assert(entity->kind == ENTITY_VARIABLE);
4487
4488         ir_visibility vis;
4489         switch ((storage_class_tag_t)entity->declaration.storage_class) {
4490                 case STORAGE_CLASS_STATIC: vis = visibility_local;              break;
4491                 case STORAGE_CLASS_EXTERN: vis = visibility_external_allocated; break;
4492                 case STORAGE_CLASS_NONE:   vis = visibility_external_visible;   break;
4493
4494                 default: panic("Invalid storage class for global variable");
4495         }
4496
4497         ir_type *var_type = entity->variable.thread_local ?
4498                 get_tls_type() : get_glob_type();
4499         create_variable_entity(entity,
4500                         DECLARATION_KIND_GLOBAL_VARIABLE, var_type);
4501         set_entity_visibility(entity->variable.v.entity, vis);
4502 }
4503
4504 static void create_local_declaration(entity_t *entity)
4505 {
4506         assert(is_declaration(entity));
4507
4508         /* construct type */
4509         (void) get_ir_type(entity->declaration.type);
4510         if (entity->base.symbol == NULL) {
4511                 return;
4512         }
4513
4514         switch ((storage_class_tag_t) entity->declaration.storage_class) {
4515         case STORAGE_CLASS_STATIC:
4516                 create_local_static_variable(entity);
4517                 return;
4518         case STORAGE_CLASS_EXTERN:
4519                 if (entity->kind == ENTITY_FUNCTION) {
4520                         assert(entity->function.statement == NULL);
4521                         get_function_entity(entity);
4522                 } else {
4523                         create_global_variable(entity);
4524                         create_variable_initializer(entity);
4525                 }
4526                 return;
4527         case STORAGE_CLASS_NONE:
4528         case STORAGE_CLASS_AUTO:
4529         case STORAGE_CLASS_REGISTER:
4530                 if (entity->kind == ENTITY_FUNCTION) {
4531                         if (entity->function.statement != NULL) {
4532                                 get_function_entity(entity);
4533                                 entity->declaration.kind = DECLARATION_KIND_INNER_FUNCTION;
4534                                 enqueue_inner_function(entity);
4535                         } else {
4536                                 get_function_entity(entity);
4537                         }
4538                 } else {
4539                         create_local_variable(entity);
4540                 }
4541                 return;
4542         case STORAGE_CLASS_TYPEDEF:
4543                 break;
4544         }
4545         panic("invalid storage class found");
4546 }
4547
4548 static void initialize_local_declaration(entity_t *entity)
4549 {
4550         if (entity->base.symbol == NULL)
4551                 return;
4552
4553         switch ((declaration_kind_t) entity->declaration.kind) {
4554         case DECLARATION_KIND_LOCAL_VARIABLE:
4555         case DECLARATION_KIND_LOCAL_VARIABLE_ENTITY:
4556                 create_variable_initializer(entity);
4557                 return;
4558
4559         case DECLARATION_KIND_VARIABLE_LENGTH_ARRAY:
4560                 allocate_variable_length_array(entity);
4561                 return;
4562
4563         case DECLARATION_KIND_COMPOUND_MEMBER:
4564         case DECLARATION_KIND_GLOBAL_VARIABLE:
4565         case DECLARATION_KIND_FUNCTION:
4566         case DECLARATION_KIND_INNER_FUNCTION:
4567                 return;
4568
4569         case DECLARATION_KIND_PARAMETER:
4570         case DECLARATION_KIND_PARAMETER_ENTITY:
4571                 panic("can't initialize parameters");
4572
4573         case DECLARATION_KIND_UNKNOWN:
4574                 panic("can't initialize unknown declaration");
4575         }
4576         panic("invalid declaration kind");
4577 }
4578
4579 static void declaration_statement_to_firm(declaration_statement_t *statement)
4580 {
4581         entity_t *entity = statement->declarations_begin;
4582         if (entity == NULL)
4583                 return;
4584
4585         entity_t *const last = statement->declarations_end;
4586         for ( ;; entity = entity->base.next) {
4587                 if (is_declaration(entity)) {
4588                         initialize_local_declaration(entity);
4589                 } else if (entity->kind == ENTITY_TYPEDEF) {
4590                         type_t *const type = skip_typeref(entity->typedefe.type);
4591                         if (is_type_array(type) && type->array.is_vla)
4592                                 get_vla_size(&type->array);
4593                 }
4594                 if (entity == last)
4595                         break;
4596         }
4597 }
4598
4599 static void if_statement_to_firm(if_statement_t *statement)
4600 {
4601         ir_node *cur_block = get_cur_block();
4602
4603         ir_node *fallthrough_block = NULL;
4604
4605         /* the true (blocks) */
4606         ir_node *true_block = NULL;
4607         if (statement->true_statement != NULL) {
4608                 true_block = new_immBlock();
4609                 set_cur_block(true_block);
4610                 statement_to_firm(statement->true_statement);
4611                 if (get_cur_block() != NULL) {
4612                         ir_node *jmp = new_Jmp();
4613                         if (fallthrough_block == NULL)
4614                                 fallthrough_block = new_immBlock();
4615                         add_immBlock_pred(fallthrough_block, jmp);
4616                 }
4617         }
4618
4619         /* the false (blocks) */
4620         ir_node *false_block = NULL;
4621         if (statement->false_statement != NULL) {
4622                 false_block = new_immBlock();
4623                 set_cur_block(false_block);
4624
4625                 statement_to_firm(statement->false_statement);
4626                 if (get_cur_block() != NULL) {
4627                         ir_node *jmp = new_Jmp();
4628                         if (fallthrough_block == NULL)
4629                                 fallthrough_block = new_immBlock();
4630                         add_immBlock_pred(fallthrough_block, jmp);
4631                 }
4632         }
4633
4634         /* create the condition */
4635         if (cur_block != NULL) {
4636                 if (true_block == NULL || false_block == NULL) {
4637                         if (fallthrough_block == NULL)
4638                                 fallthrough_block = new_immBlock();
4639                         if (true_block == NULL)
4640                                 true_block = fallthrough_block;
4641                         if (false_block == NULL)
4642                                 false_block = fallthrough_block;
4643                 }
4644
4645                 set_cur_block(cur_block);
4646                 create_condition_evaluation(statement->condition, true_block,
4647                                             false_block);
4648         }
4649
4650         mature_immBlock(true_block);
4651         if (false_block != fallthrough_block && false_block != NULL) {
4652                 mature_immBlock(false_block);
4653         }
4654         if (fallthrough_block != NULL) {
4655                 mature_immBlock(fallthrough_block);
4656         }
4657
4658         set_cur_block(fallthrough_block);
4659 }
4660
4661 static void while_statement_to_firm(while_statement_t *statement)
4662 {
4663         ir_node *jmp = NULL;
4664         if (get_cur_block() != NULL) {
4665                 jmp = new_Jmp();
4666         }
4667
4668         /* create the header block */
4669         ir_node *header_block = new_immBlock();
4670         if (jmp != NULL) {
4671                 add_immBlock_pred(header_block, jmp);
4672         }
4673
4674         /* the loop body */
4675         ir_node *old_continue_label = continue_label;
4676         ir_node *old_break_label    = break_label;
4677         continue_label              = header_block;
4678         break_label                 = NULL;
4679
4680         ir_node *body_block = new_immBlock();
4681         set_cur_block(body_block);
4682         statement_to_firm(statement->body);
4683         ir_node *false_block = break_label;
4684
4685         assert(continue_label == header_block);
4686         continue_label = old_continue_label;
4687         break_label    = old_break_label;
4688
4689         if (get_cur_block() != NULL) {
4690                 jmp = new_Jmp();
4691                 add_immBlock_pred(header_block, jmp);
4692         }
4693
4694         /* shortcut for while(true) */
4695         if (is_constant_expression(statement->condition)
4696                         && fold_constant(statement->condition) != 0) {
4697                 set_cur_block(header_block);
4698                 ir_node *header_jmp = new_Jmp();
4699                 add_immBlock_pred(body_block, header_jmp);
4700
4701                 keep_alive(body_block);
4702                 keep_all_memory(body_block);
4703                 set_cur_block(body_block);
4704         } else {
4705                 if (false_block == NULL) {
4706                         false_block = new_immBlock();
4707                 }
4708
4709                 /* create the condition */
4710                 set_cur_block(header_block);
4711
4712                 create_condition_evaluation(statement->condition, body_block,
4713                                             false_block);
4714         }
4715
4716         mature_immBlock(body_block);
4717         mature_immBlock(header_block);
4718         if (false_block != NULL) {
4719                 mature_immBlock(false_block);
4720         }
4721
4722         set_cur_block(false_block);
4723 }
4724
4725 static void do_while_statement_to_firm(do_while_statement_t *statement)
4726 {
4727         ir_node *jmp = NULL;
4728         if (get_cur_block() != NULL) {
4729                 jmp = new_Jmp();
4730         }
4731
4732         /* create the header block */
4733         ir_node *header_block = new_immBlock();
4734
4735         /* the loop body */
4736         ir_node *body_block = new_immBlock();
4737         if (jmp != NULL) {
4738                 add_immBlock_pred(body_block, jmp);
4739         }
4740
4741         ir_node *old_continue_label = continue_label;
4742         ir_node *old_break_label    = break_label;
4743         continue_label              = header_block;
4744         break_label                 = NULL;
4745
4746         set_cur_block(body_block);
4747         statement_to_firm(statement->body);
4748         ir_node *false_block = break_label;
4749
4750         assert(continue_label == header_block);
4751         continue_label = old_continue_label;
4752         break_label    = old_break_label;
4753
4754         if (get_cur_block() != NULL) {
4755                 ir_node *body_jmp = new_Jmp();
4756                 add_immBlock_pred(header_block, body_jmp);
4757                 mature_immBlock(header_block);
4758         }
4759
4760         if (false_block == NULL) {
4761                 false_block = new_immBlock();
4762         }
4763
4764         /* create the condition */
4765         set_cur_block(header_block);
4766
4767         create_condition_evaluation(statement->condition, body_block, false_block);
4768         mature_immBlock(body_block);
4769         mature_immBlock(header_block);
4770         mature_immBlock(false_block);
4771
4772         set_cur_block(false_block);
4773 }
4774
4775 static void for_statement_to_firm(for_statement_t *statement)
4776 {
4777         ir_node *jmp = NULL;
4778
4779         /* create declarations */
4780         entity_t *entity = statement->scope.entities;
4781         for ( ; entity != NULL; entity = entity->base.next) {
4782                 if (!is_declaration(entity))
4783                         continue;
4784
4785                 create_local_declaration(entity);
4786         }
4787
4788         if (get_cur_block() != NULL) {
4789                 entity = statement->scope.entities;
4790                 for ( ; entity != NULL; entity = entity->base.next) {
4791                         if (!is_declaration(entity))
4792                                 continue;
4793
4794                         initialize_local_declaration(entity);
4795                 }
4796
4797                 if (statement->initialisation != NULL) {
4798                         expression_to_firm(statement->initialisation);
4799                 }
4800
4801                 jmp = new_Jmp();
4802         }
4803
4804
4805         /* create the step block */
4806         ir_node *const step_block = new_immBlock();
4807         set_cur_block(step_block);
4808         if (statement->step != NULL) {
4809                 expression_to_firm(statement->step);
4810         }
4811         ir_node *const step_jmp = new_Jmp();
4812
4813         /* create the header block */
4814         ir_node *const header_block = new_immBlock();
4815         set_cur_block(header_block);
4816         if (jmp != NULL) {
4817                 add_immBlock_pred(header_block, jmp);
4818         }
4819         add_immBlock_pred(header_block, step_jmp);
4820
4821         /* the false block */
4822         ir_node *const false_block = new_immBlock();
4823
4824         /* the loop body */
4825         ir_node *body_block;
4826         if (statement->body != NULL) {
4827                 ir_node *const old_continue_label = continue_label;
4828                 ir_node *const old_break_label    = break_label;
4829                 continue_label = step_block;
4830                 break_label    = false_block;
4831
4832                 body_block = new_immBlock();
4833                 set_cur_block(body_block);
4834                 statement_to_firm(statement->body);
4835
4836                 assert(continue_label == step_block);
4837                 assert(break_label    == false_block);
4838                 continue_label = old_continue_label;
4839                 break_label    = old_break_label;
4840
4841                 if (get_cur_block() != NULL) {
4842                         jmp = new_Jmp();
4843                         add_immBlock_pred(step_block, jmp);
4844                 }
4845         } else {
4846                 body_block = step_block;
4847         }
4848
4849         /* create the condition */
4850         set_cur_block(header_block);
4851         if (statement->condition != NULL) {
4852                 create_condition_evaluation(statement->condition, body_block,
4853                                             false_block);
4854         } else {
4855                 keep_alive(header_block);
4856                 keep_all_memory(header_block);
4857                 jmp = new_Jmp();
4858                 add_immBlock_pred(body_block, jmp);
4859         }
4860
4861         mature_immBlock(body_block);
4862         mature_immBlock(false_block);
4863         mature_immBlock(step_block);
4864         mature_immBlock(header_block);
4865         mature_immBlock(false_block);
4866
4867         set_cur_block(false_block);
4868 }
4869
4870 static void create_jump_statement(const statement_t *statement,
4871                                   ir_node *target_block)
4872 {
4873         if (get_cur_block() == NULL)
4874                 return;
4875
4876         dbg_info *dbgi = get_dbg_info(&statement->base.source_position);
4877         ir_node  *jump = new_d_Jmp(dbgi);
4878         add_immBlock_pred(target_block, jump);
4879
4880         set_cur_block(NULL);
4881 }
4882
4883 static ir_node *get_break_label(void)
4884 {
4885         if (break_label == NULL) {
4886                 break_label = new_immBlock();
4887         }
4888         return break_label;
4889 }
4890
4891 static void switch_statement_to_firm(switch_statement_t *statement)
4892 {
4893         dbg_info *dbgi = get_dbg_info(&statement->base.source_position);
4894
4895         ir_node *expression  = expression_to_firm(statement->expression);
4896         ir_node *cond        = new_d_Cond(dbgi, expression);
4897
4898         set_cur_block(NULL);
4899
4900         ir_node *const old_switch_cond       = current_switch_cond;
4901         ir_node *const old_break_label       = break_label;
4902         const bool     old_saw_default_label = saw_default_label;
4903         saw_default_label                    = false;
4904         current_switch_cond                  = cond;
4905         break_label                          = NULL;
4906         switch_statement_t *const old_switch = current_switch;
4907         current_switch                       = statement;
4908
4909         /* determine a free number for the default label */
4910         unsigned long num_cases = 0;
4911         long def_nr = 0;
4912         for (case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
4913                 if (l->expression == NULL) {
4914                         /* default case */
4915                         continue;
4916                 }
4917                 if (l->last_case >= l->first_case)
4918                         num_cases += l->last_case - l->first_case + 1;
4919                 if (l->last_case > def_nr)
4920                         def_nr = l->last_case;
4921         }
4922
4923         if (def_nr == INT_MAX) {
4924                 /* Bad: an overflow will occurr, we cannot be sure that the
4925                  * maximum + 1 is a free number. Scan the values a second
4926                  * time to find a free number.
4927                  */
4928                 unsigned char *bits = xmalloc((num_cases + 7) >> 3);
4929
4930                 memset(bits, 0, (num_cases + 7) >> 3);
4931                 for (case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
4932                         if (l->expression == NULL) {
4933                                 /* default case */
4934                                 continue;
4935                         }
4936                         unsigned long start = l->first_case > 0 ? (unsigned long)l->first_case : 0;
4937                         if (start < num_cases && l->last_case >= 0) {
4938                                 unsigned long end  = (unsigned long)l->last_case < num_cases ?
4939                                         (unsigned long)l->last_case : num_cases - 1;
4940                                 for (unsigned long cns = start; cns <= end; ++cns) {
4941                                         bits[cns >> 3] |= (1 << (cns & 7));
4942                                 }
4943                         }
4944                 }
4945                 /* We look at the first num_cases constants:
4946                  * Either they are densed, so we took the last (num_cases)
4947                  * one, or they are non densed, so we will find one free
4948                  * there...
4949                  */
4950                 unsigned long i;
4951                 for (i = 0; i < num_cases; ++i)
4952                         if ((bits[i >> 3] & (1 << (i & 7))) == 0)
4953                                 break;
4954
4955                 free(bits);
4956                 def_nr = i;
4957         } else {
4958                 ++def_nr;
4959         }
4960         statement->default_proj_nr = def_nr;
4961
4962         if (statement->body != NULL) {
4963                 statement_to_firm(statement->body);
4964         }
4965
4966         if (get_cur_block() != NULL) {
4967                 ir_node *jmp = new_Jmp();
4968                 add_immBlock_pred(get_break_label(), jmp);
4969         }
4970
4971         if (!saw_default_label) {
4972                 set_cur_block(get_nodes_block(cond));
4973                 ir_node *const proj = new_d_defaultProj(dbgi, cond,
4974                                                         statement->default_proj_nr);
4975                 add_immBlock_pred(get_break_label(), proj);
4976         }
4977
4978         if (break_label != NULL) {
4979                 mature_immBlock(break_label);
4980         }
4981         set_cur_block(break_label);
4982
4983         assert(current_switch_cond == cond);
4984         current_switch      = old_switch;
4985         current_switch_cond = old_switch_cond;
4986         break_label         = old_break_label;
4987         saw_default_label   = old_saw_default_label;
4988 }
4989
4990 static void case_label_to_firm(const case_label_statement_t *statement)
4991 {
4992         if (statement->is_empty_range)
4993                 return;
4994
4995         dbg_info *dbgi = get_dbg_info(&statement->base.source_position);
4996
4997         ir_node *const fallthrough = (get_cur_block() == NULL ? NULL : new_Jmp());
4998
4999         ir_node *proj;
5000         ir_node *block     = new_immBlock();
5001
5002         set_cur_block(get_nodes_block(current_switch_cond));
5003         if (statement->expression != NULL) {
5004                 long pn     = statement->first_case;
5005                 long end_pn = statement->last_case;
5006                 assert(pn <= end_pn);
5007                 /* create jumps for all cases in the given range */
5008                 do {
5009                         proj = new_d_Proj(dbgi, current_switch_cond, mode_X, pn);
5010                         add_immBlock_pred(block, proj);
5011                 } while(pn++ < end_pn);
5012         } else {
5013                 saw_default_label = true;
5014                 proj = new_d_defaultProj(dbgi, current_switch_cond,
5015                                          current_switch->default_proj_nr);
5016
5017                 add_immBlock_pred(block, proj);
5018         }
5019
5020         if (fallthrough != NULL) {
5021                 add_immBlock_pred(block, fallthrough);
5022         }
5023         mature_immBlock(block);
5024         set_cur_block(block);
5025
5026         if (statement->statement != NULL) {
5027                 statement_to_firm(statement->statement);
5028         }
5029 }
5030
5031 static void label_to_firm(const label_statement_t *statement)
5032 {
5033         ir_node *block = get_label_block(statement->label);
5034
5035         if (get_cur_block() != NULL) {
5036                 ir_node *jmp = new_Jmp();
5037                 add_immBlock_pred(block, jmp);
5038         }
5039
5040         set_cur_block(block);
5041         keep_alive(block);
5042         keep_all_memory(block);
5043
5044         if (statement->statement != NULL) {
5045                 statement_to_firm(statement->statement);
5046         }
5047 }
5048
5049 static void goto_to_firm(const goto_statement_t *statement)
5050 {
5051         if (get_cur_block() == NULL)
5052                 return;
5053
5054         if (statement->expression) {
5055                 ir_node  *irn  = expression_to_firm(statement->expression);
5056                 dbg_info *dbgi = get_dbg_info(&statement->base.source_position);
5057                 ir_node  *ijmp = new_d_IJmp(dbgi, irn);
5058
5059                 set_irn_link(ijmp, ijmp_list);
5060                 ijmp_list = ijmp;
5061         } else {
5062                 ir_node *block = get_label_block(statement->label);
5063                 ir_node *jmp   = new_Jmp();
5064                 add_immBlock_pred(block, jmp);
5065         }
5066         set_cur_block(NULL);
5067 }
5068
5069 static void asm_statement_to_firm(const asm_statement_t *statement)
5070 {
5071         bool needs_memory = false;
5072
5073         if (statement->is_volatile) {
5074                 needs_memory = true;
5075         }
5076
5077         size_t         n_clobbers = 0;
5078         asm_clobber_t *clobber    = statement->clobbers;
5079         for ( ; clobber != NULL; clobber = clobber->next) {
5080                 const char *clobber_str = clobber->clobber.begin;
5081
5082                 if (!be_is_valid_clobber(clobber_str)) {
5083                         errorf(&statement->base.source_position,
5084                                    "invalid clobber '%s' specified", clobber->clobber);
5085                         continue;
5086                 }
5087
5088                 if (strcmp(clobber_str, "memory") == 0) {
5089                         needs_memory = true;
5090                         continue;
5091                 }
5092
5093                 ident *id = new_id_from_str(clobber_str);
5094                 obstack_ptr_grow(&asm_obst, id);
5095                 ++n_clobbers;
5096         }
5097         assert(obstack_object_size(&asm_obst) == n_clobbers * sizeof(ident*));
5098         ident **clobbers = NULL;
5099         if (n_clobbers > 0) {
5100                 clobbers = obstack_finish(&asm_obst);
5101         }
5102
5103         size_t n_inputs  = 0;
5104         asm_argument_t *argument = statement->inputs;
5105         for ( ; argument != NULL; argument = argument->next)
5106                 n_inputs++;
5107         size_t n_outputs = 0;
5108         argument = statement->outputs;
5109         for ( ; argument != NULL; argument = argument->next)
5110                 n_outputs++;
5111
5112         unsigned next_pos = 0;
5113
5114         ir_node *ins[n_inputs + n_outputs + 1];
5115         size_t   in_size = 0;
5116
5117         ir_asm_constraint tmp_in_constraints[n_outputs];
5118
5119         const expression_t *out_exprs[n_outputs];
5120         ir_node            *out_addrs[n_outputs];
5121         size_t              out_size = 0;
5122
5123         argument = statement->outputs;
5124         for ( ; argument != NULL; argument = argument->next) {
5125                 const char *constraints = argument->constraints.begin;
5126                 asm_constraint_flags_t asm_flags
5127                         = be_parse_asm_constraints(constraints);
5128
5129                 if (asm_flags & ASM_CONSTRAINT_FLAG_NO_SUPPORT) {
5130                         warningf(&statement->base.source_position,
5131                                "some constraints in '%s' are not supported", constraints);
5132                 }
5133                 if (asm_flags & ASM_CONSTRAINT_FLAG_INVALID) {
5134                         errorf(&statement->base.source_position,
5135                                "some constraints in '%s' are invalid", constraints);
5136                         continue;
5137                 }
5138                 if (! (asm_flags & ASM_CONSTRAINT_FLAG_MODIFIER_WRITE)) {
5139                         errorf(&statement->base.source_position,
5140                                "no write flag specified for output constraints '%s'",
5141                                constraints);
5142                         continue;
5143                 }
5144
5145                 unsigned pos = next_pos++;
5146                 if ( (asm_flags & ASM_CONSTRAINT_FLAG_SUPPORTS_IMMEDIATE)
5147                                 || (asm_flags & ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER) ) {
5148                         expression_t *expr = argument->expression;
5149                         ir_node      *addr = expression_to_addr(expr);
5150                         /* in+output, construct an artifical same_as constraint on the
5151                          * input */
5152                         if (asm_flags & ASM_CONSTRAINT_FLAG_MODIFIER_READ) {
5153                                 char     buf[64];
5154                                 ir_node *value = get_value_from_lvalue(expr, addr);
5155
5156                                 snprintf(buf, sizeof(buf), "%u", pos);
5157
5158                                 ir_asm_constraint constraint;
5159                                 constraint.pos              = pos;
5160                                 constraint.constraint       = new_id_from_str(buf);
5161                                 constraint.mode             = get_ir_mode_storage(expr->base.type);
5162                                 tmp_in_constraints[in_size] = constraint;
5163                                 ins[in_size] = value;
5164
5165                                 ++in_size;
5166                         }
5167
5168                         out_exprs[out_size] = expr;
5169                         out_addrs[out_size] = addr;
5170                         ++out_size;
5171                 } else if (asm_flags & ASM_CONSTRAINT_FLAG_SUPPORTS_MEMOP) {
5172                         /* pure memory ops need no input (but we have to make sure we
5173                          * attach to the memory) */
5174                         assert(! (asm_flags &
5175                                                 (ASM_CONSTRAINT_FLAG_SUPPORTS_IMMEDIATE
5176                                                  | ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER)));
5177                         needs_memory = true;
5178
5179                         /* we need to attach the address to the inputs */
5180                         expression_t *expr = argument->expression;
5181
5182                         ir_asm_constraint constraint;
5183                         constraint.pos              = pos;
5184                         constraint.constraint       = new_id_from_str(constraints);
5185                         constraint.mode             = NULL;
5186                         tmp_in_constraints[in_size] = constraint;
5187
5188                         ins[in_size]          = expression_to_addr(expr);
5189                         ++in_size;
5190                         continue;
5191                 } else {
5192                         errorf(&statement->base.source_position,
5193                                "only modifiers but no place set in constraints '%s'",
5194                                constraints);
5195                         continue;
5196                 }
5197
5198                 ir_asm_constraint constraint;
5199                 constraint.pos        = pos;
5200                 constraint.constraint = new_id_from_str(constraints);
5201                 constraint.mode       = get_ir_mode_storage(argument->expression->base.type);
5202
5203                 obstack_grow(&asm_obst, &constraint, sizeof(constraint));
5204         }
5205         assert(obstack_object_size(&asm_obst)
5206                         == out_size * sizeof(ir_asm_constraint));
5207         ir_asm_constraint *output_constraints = obstack_finish(&asm_obst);
5208
5209
5210         obstack_grow(&asm_obst, tmp_in_constraints,
5211                      in_size * sizeof(tmp_in_constraints[0]));
5212         /* find and count input and output arguments */
5213         argument = statement->inputs;
5214         for ( ; argument != NULL; argument = argument->next) {
5215                 const char *constraints = argument->constraints.begin;
5216                 asm_constraint_flags_t asm_flags
5217                         = be_parse_asm_constraints(constraints);
5218
5219                 if (asm_flags & ASM_CONSTRAINT_FLAG_NO_SUPPORT) {
5220                         errorf(&statement->base.source_position,
5221                                "some constraints in '%s' are not supported", constraints);
5222                         continue;
5223                 }
5224                 if (asm_flags & ASM_CONSTRAINT_FLAG_INVALID) {
5225                         errorf(&statement->base.source_position,
5226                                "some constraints in '%s' are invalid", constraints);
5227                         continue;
5228                 }
5229                 if (asm_flags & ASM_CONSTRAINT_FLAG_MODIFIER_WRITE) {
5230                         errorf(&statement->base.source_position,
5231                                "write flag specified for input constraints '%s'",
5232                                constraints);
5233                         continue;
5234                 }
5235
5236                 ir_node *input;
5237                 if ( (asm_flags & ASM_CONSTRAINT_FLAG_SUPPORTS_IMMEDIATE)
5238                                 || (asm_flags & ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER) ) {
5239                         /* we can treat this as "normal" input */
5240                         input = expression_to_firm(argument->expression);
5241                 } else if (asm_flags & ASM_CONSTRAINT_FLAG_SUPPORTS_MEMOP) {
5242                         /* pure memory ops need no input (but we have to make sure we
5243                          * attach to the memory) */
5244                         assert(! (asm_flags &
5245                                                 (ASM_CONSTRAINT_FLAG_SUPPORTS_IMMEDIATE
5246                                                  | ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER)));
5247                         needs_memory = true;
5248                         input = expression_to_addr(argument->expression);
5249                 } else {
5250                         errorf(&statement->base.source_position,
5251                                "only modifiers but no place set in constraints '%s'",
5252                                constraints);
5253                         continue;
5254                 }
5255
5256                 ir_asm_constraint constraint;
5257                 constraint.pos        = next_pos++;
5258                 constraint.constraint = new_id_from_str(constraints);
5259                 constraint.mode       = get_irn_mode(input);
5260
5261                 obstack_grow(&asm_obst, &constraint, sizeof(constraint));
5262                 ins[in_size++] = input;
5263         }
5264
5265         if (needs_memory) {
5266                 ir_asm_constraint constraint;
5267                 constraint.pos        = next_pos++;
5268                 constraint.constraint = new_id_from_str("");
5269                 constraint.mode       = mode_M;
5270
5271                 obstack_grow(&asm_obst, &constraint, sizeof(constraint));
5272                 ins[in_size++] = get_store();
5273         }
5274
5275         assert(obstack_object_size(&asm_obst)
5276                         == in_size * sizeof(ir_asm_constraint));
5277         ir_asm_constraint *input_constraints = obstack_finish(&asm_obst);
5278
5279         /* create asm node */
5280         dbg_info *dbgi = get_dbg_info(&statement->base.source_position);
5281
5282         ident *asm_text = new_id_from_str(statement->asm_text.begin);
5283
5284         ir_node *node = new_d_ASM(dbgi, in_size, ins, input_constraints,
5285                                   out_size, output_constraints,
5286                                   n_clobbers, clobbers, asm_text);
5287
5288         if (statement->is_volatile) {
5289                 set_irn_pinned(node, op_pin_state_pinned);
5290         } else {
5291                 set_irn_pinned(node, op_pin_state_floats);
5292         }
5293
5294         /* create output projs & connect them */
5295         if (needs_memory) {
5296                 ir_node *projm = new_Proj(node, mode_M, out_size+1);
5297                 set_store(projm);
5298         }
5299
5300         size_t i;
5301         for (i = 0; i < out_size; ++i) {
5302                 const expression_t *out_expr = out_exprs[i];
5303                 long                pn       = i;
5304                 ir_mode            *mode     = get_ir_mode_storage(out_expr->base.type);
5305                 ir_node            *proj     = new_Proj(node, mode, pn);
5306                 ir_node            *addr     = out_addrs[i];
5307
5308                 set_value_for_expression_addr(out_expr, proj, addr);
5309         }
5310 }
5311
5312 static void     ms_try_statement_to_firm(ms_try_statement_t *statement)
5313 {
5314         statement_to_firm(statement->try_statement);
5315         warningf(&statement->base.source_position, "structured exception handling ignored");
5316 }
5317
5318 static void     leave_statement_to_firm(leave_statement_t *statement)
5319 {
5320         errorf(&statement->base.source_position, "__leave not supported yet");
5321 }
5322
5323 /**
5324  * Transform a statement.
5325  */
5326 static void statement_to_firm(statement_t *statement)
5327 {
5328 #ifndef NDEBUG
5329         assert(!statement->base.transformed);
5330         statement->base.transformed = true;
5331 #endif
5332
5333         switch (statement->kind) {
5334         case STATEMENT_INVALID:
5335                 panic("invalid statement found");
5336         case STATEMENT_EMPTY:
5337                 /* nothing */
5338                 return;
5339         case STATEMENT_COMPOUND:
5340                 compound_statement_to_firm(&statement->compound);
5341                 return;
5342         case STATEMENT_RETURN:
5343                 return_statement_to_firm(&statement->returns);
5344                 return;
5345         case STATEMENT_EXPRESSION:
5346                 expression_statement_to_firm(&statement->expression);
5347                 return;
5348         case STATEMENT_IF:
5349                 if_statement_to_firm(&statement->ifs);
5350                 return;
5351         case STATEMENT_WHILE:
5352                 while_statement_to_firm(&statement->whiles);
5353                 return;
5354         case STATEMENT_DO_WHILE:
5355                 do_while_statement_to_firm(&statement->do_while);
5356                 return;
5357         case STATEMENT_DECLARATION:
5358                 declaration_statement_to_firm(&statement->declaration);
5359                 return;
5360         case STATEMENT_BREAK:
5361                 create_jump_statement(statement, get_break_label());
5362                 return;
5363         case STATEMENT_CONTINUE:
5364                 create_jump_statement(statement, continue_label);
5365                 return;
5366         case STATEMENT_SWITCH:
5367                 switch_statement_to_firm(&statement->switchs);
5368                 return;
5369         case STATEMENT_CASE_LABEL:
5370                 case_label_to_firm(&statement->case_label);
5371                 return;
5372         case STATEMENT_FOR:
5373                 for_statement_to_firm(&statement->fors);
5374                 return;
5375         case STATEMENT_LABEL:
5376                 label_to_firm(&statement->label);
5377                 return;
5378         case STATEMENT_GOTO:
5379                 goto_to_firm(&statement->gotos);
5380                 return;
5381         case STATEMENT_ASM:
5382                 asm_statement_to_firm(&statement->asms);
5383                 return;
5384         case STATEMENT_MS_TRY:
5385                 ms_try_statement_to_firm(&statement->ms_try);
5386                 return;
5387         case STATEMENT_LEAVE:
5388                 leave_statement_to_firm(&statement->leave);
5389                 return;
5390         }
5391         panic("statement not implemented");
5392 }
5393
5394 static int count_local_variables(const entity_t *entity,
5395                                  const entity_t *const last)
5396 {
5397         int count = 0;
5398         entity_t const *const end = last != NULL ? last->base.next : NULL;
5399         for (; entity != end; entity = entity->base.next) {
5400                 type_t *type;
5401                 bool    address_taken;
5402
5403                 if (entity->kind == ENTITY_VARIABLE) {
5404                         type          = skip_typeref(entity->declaration.type);
5405                         address_taken = entity->variable.address_taken;
5406                 } else if (entity->kind == ENTITY_PARAMETER) {
5407                         type          = skip_typeref(entity->declaration.type);
5408                         address_taken = entity->parameter.address_taken;
5409                 } else {
5410                         continue;
5411                 }
5412
5413                 if (!address_taken && is_type_scalar(type))
5414                         ++count;
5415         }
5416         return count;
5417 }
5418
5419 static void count_local_variables_in_stmt(statement_t *stmt, void *const env)
5420 {
5421         int *const count = env;
5422
5423         switch (stmt->kind) {
5424         case STATEMENT_DECLARATION: {
5425                 const declaration_statement_t *const decl_stmt = &stmt->declaration;
5426                 *count += count_local_variables(decl_stmt->declarations_begin,
5427                                 decl_stmt->declarations_end);
5428                 break;
5429         }
5430
5431         case STATEMENT_FOR:
5432                 *count += count_local_variables(stmt->fors.scope.entities, NULL);
5433                 break;
5434
5435         default:
5436                 break;
5437         }
5438 }
5439
5440 static int get_function_n_local_vars(entity_t *entity)
5441 {
5442         int count = 0;
5443
5444         /* count parameters */
5445         count += count_local_variables(entity->function.parameters.entities, NULL);
5446
5447         /* count local variables declared in body */
5448         walk_statements(entity->function.statement, count_local_variables_in_stmt,
5449                         &count);
5450         return count;
5451 }
5452
5453 static void initialize_function_parameters(entity_t *entity)
5454 {
5455         assert(entity->kind == ENTITY_FUNCTION);
5456         ir_graph *irg             = current_ir_graph;
5457         ir_node  *args            = get_irg_args(irg);
5458         ir_node  *start_block     = get_irg_start_block(irg);
5459         ir_type  *function_irtype = get_ir_type(entity->declaration.type);
5460
5461         int       n         = 0;
5462         entity_t *parameter = entity->function.parameters.entities;
5463         for ( ; parameter != NULL; parameter = parameter->base.next, ++n) {
5464                 if (parameter->kind != ENTITY_PARAMETER)
5465                         continue;
5466
5467                 assert(parameter->declaration.kind == DECLARATION_KIND_UNKNOWN);
5468                 type_t *type = skip_typeref(parameter->declaration.type);
5469
5470                 bool needs_entity = parameter->parameter.address_taken;
5471                 assert(!is_type_array(type));
5472                 if (is_type_compound(type)) {
5473                         needs_entity = true;
5474                 }
5475
5476                 if (needs_entity) {
5477                         ir_entity *entity = get_method_value_param_ent(function_irtype, n);
5478                         ident     *id     = new_id_from_str(parameter->base.symbol->string);
5479                         set_entity_ident(entity, id);
5480
5481                         parameter->declaration.kind
5482                                 = DECLARATION_KIND_PARAMETER_ENTITY;
5483                         parameter->parameter.v.entity = entity;
5484                         continue;
5485                 }
5486
5487                 ir_type *param_irtype = get_method_param_type(function_irtype, n);
5488                 ir_mode *param_mode   = get_type_mode(param_irtype);
5489
5490                 long     pn    = n;
5491                 ir_node *value = new_r_Proj(irg, start_block, args, param_mode, pn);
5492
5493                 ir_mode *mode = get_ir_mode_storage(type);
5494                 value = create_conv(NULL, value, mode);
5495                 value = do_strict_conv(NULL, value);
5496
5497                 parameter->declaration.kind         = DECLARATION_KIND_PARAMETER;
5498                 parameter->parameter.v.value_number = next_value_number_function;
5499                 set_irg_loc_description(current_ir_graph, next_value_number_function,
5500                                         parameter);
5501                 ++next_value_number_function;
5502
5503                 set_value(parameter->parameter.v.value_number, value);
5504         }
5505 }
5506
5507 /**
5508  * Handle additional decl modifiers for IR-graphs
5509  *
5510  * @param irg            the IR-graph
5511  * @param dec_modifiers  additional modifiers
5512  */
5513 static void handle_decl_modifier_irg(ir_graph_ptr irg, decl_modifiers_t decl_modifiers)
5514 {
5515         if (decl_modifiers & DM_RETURNS_TWICE) {
5516                 /* TRUE if the declaration includes __attribute__((returns_twice)) */
5517                 set_irg_additional_property(irg, mtp_property_returns_twice);
5518         }
5519         if (decl_modifiers & DM_NORETURN) {
5520                 /* TRUE if the declaration includes the Microsoft
5521                    __declspec(noreturn) specifier. */
5522                 set_irg_additional_property(irg, mtp_property_noreturn);
5523         }
5524         if (decl_modifiers & DM_NOTHROW) {
5525                 /* TRUE if the declaration includes the Microsoft
5526                    __declspec(nothrow) specifier. */
5527                 set_irg_additional_property(irg, mtp_property_nothrow);
5528         }
5529         if (decl_modifiers & DM_NAKED) {
5530                 /* TRUE if the declaration includes the Microsoft
5531                    __declspec(naked) specifier. */
5532                 set_irg_additional_property(irg, mtp_property_naked);
5533         }
5534         if (decl_modifiers & DM_FORCEINLINE) {
5535                 /* TRUE if the declaration includes the
5536                    Microsoft __forceinline specifier. */
5537                 set_irg_inline_property(irg, irg_inline_forced);
5538         }
5539         if (decl_modifiers & DM_NOINLINE) {
5540                 /* TRUE if the declaration includes the Microsoft
5541                    __declspec(noinline) specifier. */
5542                 set_irg_inline_property(irg, irg_inline_forbidden);
5543         }
5544 }
5545
5546 static void add_function_pointer(ir_type *segment, ir_entity *method,
5547                                  const char *unique_template)
5548 {
5549         ir_type   *method_type  = get_entity_type(method);
5550         ident     *id           = id_unique(unique_template);
5551         ir_type   *ptr_type     = new_type_pointer(id, method_type, mode_P_code);
5552
5553         ident     *ide          = id_unique(unique_template);
5554         ir_entity *ptr          = new_entity(segment, ide, ptr_type);
5555         ir_graph  *irg          = get_const_code_irg();
5556         ir_node   *val          = new_rd_SymConst_addr_ent(NULL, irg, mode_P_code,
5557                                                            method, NULL);
5558
5559         set_entity_compiler_generated(ptr, 1);
5560         set_entity_variability(ptr, variability_constant);
5561         set_atomic_ent_value(ptr, val);
5562 }
5563
5564 /**
5565  * Generate possible IJmp branches to a given label block.
5566  */
5567 static void gen_ijmp_branches(ir_node *block)
5568 {
5569         ir_node *ijmp;
5570         for (ijmp = ijmp_list; ijmp != NULL; ijmp = get_irn_link(ijmp)) {
5571                 add_immBlock_pred(block, ijmp);
5572         }
5573 }
5574
5575 /**
5576  * Create code for a function.
5577  */
5578 static void create_function(entity_t *entity)
5579 {
5580         assert(entity->kind == ENTITY_FUNCTION);
5581         ir_entity *function_entity = get_function_entity(entity);
5582
5583         if (entity->function.statement == NULL)
5584                 return;
5585
5586         if (entity->declaration.modifiers & DM_CONSTRUCTOR) {
5587                 ir_type *segment = get_segment_type(IR_SEGMENT_CONSTRUCTORS);
5588                 add_function_pointer(segment, function_entity, "constructor_ptr.%u");
5589         }
5590         if (entity->declaration.modifiers & DM_DESTRUCTOR) {
5591                 ir_type *segment = get_segment_type(IR_SEGMENT_DESTRUCTORS);
5592                 add_function_pointer(segment, function_entity, "destructor_ptr.%u");
5593         }
5594
5595         current_function_entity = entity;
5596         current_function_name   = NULL;
5597         current_funcsig         = NULL;
5598
5599         assert(all_labels == NULL);
5600         all_labels = NEW_ARR_F(label_t *, 0);
5601         ijmp_list  = NULL;
5602
5603         int       n_local_vars = get_function_n_local_vars(entity);
5604         ir_graph *irg          = new_ir_graph(function_entity, n_local_vars);
5605
5606         ir_graph *old_current_function = current_function;
5607         current_function = irg;
5608
5609         set_irg_fp_model(irg, firm_opt.fp_model);
5610         tarval_enable_fp_ops(1);
5611         set_irn_dbg_info(get_irg_start_block(irg), get_entity_dbg_info(function_entity));
5612
5613         ir_node *first_block = get_cur_block();
5614
5615         /* set inline flags */
5616         if (entity->function.is_inline)
5617                 set_irg_inline_property(irg, irg_inline_recomended);
5618         handle_decl_modifier_irg(irg, entity->declaration.modifiers);
5619
5620         next_value_number_function = 0;
5621         initialize_function_parameters(entity);
5622
5623         statement_to_firm(entity->function.statement);
5624
5625         ir_node *end_block = get_irg_end_block(irg);
5626
5627         /* do we have a return statement yet? */
5628         if (get_cur_block() != NULL) {
5629                 type_t *type = skip_typeref(entity->declaration.type);
5630                 assert(is_type_function(type));
5631                 const function_type_t *func_type   = &type->function;
5632                 const type_t          *return_type
5633                         = skip_typeref(func_type->return_type);
5634
5635                 ir_node *ret;
5636                 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
5637                         ret = new_Return(get_store(), 0, NULL);
5638                 } else {
5639                         ir_mode *mode;
5640                         if (is_type_scalar(return_type)) {
5641                                 mode = get_ir_mode_storage(func_type->return_type);
5642                         } else {
5643                                 mode = mode_P_data;
5644                         }
5645
5646                         ir_node *in[1];
5647                         /* ยง5.1.2.2.3 main implicitly returns 0 */
5648                         if (is_main(entity)) {
5649                                 in[0] = new_Const(get_mode_null(mode));
5650                         } else {
5651                                 in[0] = new_Unknown(mode);
5652                         }
5653                         ret = new_Return(get_store(), 1, in);
5654                 }
5655                 add_immBlock_pred(end_block, ret);
5656         }
5657
5658         bool has_computed_gotos = false;
5659         for (int i = ARR_LEN(all_labels) - 1; i >= 0; --i) {
5660                 label_t *label = all_labels[i];
5661                 if (label->address_taken) {
5662                         gen_ijmp_branches(label->block);
5663                         has_computed_gotos = true;
5664                 }
5665                 mature_immBlock(label->block);
5666         }
5667         if (has_computed_gotos) {
5668                 /* if we have computed goto's in the function, we cannot inline it */
5669                 if (get_irg_inline_property(irg) >= irg_inline_recomended) {
5670                         warningf(&entity->base.source_position,
5671                                  "function '%Y' can never be inlined because it contains a computed goto",
5672                                  entity->base.symbol);
5673                 }
5674                 set_irg_inline_property(irg, irg_inline_forbidden);
5675         }
5676
5677         DEL_ARR_F(all_labels);
5678         all_labels = NULL;
5679
5680         mature_immBlock(first_block);
5681         mature_immBlock(end_block);
5682
5683         irg_finalize_cons(irg);
5684
5685         /* finalize the frame type */
5686         ir_type *frame_type = get_irg_frame_type(irg);
5687         int      n          = get_compound_n_members(frame_type);
5688         int      align_all  = 4;
5689         int      offset     = 0;
5690         for (int i = 0; i < n; ++i) {
5691                 ir_entity *entity      = get_compound_member(frame_type, i);
5692                 ir_type   *entity_type = get_entity_type(entity);
5693
5694                 int align = get_type_alignment_bytes(entity_type);
5695                 if (align > align_all)
5696                         align_all = align;
5697                 int misalign = 0;
5698                 if (align > 0) {
5699                         misalign  = offset % align;
5700                         if (misalign > 0) {
5701                                 offset += align - misalign;
5702                         }
5703                 }
5704
5705                 set_entity_offset(entity, offset);
5706                 offset += get_type_size_bytes(entity_type);
5707         }
5708         set_type_size_bytes(frame_type, offset);
5709         set_type_alignment_bytes(frame_type, align_all);
5710
5711         irg_vrfy(irg);
5712         current_function = old_current_function;
5713
5714         /* create inner functions */
5715         entity_t *inner;
5716         for (inner = next_inner_function(); inner != NULL;
5717              inner = next_inner_function()) {
5718                 create_function(inner);
5719         }
5720 }
5721
5722 static void scope_to_firm(scope_t *scope)
5723 {
5724         /* first pass: create declarations */
5725         entity_t *entity = scope->entities;
5726         for ( ; entity != NULL; entity = entity->base.next) {
5727                 if (entity->base.symbol == NULL)
5728                         continue;
5729
5730                 if (entity->kind == ENTITY_FUNCTION) {
5731                         if (entity->function.btk != bk_none) {
5732                                 /* builtins have no representation */
5733                                 continue;
5734                         }
5735                         get_function_entity(entity);
5736                 } else if (entity->kind == ENTITY_VARIABLE) {
5737                         create_global_variable(entity);
5738                 }
5739         }
5740
5741         /* second pass: create code/initializers */
5742         entity = scope->entities;
5743         for ( ; entity != NULL; entity = entity->base.next) {
5744                 if (entity->base.symbol == NULL)
5745                         continue;
5746
5747                 if (entity->kind == ENTITY_FUNCTION) {
5748                         if (entity->function.btk != bk_none) {
5749                                 /* builtins have no representation */
5750                                 continue;
5751                         }
5752                         create_function(entity);
5753                 } else if (entity->kind == ENTITY_VARIABLE) {
5754                         assert(entity->declaration.kind
5755                                         == DECLARATION_KIND_GLOBAL_VARIABLE);
5756                         current_ir_graph = get_const_code_irg();
5757                         create_variable_initializer(entity);
5758                 }
5759         }
5760 }
5761
5762 void init_ast2firm(void)
5763 {
5764         obstack_init(&asm_obst);
5765         init_atomic_modes();
5766
5767         /* OS option must be set to the backend */
5768         switch (firm_opt.os_support) {
5769         case OS_SUPPORT_MINGW:
5770                 create_ld_ident = create_name_win32;
5771                 break;
5772         case OS_SUPPORT_LINUX:
5773                 create_ld_ident = create_name_linux_elf;
5774                 break;
5775         case OS_SUPPORT_MACHO:
5776                 create_ld_ident = create_name_macho;
5777                 break;
5778         default:
5779                 panic("unexpected OS support mode");
5780         }
5781
5782         /* create idents for all known runtime functions */
5783         for (size_t i = 0; i < lengthof(rts_data); ++i) {
5784                 rts_idents[i] = new_id_from_str(rts_data[i].name);
5785         }
5786
5787         entitymap_init(&entitymap);
5788 }
5789
5790 static void init_ir_types(void)
5791 {
5792         static int ir_types_initialized = 0;
5793         if (ir_types_initialized)
5794                 return;
5795         ir_types_initialized = 1;
5796
5797         ir_type_int        = get_ir_type(type_int);
5798         ir_type_const_char = get_ir_type(type_const_char);
5799         ir_type_wchar_t    = get_ir_type(type_wchar_t);
5800         ir_type_void       = get_ir_type(type_void);
5801
5802         const backend_params *be_params = be_get_backend_param();
5803         mode_float_arithmetic = be_params->mode_float_arithmetic;
5804 }
5805
5806 void exit_ast2firm(void)
5807 {
5808         entitymap_destroy(&entitymap);
5809         obstack_free(&asm_obst, NULL);
5810 }
5811
5812 static void global_asm_to_firm(statement_t *s)
5813 {
5814         for (; s != NULL; s = s->base.next) {
5815                 assert(s->kind == STATEMENT_ASM);
5816
5817                 char const *const text = s->asms.asm_text.begin;
5818                 size_t            size = s->asms.asm_text.size;
5819
5820                 /* skip the last \0 */
5821                 if (text[size - 1] == '\0')
5822                         --size;
5823
5824                 ident *const id = new_id_from_chars(text, size);
5825                 add_irp_asm(id);
5826         }
5827 }
5828
5829 void translation_unit_to_firm(translation_unit_t *unit)
5830 {
5831         /* just to be sure */
5832         continue_label           = NULL;
5833         break_label              = NULL;
5834         current_switch_cond      = NULL;
5835         current_translation_unit = unit;
5836
5837         init_ir_types();
5838         inner_functions = NEW_ARR_F(entity_t *, 0);
5839
5840         scope_to_firm(&unit->scope);
5841         global_asm_to_firm(unit->global_asm);
5842
5843         DEL_ARR_F(inner_functions);
5844         inner_functions  = NULL;
5845
5846         current_ir_graph         = NULL;
5847         current_translation_unit = NULL;
5848 }