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