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