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