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