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