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