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