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