rewrite of attribute handling
[cparser] / ast2firm.c
1 /*
2  * This file is part of cparser.
3  * Copyright (C) 2007-2008 Matthias Braun <matze@braunis.de>
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
18  * 02111-1307, USA.
19  */
20 #include <config.h>
21
22 #include <assert.h>
23 #include <string.h>
24 #include <stdbool.h>
25 #include <limits.h>
26
27 #include <libfirm/firm.h>
28 #include <libfirm/adt/obst.h>
29 #include <libfirm/be.h>
30
31 #include "ast2firm.h"
32
33 #include "adt/error.h"
34 #include "adt/array.h"
35 #include "adt/util.h"
36 #include "symbol_t.h"
37 #include "token_t.h"
38 #include "type_t.h"
39 #include "ast_t.h"
40 #include "entity_t.h"
41 #include "parser.h"
42 #include "diagnostic.h"
43 #include "lang_features.h"
44 #include "types.h"
45 #include "type_hash.h"
46 #include "mangle.h"
47 #include "walk_statements.h"
48 #include "warning.h"
49 #include "entitymap_t.h"
50 #include "driver/firm_opt.h"
51 #include "driver/firm_cmdline.h"
52
53 typedef struct trampoline_region trampoline_region;
54 struct trampoline_region {
55         ir_entity        *function;    /**< The function that is called by this trampoline */
56         ir_entity        *region;      /**< created region for the trampoline */
57 };
58
59 static const backend_params *be_params;
60
61 static ir_type *ir_type_char;
62 static ir_type *ir_type_const_char;
63 static ir_type *ir_type_wchar_t;
64 static ir_type *ir_type_void;
65 static ir_type *ir_type_int;
66
67 /* architecture specific floating point arithmetic mode (if any) */
68 static ir_mode *mode_float_arithmetic;
69
70 /* alignment of stack parameters */
71 static unsigned stack_param_align;
72
73 static int        next_value_number_function;
74 static ir_node   *continue_label;
75 static ir_node   *break_label;
76 static ir_node   *current_switch_cond;
77 static bool       saw_default_label;
78 static label_t  **all_labels;
79 static entity_t **inner_functions;
80 static ir_node   *ijmp_list;
81 static bool       constant_folding;
82
83 extern bool       have_const_functions;
84
85 static const entity_t     *current_function_entity;
86 static ir_node            *current_function_name;
87 static ir_node            *current_funcsig;
88 static switch_statement_t *current_switch;
89 static ir_graph           *current_function;
90 static translation_unit_t *current_translation_unit;
91 static trampoline_region  *current_trampolines;
92 static ir_type            *current_outer_frame;
93 static ir_type            *current_outer_value_type;
94 static ir_node            *current_static_link;
95
96 static entitymap_t  entitymap;
97
98 static struct obstack asm_obst;
99
100 typedef enum declaration_kind_t {
101         DECLARATION_KIND_UNKNOWN,
102         DECLARATION_KIND_VARIABLE_LENGTH_ARRAY,
103         DECLARATION_KIND_GLOBAL_VARIABLE,
104         DECLARATION_KIND_LOCAL_VARIABLE,
105         DECLARATION_KIND_LOCAL_VARIABLE_ENTITY,
106         DECLARATION_KIND_PARAMETER,
107         DECLARATION_KIND_PARAMETER_ENTITY,
108         DECLARATION_KIND_FUNCTION,
109         DECLARATION_KIND_COMPOUND_MEMBER,
110         DECLARATION_KIND_INNER_FUNCTION
111 } declaration_kind_t;
112
113 static ir_mode *get_ir_mode_storage(type_t *type);
114 /*
115  * get arithmetic mode for a type. This is different from get_ir_mode_storage,
116  * int that it returns bigger modes for floating point on some platforms
117  * (x87 internally does arithemtic with 80bits)
118  */
119 static ir_mode *get_ir_mode_arithmetic(type_t *type);
120
121 static ir_type *get_ir_type_incomplete(type_t *type);
122
123 static void enqueue_inner_function(entity_t *entity)
124 {
125         if (inner_functions == NULL)
126                 inner_functions = NEW_ARR_F(entity_t *, 0);
127         ARR_APP1(entity_t*, inner_functions, entity);
128 }
129
130 ir_node *uninitialized_local_var(ir_graph *irg, ir_mode *mode, int pos)
131 {
132         const entity_t *entity = get_irg_loc_description(irg, pos);
133
134         if (entity != NULL) {
135                 warningf(&entity->base.source_position,
136                          "%s '%#T' might be used uninitialized",
137                          get_entity_kind_name(entity->kind),
138                          entity->declaration.type, entity->base.symbol);
139         }
140         return new_r_Unknown(irg, mode);
141 }
142
143 unsigned dbg_snprint(char *buf, unsigned len, const dbg_info *dbg)
144 {
145         const source_position_t *pos = (const source_position_t*) dbg;
146         if (pos == NULL)
147                 return 0;
148         return (unsigned) snprintf(buf, len, "%s:%u", pos->input_name,
149                                    pos->linenr);
150 }
151
152 const char *dbg_retrieve(const dbg_info *dbg, unsigned *line)
153 {
154         const source_position_t *pos = (const source_position_t*) dbg;
155         if (pos == NULL)
156                 return NULL;
157         if (line != NULL)
158                 *line = pos->linenr;
159         return pos->input_name;
160 }
161
162 static dbg_info *get_dbg_info(const source_position_t *pos)
163 {
164         return (dbg_info*) pos;
165 }
166
167 static ir_mode *atomic_modes[ATOMIC_TYPE_LAST+1];
168
169 static ir_mode *mode_int, *mode_uint;
170
171 static ir_node *_expression_to_firm(const expression_t *expression);
172 static ir_node *expression_to_firm(const expression_t *expression);
173 static void create_local_declaration(entity_t *entity);
174
175 static ir_mode *init_atomic_ir_mode(atomic_type_kind_t kind)
176 {
177         unsigned flags = get_atomic_type_flags(kind);
178         unsigned size  = get_atomic_type_size(kind);
179         if ( (flags & (ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_FLOAT))
180                         && !(flags & ATOMIC_TYPE_FLAG_COMPLEX)) {
181                 char            name[64];
182                 ir_mode_sort    sort;
183                 unsigned        bit_size     = size * 8;
184                 bool            is_signed    = (flags & ATOMIC_TYPE_FLAG_SIGNED) != 0;
185                 unsigned        modulo_shift;
186                 ir_mode_arithmetic arithmetic;
187
188                 if (flags & ATOMIC_TYPE_FLAG_INTEGER) {
189                         assert(! (flags & ATOMIC_TYPE_FLAG_FLOAT));
190                         snprintf(name, sizeof(name), "%s%u", is_signed ? "I" : "U",
191                                  bit_size);
192                         sort         = irms_int_number;
193                         arithmetic   = irma_twos_complement;
194                         modulo_shift = bit_size < machine_size ? machine_size : bit_size;
195                 } else {
196                         assert(flags & ATOMIC_TYPE_FLAG_FLOAT);
197                         snprintf(name, sizeof(name), "F%u", bit_size);
198                         sort         = irms_float_number;
199                         arithmetic   = irma_ieee754;
200                         modulo_shift = 0;
201                 }
202                 return new_ir_mode(name, sort, bit_size, is_signed, arithmetic,
203                                    modulo_shift);
204         }
205
206         return NULL;
207 }
208
209 /**
210  * Initialises the atomic modes depending on the machine size.
211  */
212 static void init_atomic_modes(void)
213 {
214         for (int i = 0; i <= ATOMIC_TYPE_LAST; ++i) {
215                 atomic_modes[i] = init_atomic_ir_mode((atomic_type_kind_t) i);
216         }
217         mode_int  = atomic_modes[ATOMIC_TYPE_INT];
218         mode_uint = atomic_modes[ATOMIC_TYPE_UINT];
219
220         /* there's no real void type in firm */
221         atomic_modes[ATOMIC_TYPE_VOID] = atomic_modes[ATOMIC_TYPE_CHAR];
222
223         /* initialize pointer modes */
224         char            name[64];
225         ir_mode_sort    sort         = irms_reference;
226         unsigned        bit_size     = machine_size;
227         bool            is_signed    = 0;
228         ir_mode_arithmetic arithmetic   = irma_twos_complement;
229         unsigned        modulo_shift
230                 = bit_size < machine_size ? machine_size : bit_size;
231
232         snprintf(name, sizeof(name), "p%u", machine_size);
233         ir_mode *ptr_mode = new_ir_mode(name, sort, bit_size, is_signed, arithmetic,
234                                         modulo_shift);
235
236         set_reference_mode_signed_eq(ptr_mode, atomic_modes[get_intptr_kind()]);
237         set_reference_mode_unsigned_eq(ptr_mode, atomic_modes[get_uintptr_kind()]);
238
239         /* Hmm, pointers should be machine size */
240         set_modeP_data(ptr_mode);
241         set_modeP_code(ptr_mode);
242 }
243
244 ir_mode *get_atomic_mode(atomic_type_kind_t kind)
245 {
246         assert(kind <= ATOMIC_TYPE_LAST);
247         return atomic_modes[kind];
248 }
249
250 static ir_node *get_vla_size(array_type_t *const type)
251 {
252         ir_node *size_node = type->size_node;
253         if (size_node == NULL) {
254                 size_node = expression_to_firm(type->size_expression);
255                 type->size_node = size_node;
256         }
257         return size_node;
258 }
259
260 /**
261  * Return a node representing the size of a type.
262  */
263 static ir_node *get_type_size_node(type_t *type)
264 {
265         type = skip_typeref(type);
266
267         if (is_type_array(type) && type->array.is_vla) {
268                 ir_node *size_node = get_vla_size(&type->array);
269                 ir_node *elem_size = get_type_size_node(type->array.element_type);
270                 ir_mode *mode      = get_irn_mode(size_node);
271                 ir_node *real_size = new_d_Mul(NULL, size_node, elem_size, mode);
272                 return real_size;
273         }
274
275         ir_mode *mode = get_ir_mode_storage(type_size_t);
276         symconst_symbol sym;
277         sym.type_p = get_ir_type(type);
278         return new_SymConst(mode, sym, symconst_type_size);
279 }
280
281 static unsigned count_parameters(const function_type_t *function_type)
282 {
283         unsigned count = 0;
284
285         function_parameter_t *parameter = function_type->parameters;
286         for ( ; parameter != NULL; parameter = parameter->next) {
287                 ++count;
288         }
289
290         return count;
291 }
292
293 /**
294  * Creates a Firm type for an atomic type
295  */
296 static ir_type *create_atomic_type(atomic_type_kind_t akind)
297 {
298         ir_mode        *mode      = atomic_modes[akind];
299         ident          *id        = get_mode_ident(mode);
300         ir_type        *irtype    = new_type_primitive(id, mode);
301         il_alignment_t  alignment = get_atomic_type_alignment(akind);
302
303         set_type_alignment_bytes(irtype, alignment);
304
305         return irtype;
306 }
307
308 /**
309  * Creates a Firm type for a complex type
310  */
311 static ir_type *create_complex_type(const complex_type_t *type)
312 {
313         atomic_type_kind_t  kind = type->akind;
314         ir_mode            *mode = atomic_modes[kind];
315         ident              *id   = get_mode_ident(mode);
316
317         (void) id;
318
319         /* FIXME: finish the array */
320         return NULL;
321 }
322
323 /**
324  * Creates a Firm type for an imaginary type
325  */
326 static ir_type *create_imaginary_type(const imaginary_type_t *type)
327 {
328         atomic_type_kind_t  kind      = type->akind;
329         ir_mode            *mode      = atomic_modes[kind];
330         ident              *id        = get_mode_ident(mode);
331         ir_type            *irtype    = new_type_primitive(id, mode);
332         il_alignment_t      alignment = get_type_alignment((const type_t*) type);
333
334         set_type_alignment_bytes(irtype, alignment);
335
336         return irtype;
337 }
338
339 /**
340  * return type of a parameter (and take transparent union gnu extension into
341  * account)
342  */
343 static type_t *get_parameter_type(type_t *orig_type)
344 {
345         type_t *type = skip_typeref(orig_type);
346         if (is_type_union(type)
347                         && get_type_modifiers(orig_type) & DM_TRANSPARENT_UNION) {
348                 compound_t *compound = type->compound.compound;
349                 type                 = compound->members.entities->declaration.type;
350         }
351
352         return type;
353 }
354
355 static ir_type *create_method_type(const function_type_t *function_type, bool for_closure)
356 {
357         type_t  *return_type  = skip_typeref(function_type->return_type);
358
359         ident   *id           = id_unique("functiontype.%u");
360         int      n_parameters = count_parameters(function_type) + (for_closure ? 1 : 0);
361         int      n_results    = return_type == type_void ? 0 : 1;
362         ir_type *irtype       = new_type_method(id, n_parameters, n_results);
363
364         if (return_type != type_void) {
365                 ir_type *restype = get_ir_type(return_type);
366                 set_method_res_type(irtype, 0, restype);
367         }
368
369         function_parameter_t *parameter = function_type->parameters;
370         int                   n         = 0;
371         if (for_closure) {
372                 ir_type *p_irtype = get_ir_type(type_void_ptr);
373                 set_method_param_type(irtype, n, p_irtype);
374                 ++n;
375         }
376         for ( ; parameter != NULL; parameter = parameter->next) {
377                 type_t  *type     = get_parameter_type(parameter->type);
378                 ir_type *p_irtype = get_ir_type(type);
379                 set_method_param_type(irtype, n, p_irtype);
380                 ++n;
381         }
382
383         if (function_type->variadic || function_type->unspecified_parameters) {
384                 set_method_variadicity(irtype, variadicity_variadic);
385         }
386
387         unsigned cc = get_method_calling_convention(irtype);
388         switch (function_type->calling_convention) {
389         case CC_DEFAULT: /* unspecified calling convention, equal to one of the other, typically cdecl */
390         case CC_CDECL:
391 is_cdecl:
392                 set_method_calling_convention(irtype, SET_CDECL(cc));
393                 break;
394
395         case CC_STDCALL:
396                 if (function_type->variadic || function_type->unspecified_parameters)
397                         goto is_cdecl;
398
399                 /* only non-variadic function can use stdcall, else use cdecl */
400                 set_method_calling_convention(irtype, SET_STDCALL(cc));
401                 break;
402
403         case CC_FASTCALL:
404                 if (function_type->variadic || function_type->unspecified_parameters)
405                         goto is_cdecl;
406                 /* only non-variadic function can use fastcall, else use cdecl */
407                 set_method_calling_convention(irtype, SET_FASTCALL(cc));
408                 break;
409
410         case CC_THISCALL:
411                 /* Hmm, leave default, not accepted by the parser yet. */
412                 break;
413         }
414
415         if (for_closure)
416                 set_method_calling_convention(irtype, get_method_calling_convention(irtype) | cc_this_call);
417
418         return irtype;
419 }
420
421 static ir_type *create_pointer_type(pointer_type_t *type)
422 {
423         type_t   *points_to    = type->points_to;
424         ir_type  *ir_points_to = get_ir_type_incomplete(points_to);
425         ir_type  *ir_type      = new_type_pointer(id_unique("pointer.%u"),
426                                                   ir_points_to, mode_P_data);
427
428         return ir_type;
429 }
430
431 static ir_type *create_reference_type(reference_type_t *type)
432 {
433         type_t  *refers_to    = type->refers_to;
434         ir_type *ir_refers_to = get_ir_type_incomplete(refers_to);
435         ir_type *ir_type      = new_type_pointer(id_unique("reference.%u"),
436                                                  ir_refers_to, mode_P_data);
437
438         return ir_type;
439 }
440
441 static ir_type *create_array_type(array_type_t *type)
442 {
443         type_t  *element_type    = type->element_type;
444         ir_type *ir_element_type = get_ir_type(element_type);
445
446         ident    *id      = id_unique("array.%u");
447         ir_type  *ir_type = new_type_array(id, 1, ir_element_type);
448
449         const int align = get_type_alignment_bytes(ir_element_type);
450         set_type_alignment_bytes(ir_type, align);
451
452         if (type->size_constant) {
453                 int n_elements = type->size;
454
455                 set_array_bounds_int(ir_type, 0, 0, n_elements);
456
457                 size_t elemsize = get_type_size_bytes(ir_element_type);
458                 if (elemsize % align > 0) {
459                         elemsize += align - (elemsize % align);
460                 }
461                 set_type_size_bytes(ir_type, n_elements * elemsize);
462         } else {
463                 set_array_lower_bound_int(ir_type, 0, 0);
464         }
465         set_type_state(ir_type, layout_fixed);
466
467         return ir_type;
468 }
469
470 /**
471  * Return the signed integer type of size bits.
472  *
473  * @param size   the size
474  */
475 static ir_type *get_signed_int_type_for_bit_size(ir_type *base_tp,
476                                                  unsigned size)
477 {
478         static ir_mode *s_modes[64 + 1] = {NULL, };
479         ir_type *res;
480         ir_mode *mode;
481
482         if (size <= 0 || size > 64)
483                 return NULL;
484
485         mode = s_modes[size];
486         if (mode == NULL) {
487                 char name[32];
488
489                 snprintf(name, sizeof(name), "bf_I%u", size);
490                 mode = new_ir_mode(name, irms_int_number, size, 1, irma_twos_complement,
491                                    size <= 32 ? 32 : size );
492                 s_modes[size] = mode;
493         }
494
495         char name[32];
496         snprintf(name, sizeof(name), "I%u", size);
497         ident *id = new_id_from_str(name);
498         dbg_info *dbgi = get_dbg_info(&builtin_source_position);
499         res = new_d_type_primitive(id_mangle_u(get_type_ident(base_tp), id), mode, dbgi);
500         set_primitive_base_type(res, base_tp);
501
502         return res;
503 }
504
505 /**
506  * Return the unsigned integer type of size bits.
507  *
508  * @param size   the size
509  */
510 static ir_type *get_unsigned_int_type_for_bit_size(ir_type *base_tp,
511                                                    unsigned size)
512 {
513         static ir_mode *u_modes[64 + 1] = {NULL, };
514         ir_type *res;
515         ir_mode *mode;
516
517         if (size <= 0 || size > 64)
518                 return NULL;
519
520         mode = u_modes[size];
521         if (mode == NULL) {
522                 char name[32];
523
524                 snprintf(name, sizeof(name), "bf_U%u", size);
525                 mode = new_ir_mode(name, irms_int_number, size, 0, irma_twos_complement,
526                                    size <= 32 ? 32 : size );
527                 u_modes[size] = mode;
528         }
529
530         char name[32];
531
532         snprintf(name, sizeof(name), "U%u", size);
533         ident *id = new_id_from_str(name);
534         dbg_info *dbgi = get_dbg_info(&builtin_source_position);
535         res = new_d_type_primitive(id_mangle_u(get_type_ident(base_tp), id), mode, dbgi);
536         set_primitive_base_type(res, base_tp);
537
538         return res;
539 }
540
541 static ir_type *create_bitfield_type(bitfield_type_t *const type)
542 {
543         type_t *base = skip_typeref(type->base_type);
544         assert(base->kind == TYPE_ATOMIC || base->kind == TYPE_ENUM);
545         ir_type *irbase = get_ir_type(base);
546
547         unsigned size = type->bit_size;
548
549         assert(!is_type_float(base));
550         if (is_type_signed(base)) {
551                 return get_signed_int_type_for_bit_size(irbase, size);
552         } else {
553                 return get_unsigned_int_type_for_bit_size(irbase, size);
554         }
555 }
556
557 #define INVALID_TYPE ((ir_type_ptr)-1)
558
559 enum {
560         COMPOUND_IS_STRUCT = false,
561         COMPOUND_IS_UNION  = true
562 };
563
564 /**
565  * Construct firm type from ast struct type.
566  *
567  * 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         assert(is_type_valid(skip_typeref(expression->base.type)));
3092
3093         bool constant_folding_old = constant_folding;
3094         constant_folding = true;
3095
3096         init_ir_types();
3097
3098         assert(is_constant_expression(expression));
3099
3100         ir_graph *old_current_ir_graph = current_ir_graph;
3101         current_ir_graph = get_const_code_irg();
3102
3103         ir_node *cnst = expression_to_firm(expression);
3104         current_ir_graph = old_current_ir_graph;
3105
3106         if (!is_Const(cnst)) {
3107                 panic("couldn't fold constant");
3108         }
3109
3110         tarval *tv = get_Const_tarval(cnst);
3111         if (!tarval_is_long(tv)) {
3112                 panic("result of constant folding is not integer");
3113         }
3114
3115         constant_folding = constant_folding_old;
3116
3117         return get_tarval_long(tv);
3118 }
3119
3120 static ir_node *conditional_to_firm(const conditional_expression_t *expression)
3121 {
3122         dbg_info *const dbgi = get_dbg_info(&expression->base.source_position);
3123
3124         /* first try to fold a constant condition */
3125         if (is_constant_expression(expression->condition)) {
3126                 long val = fold_constant(expression->condition);
3127                 if (val) {
3128                         expression_t *true_expression = expression->true_expression;
3129                         if (true_expression == NULL)
3130                                 true_expression = expression->condition;
3131                         return expression_to_firm(true_expression);
3132                 } else {
3133                         return expression_to_firm(expression->false_expression);
3134                 }
3135         }
3136
3137         ir_node *cur_block   = get_cur_block();
3138
3139         /* create the true block */
3140         ir_node *true_block  = new_immBlock();
3141         set_cur_block(true_block);
3142
3143         ir_node *true_val = expression->true_expression != NULL ?
3144                 expression_to_firm(expression->true_expression) : NULL;
3145         ir_node *true_jmp = new_Jmp();
3146
3147         /* create the false block */
3148         ir_node *false_block = new_immBlock();
3149         set_cur_block(false_block);
3150
3151         ir_node *false_val = expression_to_firm(expression->false_expression);
3152         ir_node *false_jmp = new_Jmp();
3153
3154         /* create the condition evaluation */
3155         set_cur_block(cur_block);
3156         ir_node *const cond_expr = create_condition_evaluation(expression->condition, true_block, false_block);
3157         if (expression->true_expression == NULL) {
3158                 if (cond_expr != NULL && get_irn_mode(cond_expr) != mode_b) {
3159                         true_val = cond_expr;
3160                 } else {
3161                         /* Condition ended with a short circuit (&&, ||, !) operation or a
3162                          * comparison.  Generate a "1" as value for the true branch. */
3163                         true_val = new_Const(get_mode_one(mode_Is));
3164                 }
3165         }
3166         mature_immBlock(true_block);
3167         mature_immBlock(false_block);
3168
3169         /* create the common block */
3170         ir_node *in_cf[2] = { true_jmp, false_jmp };
3171         new_Block(2, in_cf);
3172
3173         /* TODO improve static semantics, so either both or no values are NULL */
3174         if (true_val == NULL || false_val == NULL)
3175                 return NULL;
3176
3177         ir_node *in[2] = { true_val, false_val };
3178         ir_mode *mode  = get_irn_mode(true_val);
3179         assert(get_irn_mode(false_val) == mode);
3180         ir_node *val   = new_d_Phi(dbgi, 2, in, mode);
3181
3182         return val;
3183 }
3184
3185 /**
3186  * Returns an IR-node representing the address of a field.
3187  */
3188 static ir_node *select_addr(const select_expression_t *expression)
3189 {
3190         dbg_info *dbgi = get_dbg_info(&expression->base.source_position);
3191
3192         construct_select_compound(expression);
3193
3194         ir_node *compound_addr = expression_to_firm(expression->compound);
3195
3196         entity_t *entry = expression->compound_entry;
3197         assert(entry->kind == ENTITY_COMPOUND_MEMBER);
3198         assert(entry->declaration.kind == DECLARATION_KIND_COMPOUND_MEMBER);
3199
3200         if (constant_folding) {
3201                 ir_mode *mode = get_irn_mode(compound_addr);
3202                 /* FIXME: here, we need an integer mode with the same number of bits as mode */
3203                 ir_node *ofs  = new_Const_long(mode_uint, entry->compound_member.offset);
3204                 return new_d_Add(dbgi, compound_addr, ofs, mode);
3205         } else {
3206                 ir_entity *irentity = entry->compound_member.entity;
3207                 assert(irentity != NULL);
3208                 return new_d_simpleSel(dbgi, new_NoMem(), compound_addr, irentity);
3209         }
3210 }
3211
3212 static ir_node *select_to_firm(const select_expression_t *expression)
3213 {
3214         dbg_info *dbgi = get_dbg_info(&expression->base.source_position);
3215         ir_node  *addr = select_addr(expression);
3216         type_t   *type = revert_automatic_type_conversion(
3217                         (const expression_t*) expression);
3218         type           = skip_typeref(type);
3219
3220         entity_t *entry      = expression->compound_entry;
3221         assert(entry->kind == ENTITY_COMPOUND_MEMBER);
3222         type_t   *entry_type = skip_typeref(entry->declaration.type);
3223
3224         if (entry_type->kind == TYPE_BITFIELD) {
3225                 return bitfield_extract_to_firm(expression, addr);
3226         }
3227
3228         return deref_address(dbgi, type, addr);
3229 }
3230
3231 /* Values returned by __builtin_classify_type. */
3232 typedef enum gcc_type_class
3233 {
3234         no_type_class = -1,
3235         void_type_class,
3236         integer_type_class,
3237         char_type_class,
3238         enumeral_type_class,
3239         boolean_type_class,
3240         pointer_type_class,
3241         reference_type_class,
3242         offset_type_class,
3243         real_type_class,
3244         complex_type_class,
3245         function_type_class,
3246         method_type_class,
3247         record_type_class,
3248         union_type_class,
3249         array_type_class,
3250         string_type_class,
3251         set_type_class,
3252         file_type_class,
3253         lang_type_class
3254 } gcc_type_class;
3255
3256 static ir_node *classify_type_to_firm(const classify_type_expression_t *const expr)
3257 {
3258         type_t *type = expr->type_expression->base.type;
3259
3260         /* FIXME gcc returns different values depending on whether compiling C or C++
3261          * e.g. int x[10] is pointer_type_class in C, but array_type_class in C++ */
3262         gcc_type_class tc;
3263         for (;;) {
3264                 type = skip_typeref(type);
3265                 switch (type->kind) {
3266                         case TYPE_ATOMIC: {
3267                                 const atomic_type_t *const atomic_type = &type->atomic;
3268                                 switch (atomic_type->akind) {
3269                                         /* should not be reached */
3270                                         case ATOMIC_TYPE_INVALID:
3271                                                 tc = no_type_class;
3272                                                 goto make_const;
3273
3274                                         /* gcc cannot do that */
3275                                         case ATOMIC_TYPE_VOID:
3276                                                 tc = void_type_class;
3277                                                 goto make_const;
3278
3279                                         case ATOMIC_TYPE_WCHAR_T:   /* gcc handles this as integer */
3280                                         case ATOMIC_TYPE_CHAR:      /* gcc handles this as integer */
3281                                         case ATOMIC_TYPE_SCHAR:     /* gcc handles this as integer */
3282                                         case ATOMIC_TYPE_UCHAR:     /* gcc handles this as integer */
3283                                         case ATOMIC_TYPE_SHORT:
3284                                         case ATOMIC_TYPE_USHORT:
3285                                         case ATOMIC_TYPE_INT:
3286                                         case ATOMIC_TYPE_UINT:
3287                                         case ATOMIC_TYPE_LONG:
3288                                         case ATOMIC_TYPE_ULONG:
3289                                         case ATOMIC_TYPE_LONGLONG:
3290                                         case ATOMIC_TYPE_ULONGLONG:
3291                                         case ATOMIC_TYPE_BOOL:      /* gcc handles this as integer */
3292                                                 tc = integer_type_class;
3293                                                 goto make_const;
3294
3295                                         case ATOMIC_TYPE_FLOAT:
3296                                         case ATOMIC_TYPE_DOUBLE:
3297                                         case ATOMIC_TYPE_LONG_DOUBLE:
3298                                                 tc = real_type_class;
3299                                                 goto make_const;
3300                                 }
3301                                 panic("Unexpected atomic type in classify_type_to_firm().");
3302                         }
3303
3304                         case TYPE_COMPLEX:         tc = complex_type_class; goto make_const;
3305                         case TYPE_IMAGINARY:       tc = complex_type_class; goto make_const;
3306                         case TYPE_BITFIELD:        tc = integer_type_class; goto make_const;
3307                         case TYPE_ARRAY:           /* gcc handles this as pointer */
3308                         case TYPE_FUNCTION:        /* gcc handles this as pointer */
3309                         case TYPE_POINTER:         tc = pointer_type_class; goto make_const;
3310                         case TYPE_COMPOUND_STRUCT: tc = record_type_class;  goto make_const;
3311                         case TYPE_COMPOUND_UNION:  tc = union_type_class;   goto make_const;
3312
3313                         /* gcc handles this as integer */
3314                         case TYPE_ENUM:            tc = integer_type_class; goto make_const;
3315
3316                         /* gcc classifies the referenced type */
3317                         case TYPE_REFERENCE: type = type->reference.refers_to; continue;
3318
3319                         case TYPE_BUILTIN:
3320                         /* typedef/typeof should be skipped already */
3321                         case TYPE_TYPEDEF:
3322                         case TYPE_TYPEOF:
3323                         case TYPE_INVALID:
3324                         case TYPE_ERROR:
3325                                 break;
3326                 }
3327                 panic("unexpected TYPE classify_type_to_firm().");
3328         }
3329
3330 make_const:;
3331         dbg_info *const dbgi = get_dbg_info(&expr->base.source_position);
3332         tarval   *const tv   = new_tarval_from_long(tc, mode_int);
3333         return new_d_Const(dbgi, tv);
3334 }
3335
3336 static ir_node *function_name_to_firm(
3337                 const funcname_expression_t *const expr)
3338 {
3339         switch(expr->kind) {
3340         case FUNCNAME_FUNCTION:
3341         case FUNCNAME_PRETTY_FUNCTION:
3342         case FUNCNAME_FUNCDNAME:
3343                 if (current_function_name == NULL) {
3344                         const source_position_t *const src_pos = &expr->base.source_position;
3345                         const char    *name  = current_function_entity->base.symbol->string;
3346                         const string_t string = { name, strlen(name) + 1 };
3347                         current_function_name = string_to_firm(src_pos, "__func__.%u", &string);
3348                 }
3349                 return current_function_name;
3350         case FUNCNAME_FUNCSIG:
3351                 if (current_funcsig == NULL) {
3352                         const source_position_t *const src_pos = &expr->base.source_position;
3353                         ir_entity *ent = get_irg_entity(current_ir_graph);
3354                         const char *const name = get_entity_ld_name(ent);
3355                         const string_t string = { name, strlen(name) + 1 };
3356                         current_funcsig = string_to_firm(src_pos, "__FUNCSIG__.%u", &string);
3357                 }
3358                 return current_funcsig;
3359         }
3360         panic("Unsupported function name");
3361 }
3362
3363 static ir_node *statement_expression_to_firm(const statement_expression_t *expr)
3364 {
3365         statement_t *statement = expr->statement;
3366
3367         assert(statement->kind == STATEMENT_COMPOUND);
3368         return compound_statement_to_firm(&statement->compound);
3369 }
3370
3371 static ir_node *va_start_expression_to_firm(
3372         const va_start_expression_t *const expr)
3373 {
3374         type_t    *const type        = current_function_entity->declaration.type;
3375         ir_type   *const method_type = get_ir_type(type);
3376         int        const n           = get_method_n_params(method_type) - 1;
3377         ir_entity *const parm_ent    = get_method_value_param_ent(method_type, n);
3378         ir_node   *const frame       = get_irg_frame(current_ir_graph);
3379         dbg_info  *const dbgi        = get_dbg_info(&expr->base.source_position);
3380         ir_node   *const no_mem      = new_NoMem();
3381         ir_node   *const arg_sel     =
3382                 new_d_simpleSel(dbgi, no_mem, frame, parm_ent);
3383
3384         type_t    *const param_type  = expr->parameter->base.type;
3385         ir_node   *const cnst        = get_type_size_node(param_type);
3386         ir_mode   *const mode        = get_irn_mode(cnst);
3387         ir_node   *const c1          = new_Const_long(mode, stack_param_align - 1);
3388         ir_node   *const c2          = new_d_Add(dbgi, cnst, c1, mode);
3389         ir_node   *const c3          = new_Const_long(mode, -(long)stack_param_align);
3390         ir_node   *const c4          = new_d_And(dbgi, c2, c3, mode);
3391         ir_node   *const add         = new_d_Add(dbgi, arg_sel, c4, mode_P_data);
3392         set_value_for_expression(expr->ap, add);
3393
3394         return NULL;
3395 }
3396
3397 static ir_node *va_arg_expression_to_firm(const va_arg_expression_t *const expr)
3398 {
3399         type_t       *const type    = expr->base.type;
3400         expression_t *const ap_expr = expr->ap;
3401         ir_node      *const ap_addr = expression_to_addr(ap_expr);
3402         ir_node      *const ap      = get_value_from_lvalue(ap_expr, ap_addr);
3403         dbg_info     *const dbgi    = get_dbg_info(&expr->base.source_position);
3404         ir_node      *const res     = deref_address(dbgi, type, ap);
3405
3406         ir_node      *const cnst    = get_type_size_node(expr->base.type);
3407         ir_mode      *const mode    = get_irn_mode(cnst);
3408         ir_node      *const c1      = new_Const_long(mode, stack_param_align - 1);
3409         ir_node      *const c2      = new_d_Add(dbgi, cnst, c1, mode);
3410         ir_node      *const c3      = new_Const_long(mode, -(long)stack_param_align);
3411         ir_node      *const c4      = new_d_And(dbgi, c2, c3, mode);
3412         ir_node      *const add     = new_d_Add(dbgi, ap, c4, mode_P_data);
3413
3414         set_value_for_expression_addr(ap_expr, add, ap_addr);
3415
3416         return res;
3417 }
3418
3419 /**
3420  * Generate Firm for a va_copy expression.
3421  */
3422 static ir_node *va_copy_expression_to_firm(const va_copy_expression_t *const expr)
3423 {
3424         ir_node *const src = expression_to_firm(expr->src);
3425         set_value_for_expression(expr->dst, src);
3426         return NULL;
3427 }
3428
3429 static ir_node *dereference_addr(const unary_expression_t *const expression)
3430 {
3431         assert(expression->base.kind == EXPR_UNARY_DEREFERENCE);
3432         return expression_to_firm(expression->value);
3433 }
3434
3435 /**
3436  * Returns a IR-node representing an lvalue of the given expression.
3437  */
3438 static ir_node *expression_to_addr(const expression_t *expression)
3439 {
3440         switch(expression->kind) {
3441         case EXPR_ARRAY_ACCESS:
3442                 return array_access_addr(&expression->array_access);
3443         case EXPR_CALL:
3444                 return call_expression_to_firm(&expression->call);
3445         case EXPR_COMPOUND_LITERAL:
3446                 return compound_literal_to_firm(&expression->compound_literal);
3447         case EXPR_REFERENCE:
3448                 return reference_addr(&expression->reference);
3449         case EXPR_SELECT:
3450                 return select_addr(&expression->select);
3451         case EXPR_UNARY_DEREFERENCE:
3452                 return dereference_addr(&expression->unary);
3453         default:
3454                 break;
3455         }
3456         panic("trying to get address of non-lvalue");
3457 }
3458
3459 static ir_node *builtin_constant_to_firm(
3460                 const builtin_constant_expression_t *expression)
3461 {
3462         ir_mode *mode = get_ir_mode_arithmetic(expression->base.type);
3463         long     v;
3464
3465         if (is_constant_expression(expression->value)) {
3466                 v = 1;
3467         } else {
3468                 v = 0;
3469         }
3470         return new_Const_long(mode, v);
3471 }
3472
3473 static ir_node *builtin_types_compatible_to_firm(
3474                 const builtin_types_compatible_expression_t *expression)
3475 {
3476         type_t  *const left  = get_unqualified_type(skip_typeref(expression->left));
3477         type_t  *const right = get_unqualified_type(skip_typeref(expression->right));
3478         long     const value = types_compatible(left, right) ? 1 : 0;
3479         ir_mode *const mode  = get_ir_mode_arithmetic(expression->base.type);
3480         return new_Const_long(mode, value);
3481 }
3482
3483 static ir_node *get_label_block(label_t *label)
3484 {
3485         if (label->block != NULL)
3486                 return label->block;
3487
3488         /* beware: might be called from create initializer with current_ir_graph
3489          * set to const_code_irg. */
3490         ir_graph *rem    = current_ir_graph;
3491         current_ir_graph = current_function;
3492
3493         ir_node *block = new_immBlock();
3494
3495         label->block = block;
3496
3497         ARR_APP1(label_t *, all_labels, label);
3498
3499         current_ir_graph = rem;
3500         return block;
3501 }
3502
3503 /**
3504  * Pointer to a label.  This is used for the
3505  * GNU address-of-label extension.
3506  */
3507 static ir_node *label_address_to_firm(
3508                 const label_address_expression_t *label)
3509 {
3510         ir_node    *block = get_label_block(label->label);
3511         ir_label_t  nr    = get_Block_label(block);
3512
3513         if (nr == 0) {
3514                 nr = get_irp_next_label_nr();
3515                 set_Block_label(block, nr);
3516         }
3517         symconst_symbol value;
3518         value.label = nr;
3519         return new_SymConst(mode_P_code, value, symconst_label);
3520 }
3521
3522 /**
3523  * creates firm nodes for an expression. The difference between this function
3524  * and expression_to_firm is, that this version might produce mode_b nodes
3525  * instead of mode_Is.
3526  */
3527 static ir_node *_expression_to_firm(const expression_t *expression)
3528 {
3529 #ifndef NDEBUG
3530         if (!constant_folding) {
3531                 assert(!expression->base.transformed);
3532                 ((expression_t*) expression)->base.transformed = true;
3533         }
3534 #endif
3535
3536         switch (expression->kind) {
3537         case EXPR_CHARACTER_CONSTANT:
3538                 return character_constant_to_firm(&expression->conste);
3539         case EXPR_WIDE_CHARACTER_CONSTANT:
3540                 return wide_character_constant_to_firm(&expression->conste);
3541         case EXPR_CONST:
3542                 return const_to_firm(&expression->conste);
3543         case EXPR_STRING_LITERAL:
3544                 return string_literal_to_firm(&expression->string);
3545         case EXPR_WIDE_STRING_LITERAL:
3546                 return wide_string_literal_to_firm(&expression->wide_string);
3547         case EXPR_REFERENCE:
3548                 return reference_expression_to_firm(&expression->reference);
3549         case EXPR_REFERENCE_ENUM_VALUE:
3550                 return reference_expression_enum_value_to_firm(&expression->reference);
3551         case EXPR_CALL:
3552                 return call_expression_to_firm(&expression->call);
3553         EXPR_UNARY_CASES
3554                 return unary_expression_to_firm(&expression->unary);
3555         EXPR_BINARY_CASES
3556                 return binary_expression_to_firm(&expression->binary);
3557         case EXPR_ARRAY_ACCESS:
3558                 return array_access_to_firm(&expression->array_access);
3559         case EXPR_SIZEOF:
3560                 return sizeof_to_firm(&expression->typeprop);
3561         case EXPR_ALIGNOF:
3562                 return alignof_to_firm(&expression->typeprop);
3563         case EXPR_CONDITIONAL:
3564                 return conditional_to_firm(&expression->conditional);
3565         case EXPR_SELECT:
3566                 return select_to_firm(&expression->select);
3567         case EXPR_CLASSIFY_TYPE:
3568                 return classify_type_to_firm(&expression->classify_type);
3569         case EXPR_FUNCNAME:
3570                 return function_name_to_firm(&expression->funcname);
3571         case EXPR_STATEMENT:
3572                 return statement_expression_to_firm(&expression->statement);
3573         case EXPR_VA_START:
3574                 return va_start_expression_to_firm(&expression->va_starte);
3575         case EXPR_VA_ARG:
3576                 return va_arg_expression_to_firm(&expression->va_arge);
3577         case EXPR_VA_COPY:
3578                 return va_copy_expression_to_firm(&expression->va_copye);
3579         case EXPR_BUILTIN_CONSTANT_P:
3580                 return builtin_constant_to_firm(&expression->builtin_constant);
3581         case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
3582                 return builtin_types_compatible_to_firm(&expression->builtin_types_compatible);
3583         case EXPR_OFFSETOF:
3584                 return offsetof_to_firm(&expression->offsetofe);
3585         case EXPR_COMPOUND_LITERAL:
3586                 return compound_literal_to_firm(&expression->compound_literal);
3587         case EXPR_LABEL_ADDRESS:
3588                 return label_address_to_firm(&expression->label_address);
3589
3590         case EXPR_UNKNOWN:
3591         case EXPR_INVALID:
3592                 break;
3593         }
3594         panic("invalid expression found");
3595 }
3596
3597 /**
3598  * Check if a given expression is a GNU __builtin_expect() call.
3599  */
3600 static bool is_builtin_expect(const expression_t *expression)
3601 {
3602         if (expression->kind != EXPR_CALL)
3603                 return false;
3604
3605         expression_t *function = expression->call.function;
3606         if (function->kind != EXPR_REFERENCE)
3607                 return false;
3608         reference_expression_t *ref = &function->reference;
3609         if (ref->entity->kind         != ENTITY_FUNCTION ||
3610             ref->entity->function.btk != bk_gnu_builtin_expect)
3611                 return false;
3612
3613         return true;
3614 }
3615
3616 static bool produces_mode_b(const expression_t *expression)
3617 {
3618         switch (expression->kind) {
3619         case EXPR_BINARY_EQUAL:
3620         case EXPR_BINARY_NOTEQUAL:
3621         case EXPR_BINARY_LESS:
3622         case EXPR_BINARY_LESSEQUAL:
3623         case EXPR_BINARY_GREATER:
3624         case EXPR_BINARY_GREATEREQUAL:
3625         case EXPR_BINARY_ISGREATER:
3626         case EXPR_BINARY_ISGREATEREQUAL:
3627         case EXPR_BINARY_ISLESS:
3628         case EXPR_BINARY_ISLESSEQUAL:
3629         case EXPR_BINARY_ISLESSGREATER:
3630         case EXPR_BINARY_ISUNORDERED:
3631         case EXPR_UNARY_NOT:
3632                 return true;
3633
3634         case EXPR_CALL:
3635                 if (is_builtin_expect(expression)) {
3636                         expression_t *argument = expression->call.arguments->expression;
3637                         return produces_mode_b(argument);
3638                 }
3639                 return false;
3640         case EXPR_BINARY_COMMA:
3641                 return produces_mode_b(expression->binary.right);
3642
3643         default:
3644                 return false;
3645         }
3646 }
3647
3648 static ir_node *expression_to_firm(const expression_t *expression)
3649 {
3650         if (!produces_mode_b(expression)) {
3651                 ir_node *res = _expression_to_firm(expression);
3652                 assert(res == NULL || get_irn_mode(res) != mode_b);
3653                 return res;
3654         }
3655
3656         if (is_constant_expression(expression)) {
3657                 ir_node *res  = _expression_to_firm(expression);
3658                 ir_mode *mode = get_ir_mode_arithmetic(expression->base.type);
3659                 assert(is_Const(res));
3660                 if (is_Const_null(res)) {
3661                         return new_Const_long(mode, 0);
3662                 } else {
3663                         return new_Const_long(mode, 1);
3664                 }
3665         }
3666
3667         /* we have to produce a 0/1 from the mode_b expression */
3668         dbg_info *dbgi = get_dbg_info(&expression->base.source_position);
3669         ir_mode  *mode = get_ir_mode_arithmetic(expression->base.type);
3670         return produce_condition_result(expression, mode, dbgi);
3671 }
3672
3673 /**
3674  * create a short-circuit expression evaluation that tries to construct
3675  * efficient control flow structures for &&, || and ! expressions
3676  */
3677 static ir_node *create_condition_evaluation(const expression_t *expression,
3678                                             ir_node *true_block,
3679                                             ir_node *false_block)
3680 {
3681         switch(expression->kind) {
3682         case EXPR_UNARY_NOT: {
3683                 const unary_expression_t *unary_expression = &expression->unary;
3684                 create_condition_evaluation(unary_expression->value, false_block,
3685                                             true_block);
3686                 return NULL;
3687         }
3688         case EXPR_BINARY_LOGICAL_AND: {
3689                 const binary_expression_t *binary_expression = &expression->binary;
3690
3691                 ir_node *extra_block = new_immBlock();
3692                 create_condition_evaluation(binary_expression->left, extra_block,
3693                                             false_block);
3694                 mature_immBlock(extra_block);
3695                 set_cur_block(extra_block);
3696                 create_condition_evaluation(binary_expression->right, true_block,
3697                                             false_block);
3698                 return NULL;
3699         }
3700         case EXPR_BINARY_LOGICAL_OR: {
3701                 const binary_expression_t *binary_expression = &expression->binary;
3702
3703                 ir_node *extra_block = new_immBlock();
3704                 create_condition_evaluation(binary_expression->left, true_block,
3705                                             extra_block);
3706                 mature_immBlock(extra_block);
3707                 set_cur_block(extra_block);
3708                 create_condition_evaluation(binary_expression->right, true_block,
3709                                             false_block);
3710                 return NULL;
3711         }
3712         default:
3713                 break;
3714         }
3715
3716         dbg_info *dbgi       = get_dbg_info(&expression->base.source_position);
3717         ir_node  *cond_expr  = _expression_to_firm(expression);
3718         ir_node  *condition  = create_conv(dbgi, cond_expr, mode_b);
3719         ir_node  *cond       = new_d_Cond(dbgi, condition);
3720         ir_node  *true_proj  = new_d_Proj(dbgi, cond, mode_X, pn_Cond_true);
3721         ir_node  *false_proj = new_d_Proj(dbgi, cond, mode_X, pn_Cond_false);
3722
3723         /* set branch prediction info based on __builtin_expect */
3724         if (is_builtin_expect(expression) && is_Cond(cond)) {
3725                 call_argument_t *argument = expression->call.arguments->next;
3726                 if (is_constant_expression(argument->expression)) {
3727                         long               cnst = fold_constant(argument->expression);
3728                         cond_jmp_predicate pred;
3729
3730                         if (cnst == 0) {
3731                                 pred = COND_JMP_PRED_FALSE;
3732                         } else {
3733                                 pred = COND_JMP_PRED_TRUE;
3734                         }
3735                         set_Cond_jmp_pred(cond, pred);
3736                 }
3737         }
3738
3739         add_immBlock_pred(true_block, true_proj);
3740         add_immBlock_pred(false_block, false_proj);
3741
3742         set_cur_block(NULL);
3743         return cond_expr;
3744 }
3745
3746 static void create_variable_entity(entity_t *variable,
3747                                    declaration_kind_t declaration_kind,
3748                                    ir_type *parent_type)
3749 {
3750         assert(variable->kind == ENTITY_VARIABLE);
3751         type_t    *type = skip_typeref(variable->declaration.type);
3752
3753         ident     *const id        = new_id_from_str(variable->base.symbol->string);
3754         ir_type   *const irtype    = get_ir_type(type);
3755         dbg_info  *const dbgi      = get_dbg_info(&variable->base.source_position);
3756         ir_entity *const irentity  = new_d_entity(parent_type, id, irtype, dbgi);
3757         unsigned         alignment = variable->declaration.alignment;
3758
3759         set_entity_alignment(irentity, alignment);
3760
3761         handle_decl_modifiers(irentity, variable);
3762
3763         variable->declaration.kind  = (unsigned char) declaration_kind;
3764         variable->variable.v.entity = irentity;
3765         set_entity_variability(irentity, variability_uninitialized);
3766         set_entity_ld_ident(irentity, create_ld_ident(variable));
3767
3768         if (parent_type == get_tls_type())
3769                 set_entity_allocation(irentity, allocation_automatic);
3770         else if (declaration_kind == DECLARATION_KIND_GLOBAL_VARIABLE)
3771                 set_entity_allocation(irentity, allocation_static);
3772
3773         if (type->base.qualifiers & TYPE_QUALIFIER_VOLATILE) {
3774                 set_entity_volatility(irentity, volatility_is_volatile);
3775         }
3776 }
3777
3778
3779 typedef struct type_path_entry_t type_path_entry_t;
3780 struct type_path_entry_t {
3781         type_t           *type;
3782         ir_initializer_t *initializer;
3783         size_t            index;
3784         entity_t         *compound_entry;
3785 };
3786
3787 typedef struct type_path_t type_path_t;
3788 struct type_path_t {
3789         type_path_entry_t *path;
3790         type_t            *top_type;
3791         bool               invalid;
3792 };
3793
3794 static __attribute__((unused)) void debug_print_type_path(const type_path_t *path)
3795 {
3796         size_t len = ARR_LEN(path->path);
3797
3798         for (size_t i = 0; i < len; ++i) {
3799                 const type_path_entry_t *entry = & path->path[i];
3800
3801                 type_t *type = skip_typeref(entry->type);
3802                 if (is_type_compound(type)) {
3803                         fprintf(stderr, ".%s", entry->compound_entry->base.symbol->string);
3804                 } else if (is_type_array(type)) {
3805                         fprintf(stderr, "[%u]", (unsigned) entry->index);
3806                 } else {
3807                         fprintf(stderr, "-INVALID-");
3808                 }
3809         }
3810         fprintf(stderr, "  (");
3811         print_type(path->top_type);
3812         fprintf(stderr, ")");
3813 }
3814
3815 static type_path_entry_t *get_type_path_top(const type_path_t *path)
3816 {
3817         size_t len = ARR_LEN(path->path);
3818         assert(len > 0);
3819         return & path->path[len-1];
3820 }
3821
3822 static type_path_entry_t *append_to_type_path(type_path_t *path)
3823 {
3824         size_t len = ARR_LEN(path->path);
3825         ARR_RESIZE(type_path_entry_t, path->path, len+1);
3826
3827         type_path_entry_t *result = & path->path[len];
3828         memset(result, 0, sizeof(result[0]));
3829         return result;
3830 }
3831
3832 static size_t get_compound_member_count(const compound_type_t *type)
3833 {
3834         compound_t *compound  = type->compound;
3835         size_t      n_members = 0;
3836         entity_t   *member    = compound->members.entities;
3837         for ( ; member != NULL; member = member->base.next) {
3838                 ++n_members;
3839         }
3840
3841         return n_members;
3842 }
3843
3844 static ir_initializer_t *get_initializer_entry(type_path_t *path)
3845 {
3846         type_t *orig_top_type = path->top_type;
3847         type_t *top_type      = skip_typeref(orig_top_type);
3848
3849         assert(is_type_compound(top_type) || is_type_array(top_type));
3850
3851         if (ARR_LEN(path->path) == 0) {
3852                 return NULL;
3853         } else {
3854                 type_path_entry_t *top         = get_type_path_top(path);
3855                 ir_initializer_t  *initializer = top->initializer;
3856                 return get_initializer_compound_value(initializer, top->index);
3857         }
3858 }
3859
3860 static void descend_into_subtype(type_path_t *path)
3861 {
3862         type_t *orig_top_type = path->top_type;
3863         type_t *top_type      = skip_typeref(orig_top_type);
3864
3865         assert(is_type_compound(top_type) || is_type_array(top_type));
3866
3867         ir_initializer_t *initializer = get_initializer_entry(path);
3868
3869         type_path_entry_t *top = append_to_type_path(path);
3870         top->type              = top_type;
3871
3872         size_t len;
3873
3874         if (is_type_compound(top_type)) {
3875                 compound_t *compound = top_type->compound.compound;
3876                 entity_t   *entry    = compound->members.entities;
3877
3878                 top->compound_entry = entry;
3879                 top->index          = 0;
3880                 len                 = get_compound_member_count(&top_type->compound);
3881                 if (entry != NULL) {
3882                         assert(entry->kind == ENTITY_COMPOUND_MEMBER);
3883                         path->top_type = entry->declaration.type;
3884                 }
3885         } else {
3886                 assert(is_type_array(top_type));
3887                 assert(top_type->array.size > 0);
3888
3889                 top->index     = 0;
3890                 path->top_type = top_type->array.element_type;
3891                 len            = top_type->array.size;
3892         }
3893         if (initializer == NULL
3894                         || get_initializer_kind(initializer) == IR_INITIALIZER_NULL) {
3895                 initializer = create_initializer_compound(len);
3896                 /* we have to set the entry at the 2nd latest path entry... */
3897                 size_t path_len = ARR_LEN(path->path);
3898                 assert(path_len >= 1);
3899                 if (path_len > 1) {
3900                         type_path_entry_t *entry        = & path->path[path_len-2];
3901                         ir_initializer_t  *tinitializer = entry->initializer;
3902                         set_initializer_compound_value(tinitializer, entry->index,
3903                                                        initializer);
3904                 }
3905         }
3906         top->initializer = initializer;
3907 }
3908
3909 static void ascend_from_subtype(type_path_t *path)
3910 {
3911         type_path_entry_t *top = get_type_path_top(path);
3912
3913         path->top_type = top->type;
3914
3915         size_t len = ARR_LEN(path->path);
3916         ARR_RESIZE(type_path_entry_t, path->path, len-1);
3917 }
3918
3919 static void walk_designator(type_path_t *path, const designator_t *designator)
3920 {
3921         /* designators start at current object type */
3922         ARR_RESIZE(type_path_entry_t, path->path, 1);
3923
3924         for ( ; designator != NULL; designator = designator->next) {
3925                 type_path_entry_t *top         = get_type_path_top(path);
3926                 type_t            *orig_type   = top->type;
3927                 type_t            *type        = skip_typeref(orig_type);
3928
3929                 if (designator->symbol != NULL) {
3930                         assert(is_type_compound(type));
3931                         size_t    index  = 0;
3932                         symbol_t *symbol = designator->symbol;
3933
3934                         compound_t *compound = type->compound.compound;
3935                         entity_t   *iter     = compound->members.entities;
3936                         for ( ; iter != NULL; iter = iter->base.next, ++index) {
3937                                 if (iter->base.symbol == symbol) {
3938                                         assert(iter->kind == ENTITY_COMPOUND_MEMBER);
3939                                         break;
3940                                 }
3941                         }
3942                         assert(iter != NULL);
3943
3944                         top->type           = orig_type;
3945                         top->compound_entry = iter;
3946                         top->index          = index;
3947                         orig_type           = iter->declaration.type;
3948                 } else {
3949                         expression_t *array_index = designator->array_index;
3950                         assert(designator->array_index != NULL);
3951                         assert(is_type_array(type));
3952
3953                         long index = fold_constant(array_index);
3954                         assert(index >= 0);
3955 #ifndef NDEBUG
3956                         if (type->array.size_constant) {
3957                                 long array_size = type->array.size;
3958                                 assert(index < array_size);
3959                         }
3960 #endif
3961
3962                         top->type  = orig_type;
3963                         top->index = (size_t) index;
3964                         orig_type  = type->array.element_type;
3965                 }
3966                 path->top_type = orig_type;
3967
3968                 if (designator->next != NULL) {
3969                         descend_into_subtype(path);
3970                 }
3971         }
3972
3973         path->invalid  = false;
3974 }
3975
3976 static void advance_current_object(type_path_t *path)
3977 {
3978         if (path->invalid) {
3979                 /* TODO: handle this... */
3980                 panic("invalid initializer in ast2firm (excessive elements)");
3981         }
3982
3983         type_path_entry_t *top = get_type_path_top(path);
3984
3985         type_t *type = skip_typeref(top->type);
3986         if (is_type_union(type)) {
3987                 top->compound_entry = NULL;
3988         } else if (is_type_struct(type)) {
3989                 entity_t *entry = top->compound_entry;
3990
3991                 top->index++;
3992                 entry               = entry->base.next;
3993                 top->compound_entry = entry;
3994                 if (entry != NULL) {
3995                         assert(entry->kind == ENTITY_COMPOUND_MEMBER);
3996                         path->top_type = entry->declaration.type;
3997                         return;
3998                 }
3999         } else {
4000                 assert(is_type_array(type));
4001
4002                 top->index++;
4003                 if (!type->array.size_constant || top->index < type->array.size) {
4004                         return;
4005                 }
4006         }
4007
4008         /* we're past the last member of the current sub-aggregate, try if we
4009          * can ascend in the type hierarchy and continue with another subobject */
4010         size_t len = ARR_LEN(path->path);
4011
4012         if (len > 1) {
4013                 ascend_from_subtype(path);
4014                 advance_current_object(path);
4015         } else {
4016                 path->invalid = true;
4017         }
4018 }
4019
4020
4021 static ir_initializer_t *create_ir_initializer(
4022                 const initializer_t *initializer, type_t *type);
4023
4024 static ir_initializer_t *create_ir_initializer_value(
4025                 const initializer_value_t *initializer)
4026 {
4027         if (is_type_compound(initializer->value->base.type)) {
4028                 panic("initializer creation for compounds not implemented yet");
4029         }
4030         ir_node *value = expression_to_firm(initializer->value);
4031         type_t  *type  = initializer->value->base.type;
4032         ir_mode *mode  = get_ir_mode_storage(type);
4033         value          = create_conv(NULL, value, mode);
4034         return create_initializer_const(value);
4035 }
4036
4037 /** test wether type can be initialized by a string constant */
4038 static bool is_string_type(type_t *type)
4039 {
4040         type_t *inner;
4041         if (is_type_pointer(type)) {
4042                 inner = skip_typeref(type->pointer.points_to);
4043         } else if(is_type_array(type)) {
4044                 inner = skip_typeref(type->array.element_type);
4045         } else {
4046                 return false;
4047         }
4048
4049         return is_type_integer(inner);
4050 }
4051
4052 static ir_initializer_t *create_ir_initializer_list(
4053                 const initializer_list_t *initializer, type_t *type)
4054 {
4055         type_path_t path;
4056         memset(&path, 0, sizeof(path));
4057         path.top_type = type;
4058         path.path     = NEW_ARR_F(type_path_entry_t, 0);
4059
4060         descend_into_subtype(&path);
4061
4062         for (size_t i = 0; i < initializer->len; ++i) {
4063                 const initializer_t *sub_initializer = initializer->initializers[i];
4064
4065                 if (sub_initializer->kind == INITIALIZER_DESIGNATOR) {
4066                         walk_designator(&path, sub_initializer->designator.designator);
4067                         continue;
4068                 }
4069
4070                 if (sub_initializer->kind == INITIALIZER_VALUE) {
4071                         /* we might have to descend into types until we're at a scalar
4072                          * type */
4073                         while(true) {
4074                                 type_t *orig_top_type = path.top_type;
4075                                 type_t *top_type      = skip_typeref(orig_top_type);
4076
4077                                 if (is_type_scalar(top_type))
4078                                         break;
4079                                 descend_into_subtype(&path);
4080                         }
4081                 } else if (sub_initializer->kind == INITIALIZER_STRING
4082                                 || sub_initializer->kind == INITIALIZER_WIDE_STRING) {
4083                         /* we might have to descend into types until we're at a scalar
4084                          * type */
4085                         while (true) {
4086                                 type_t *orig_top_type = path.top_type;
4087                                 type_t *top_type      = skip_typeref(orig_top_type);
4088
4089                                 if (is_string_type(top_type))
4090                                         break;
4091                                 descend_into_subtype(&path);
4092                         }
4093                 }
4094
4095                 ir_initializer_t *sub_irinitializer
4096                         = create_ir_initializer(sub_initializer, path.top_type);
4097
4098                 size_t path_len = ARR_LEN(path.path);
4099                 assert(path_len >= 1);
4100                 type_path_entry_t *entry        = & path.path[path_len-1];
4101                 ir_initializer_t  *tinitializer = entry->initializer;
4102                 set_initializer_compound_value(tinitializer, entry->index,
4103                                                sub_irinitializer);
4104
4105                 advance_current_object(&path);
4106         }
4107
4108         assert(ARR_LEN(path.path) >= 1);
4109         ir_initializer_t *result = path.path[0].initializer;
4110         DEL_ARR_F(path.path);
4111
4112         return result;
4113 }
4114
4115 static ir_initializer_t *create_ir_initializer_string(
4116                 const initializer_string_t *initializer, type_t *type)
4117 {
4118         type = skip_typeref(type);
4119
4120         size_t            string_len    = initializer->string.size;
4121         assert(type->kind == TYPE_ARRAY);
4122         assert(type->array.size_constant);
4123         size_t            len           = type->array.size;
4124         ir_initializer_t *irinitializer = create_initializer_compound(len);
4125
4126         const char *string = initializer->string.begin;
4127         ir_mode    *mode   = get_ir_mode_storage(type->array.element_type);
4128
4129         for (size_t i = 0; i < len; ++i) {
4130                 char c = 0;
4131                 if (i < string_len)
4132                         c = string[i];
4133
4134                 tarval           *tv = new_tarval_from_long(c, mode);
4135                 ir_initializer_t *char_initializer = create_initializer_tarval(tv);
4136
4137                 set_initializer_compound_value(irinitializer, i, char_initializer);
4138         }
4139
4140         return irinitializer;
4141 }
4142
4143 static ir_initializer_t *create_ir_initializer_wide_string(
4144                 const initializer_wide_string_t *initializer, type_t *type)
4145 {
4146         size_t            string_len    = initializer->string.size;
4147         assert(type->kind == TYPE_ARRAY);
4148         assert(type->array.size_constant);
4149         size_t            len           = type->array.size;
4150         ir_initializer_t *irinitializer = create_initializer_compound(len);
4151
4152         const wchar_rep_t *string = initializer->string.begin;
4153         ir_mode           *mode   = get_type_mode(ir_type_wchar_t);
4154
4155         for (size_t i = 0; i < len; ++i) {
4156                 wchar_rep_t c = 0;
4157                 if (i < string_len) {
4158                         c = string[i];
4159                 }
4160                 tarval *tv = new_tarval_from_long(c, mode);
4161                 ir_initializer_t *char_initializer = create_initializer_tarval(tv);
4162
4163                 set_initializer_compound_value(irinitializer, i, char_initializer);
4164         }
4165
4166         return irinitializer;
4167 }
4168
4169 static ir_initializer_t *create_ir_initializer(
4170                 const initializer_t *initializer, type_t *type)
4171 {
4172         switch(initializer->kind) {
4173                 case INITIALIZER_STRING:
4174                         return create_ir_initializer_string(&initializer->string, type);
4175
4176                 case INITIALIZER_WIDE_STRING:
4177                         return create_ir_initializer_wide_string(&initializer->wide_string,
4178                                                                  type);
4179
4180                 case INITIALIZER_LIST:
4181                         return create_ir_initializer_list(&initializer->list, type);
4182
4183                 case INITIALIZER_VALUE:
4184                         return create_ir_initializer_value(&initializer->value);
4185
4186                 case INITIALIZER_DESIGNATOR:
4187                         panic("unexpected designator initializer found");
4188         }
4189         panic("unknown initializer");
4190 }
4191
4192 static void create_dynamic_null_initializer(ir_type *type, dbg_info *dbgi,
4193                 ir_node *base_addr)
4194 {
4195         if (is_atomic_type(type)) {
4196                 ir_mode *mode = get_type_mode(type);
4197                 tarval  *zero = get_mode_null(mode);
4198                 ir_node *cnst = new_d_Const(dbgi, zero);
4199
4200                 /* TODO: bitfields */
4201                 ir_node *mem    = get_store();
4202                 ir_node *store  = new_d_Store(dbgi, mem, base_addr, cnst, cons_none);
4203                 ir_node *proj_m = new_Proj(store, mode_M, pn_Store_M);
4204                 set_store(proj_m);
4205         } else {
4206                 assert(is_compound_type(type));
4207
4208                 int n_members;
4209                 if (is_Array_type(type)) {
4210                         assert(has_array_upper_bound(type, 0));
4211                         n_members = get_array_upper_bound_int(type, 0);
4212                 } else {
4213                         n_members = get_compound_n_members(type);
4214                 }
4215
4216                 for (int i = 0; i < n_members; ++i) {
4217                         ir_node *addr;
4218                         ir_type *irtype;
4219                         if (is_Array_type(type)) {
4220                                 ir_entity *entity   = get_array_element_entity(type);
4221                                 tarval    *index_tv = new_tarval_from_long(i, mode_uint);
4222                                 ir_node   *cnst     = new_d_Const(dbgi, index_tv);
4223                                 ir_node   *in[1]    = { cnst };
4224                                 irtype = get_array_element_type(type);
4225                                 addr   = new_d_Sel(dbgi, new_NoMem(), base_addr, 1, in, entity);
4226                         } else {
4227                                 ir_entity *member = get_compound_member(type, i);
4228
4229                                 irtype = get_entity_type(member);
4230                                 addr   = new_d_simpleSel(dbgi, new_NoMem(), base_addr, member);
4231                         }
4232
4233                         create_dynamic_null_initializer(irtype, dbgi, addr);
4234                 }
4235         }
4236 }
4237
4238 static void create_dynamic_initializer_sub(ir_initializer_t *initializer,
4239                 ir_entity *entity, ir_type *type, dbg_info *dbgi, ir_node *base_addr)
4240 {
4241         switch(get_initializer_kind(initializer)) {
4242         case IR_INITIALIZER_NULL: {
4243                 create_dynamic_null_initializer(type, dbgi, base_addr);
4244                 return;
4245         }
4246         case IR_INITIALIZER_CONST: {
4247                 ir_node *node     = get_initializer_const_value(initializer);
4248                 ir_mode *mode     = get_irn_mode(node);
4249                 ir_type *ent_type = get_entity_type(entity);
4250
4251                 /* is it a bitfield type? */
4252                 if (is_Primitive_type(ent_type) &&
4253                                 get_primitive_base_type(ent_type) != NULL) {
4254                         bitfield_store_to_firm(dbgi, entity, base_addr, node, false);
4255                         return;
4256                 }
4257
4258                 assert(get_type_mode(type) == mode);
4259                 ir_node *mem    = get_store();
4260                 ir_node *store  = new_d_Store(dbgi, mem, base_addr, node, cons_none);
4261                 ir_node *proj_m = new_Proj(store, mode_M, pn_Store_M);
4262                 set_store(proj_m);
4263                 return;
4264         }
4265         case IR_INITIALIZER_TARVAL: {
4266                 tarval  *tv       = get_initializer_tarval_value(initializer);
4267                 ir_mode *mode     = get_tarval_mode(tv);
4268                 ir_node *cnst     = new_d_Const(dbgi, tv);
4269                 ir_type *ent_type = get_entity_type(entity);
4270
4271                 /* is it a bitfield type? */
4272                 if (is_Primitive_type(ent_type) &&
4273                                 get_primitive_base_type(ent_type) != NULL) {
4274                         bitfield_store_to_firm(dbgi, entity, base_addr, cnst, false);
4275                         return;
4276                 }
4277
4278                 assert(get_type_mode(type) == mode);
4279                 ir_node *mem    = get_store();
4280                 ir_node *store  = new_d_Store(dbgi, mem, base_addr, cnst, cons_none);
4281                 ir_node *proj_m = new_Proj(store, mode_M, pn_Store_M);
4282                 set_store(proj_m);
4283                 return;
4284         }
4285         case IR_INITIALIZER_COMPOUND: {
4286                 assert(is_compound_type(type));
4287                 int n_members;
4288                 if (is_Array_type(type)) {
4289                         assert(has_array_upper_bound(type, 0));
4290                         n_members = get_array_upper_bound_int(type, 0);
4291                 } else {
4292                         n_members = get_compound_n_members(type);
4293                 }
4294
4295                 if (get_initializer_compound_n_entries(initializer)
4296                                 != (unsigned) n_members)
4297                         panic("initializer doesn't match compound type");
4298
4299                 for (int i = 0; i < n_members; ++i) {
4300                         ir_node   *addr;
4301                         ir_type   *irtype;
4302                         ir_entity *sub_entity;
4303                         if (is_Array_type(type)) {
4304                                 tarval    *index_tv = new_tarval_from_long(i, mode_uint);
4305                                 ir_node   *cnst     = new_d_Const(dbgi, index_tv);
4306                                 ir_node   *in[1]    = { cnst };
4307                                 irtype     = get_array_element_type(type);
4308                                 sub_entity = get_array_element_entity(type);
4309                                 addr       = new_d_Sel(dbgi, new_NoMem(), base_addr, 1, in,
4310                                                        sub_entity);
4311                         } else {
4312                                 sub_entity = get_compound_member(type, i);
4313                                 irtype     = get_entity_type(sub_entity);
4314                                 addr       = new_d_simpleSel(dbgi, new_NoMem(), base_addr,
4315                                                              sub_entity);
4316                         }
4317
4318                         ir_initializer_t *sub_init
4319                                 = get_initializer_compound_value(initializer, i);
4320
4321                         create_dynamic_initializer_sub(sub_init, sub_entity, irtype, dbgi,
4322                                                        addr);
4323                 }
4324                 return;
4325         }
4326         }
4327
4328         panic("invalid IR_INITIALIZER found");
4329 }
4330
4331 static void create_dynamic_initializer(ir_initializer_t *initializer,
4332                 dbg_info *dbgi, ir_entity *entity)
4333 {
4334         ir_node *frame     = get_irg_frame(current_ir_graph);
4335         ir_node *base_addr = new_d_simpleSel(dbgi, new_NoMem(), frame, entity);
4336         ir_type *type      = get_entity_type(entity);
4337
4338         create_dynamic_initializer_sub(initializer, entity, type, dbgi, base_addr);
4339 }
4340
4341 static void create_local_initializer(initializer_t *initializer, dbg_info *dbgi,
4342                                      ir_entity *entity, type_t *type)
4343 {
4344         ir_node *memory = get_store();
4345         ir_node *nomem  = new_NoMem();
4346         ir_node *frame  = get_irg_frame(current_ir_graph);
4347         ir_node *addr   = new_d_simpleSel(dbgi, nomem, frame, entity);
4348
4349         if (initializer->kind == INITIALIZER_VALUE) {
4350                 initializer_value_t *initializer_value = &initializer->value;
4351
4352                 ir_node *value = expression_to_firm(initializer_value->value);
4353                 type = skip_typeref(type);
4354                 assign_value(dbgi, addr, type, value);
4355                 return;
4356         }
4357
4358         if (!is_constant_initializer(initializer)) {
4359                 ir_initializer_t *irinitializer
4360                         = create_ir_initializer(initializer, type);
4361
4362                 create_dynamic_initializer(irinitializer, dbgi, entity);
4363                 return;
4364         }
4365
4366         /* create the ir_initializer */
4367         ir_graph *const old_current_ir_graph = current_ir_graph;
4368         current_ir_graph = get_const_code_irg();
4369
4370         ir_initializer_t *irinitializer = create_ir_initializer(initializer, type);
4371
4372         assert(current_ir_graph == get_const_code_irg());
4373         current_ir_graph = old_current_ir_graph;
4374
4375         /* create a "template" entity which is copied to the entity on the stack */
4376         ident     *const id          = id_unique("initializer.%u");
4377         ir_type   *const irtype      = get_ir_type(type);
4378         ir_type   *const global_type = get_glob_type();
4379         ir_entity *const init_entity = new_d_entity(global_type, id, irtype, dbgi);
4380         set_entity_ld_ident(init_entity, id);
4381
4382         set_entity_variability(init_entity, variability_initialized);
4383         set_entity_visibility(init_entity, visibility_local);
4384         set_entity_allocation(init_entity, allocation_static);
4385
4386         set_entity_initializer(init_entity, irinitializer);
4387
4388         ir_node *const src_addr = create_symconst(dbgi, mode_P_data, init_entity);
4389         ir_node *const copyb    = new_d_CopyB(dbgi, memory, addr, src_addr, irtype);
4390
4391         ir_node *const copyb_mem = new_Proj(copyb, mode_M, pn_CopyB_M_regular);
4392         set_store(copyb_mem);
4393 }
4394
4395 static void create_initializer_local_variable_entity(entity_t *entity)
4396 {
4397         assert(entity->kind == ENTITY_VARIABLE);
4398         initializer_t *initializer = entity->variable.initializer;
4399         dbg_info      *dbgi        = get_dbg_info(&entity->base.source_position);
4400         ir_entity     *irentity    = entity->variable.v.entity;
4401         type_t        *type        = entity->declaration.type;
4402
4403         create_local_initializer(initializer, dbgi, irentity, type);
4404 }
4405
4406 static void create_variable_initializer(entity_t *entity)
4407 {
4408         assert(entity->kind == ENTITY_VARIABLE);
4409         initializer_t *initializer = entity->variable.initializer;
4410         if (initializer == NULL)
4411                 return;
4412
4413         declaration_kind_t declaration_kind
4414                 = (declaration_kind_t) entity->declaration.kind;
4415         if (declaration_kind == DECLARATION_KIND_LOCAL_VARIABLE_ENTITY) {
4416                 create_initializer_local_variable_entity(entity);
4417                 return;
4418         }
4419
4420         type_t            *type = entity->declaration.type;
4421         type_qualifiers_t  tq   = get_type_qualifier(type, true);
4422
4423         if (initializer->kind == INITIALIZER_VALUE) {
4424                 initializer_value_t *initializer_value = &initializer->value;
4425                 dbg_info            *dbgi = get_dbg_info(&entity->base.source_position);
4426
4427                 ir_node *value = expression_to_firm(initializer_value->value);
4428
4429                 type_t  *type = initializer_value->value->base.type;
4430                 ir_mode *mode = get_ir_mode_storage(type);
4431                 value = create_conv(dbgi, value, mode);
4432                 value = do_strict_conv(dbgi, value);
4433
4434                 if (declaration_kind == DECLARATION_KIND_LOCAL_VARIABLE) {
4435                         set_value(entity->variable.v.value_number, value);
4436                 } else {
4437                         assert(declaration_kind == DECLARATION_KIND_GLOBAL_VARIABLE);
4438
4439                         ir_entity *irentity = entity->variable.v.entity;
4440
4441                         if (tq & TYPE_QUALIFIER_CONST) {
4442                                 set_entity_variability(irentity, variability_constant);
4443                         } else {
4444                                 set_entity_variability(irentity, variability_initialized);
4445                         }
4446                         set_atomic_ent_value(irentity, value);
4447                 }
4448         } else {
4449                 assert(declaration_kind == DECLARATION_KIND_LOCAL_VARIABLE_ENTITY ||
4450                        declaration_kind == DECLARATION_KIND_GLOBAL_VARIABLE);
4451
4452                 ir_entity        *irentity        = entity->variable.v.entity;
4453                 ir_initializer_t *irinitializer
4454                         = create_ir_initializer(initializer, type);
4455
4456                 if (tq & TYPE_QUALIFIER_CONST) {
4457                         set_entity_variability(irentity, variability_constant);
4458                 } else {
4459                         set_entity_variability(irentity, variability_initialized);
4460                 }
4461                 set_entity_initializer(irentity, irinitializer);
4462         }
4463 }
4464
4465 static void create_variable_length_array(entity_t *entity)
4466 {
4467         assert(entity->kind == ENTITY_VARIABLE);
4468         assert(entity->variable.initializer == NULL);
4469
4470         entity->declaration.kind    = DECLARATION_KIND_VARIABLE_LENGTH_ARRAY;
4471         entity->variable.v.vla_base = NULL;
4472
4473         /* TODO: record VLA somewhere so we create the free node when we leave
4474          * it's scope */
4475 }
4476
4477 static void allocate_variable_length_array(entity_t *entity)
4478 {
4479         assert(entity->kind == ENTITY_VARIABLE);
4480         assert(entity->variable.initializer == NULL);
4481         assert(get_cur_block() != NULL);
4482
4483         dbg_info *dbgi      = get_dbg_info(&entity->base.source_position);
4484         type_t   *type      = entity->declaration.type;
4485         ir_type  *el_type   = get_ir_type(type->array.element_type);
4486
4487         /* make sure size_node is calculated */
4488         get_type_size_node(type);
4489         ir_node  *elems = type->array.size_node;
4490         ir_node  *mem   = get_store();
4491         ir_node  *alloc = new_d_Alloc(dbgi, mem, elems, el_type, stack_alloc);
4492
4493         ir_node  *proj_m = new_d_Proj(dbgi, alloc, mode_M, pn_Alloc_M);
4494         ir_node  *addr   = new_d_Proj(dbgi, alloc, mode_P_data, pn_Alloc_res);
4495         set_store(proj_m);
4496
4497         assert(entity->declaration.kind == DECLARATION_KIND_VARIABLE_LENGTH_ARRAY);
4498         entity->variable.v.vla_base = addr;
4499 }
4500
4501 /**
4502  * Creates a Firm local variable from a declaration.
4503  */
4504 static void create_local_variable(entity_t *entity)
4505 {
4506         assert(entity->kind == ENTITY_VARIABLE);
4507         assert(entity->declaration.kind == DECLARATION_KIND_UNKNOWN);
4508
4509         bool needs_entity = entity->variable.address_taken;
4510         type_t *type = skip_typeref(entity->declaration.type);
4511
4512         /* is it a variable length array? */
4513         if (is_type_array(type) && !type->array.size_constant) {
4514                 create_variable_length_array(entity);
4515                 return;
4516         } else if (is_type_array(type) || is_type_compound(type)) {
4517                 needs_entity = true;
4518         } else if (type->base.qualifiers & TYPE_QUALIFIER_VOLATILE) {
4519                 needs_entity = true;
4520         }
4521
4522         if (needs_entity) {
4523                 ir_type *frame_type = get_irg_frame_type(current_ir_graph);
4524                 create_variable_entity(entity,
4525                                        DECLARATION_KIND_LOCAL_VARIABLE_ENTITY,
4526                                        frame_type);
4527         } else {
4528                 entity->declaration.kind        = DECLARATION_KIND_LOCAL_VARIABLE;
4529                 entity->variable.v.value_number = next_value_number_function;
4530                 set_irg_loc_description(current_ir_graph, next_value_number_function,
4531                                         entity);
4532                 ++next_value_number_function;
4533         }
4534 }
4535
4536 static void create_local_static_variable(entity_t *entity)
4537 {
4538         assert(entity->kind == ENTITY_VARIABLE);
4539         assert(entity->declaration.kind == DECLARATION_KIND_UNKNOWN);
4540
4541         type_t   *type           = skip_typeref(entity->declaration.type);
4542         ir_type  *const var_type = entity->variable.thread_local ?
4543                 get_tls_type() : get_glob_type();
4544         ir_type  *const irtype   = get_ir_type(type);
4545         dbg_info *const dbgi     = get_dbg_info(&entity->base.source_position);
4546
4547         size_t l = strlen(entity->base.symbol->string);
4548         char   buf[l + sizeof(".%u")];
4549         snprintf(buf, sizeof(buf), "%s.%%u", entity->base.symbol->string);
4550         ident     *const id = id_unique(buf);
4551
4552         ir_entity *const irentity = new_d_entity(var_type, id, irtype, dbgi);
4553
4554         if (type->base.qualifiers & TYPE_QUALIFIER_VOLATILE) {
4555                 set_entity_volatility(irentity, volatility_is_volatile);
4556         }
4557
4558         entity->declaration.kind  = DECLARATION_KIND_GLOBAL_VARIABLE;
4559         entity->variable.v.entity = irentity;
4560
4561         set_entity_ld_ident(irentity, id);
4562         set_entity_variability(irentity, variability_uninitialized);
4563         set_entity_visibility(irentity, visibility_local);
4564         set_entity_allocation(irentity, entity->variable.thread_local ?
4565                 allocation_automatic : allocation_static);
4566
4567         ir_graph *const old_current_ir_graph = current_ir_graph;
4568         current_ir_graph = get_const_code_irg();
4569
4570         create_variable_initializer(entity);
4571
4572         assert(current_ir_graph == get_const_code_irg());
4573         current_ir_graph = old_current_ir_graph;
4574 }
4575
4576
4577
4578 static void return_statement_to_firm(return_statement_t *statement)
4579 {
4580         if (get_cur_block() == NULL)
4581                 return;
4582
4583         dbg_info *dbgi        = get_dbg_info(&statement->base.source_position);
4584         type_t   *type        = current_function_entity->declaration.type;
4585         ir_type  *func_irtype = get_ir_type(type);
4586
4587
4588         ir_node *in[1];
4589         int      in_len;
4590         if (get_method_n_ress(func_irtype) > 0) {
4591                 ir_type *res_type = get_method_res_type(func_irtype, 0);
4592
4593                 if (statement->value != NULL) {
4594                         ir_node *node = expression_to_firm(statement->value);
4595                         if (!is_compound_type(res_type)) {
4596                                 type_t  *type = statement->value->base.type;
4597                                 ir_mode *mode = get_ir_mode_storage(type);
4598                                 node          = create_conv(dbgi, node, mode);
4599                                 node          = do_strict_conv(dbgi, node);
4600                         }
4601                         in[0] = node;
4602                 } else {
4603                         ir_mode *mode;
4604                         if (is_compound_type(res_type)) {
4605                                 mode = mode_P_data;
4606                         } else {
4607                                 mode = get_type_mode(res_type);
4608                         }
4609                         in[0] = new_Unknown(mode);
4610                 }
4611                 in_len = 1;
4612         } else {
4613                 /* build return_value for its side effects */
4614                 if (statement->value != NULL) {
4615                         expression_to_firm(statement->value);
4616                 }
4617                 in_len = 0;
4618         }
4619
4620         ir_node  *store = get_store();
4621         ir_node  *ret   = new_d_Return(dbgi, store, in_len, in);
4622
4623         ir_node *end_block = get_irg_end_block(current_ir_graph);
4624         add_immBlock_pred(end_block, ret);
4625
4626         set_cur_block(NULL);
4627 }
4628
4629 static ir_node *expression_statement_to_firm(expression_statement_t *statement)
4630 {
4631         if (get_cur_block() == NULL)
4632                 return NULL;
4633
4634         return expression_to_firm(statement->expression);
4635 }
4636
4637 static ir_node *compound_statement_to_firm(compound_statement_t *compound)
4638 {
4639         entity_t *entity = compound->scope.entities;
4640         for ( ; entity != NULL; entity = entity->base.next) {
4641                 if (!is_declaration(entity))
4642                         continue;
4643
4644                 create_local_declaration(entity);
4645         }
4646
4647         ir_node     *result    = NULL;
4648         statement_t *statement = compound->statements;
4649         for ( ; statement != NULL; statement = statement->base.next) {
4650                 if (statement->base.next == NULL
4651                                 && statement->kind == STATEMENT_EXPRESSION) {
4652                         result = expression_statement_to_firm(
4653                                         &statement->expression);
4654                         break;
4655                 }
4656                 statement_to_firm(statement);
4657         }
4658
4659         return result;
4660 }
4661
4662 static void create_global_variable(entity_t *entity)
4663 {
4664         assert(entity->kind == ENTITY_VARIABLE);
4665
4666         ir_visibility vis;
4667         switch ((storage_class_tag_t)entity->declaration.storage_class) {
4668                 case STORAGE_CLASS_STATIC: vis = visibility_local;              break;
4669                 case STORAGE_CLASS_EXTERN: vis = visibility_external_allocated; break;
4670                 case STORAGE_CLASS_NONE:   vis = visibility_external_visible;   break;
4671
4672                 default: panic("Invalid storage class for global variable");
4673         }
4674
4675         ir_type *var_type = entity->variable.thread_local ?
4676                 get_tls_type() : get_glob_type();
4677         create_variable_entity(entity,
4678                         DECLARATION_KIND_GLOBAL_VARIABLE, var_type);
4679         set_entity_visibility(entity->variable.v.entity, vis);
4680 }
4681
4682 static void create_local_declaration(entity_t *entity)
4683 {
4684         assert(is_declaration(entity));
4685
4686         /* construct type */
4687         (void) get_ir_type(entity->declaration.type);
4688         if (entity->base.symbol == NULL) {
4689                 return;
4690         }
4691
4692         switch ((storage_class_tag_t) entity->declaration.storage_class) {
4693         case STORAGE_CLASS_STATIC:
4694                 create_local_static_variable(entity);
4695                 return;
4696         case STORAGE_CLASS_EXTERN:
4697                 if (entity->kind == ENTITY_FUNCTION) {
4698                         assert(entity->function.statement == NULL);
4699                         (void)get_function_entity(entity, NULL);
4700                 } else {
4701                         create_global_variable(entity);
4702                         create_variable_initializer(entity);
4703                 }
4704                 return;
4705         case STORAGE_CLASS_NONE:
4706         case STORAGE_CLASS_AUTO:
4707         case STORAGE_CLASS_REGISTER:
4708                 if (entity->kind == ENTITY_FUNCTION) {
4709                         if (entity->function.statement != NULL) {
4710                                 ir_type *owner = get_irg_frame_type(current_ir_graph);
4711                                 (void)get_function_entity(entity, owner);
4712                                 entity->declaration.kind = DECLARATION_KIND_INNER_FUNCTION;
4713                                 enqueue_inner_function(entity);
4714                         } else {
4715                                 (void)get_function_entity(entity, NULL);
4716                         }
4717                 } else {
4718                         create_local_variable(entity);
4719                 }
4720                 return;
4721         case STORAGE_CLASS_TYPEDEF:
4722                 break;
4723         }
4724         panic("invalid storage class found");
4725 }
4726
4727 static void initialize_local_declaration(entity_t *entity)
4728 {
4729         if (entity->base.symbol == NULL)
4730                 return;
4731
4732         // no need to emit code in dead blocks
4733         if (entity->declaration.storage_class != STORAGE_CLASS_STATIC
4734                         && get_cur_block() == NULL)
4735                 return;
4736
4737         switch ((declaration_kind_t) entity->declaration.kind) {
4738         case DECLARATION_KIND_LOCAL_VARIABLE:
4739         case DECLARATION_KIND_LOCAL_VARIABLE_ENTITY:
4740                 create_variable_initializer(entity);
4741                 return;
4742
4743         case DECLARATION_KIND_VARIABLE_LENGTH_ARRAY:
4744                 allocate_variable_length_array(entity);
4745                 return;
4746
4747         case DECLARATION_KIND_COMPOUND_MEMBER:
4748         case DECLARATION_KIND_GLOBAL_VARIABLE:
4749         case DECLARATION_KIND_FUNCTION:
4750         case DECLARATION_KIND_INNER_FUNCTION:
4751                 return;
4752
4753         case DECLARATION_KIND_PARAMETER:
4754         case DECLARATION_KIND_PARAMETER_ENTITY:
4755                 panic("can't initialize parameters");
4756
4757         case DECLARATION_KIND_UNKNOWN:
4758                 panic("can't initialize unknown declaration");
4759         }
4760         panic("invalid declaration kind");
4761 }
4762
4763 static void declaration_statement_to_firm(declaration_statement_t *statement)
4764 {
4765         entity_t *entity = statement->declarations_begin;
4766         if (entity == NULL)
4767                 return;
4768
4769         entity_t *const last = statement->declarations_end;
4770         for ( ;; entity = entity->base.next) {
4771                 if (is_declaration(entity)) {
4772                         initialize_local_declaration(entity);
4773                 } else if (entity->kind == ENTITY_TYPEDEF) {
4774                         /* ยง6.7.7:3  Any array size expressions associated with variable length
4775                          * array declarators are evaluated each time the declaration of the
4776                          * typedef name is reached in the order of execution. */
4777                         type_t *const type = skip_typeref(entity->typedefe.type);
4778                         if (is_type_array(type) && type->array.is_vla)
4779                                 get_vla_size(&type->array);
4780                 }
4781                 if (entity == last)
4782                         break;
4783         }
4784 }
4785
4786 static void if_statement_to_firm(if_statement_t *statement)
4787 {
4788         ir_node *cur_block = get_cur_block();
4789
4790         ir_node *fallthrough_block = NULL;
4791
4792         /* the true (blocks) */
4793         ir_node *true_block = NULL;
4794         if (statement->true_statement != NULL) {
4795                 true_block = new_immBlock();
4796                 set_cur_block(true_block);
4797                 statement_to_firm(statement->true_statement);
4798                 if (get_cur_block() != NULL) {
4799                         ir_node *jmp = new_Jmp();
4800                         if (fallthrough_block == NULL)
4801                                 fallthrough_block = new_immBlock();
4802                         add_immBlock_pred(fallthrough_block, jmp);
4803                 }
4804         }
4805
4806         /* the false (blocks) */
4807         ir_node *false_block = NULL;
4808         if (statement->false_statement != NULL) {
4809                 false_block = new_immBlock();
4810                 set_cur_block(false_block);
4811
4812                 statement_to_firm(statement->false_statement);
4813                 if (get_cur_block() != NULL) {
4814                         ir_node *jmp = new_Jmp();
4815                         if (fallthrough_block == NULL)
4816                                 fallthrough_block = new_immBlock();
4817                         add_immBlock_pred(fallthrough_block, jmp);
4818                 }
4819         }
4820
4821         /* create the condition */
4822         if (cur_block != NULL) {
4823                 if (true_block == NULL || false_block == NULL) {
4824                         if (fallthrough_block == NULL)
4825                                 fallthrough_block = new_immBlock();
4826                         if (true_block == NULL)
4827                                 true_block = fallthrough_block;
4828                         if (false_block == NULL)
4829                                 false_block = fallthrough_block;
4830                 }
4831
4832                 set_cur_block(cur_block);
4833                 create_condition_evaluation(statement->condition, true_block,
4834                                             false_block);
4835         }
4836
4837         mature_immBlock(true_block);
4838         if (false_block != fallthrough_block && false_block != NULL) {
4839                 mature_immBlock(false_block);
4840         }
4841         if (fallthrough_block != NULL) {
4842                 mature_immBlock(fallthrough_block);
4843         }
4844
4845         set_cur_block(fallthrough_block);
4846 }
4847
4848 static void while_statement_to_firm(while_statement_t *statement)
4849 {
4850         ir_node *jmp = NULL;
4851         if (get_cur_block() != NULL) {
4852                 jmp = new_Jmp();
4853         }
4854
4855         /* create the header block */
4856         ir_node *header_block = new_immBlock();
4857         if (jmp != NULL) {
4858                 add_immBlock_pred(header_block, jmp);
4859         }
4860
4861         /* the loop body */
4862         ir_node *old_continue_label = continue_label;
4863         ir_node *old_break_label    = break_label;
4864         continue_label              = header_block;
4865         break_label                 = NULL;
4866
4867         ir_node *body_block = new_immBlock();
4868         set_cur_block(body_block);
4869         statement_to_firm(statement->body);
4870         ir_node *false_block = break_label;
4871
4872         assert(continue_label == header_block);
4873         continue_label = old_continue_label;
4874         break_label    = old_break_label;
4875
4876         if (get_cur_block() != NULL) {
4877                 jmp = new_Jmp();
4878                 add_immBlock_pred(header_block, jmp);
4879         }
4880
4881         /* shortcut for while(true) */
4882         if (is_constant_expression(statement->condition)
4883                         && fold_constant(statement->condition) != 0) {
4884                 set_cur_block(header_block);
4885                 ir_node *header_jmp = new_Jmp();
4886                 add_immBlock_pred(body_block, header_jmp);
4887
4888                 keep_alive(body_block);
4889                 keep_all_memory(body_block);
4890                 set_cur_block(body_block);
4891         } else {
4892                 if (false_block == NULL) {
4893                         false_block = new_immBlock();
4894                 }
4895
4896                 /* create the condition */
4897                 set_cur_block(header_block);
4898
4899                 create_condition_evaluation(statement->condition, body_block,
4900                                             false_block);
4901         }
4902
4903         mature_immBlock(body_block);
4904         mature_immBlock(header_block);
4905         if (false_block != NULL) {
4906                 mature_immBlock(false_block);
4907         }
4908
4909         set_cur_block(false_block);
4910 }
4911
4912 static void do_while_statement_to_firm(do_while_statement_t *statement)
4913 {
4914         ir_node *jmp = NULL;
4915         if (get_cur_block() != NULL) {
4916                 jmp = new_Jmp();
4917         }
4918
4919         /* create the header block */
4920         ir_node *header_block = new_immBlock();
4921
4922         /* the loop body */
4923         ir_node *body_block = new_immBlock();
4924         if (jmp != NULL) {
4925                 add_immBlock_pred(body_block, jmp);
4926         }
4927
4928         ir_node *old_continue_label = continue_label;
4929         ir_node *old_break_label    = break_label;
4930         continue_label              = header_block;
4931         break_label                 = NULL;
4932
4933         set_cur_block(body_block);
4934         statement_to_firm(statement->body);
4935         ir_node *false_block = break_label;
4936
4937         assert(continue_label == header_block);
4938         continue_label = old_continue_label;
4939         break_label    = old_break_label;
4940
4941         if (get_cur_block() != NULL) {
4942                 ir_node *body_jmp = new_Jmp();
4943                 add_immBlock_pred(header_block, body_jmp);
4944                 mature_immBlock(header_block);
4945         }
4946
4947         if (false_block == NULL) {
4948                 false_block = new_immBlock();
4949         }
4950
4951         /* create the condition */
4952         set_cur_block(header_block);
4953
4954         create_condition_evaluation(statement->condition, body_block, false_block);
4955         mature_immBlock(body_block);
4956         mature_immBlock(header_block);
4957         mature_immBlock(false_block);
4958
4959         set_cur_block(false_block);
4960 }
4961
4962 static void for_statement_to_firm(for_statement_t *statement)
4963 {
4964         ir_node *jmp = NULL;
4965
4966         /* create declarations */
4967         entity_t *entity = statement->scope.entities;
4968         for ( ; entity != NULL; entity = entity->base.next) {
4969                 if (!is_declaration(entity))
4970                         continue;
4971
4972                 create_local_declaration(entity);
4973         }
4974
4975         if (get_cur_block() != NULL) {
4976                 entity = statement->scope.entities;
4977                 for ( ; entity != NULL; entity = entity->base.next) {
4978                         if (!is_declaration(entity))
4979                                 continue;
4980
4981                         initialize_local_declaration(entity);
4982                 }
4983
4984                 if (statement->initialisation != NULL) {
4985                         expression_to_firm(statement->initialisation);
4986                 }
4987
4988                 jmp = new_Jmp();
4989         }
4990
4991
4992         /* create the step block */
4993         ir_node *const step_block = new_immBlock();
4994         set_cur_block(step_block);
4995         if (statement->step != NULL) {
4996                 expression_to_firm(statement->step);
4997         }
4998         ir_node *const step_jmp = new_Jmp();
4999
5000         /* create the header block */
5001         ir_node *const header_block = new_immBlock();
5002         set_cur_block(header_block);
5003         if (jmp != NULL) {
5004                 add_immBlock_pred(header_block, jmp);
5005         }
5006         add_immBlock_pred(header_block, step_jmp);
5007
5008         /* the false block */
5009         ir_node *const false_block = new_immBlock();
5010
5011         /* the loop body */
5012         ir_node *body_block;
5013         if (statement->body != NULL) {
5014                 ir_node *const old_continue_label = continue_label;
5015                 ir_node *const old_break_label    = break_label;
5016                 continue_label = step_block;
5017                 break_label    = false_block;
5018
5019                 body_block = new_immBlock();
5020                 set_cur_block(body_block);
5021                 statement_to_firm(statement->body);
5022
5023                 assert(continue_label == step_block);
5024                 assert(break_label    == false_block);
5025                 continue_label = old_continue_label;
5026                 break_label    = old_break_label;
5027
5028                 if (get_cur_block() != NULL) {
5029                         jmp = new_Jmp();
5030                         add_immBlock_pred(step_block, jmp);
5031                 }
5032         } else {
5033                 body_block = step_block;
5034         }
5035
5036         /* create the condition */
5037         set_cur_block(header_block);
5038         if (statement->condition != NULL) {
5039                 create_condition_evaluation(statement->condition, body_block,
5040                                             false_block);
5041         } else {
5042                 keep_alive(header_block);
5043                 keep_all_memory(header_block);
5044                 jmp = new_Jmp();
5045                 add_immBlock_pred(body_block, jmp);
5046         }
5047
5048         mature_immBlock(body_block);
5049         mature_immBlock(false_block);
5050         mature_immBlock(step_block);
5051         mature_immBlock(header_block);
5052         mature_immBlock(false_block);
5053
5054         set_cur_block(false_block);
5055 }
5056
5057 static void create_jump_statement(const statement_t *statement,
5058                                   ir_node *target_block)
5059 {
5060         if (get_cur_block() == NULL)
5061                 return;
5062
5063         dbg_info *dbgi = get_dbg_info(&statement->base.source_position);
5064         ir_node  *jump = new_d_Jmp(dbgi);
5065         add_immBlock_pred(target_block, jump);
5066
5067         set_cur_block(NULL);
5068 }
5069
5070 static ir_node *get_break_label(void)
5071 {
5072         if (break_label == NULL) {
5073                 break_label = new_immBlock();
5074         }
5075         return break_label;
5076 }
5077
5078 static void switch_statement_to_firm(switch_statement_t *statement)
5079 {
5080         dbg_info *dbgi = get_dbg_info(&statement->base.source_position);
5081
5082         ir_node *expression  = expression_to_firm(statement->expression);
5083         ir_node *cond        = new_d_Cond(dbgi, expression);
5084
5085         set_cur_block(NULL);
5086
5087         ir_node *const old_switch_cond       = current_switch_cond;
5088         ir_node *const old_break_label       = break_label;
5089         const bool     old_saw_default_label = saw_default_label;
5090         saw_default_label                    = false;
5091         current_switch_cond                  = cond;
5092         break_label                          = NULL;
5093         switch_statement_t *const old_switch = current_switch;
5094         current_switch                       = statement;
5095
5096         /* determine a free number for the default label */
5097         unsigned long num_cases = 0;
5098         long def_nr = 0;
5099         for (case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
5100                 if (l->expression == NULL) {
5101                         /* default case */
5102                         continue;
5103                 }
5104                 if (l->last_case >= l->first_case)
5105                         num_cases += l->last_case - l->first_case + 1;
5106                 if (l->last_case > def_nr)
5107                         def_nr = l->last_case;
5108         }
5109
5110         if (def_nr == INT_MAX) {
5111                 /* Bad: an overflow will occur, we cannot be sure that the
5112                  * maximum + 1 is a free number. Scan the values a second
5113                  * time to find a free number.
5114                  */
5115                 unsigned char *bits = xmalloc((num_cases + 7) >> 3);
5116
5117                 memset(bits, 0, (num_cases + 7) >> 3);
5118                 for (case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
5119                         if (l->expression == NULL) {
5120                                 /* default case */
5121                                 continue;
5122                         }
5123                         unsigned long start = l->first_case > 0 ? (unsigned long)l->first_case : 0;
5124                         if (start < num_cases && l->last_case >= 0) {
5125                                 unsigned long end  = (unsigned long)l->last_case < num_cases ?
5126                                         (unsigned long)l->last_case : num_cases - 1;
5127                                 for (unsigned long cns = start; cns <= end; ++cns) {
5128                                         bits[cns >> 3] |= (1 << (cns & 7));
5129                                 }
5130                         }
5131                 }
5132                 /* We look at the first num_cases constants:
5133                  * Either they are dense, so we took the last (num_cases)
5134                  * one, or they are not dense, so we will find one free
5135                  * there...
5136                  */
5137                 unsigned long i;
5138                 for (i = 0; i < num_cases; ++i)
5139                         if ((bits[i >> 3] & (1 << (i & 7))) == 0)
5140                                 break;
5141
5142                 free(bits);
5143                 def_nr = i;
5144         } else {
5145                 ++def_nr;
5146         }
5147         statement->default_proj_nr = def_nr;
5148
5149         if (statement->body != NULL) {
5150                 statement_to_firm(statement->body);
5151         }
5152
5153         if (get_cur_block() != NULL) {
5154                 ir_node *jmp = new_Jmp();
5155                 add_immBlock_pred(get_break_label(), jmp);
5156         }
5157
5158         if (!saw_default_label) {
5159                 set_cur_block(get_nodes_block(cond));
5160                 ir_node *const proj = new_d_defaultProj(dbgi, cond,
5161                                                         statement->default_proj_nr);
5162                 add_immBlock_pred(get_break_label(), proj);
5163         }
5164
5165         if (break_label != NULL) {
5166                 mature_immBlock(break_label);
5167         }
5168         set_cur_block(break_label);
5169
5170         assert(current_switch_cond == cond);
5171         current_switch      = old_switch;
5172         current_switch_cond = old_switch_cond;
5173         break_label         = old_break_label;
5174         saw_default_label   = old_saw_default_label;
5175 }
5176
5177 static void case_label_to_firm(const case_label_statement_t *statement)
5178 {
5179         if (statement->is_empty_range)
5180                 return;
5181
5182         dbg_info *dbgi = get_dbg_info(&statement->base.source_position);
5183
5184         ir_node *const fallthrough = (get_cur_block() == NULL ? NULL : new_Jmp());
5185
5186         ir_node *proj;
5187         ir_node *block     = new_immBlock();
5188
5189         set_cur_block(get_nodes_block(current_switch_cond));
5190         if (statement->expression != NULL) {
5191                 long pn     = statement->first_case;
5192                 long end_pn = statement->last_case;
5193                 assert(pn <= end_pn);
5194                 /* create jumps for all cases in the given range */
5195                 do {
5196                         proj = new_d_Proj(dbgi, current_switch_cond, mode_X, pn);
5197                         add_immBlock_pred(block, proj);
5198                 } while (pn++ < end_pn);
5199         } else {
5200                 saw_default_label = true;
5201                 proj = new_d_defaultProj(dbgi, current_switch_cond,
5202                                          current_switch->default_proj_nr);
5203
5204                 add_immBlock_pred(block, proj);
5205         }
5206
5207         if (fallthrough != NULL) {
5208                 add_immBlock_pred(block, fallthrough);
5209         }
5210         mature_immBlock(block);
5211         set_cur_block(block);
5212
5213         if (statement->statement != NULL) {
5214                 statement_to_firm(statement->statement);
5215         }
5216 }
5217
5218 static void label_to_firm(const label_statement_t *statement)
5219 {
5220         ir_node *block = get_label_block(statement->label);
5221
5222         if (get_cur_block() != NULL) {
5223                 ir_node *jmp = new_Jmp();
5224                 add_immBlock_pred(block, jmp);
5225         }
5226
5227         set_cur_block(block);
5228         keep_alive(block);
5229         keep_all_memory(block);
5230
5231         if (statement->statement != NULL) {
5232                 statement_to_firm(statement->statement);
5233         }
5234 }
5235
5236 static void goto_to_firm(const goto_statement_t *statement)
5237 {
5238         if (get_cur_block() == NULL)
5239                 return;
5240
5241         if (statement->expression) {
5242                 ir_node  *irn  = expression_to_firm(statement->expression);
5243                 dbg_info *dbgi = get_dbg_info(&statement->base.source_position);
5244                 ir_node  *ijmp = new_d_IJmp(dbgi, irn);
5245
5246                 set_irn_link(ijmp, ijmp_list);
5247                 ijmp_list = ijmp;
5248         } else {
5249                 ir_node *block = get_label_block(statement->label);
5250                 ir_node *jmp   = new_Jmp();
5251                 add_immBlock_pred(block, jmp);
5252         }
5253         set_cur_block(NULL);
5254 }
5255
5256 static void asm_statement_to_firm(const asm_statement_t *statement)
5257 {
5258         bool needs_memory = false;
5259
5260         if (statement->is_volatile) {
5261                 needs_memory = true;
5262         }
5263
5264         size_t         n_clobbers = 0;
5265         asm_clobber_t *clobber    = statement->clobbers;
5266         for ( ; clobber != NULL; clobber = clobber->next) {
5267                 const char *clobber_str = clobber->clobber.begin;
5268
5269                 if (!be_is_valid_clobber(clobber_str)) {
5270                         errorf(&statement->base.source_position,
5271                                    "invalid clobber '%s' specified", clobber->clobber);
5272                         continue;
5273                 }
5274
5275                 if (strcmp(clobber_str, "memory") == 0) {
5276                         needs_memory = true;
5277                         continue;
5278                 }
5279
5280                 ident *id = new_id_from_str(clobber_str);
5281                 obstack_ptr_grow(&asm_obst, id);
5282                 ++n_clobbers;
5283         }
5284         assert(obstack_object_size(&asm_obst) == n_clobbers * sizeof(ident*));
5285         ident **clobbers = NULL;
5286         if (n_clobbers > 0) {
5287                 clobbers = obstack_finish(&asm_obst);
5288         }
5289
5290         size_t n_inputs  = 0;
5291         asm_argument_t *argument = statement->inputs;
5292         for ( ; argument != NULL; argument = argument->next)
5293                 n_inputs++;
5294         size_t n_outputs = 0;
5295         argument = statement->outputs;
5296         for ( ; argument != NULL; argument = argument->next)
5297                 n_outputs++;
5298
5299         unsigned next_pos = 0;
5300
5301         ir_node *ins[n_inputs + n_outputs + 1];
5302         size_t   in_size = 0;
5303
5304         ir_asm_constraint tmp_in_constraints[n_outputs];
5305
5306         const expression_t *out_exprs[n_outputs];
5307         ir_node            *out_addrs[n_outputs];
5308         size_t              out_size = 0;
5309
5310         argument = statement->outputs;
5311         for ( ; argument != NULL; argument = argument->next) {
5312                 const char *constraints = argument->constraints.begin;
5313                 asm_constraint_flags_t asm_flags
5314                         = be_parse_asm_constraints(constraints);
5315
5316                 if (asm_flags & ASM_CONSTRAINT_FLAG_NO_SUPPORT) {
5317                         warningf(&statement->base.source_position,
5318                                "some constraints in '%s' are not supported", constraints);
5319                 }
5320                 if (asm_flags & ASM_CONSTRAINT_FLAG_INVALID) {
5321                         errorf(&statement->base.source_position,
5322                                "some constraints in '%s' are invalid", constraints);
5323                         continue;
5324                 }
5325                 if (! (asm_flags & ASM_CONSTRAINT_FLAG_MODIFIER_WRITE)) {
5326                         errorf(&statement->base.source_position,
5327                                "no write flag specified for output constraints '%s'",
5328                                constraints);
5329                         continue;
5330                 }
5331
5332                 unsigned pos = next_pos++;
5333                 if ( (asm_flags & ASM_CONSTRAINT_FLAG_SUPPORTS_IMMEDIATE)
5334                                 || (asm_flags & ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER) ) {
5335                         expression_t *expr = argument->expression;
5336                         ir_node      *addr = expression_to_addr(expr);
5337                         /* in+output, construct an artifical same_as constraint on the
5338                          * input */
5339                         if (asm_flags & ASM_CONSTRAINT_FLAG_MODIFIER_READ) {
5340                                 char     buf[64];
5341                                 ir_node *value = get_value_from_lvalue(expr, addr);
5342
5343                                 snprintf(buf, sizeof(buf), "%u", pos);
5344
5345                                 ir_asm_constraint constraint;
5346                                 constraint.pos              = pos;
5347                                 constraint.constraint       = new_id_from_str(buf);
5348                                 constraint.mode             = get_ir_mode_storage(expr->base.type);
5349                                 tmp_in_constraints[in_size] = constraint;
5350                                 ins[in_size] = value;
5351
5352                                 ++in_size;
5353                         }
5354
5355                         out_exprs[out_size] = expr;
5356                         out_addrs[out_size] = addr;
5357                         ++out_size;
5358                 } else if (asm_flags & ASM_CONSTRAINT_FLAG_SUPPORTS_MEMOP) {
5359                         /* pure memory ops need no input (but we have to make sure we
5360                          * attach to the memory) */
5361                         assert(! (asm_flags &
5362                                                 (ASM_CONSTRAINT_FLAG_SUPPORTS_IMMEDIATE
5363                                                  | ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER)));
5364                         needs_memory = true;
5365
5366                         /* we need to attach the address to the inputs */
5367                         expression_t *expr = argument->expression;
5368
5369                         ir_asm_constraint constraint;
5370                         constraint.pos              = pos;
5371                         constraint.constraint       = new_id_from_str(constraints);
5372                         constraint.mode             = NULL;
5373                         tmp_in_constraints[in_size] = constraint;
5374
5375                         ins[in_size]          = expression_to_addr(expr);
5376                         ++in_size;
5377                         continue;
5378                 } else {
5379                         errorf(&statement->base.source_position,
5380                                "only modifiers but no place set in constraints '%s'",
5381                                constraints);
5382                         continue;
5383                 }
5384
5385                 ir_asm_constraint constraint;
5386                 constraint.pos        = pos;
5387                 constraint.constraint = new_id_from_str(constraints);
5388                 constraint.mode       = get_ir_mode_storage(argument->expression->base.type);
5389
5390                 obstack_grow(&asm_obst, &constraint, sizeof(constraint));
5391         }
5392         assert(obstack_object_size(&asm_obst)
5393                         == out_size * sizeof(ir_asm_constraint));
5394         ir_asm_constraint *output_constraints = obstack_finish(&asm_obst);
5395
5396
5397         obstack_grow(&asm_obst, tmp_in_constraints,
5398                      in_size * sizeof(tmp_in_constraints[0]));
5399         /* find and count input and output arguments */
5400         argument = statement->inputs;
5401         for ( ; argument != NULL; argument = argument->next) {
5402                 const char *constraints = argument->constraints.begin;
5403                 asm_constraint_flags_t asm_flags
5404                         = be_parse_asm_constraints(constraints);
5405
5406                 if (asm_flags & ASM_CONSTRAINT_FLAG_NO_SUPPORT) {
5407                         errorf(&statement->base.source_position,
5408                                "some constraints in '%s' are not supported", constraints);
5409                         continue;
5410                 }
5411                 if (asm_flags & ASM_CONSTRAINT_FLAG_INVALID) {
5412                         errorf(&statement->base.source_position,
5413                                "some constraints in '%s' are invalid", constraints);
5414                         continue;
5415                 }
5416                 if (asm_flags & ASM_CONSTRAINT_FLAG_MODIFIER_WRITE) {
5417                         errorf(&statement->base.source_position,
5418                                "write flag specified for input constraints '%s'",
5419                                constraints);
5420                         continue;
5421                 }
5422
5423                 ir_node *input;
5424                 if ( (asm_flags & ASM_CONSTRAINT_FLAG_SUPPORTS_IMMEDIATE)
5425                                 || (asm_flags & ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER) ) {
5426                         /* we can treat this as "normal" input */
5427                         input = expression_to_firm(argument->expression);
5428                 } else if (asm_flags & ASM_CONSTRAINT_FLAG_SUPPORTS_MEMOP) {
5429                         /* pure memory ops need no input (but we have to make sure we
5430                          * attach to the memory) */
5431                         assert(! (asm_flags &
5432                                                 (ASM_CONSTRAINT_FLAG_SUPPORTS_IMMEDIATE
5433                                                  | ASM_CONSTRAINT_FLAG_SUPPORTS_REGISTER)));
5434                         needs_memory = true;
5435                         input = expression_to_addr(argument->expression);
5436                 } else {
5437                         errorf(&statement->base.source_position,
5438                                "only modifiers but no place set in constraints '%s'",
5439                                constraints);
5440                         continue;
5441                 }
5442
5443                 ir_asm_constraint constraint;
5444                 constraint.pos        = next_pos++;
5445                 constraint.constraint = new_id_from_str(constraints);
5446                 constraint.mode       = get_irn_mode(input);
5447
5448                 obstack_grow(&asm_obst, &constraint, sizeof(constraint));
5449                 ins[in_size++] = input;
5450         }
5451
5452         if (needs_memory) {
5453                 ir_asm_constraint constraint;
5454                 constraint.pos        = next_pos++;
5455                 constraint.constraint = new_id_from_str("");
5456                 constraint.mode       = mode_M;
5457
5458                 obstack_grow(&asm_obst, &constraint, sizeof(constraint));
5459                 ins[in_size++] = get_store();
5460         }
5461
5462         assert(obstack_object_size(&asm_obst)
5463                         == in_size * sizeof(ir_asm_constraint));
5464         ir_asm_constraint *input_constraints = obstack_finish(&asm_obst);
5465
5466         /* create asm node */
5467         dbg_info *dbgi = get_dbg_info(&statement->base.source_position);
5468
5469         ident *asm_text = new_id_from_str(statement->asm_text.begin);
5470
5471         ir_node *node = new_d_ASM(dbgi, in_size, ins, input_constraints,
5472                                   out_size, output_constraints,
5473                                   n_clobbers, clobbers, asm_text);
5474
5475         if (statement->is_volatile) {
5476                 set_irn_pinned(node, op_pin_state_pinned);
5477         } else {
5478                 set_irn_pinned(node, op_pin_state_floats);
5479         }
5480
5481         /* create output projs & connect them */
5482         if (needs_memory) {
5483                 ir_node *projm = new_Proj(node, mode_M, out_size+1);
5484                 set_store(projm);
5485         }
5486
5487         size_t i;
5488         for (i = 0; i < out_size; ++i) {
5489                 const expression_t *out_expr = out_exprs[i];
5490                 long                pn       = i;
5491                 ir_mode            *mode     = get_ir_mode_storage(out_expr->base.type);
5492                 ir_node            *proj     = new_Proj(node, mode, pn);
5493                 ir_node            *addr     = out_addrs[i];
5494
5495                 set_value_for_expression_addr(out_expr, proj, addr);
5496         }
5497 }
5498
5499 static void     ms_try_statement_to_firm(ms_try_statement_t *statement)
5500 {
5501         statement_to_firm(statement->try_statement);
5502         warningf(&statement->base.source_position, "structured exception handling ignored");
5503 }
5504
5505 static void     leave_statement_to_firm(leave_statement_t *statement)
5506 {
5507         errorf(&statement->base.source_position, "__leave not supported yet");
5508 }
5509
5510 /**
5511  * Transform a statement.
5512  */
5513 static void statement_to_firm(statement_t *statement)
5514 {
5515 #ifndef NDEBUG
5516         assert(!statement->base.transformed);
5517         statement->base.transformed = true;
5518 #endif
5519
5520         switch (statement->kind) {
5521         case STATEMENT_INVALID:
5522                 panic("invalid statement found");
5523         case STATEMENT_EMPTY:
5524                 /* nothing */
5525                 return;
5526         case STATEMENT_COMPOUND:
5527                 compound_statement_to_firm(&statement->compound);
5528                 return;
5529         case STATEMENT_RETURN:
5530                 return_statement_to_firm(&statement->returns);
5531                 return;
5532         case STATEMENT_EXPRESSION:
5533                 expression_statement_to_firm(&statement->expression);
5534                 return;
5535         case STATEMENT_IF:
5536                 if_statement_to_firm(&statement->ifs);
5537                 return;
5538         case STATEMENT_WHILE:
5539                 while_statement_to_firm(&statement->whiles);
5540                 return;
5541         case STATEMENT_DO_WHILE:
5542                 do_while_statement_to_firm(&statement->do_while);
5543                 return;
5544         case STATEMENT_DECLARATION:
5545                 declaration_statement_to_firm(&statement->declaration);
5546                 return;
5547         case STATEMENT_BREAK:
5548                 create_jump_statement(statement, get_break_label());
5549                 return;
5550         case STATEMENT_CONTINUE:
5551                 create_jump_statement(statement, continue_label);
5552                 return;
5553         case STATEMENT_SWITCH:
5554                 switch_statement_to_firm(&statement->switchs);
5555                 return;
5556         case STATEMENT_CASE_LABEL:
5557                 case_label_to_firm(&statement->case_label);
5558                 return;
5559         case STATEMENT_FOR:
5560                 for_statement_to_firm(&statement->fors);
5561                 return;
5562         case STATEMENT_LABEL:
5563                 label_to_firm(&statement->label);
5564                 return;
5565         case STATEMENT_GOTO:
5566                 goto_to_firm(&statement->gotos);
5567                 return;
5568         case STATEMENT_ASM:
5569                 asm_statement_to_firm(&statement->asms);
5570                 return;
5571         case STATEMENT_MS_TRY:
5572                 ms_try_statement_to_firm(&statement->ms_try);
5573                 return;
5574         case STATEMENT_LEAVE:
5575                 leave_statement_to_firm(&statement->leave);
5576                 return;
5577         }
5578         panic("statement not implemented");
5579 }
5580
5581 static int count_local_variables(const entity_t *entity,
5582                                  const entity_t *const last)
5583 {
5584         int count = 0;
5585         entity_t const *const end = last != NULL ? last->base.next : NULL;
5586         for (; entity != end; entity = entity->base.next) {
5587                 type_t *type;
5588                 bool    address_taken;
5589
5590                 if (entity->kind == ENTITY_VARIABLE) {
5591                         type          = skip_typeref(entity->declaration.type);
5592                         address_taken = entity->variable.address_taken;
5593                 } else if (entity->kind == ENTITY_PARAMETER) {
5594                         type          = skip_typeref(entity->declaration.type);
5595                         address_taken = entity->parameter.address_taken;
5596                 } else {
5597                         continue;
5598                 }
5599
5600                 if (!address_taken && is_type_scalar(type))
5601                         ++count;
5602         }
5603         return count;
5604 }
5605
5606 static void count_local_variables_in_stmt(statement_t *stmt, void *const env)
5607 {
5608         int *const count = env;
5609
5610         switch (stmt->kind) {
5611         case STATEMENT_DECLARATION: {
5612                 const declaration_statement_t *const decl_stmt = &stmt->declaration;
5613                 *count += count_local_variables(decl_stmt->declarations_begin,
5614                                 decl_stmt->declarations_end);
5615                 break;
5616         }
5617
5618         case STATEMENT_FOR:
5619                 *count += count_local_variables(stmt->fors.scope.entities, NULL);
5620                 break;
5621
5622         default:
5623                 break;
5624         }
5625 }
5626
5627 /**
5628  * Return the number of local (alias free) variables used by a function.
5629  */
5630 static int get_function_n_local_vars(entity_t *entity)
5631 {
5632         const function_t *function = &entity->function;
5633         int count = 0;
5634
5635         /* count parameters */
5636         count += count_local_variables(function->parameters.entities, NULL);
5637
5638         /* count local variables declared in body */
5639         walk_statements(function->statement, count_local_variables_in_stmt, &count);
5640         return count;
5641 }
5642
5643 /**
5644  * Build Firm code for the parameters of a function.
5645  */
5646 static void initialize_function_parameters(entity_t *entity)
5647 {
5648         assert(entity->kind == ENTITY_FUNCTION);
5649         ir_graph *irg             = current_ir_graph;
5650         ir_node  *args            = get_irg_args(irg);
5651         ir_node  *start_block     = get_irg_start_block(irg);
5652         ir_type  *function_irtype = get_ir_type(entity->declaration.type);
5653         int      first_param_nr   = 0;
5654
5655         if (entity->function.need_closure) {
5656                 /* add an extra parameter for the static link */
5657                 entity->function.static_link = new_r_Proj(irg, start_block, args, mode_P_data, 0);
5658                 ++first_param_nr;
5659         }
5660
5661         int       n         = 0;
5662         entity_t *parameter = entity->function.parameters.entities;
5663         for ( ; parameter != NULL; parameter = parameter->base.next, ++n) {
5664                 if (parameter->kind != ENTITY_PARAMETER)
5665                         continue;
5666
5667                 assert(parameter->declaration.kind == DECLARATION_KIND_UNKNOWN);
5668                 type_t *type = skip_typeref(parameter->declaration.type);
5669
5670                 bool needs_entity = parameter->parameter.address_taken;
5671                 assert(!is_type_array(type));
5672                 if (is_type_compound(type)) {
5673                         needs_entity = true;
5674                 }
5675
5676                 if (needs_entity) {
5677                         ir_entity *entity = get_method_value_param_ent(function_irtype, n);
5678                         ident     *id     = new_id_from_str(parameter->base.symbol->string);
5679                         set_entity_ident(entity, id);
5680
5681                         parameter->declaration.kind
5682                                 = DECLARATION_KIND_PARAMETER_ENTITY;
5683                         parameter->parameter.v.entity = entity;
5684                         continue;
5685                 }
5686
5687                 ir_type *param_irtype = get_method_param_type(function_irtype, n);
5688                 ir_mode *param_mode   = get_type_mode(param_irtype);
5689
5690                 long     pn    = n + first_param_nr;
5691                 ir_node *value = new_r_Proj(irg, start_block, args, param_mode, pn);
5692
5693                 ir_mode *mode = get_ir_mode_storage(type);
5694                 value = create_conv(NULL, value, mode);
5695                 value = do_strict_conv(NULL, value);
5696
5697                 parameter->declaration.kind         = DECLARATION_KIND_PARAMETER;
5698                 parameter->parameter.v.value_number = next_value_number_function;
5699                 set_irg_loc_description(current_ir_graph, next_value_number_function,
5700                                         parameter);
5701                 ++next_value_number_function;
5702
5703                 set_value(parameter->parameter.v.value_number, value);
5704         }
5705 }
5706
5707 /**
5708  * Handle additional decl modifiers for IR-graphs
5709  *
5710  * @param irg            the IR-graph
5711  * @param dec_modifiers  additional modifiers
5712  */
5713 static void handle_decl_modifier_irg(ir_graph_ptr irg,
5714                                      decl_modifiers_t decl_modifiers)
5715 {
5716         if (decl_modifiers & DM_RETURNS_TWICE) {
5717                 /* TRUE if the declaration includes __attribute__((returns_twice)) */
5718                 set_irg_additional_property(irg, mtp_property_returns_twice);
5719         }
5720         if (decl_modifiers & DM_NORETURN) {
5721                 /* TRUE if the declaration includes the Microsoft
5722                    __declspec(noreturn) specifier. */
5723                 set_irg_additional_property(irg, mtp_property_noreturn);
5724         }
5725         if (decl_modifiers & DM_NOTHROW) {
5726                 /* TRUE if the declaration includes the Microsoft
5727                    __declspec(nothrow) specifier. */
5728                 set_irg_additional_property(irg, mtp_property_nothrow);
5729         }
5730         if (decl_modifiers & DM_NAKED) {
5731                 /* TRUE if the declaration includes the Microsoft
5732                    __declspec(naked) specifier. */
5733                 set_irg_additional_property(irg, mtp_property_naked);
5734         }
5735         if (decl_modifiers & DM_FORCEINLINE) {
5736                 /* TRUE if the declaration includes the
5737                    Microsoft __forceinline specifier. */
5738                 set_irg_inline_property(irg, irg_inline_forced);
5739         }
5740         if (decl_modifiers & DM_NOINLINE) {
5741                 /* TRUE if the declaration includes the Microsoft
5742                    __declspec(noinline) specifier. */
5743                 set_irg_inline_property(irg, irg_inline_forbidden);
5744         }
5745 }
5746
5747 static void add_function_pointer(ir_type *segment, ir_entity *method,
5748                                  const char *unique_template)
5749 {
5750         ir_type   *method_type  = get_entity_type(method);
5751         ident     *id           = id_unique(unique_template);
5752         ir_type   *ptr_type     = new_type_pointer(id, method_type, mode_P_code);
5753
5754         ident     *ide          = id_unique(unique_template);
5755         ir_entity *ptr          = new_entity(segment, ide, ptr_type);
5756         ir_graph  *irg          = get_const_code_irg();
5757         ir_node   *val          = new_rd_SymConst_addr_ent(NULL, irg, mode_P_code,
5758                                                            method, NULL);
5759
5760         set_entity_compiler_generated(ptr, 1);
5761         set_entity_variability(ptr, variability_constant);
5762         set_atomic_ent_value(ptr, val);
5763 }
5764
5765 /**
5766  * Generate possible IJmp branches to a given label block.
5767  */
5768 static void gen_ijmp_branches(ir_node *block)
5769 {
5770         ir_node *ijmp;
5771         for (ijmp = ijmp_list; ijmp != NULL; ijmp = get_irn_link(ijmp)) {
5772                 add_immBlock_pred(block, ijmp);
5773         }
5774 }
5775
5776 /**
5777  * Create code for a function and all inner functions.
5778  *
5779  * @param entity  the function entity
5780  */
5781 static void create_function(entity_t *entity)
5782 {
5783         assert(entity->kind == ENTITY_FUNCTION);
5784         ir_entity *function_entity = get_function_entity(entity, current_outer_frame);
5785
5786         if (entity->function.statement == NULL)
5787                 return;
5788
5789         inner_functions     = NULL;
5790         current_trampolines = NULL;
5791
5792         if (entity->declaration.modifiers & DM_CONSTRUCTOR) {
5793                 ir_type *segment = get_segment_type(IR_SEGMENT_CONSTRUCTORS);
5794                 add_function_pointer(segment, function_entity, "constructor_ptr.%u");
5795         }
5796         if (entity->declaration.modifiers & DM_DESTRUCTOR) {
5797                 ir_type *segment = get_segment_type(IR_SEGMENT_DESTRUCTORS);
5798                 add_function_pointer(segment, function_entity, "destructor_ptr.%u");
5799         }
5800
5801         current_function_entity = entity;
5802         current_function_name   = NULL;
5803         current_funcsig         = NULL;
5804
5805         assert(all_labels == NULL);
5806         all_labels = NEW_ARR_F(label_t *, 0);
5807         ijmp_list  = NULL;
5808
5809         int       n_local_vars = get_function_n_local_vars(entity);
5810         ir_graph *irg          = new_ir_graph(function_entity, n_local_vars);
5811
5812         ir_graph *old_current_function = current_function;
5813         current_function = irg;
5814
5815         set_irg_fp_model(irg, firm_opt.fp_model);
5816         tarval_enable_fp_ops(1);
5817         set_irn_dbg_info(get_irg_start_block(irg), get_entity_dbg_info(function_entity));
5818
5819         ir_node *first_block = get_cur_block();
5820
5821         /* set inline flags */
5822         if (entity->function.is_inline)
5823                 set_irg_inline_property(irg, irg_inline_recomended);
5824         handle_decl_modifier_irg(irg, entity->declaration.modifiers);
5825
5826         next_value_number_function = 0;
5827         initialize_function_parameters(entity);
5828         current_static_link = entity->function.static_link;
5829
5830         statement_to_firm(entity->function.statement);
5831
5832         ir_node *end_block = get_irg_end_block(irg);
5833
5834         /* do we have a return statement yet? */
5835         if (get_cur_block() != NULL) {
5836                 type_t *type = skip_typeref(entity->declaration.type);
5837                 assert(is_type_function(type));
5838                 const function_type_t *func_type   = &type->function;
5839                 const type_t          *return_type
5840                         = skip_typeref(func_type->return_type);
5841
5842                 ir_node *ret;
5843                 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
5844                         ret = new_Return(get_store(), 0, NULL);
5845                 } else {
5846                         ir_mode *mode;
5847                         if (is_type_scalar(return_type)) {
5848                                 mode = get_ir_mode_storage(func_type->return_type);
5849                         } else {
5850                                 mode = mode_P_data;
5851                         }
5852
5853                         ir_node *in[1];
5854                         /* ยง5.1.2.2.3 main implicitly returns 0 */
5855                         if (is_main(entity)) {
5856                                 in[0] = new_Const(get_mode_null(mode));
5857                         } else {
5858                                 in[0] = new_Unknown(mode);
5859                         }
5860                         ret = new_Return(get_store(), 1, in);
5861                 }
5862                 add_immBlock_pred(end_block, ret);
5863         }
5864
5865         bool has_computed_gotos = false;
5866         for (int i = ARR_LEN(all_labels) - 1; i >= 0; --i) {
5867                 label_t *label = all_labels[i];
5868                 if (label->address_taken) {
5869                         gen_ijmp_branches(label->block);
5870                         has_computed_gotos = true;
5871                 }
5872                 mature_immBlock(label->block);
5873         }
5874         if (has_computed_gotos) {
5875                 /* if we have computed goto's in the function, we cannot inline it */
5876                 if (get_irg_inline_property(irg) >= irg_inline_recomended) {
5877                         warningf(&entity->base.source_position,
5878                                  "function '%Y' can never be inlined because it contains a computed goto",
5879                                  entity->base.symbol);
5880                 }
5881                 set_irg_inline_property(irg, irg_inline_forbidden);
5882         }
5883
5884         DEL_ARR_F(all_labels);
5885         all_labels = NULL;
5886
5887         mature_immBlock(first_block);
5888         mature_immBlock(end_block);
5889
5890         irg_finalize_cons(irg);
5891
5892         /* finalize the frame type */
5893         ir_type *frame_type = get_irg_frame_type(irg);
5894         int      n          = get_compound_n_members(frame_type);
5895         int      align_all  = 4;
5896         int      offset     = 0;
5897         for (int i = 0; i < n; ++i) {
5898                 ir_entity *entity      = get_compound_member(frame_type, i);
5899                 ir_type   *entity_type = get_entity_type(entity);
5900
5901                 int align = get_type_alignment_bytes(entity_type);
5902                 if (align > align_all)
5903                         align_all = align;
5904                 int misalign = 0;
5905                 if (align > 0) {
5906                         misalign  = offset % align;
5907                         if (misalign > 0) {
5908                                 offset += align - misalign;
5909                         }
5910                 }
5911
5912                 set_entity_offset(entity, offset);
5913                 offset += get_type_size_bytes(entity_type);
5914         }
5915         set_type_size_bytes(frame_type, offset);
5916         set_type_alignment_bytes(frame_type, align_all);
5917
5918         irg_vrfy(irg);
5919         current_function = old_current_function;
5920
5921         if (current_trampolines != NULL) {
5922                 DEL_ARR_F(current_trampolines);
5923                 current_trampolines = NULL;
5924         }
5925
5926         /* create inner functions if any */
5927         entity_t **inner = inner_functions;
5928         if (inner != NULL) {
5929                 ir_type *rem_outer_frame      = current_outer_frame;
5930                 current_outer_frame           = get_irg_frame_type(current_ir_graph);
5931                 ir_type *rem_outer_value_type = current_outer_value_type;
5932                 current_outer_value_type      = get_irg_value_param_type(current_ir_graph);
5933                 for (int i = ARR_LEN(inner) - 1; i >= 0; --i) {
5934                         create_function(inner[i]);
5935                 }
5936                 DEL_ARR_F(inner);
5937
5938                 current_outer_value_type = rem_outer_value_type;
5939                 current_outer_frame      = rem_outer_frame;
5940         }
5941 }
5942
5943 static void scope_to_firm(scope_t *scope)
5944 {
5945         /* first pass: create declarations */
5946         entity_t *entity = scope->entities;
5947         for ( ; entity != NULL; entity = entity->base.next) {
5948                 if (entity->base.symbol == NULL)
5949                         continue;
5950
5951                 if (entity->kind == ENTITY_FUNCTION) {
5952                         if (entity->function.btk != bk_none) {
5953                                 /* builtins have no representation */
5954                                 continue;
5955                         }
5956                         (void)get_function_entity(entity, NULL);
5957                 } else if (entity->kind == ENTITY_VARIABLE) {
5958                         create_global_variable(entity);
5959                 }
5960         }
5961
5962         /* second pass: create code/initializers */
5963         entity = scope->entities;
5964         for ( ; entity != NULL; entity = entity->base.next) {
5965                 if (entity->base.symbol == NULL)
5966                         continue;
5967
5968                 if (entity->kind == ENTITY_FUNCTION) {
5969                         if (entity->function.btk != bk_none) {
5970                                 /* builtins have no representation */
5971                                 continue;
5972                         }
5973                         create_function(entity);
5974                 } else if (entity->kind == ENTITY_VARIABLE) {
5975                         assert(entity->declaration.kind
5976                                         == DECLARATION_KIND_GLOBAL_VARIABLE);
5977                         current_ir_graph = get_const_code_irg();
5978                         create_variable_initializer(entity);
5979                 }
5980         }
5981 }
5982
5983 void init_ast2firm(void)
5984 {
5985         obstack_init(&asm_obst);
5986         init_atomic_modes();
5987
5988         /* OS option must be set to the backend */
5989         switch (firm_opt.os_support) {
5990         case OS_SUPPORT_MINGW:
5991                 create_ld_ident = create_name_win32;
5992                 break;
5993         case OS_SUPPORT_LINUX:
5994                 create_ld_ident = create_name_linux_elf;
5995                 break;
5996         case OS_SUPPORT_MACHO:
5997                 create_ld_ident = create_name_macho;
5998                 break;
5999         default:
6000                 panic("unexpected OS support mode");
6001         }
6002
6003         /* create idents for all known runtime functions */
6004         for (size_t i = 0; i < lengthof(rts_data); ++i) {
6005                 rts_idents[i] = new_id_from_str(rts_data[i].name);
6006         }
6007
6008         entitymap_init(&entitymap);
6009 }
6010
6011 static void init_ir_types(void)
6012 {
6013         static int ir_types_initialized = 0;
6014         if (ir_types_initialized)
6015                 return;
6016         ir_types_initialized = 1;
6017
6018         ir_type_int        = get_ir_type(type_int);
6019         ir_type_char       = get_ir_type(type_char);
6020         ir_type_const_char = get_ir_type(type_const_char);
6021         ir_type_wchar_t    = get_ir_type(type_wchar_t);
6022         ir_type_void       = get_ir_type(type_void);
6023
6024         be_params             = be_get_backend_param();
6025         mode_float_arithmetic = be_params->mode_float_arithmetic;
6026
6027         stack_param_align     = be_params->stack_param_align;
6028 }
6029
6030 void exit_ast2firm(void)
6031 {
6032         entitymap_destroy(&entitymap);
6033         obstack_free(&asm_obst, NULL);
6034 }
6035
6036 static void global_asm_to_firm(statement_t *s)
6037 {
6038         for (; s != NULL; s = s->base.next) {
6039                 assert(s->kind == STATEMENT_ASM);
6040
6041                 char const *const text = s->asms.asm_text.begin;
6042                 size_t            size = s->asms.asm_text.size;
6043
6044                 /* skip the last \0 */
6045                 if (text[size - 1] == '\0')
6046                         --size;
6047
6048                 ident *const id = new_id_from_chars(text, size);
6049                 add_irp_asm(id);
6050         }
6051 }
6052
6053 void translation_unit_to_firm(translation_unit_t *unit)
6054 {
6055         /* just to be sure */
6056         continue_label           = NULL;
6057         break_label              = NULL;
6058         current_switch_cond      = NULL;
6059         current_translation_unit = unit;
6060
6061         init_ir_types();
6062
6063         scope_to_firm(&unit->scope);
6064         global_asm_to_firm(unit->global_asm);
6065
6066         current_ir_graph         = NULL;
6067         current_translation_unit = NULL;
6068 }