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