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