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