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