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