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