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