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