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