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