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