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