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