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