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