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