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