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