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