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