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