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