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