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