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