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