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