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