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