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