1cf0253f663bb733a5991554840f1c61ffbdcc99
[cparser] / driver / firm_opt.c
1 /**
2  *
3  * @file firm_opt.c -- Firm-generating back end optimizations.
4  *
5  * (C) 2005-2007  Michael Beck   beck@ipd.info.uni-karlsruhe.de
6  *
7  * $Id$
8  */
9 #include <stdlib.h>
10 #include <string.h>
11 #include <libfirm/firm.h>
12
13 #ifdef FIRM_BACKEND
14 #include <libfirm/be.h>
15 #endif /* FIRM_BACKEND */
16
17
18 #include "firm_opt.h"
19 #include "firm_codegen.h"
20 #include "firm_cmdline.h"
21 #include "firm_timing.h"
22
23 #ifdef _WIN32
24 #define snprintf _snprintf
25 #endif
26
27 #if defined(_DEBUG) || defined(FIRM_DEBUG)
28 #define DBG(x)  dbg_printf x
29 #else
30 #define DBG(x)
31 #endif /* _DEBUG || FIRM_DEBUG */
32
33
34 /** dump all the graphs depending on cond */
35 #define DUMP_ALL(cond, suffix)                             \
36   do {                                                     \
37     if (cond) {                                            \
38       timer_push(TV_VCG_DUMP);                             \
39       if (firm_dump.no_blocks)                             \
40         dump_all_ir_graphs(dump_ir_graph, suffix);         \
41       else if (firm_dump.extbb)                            \
42         dump_all_ir_graphs(dump_ir_extblock_graph, suffix);\
43       else                                                 \
44         dump_all_ir_graphs(dump_ir_block_graph, suffix);   \
45       timer_pop();                                         \
46     }                                                      \
47   } while (0)
48
49 /** dump all control flow graphs depending on cond */
50 #define DUMP_ALL_CFG(cond, suffix)                      \
51   do {                                                  \
52     if (cond) {                                         \
53       timer_push(TV_VCG_DUMP);                          \
54         dump_all_ir_graphs(dump_cfg, suffix);           \
55       timer_pop();                                      \
56     }                                                   \
57   } while (0)
58
59 /** check all graphs depending on cond */
60 #define CHECK_ALL(cond)                                 \
61   do {                                                  \
62     if (cond) {                                         \
63       int ii;                                           \
64       timer_push(TV_VERIFY);                            \
65       for (ii = get_irp_n_irgs() - 1; ii >= 0; --ii)    \
66         irg_verify(get_irp_irg(ii), VRFY_ENFORCE_SSA);  \
67       timer_pop();                                      \
68     }                                                   \
69   } while (0)
70
71
72
73 /** dump graphs irg depending on cond */
74 #define DUMP_ONE(cond, irg, suffix)                     \
75   do {                                                  \
76     if (cond) {                                         \
77       timer_push(TV_VCG_DUMP);                          \
78       if (firm_dump.no_blocks)                          \
79         dump_ir_graph(irg, suffix);                     \
80       else if (firm_dump.extbb)                         \
81         dump_ir_extblock_graph(irg, suffix);            \
82       else                                              \
83         dump_ir_block_graph(irg, suffix);               \
84       timer_pop();                                      \
85     }                                                   \
86   } while (0)
87
88 /** dump control flow graph irg depending on cond */
89 #define DUMP_ONE_CFG(cond, irg, suffix)                 \
90   do {                                                  \
91     if (cond) {                                         \
92       timer_push(TV_VCG_DUMP);                          \
93       dump_cfg(irg, suffix);                            \
94       timer_pop();                                      \
95     }                                                   \
96   } while (0)
97
98 /** check a graph irg depending on cond */
99 #define CHECK_ONE(cond, irg)                            \
100   do {                                                  \
101     if (cond) {                                         \
102       timer_push(TV_VERIFY);                            \
103         irg_verify(irg, VRFY_ENFORCE_SSA);              \
104       timer_pop();                                      \
105     }                                                   \
106   } while (0)
107
108
109 /* set by the backend parameters */
110 static const ir_settings_arch_dep_t *ad_param = NULL;
111 static create_intrinsic_fkt *arch_create_intrinsic = NULL;
112 static void *create_intrinsic_ctx = NULL;
113 static const ir_settings_if_conv_t *if_conv_info = NULL;
114
115 /* entities of runtime functions */
116 ir_entity_ptr rts_entities[rts_max];
117
118 /**
119  * factory for setting architecture dependent parameters
120  */
121 static const ir_settings_arch_dep_t *arch_factory(void)
122 {
123   static const ir_settings_arch_dep_t param = {
124       1,   /* also use subs */
125       4,   /* maximum shifts */
126      31,   /* maximum shift amount */
127      NULL, /* use default evaluator */
128
129       1, /* allow Mulhs */
130       1, /* allow Mulus */
131      32  /* Mulh allowed up to 32 bit */
132   };
133
134   return ad_param ? ad_param : &param;
135 }
136
137 /**
138  * Map runtime functions.
139  */
140 static void rts_map(void) {
141   static const struct {
142     ir_entity_ptr *ent; /**< address of the rts entity */
143     i_mapper_func func; /**< mapper function. */
144   } mapper[] = {
145     /* integer */
146     { &rts_entities[rts_abs],     i_mapper_abs },
147     { &rts_entities[rts_labs],    i_mapper_abs },
148     { &rts_entities[rts_llabs],   i_mapper_abs },
149     { &rts_entities[rts_imaxabs], i_mapper_abs },
150
151     /* double -> double */
152     { &rts_entities[rts_fabs],    i_mapper_abs },
153     { &rts_entities[rts_sqrt],    i_mapper_sqrt },
154     { &rts_entities[rts_cbrt],    i_mapper_cbrt },
155     { &rts_entities[rts_pow],     i_mapper_pow },
156     { &rts_entities[rts_exp],     i_mapper_exp },
157     { &rts_entities[rts_exp2],    i_mapper_exp },
158     { &rts_entities[rts_exp10],   i_mapper_exp },
159     { &rts_entities[rts_log],     i_mapper_log },
160     { &rts_entities[rts_log2],    i_mapper_log2 },
161     { &rts_entities[rts_log10],   i_mapper_log10 },
162     { &rts_entities[rts_sin],     i_mapper_sin },
163     { &rts_entities[rts_cos],     i_mapper_cos },
164     { &rts_entities[rts_tan],     i_mapper_tan },
165     { &rts_entities[rts_asin],    i_mapper_asin },
166     { &rts_entities[rts_acos],    i_mapper_acos },
167     { &rts_entities[rts_atan],    i_mapper_atan },
168     { &rts_entities[rts_sinh],    i_mapper_sinh },
169     { &rts_entities[rts_cosh],    i_mapper_cosh },
170     { &rts_entities[rts_tanh],    i_mapper_tanh },
171
172     /* float -> float */
173     { &rts_entities[rts_fabsf],   i_mapper_abs },
174     { &rts_entities[rts_sqrtf],   i_mapper_sqrt },
175     { &rts_entities[rts_cbrtf],   i_mapper_cbrt },
176     { &rts_entities[rts_powf],    i_mapper_pow },
177     { &rts_entities[rts_expf],    i_mapper_exp },
178     { &rts_entities[rts_exp2f],   i_mapper_exp },
179     { &rts_entities[rts_exp10f],  i_mapper_exp },
180     { &rts_entities[rts_logf],    i_mapper_log },
181     { &rts_entities[rts_log2f],   i_mapper_log2 },
182     { &rts_entities[rts_log10f],  i_mapper_log10 },
183     { &rts_entities[rts_sinf],    i_mapper_sin },
184     { &rts_entities[rts_cosf],    i_mapper_cos },
185     { &rts_entities[rts_tanf],    i_mapper_tan },
186     { &rts_entities[rts_asinf],   i_mapper_asin },
187     { &rts_entities[rts_acosf],   i_mapper_acos },
188     { &rts_entities[rts_atanf],   i_mapper_atan },
189     { &rts_entities[rts_sinhf],   i_mapper_sinh },
190     { &rts_entities[rts_coshf],   i_mapper_cosh },
191     { &rts_entities[rts_tanhf],   i_mapper_tanh },
192
193     /* long double -> long double */
194     { &rts_entities[rts_fabsl],   i_mapper_abs },
195     { &rts_entities[rts_sqrtl],   i_mapper_sqrt },
196     { &rts_entities[rts_cbrtl],   i_mapper_cbrt },
197     { &rts_entities[rts_powl],    i_mapper_pow },
198     { &rts_entities[rts_expl],    i_mapper_exp },
199     { &rts_entities[rts_exp2l],   i_mapper_exp },
200     { &rts_entities[rts_exp10l],  i_mapper_exp },
201     { &rts_entities[rts_logl],    i_mapper_log },
202     { &rts_entities[rts_log2l],   i_mapper_log2 },
203     { &rts_entities[rts_log10l],  i_mapper_log10 },
204     { &rts_entities[rts_sinl],    i_mapper_sin },
205     { &rts_entities[rts_cosl],    i_mapper_cos },
206     { &rts_entities[rts_tanl],    i_mapper_tan },
207     { &rts_entities[rts_asinl],   i_mapper_asin },
208     { &rts_entities[rts_acosl],   i_mapper_acos },
209     { &rts_entities[rts_atanl],   i_mapper_atan },
210     { &rts_entities[rts_sinhl],   i_mapper_sinh },
211     { &rts_entities[rts_coshl],   i_mapper_cosh },
212     { &rts_entities[rts_tanhl],   i_mapper_tanh },
213
214     /* string */
215     { &rts_entities[rts_memcpy],  i_mapper_memcpy },
216     { &rts_entities[rts_memset],  i_mapper_memset },
217     { &rts_entities[rts_strcmp],  i_mapper_strcmp },
218     { &rts_entities[rts_strncmp], i_mapper_strncmp },
219     { &rts_entities[rts_strlen],  i_mapper_strlen }
220   };
221   i_record rec[sizeof(mapper)/sizeof(mapper[0])];
222   unsigned i, n_map;
223
224   for (i = n_map = 0; i < sizeof(mapper)/sizeof(mapper[0]); ++i)
225     if (*mapper[i].ent != NULL) {
226       rec[n_map].i_call.kind     = INTRINSIC_CALL;
227       rec[n_map].i_call.i_ent    = *mapper[i].ent;
228       rec[n_map].i_call.i_mapper = mapper[i].func;
229       rec[n_map].i_call.ctx      = NULL;
230       rec[n_map].i_call.link     = NULL;
231       ++n_map;
232   }  /* if */
233   if (n_map > 0)
234     lower_intrinsics(rec, n_map, /* part_block_used=*/0);
235 }  /* rts_map */
236
237 static int *irg_dump_no;
238
239 static void dump_graph_count(ir_graph *const irg, const char *const suffix)
240 {
241   char name[64];
242   snprintf(name, sizeof(name), "-%02d_%s", irg_dump_no[get_irg_idx(irg)]++, suffix);
243   DUMP_ONE(1, irg, name);
244 }
245
246 static void dump_graph_cfg_count(ir_graph *const irg, const char *const suffix)
247 {
248   char name[64];
249   snprintf(name, sizeof(name), "-%02d_%s", irg_dump_no[get_irg_idx(irg)]++, suffix);
250   DUMP_ONE_CFG(1, irg, name);
251 }
252
253 static void dump_all_count(const char *const suffix)
254 {
255   const int n_irgs = get_irp_n_irgs();
256   int i;
257
258   for (i = 0; i < n_irgs; ++i)
259     dump_graph_count(get_irp_irg(i), suffix);
260 }
261
262 #define DUMP_ONE_C(cond, irg, suffix)    \
263   do {                                   \
264     if (cond) {                          \
265       dump_graph_count((irg), (suffix)); \
266     }                                    \
267   } while (0)
268
269 #define DUMP_ONE_CFG_C(cond, irg, suffix)    \
270   do {                                       \
271     if (cond) {                              \
272       dump_graph_cfg_count((irg), (suffix)); \
273     }                                        \
274   } while (0)
275
276 #define DUMP_ALL_C(cond, suffix) \
277   do {                           \
278     if (cond) {                  \
279       dump_all_count((suffix));  \
280     }                            \
281   } while (0)
282
283 /**
284  * run all the Firm optimizations
285  *
286  * @param input_filename     the name of the (main) source file
287  * @param firm_const_exists  non-zero, if the const attribute was used on functions
288  */
289 static void do_firm_optimizations(const char *input_filename, int firm_const_exists)
290 {
291   int      i;
292   ir_graph *irg;
293   unsigned aa_opt;
294
295   /* FIXME: cloning might ADD new graphs. */
296   irg_dump_no = calloc(get_irp_last_idx(), sizeof(*irg_dump_no));
297
298   set_opt_strength_red(firm_opt.strength_red);
299   set_opt_scalar_replacement(firm_opt.scalar_replace);
300   set_opt_auto_create_sync(firm_opt.auto_sync);
301   set_opt_alias_analysis(firm_opt.alias_analysis);
302
303   aa_opt = aa_opt_no_opt;
304   if (firm_opt.strict_alias)
305     aa_opt |= aa_opt_type_based | aa_opt_byte_type_may_alias;
306   if (firm_opt.no_alias)
307     aa_opt = aa_opt_no_alias;
308
309   set_irp_memory_disambiguator_options(aa_opt);
310
311   timer_start(TV_ALL_OPT);
312
313   if (firm_opt.remove_unused) {
314         ir_entity **keep_methods;
315         int         arr_len;
316
317     /* Analysis that finds the free methods,
318        i.e. methods that are dereferenced.
319        Optimizes polymorphic calls :-). */
320     cgana(&arr_len, &keep_methods);
321
322     /* Remove methods that are never called. */
323     gc_irgs(arr_len, keep_methods);
324
325     free(keep_methods);
326   }
327
328   if (! firm_opt.freestanding) {
329     rts_map();
330     DUMP_ALL_C(firm_dump.ir_graph && firm_dump.all_phases, "rts");
331     CHECK_ALL(firm_opt.check_all);
332   }
333
334   if (firm_opt.tail_rec) {
335     timer_push(TV_TAIL_REC);
336       opt_tail_recursion();
337     timer_pop();
338
339     DUMP_ALL_C(firm_dump.ir_graph && firm_dump.all_phases, "tail_rec");
340     CHECK_ALL(firm_opt.check_all);
341   }
342
343   if (firm_opt.func_calls) {
344     timer_push(TV_REAL_FUNC_CALL);
345       optimize_funccalls(firm_const_exists, NULL);
346     timer_pop();
347     DUMP_ALL_C(firm_dump.ir_graph && firm_dump.all_phases, "func_call");
348     CHECK_ALL(firm_opt.check_all);
349   }
350
351   if (firm_opt.do_inline) {
352     timer_push(TV_INLINE);
353       inline_leave_functions(500, 80, 30, FALSE);
354     timer_pop();
355     DUMP_ALL_C(firm_dump.ir_graph && firm_dump.all_phases, "inl");
356     CHECK_ALL(firm_opt.check_all);
357   }
358
359   /* do lowering on the const code irg */
360   lower_const_code();
361
362   for (i = 0; i < get_irp_n_irgs(); i++) {
363     irg = current_ir_graph = get_irp_irg(i);
364
365
366 #ifdef FIRM_EXT_GRS
367   /* If SIMD optimization is on, make sure we have only 1 return */
368   if (firm_ext_grs.create_pattern || firm_ext_grs.simd_opt)
369     normalize_one_return(irg);
370 #endif
371
372
373 #if 0
374     if (firm_opt.modes) {
375       /* convert all modes into integer if possible */
376       arch_mode_conversion(irg, predefs.mode_uint);
377     }
378 #endif
379     timer_push(TV_SCALAR_REPLACE);
380       scalar_replacement_opt(irg);
381     timer_pop();
382     DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "scalar");
383     CHECK_ONE(firm_opt.check_all, irg);
384
385     timer_push(TV_LOCAL_OPT);
386       optimize_graph_df(irg);
387     timer_pop();
388     DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "lopt");
389     CHECK_ONE(firm_opt.check_all, irg);
390
391     timer_push(TV_REASSOCIATION);
392       optimize_reassociation(irg);
393     timer_pop();
394     DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "reassoc");
395     CHECK_ONE(firm_opt.check_all, irg);
396
397     if (firm_opt.confirm) {
398       /* Confirm construction currently can only handle blocks with only one control
399          flow predecessor. Calling optimize_cf here removes Bad predecessors and help
400          the optimization of switch constructs. */
401       timer_push(TV_CF_OPT);
402         optimize_cf(irg);
403       timer_pop();
404       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "cfopt");
405       CHECK_ONE(firm_opt.check_all, irg);
406       timer_push(TV_CONFIRM_CREATE);
407         construct_confirms(irg);
408       timer_pop();
409       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "confirms");
410       CHECK_ONE(firm_opt.check_all, irg);
411     }
412
413     timer_push(TV_LOCAL_OPT);
414       optimize_graph_df(irg);
415     timer_pop();
416     DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "lopt");
417     CHECK_ONE(firm_opt.check_all, irg);
418
419     compute_doms(irg);
420     CHECK_ONE(firm_opt.check_all, irg);
421
422     if (firm_opt.code_place) {
423       timer_push(TV_CODE_PLACE);
424         set_opt_global_cse(1);
425         optimize_graph_df(irg);
426         place_code(irg);
427         set_opt_global_cse(0);
428       timer_pop();
429       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "place");
430       CHECK_ONE(firm_opt.check_all, irg);
431     }
432
433     if (firm_opt.luffig) {
434       opt_ldst2(irg);
435       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "ldst2");
436       CHECK_ONE(firm_opt.check_all, irg);
437     }
438
439     timer_push(TV_CF_OPT);
440       optimize_cf(irg);
441     timer_pop();
442     DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "cfopt");
443     CHECK_ONE(firm_opt.check_all, irg);
444
445     /* should we really remove the Confirm here? */
446     if (firm_opt.confirm) {
447       timer_push(TV_CONFIRM_CREATE);
448         remove_confirms(irg);
449       timer_pop();
450     }
451
452     irg_verify(irg, VRFY_ENFORCE_SSA);
453     if (firm_opt.gvn_pre) {
454       do_gvn_pre(irg);
455       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "pre");
456       CHECK_ONE(firm_opt.check_all, irg);
457       irg_verify(irg, VRFY_ENFORCE_SSA);
458     }
459
460     if (firm_opt.load_store) {
461       timer_push(TV_LOAD_STORE);
462         optimize_load_store(irg);
463       timer_pop();
464       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "ldst");
465       CHECK_ONE(firm_opt.check_all, irg);
466         }
467
468     lower_highlevel_graph(irg, firm_opt.lower_bitfields);
469
470     if (firm_opt.deconv) {
471       timer_push(TV_DECONV);
472         conv_opt(irg);
473       timer_pop();
474       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "deconv");
475       CHECK_ONE(firm_opt.check_all, irg);
476     }
477
478     if (firm_opt.cond_eval) {
479       timer_push(TV_COND_EVAL);
480         opt_cond_eval(irg);
481       timer_pop();
482       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "cond_eval");
483       CHECK_ONE(firm_opt.check_all, irg);
484     }
485
486     compute_doms(irg);
487     compute_postdoms(irg);
488     DUMP_ONE_CFG_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "dom");
489     CHECK_ONE(firm_opt.check_all, irg);
490
491     construct_backedges(irg);
492
493     timer_push(TV_CF_OPT);
494       optimize_cf(irg);
495     timer_pop();
496     DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "cfopt");
497     CHECK_ONE(firm_opt.check_all, irg);
498
499     if (firm_opt.if_conversion) {
500       timer_push(TV_IF_CONV);
501         opt_if_conv(current_ir_graph, if_conv_info);
502       timer_pop();
503       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "if");
504       CHECK_ONE(firm_opt.check_all, current_ir_graph);
505
506       timer_push(TV_LOCAL_OPT);
507         optimize_graph_df(current_ir_graph);
508       timer_pop();
509       timer_push(TV_CF_OPT);
510         optimize_cf(current_ir_graph);
511       timer_pop();
512       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "after_if");
513       CHECK_ONE(firm_opt.check_all, current_ir_graph);
514     }
515
516     if (firm_opt.bool_opt) {
517       opt_bool(irg);
518       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "bool");
519       CHECK_ONE(firm_opt.check_all, irg);
520     }
521
522     timer_push(TV_OSR);
523       opt_osr(current_ir_graph, osr_flag_default | osr_flag_keep_reg_pressure | osr_flag_ignore_x86_shift);
524     timer_pop();
525     DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "stred");
526     CHECK_ONE(firm_opt.check_all, irg);
527
528     timer_push(TV_LOCAL_OPT);
529       optimize_graph_df(irg);
530     timer_pop();
531     DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "lopt");
532     CHECK_ONE(firm_opt.check_all, irg);
533
534     edges_deactivate(irg);
535     timer_push(TV_DEAD_NODE);
536       dead_node_elimination(irg);
537     timer_pop();
538     DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "dead");
539     CHECK_ONE(firm_opt.check_all, irg);
540   }
541
542   if (firm_opt.cloning) {
543     proc_cloning((float)firm_opt.clone_threshold);
544     DUMP_ALL_C(firm_dump.ir_graph && firm_dump.all_phases, "clone");
545     CHECK_ALL(firm_opt.check_all);
546   }
547
548   if (firm_dump.ir_graph) {
549     /* recompute backedges for nicer dumps */
550     for (i = 0; i < get_irp_n_irgs(); i++)
551       construct_cf_backedges(get_irp_irg(i));
552   }
553
554   if (firm_opt.remove_unused) {
555     ir_entity **keep_methods;
556     int arr_len;
557
558     /* Analysis that finds the free methods,
559        i.e. methods that are dereferenced.
560        Optimizes polymorphic calls :-). */
561     cgana(&arr_len, &keep_methods);
562
563     /* Remove methods that are never called. */
564     gc_irgs(arr_len, keep_methods);
565
566     free(keep_methods);
567   }
568
569
570   DUMP_ALL(firm_dump.ir_graph, "-opt");
571
572   /* verify optimized graphs */
573   for (i = get_irp_n_irgs() - 1; i >= 0; --i)
574     irg_verify(get_irp_irg(i), VRFY_ENFORCE_SSA);
575
576   if (firm_dump.statistic & STAT_AFTER_OPT)
577     stat_dump_snapshot(input_filename, "opt");
578
579   timer_stop(TV_ALL_OPT);
580 }  /* do_firm_optimizations */
581
582 /**
583  * compute the size of a type (do implicit lowering)
584  *
585  * @param ty   a Firm type
586  */
587 static int compute_type_size(ir_type *ty)
588 {
589   optimization_state_t state;
590   unsigned             align_all = 1;
591   int                  n, size = 0, set = 0;
592   int                  i, dims, s;
593
594   if (get_type_state(ty) == layout_fixed) {
595     /* do not layout already layouted types again */
596     return 1;
597   }
598
599   if (is_Method_type(ty) || ty == get_glob_type()) {
600     /* no need for size calculation for method types or the global type */
601     return 1;
602   }
603
604   DBG(("compute type size visiting: %s\n", get_type_name(ty)));
605
606   switch (get_type_tpop_code(ty)) {
607   case tpo_class:
608   case tpo_struct:
609     for (i = 0, n = get_compound_n_members(ty); i < n; ++i) {
610       ir_entity *ent  = get_compound_member(ty, i);
611       ir_type *ent_ty = get_entity_type(ent);
612       unsigned align, misalign;
613
614       /* compute member types */
615       if (! compute_type_size(ent_ty))
616         return 0;
617
618       align     = get_type_alignment_bytes(ent_ty);
619       align_all = align > align_all ? align : align_all;
620       misalign  = (align ? size % align : 0);
621       size     += (misalign ? align - misalign : 0);
622
623       set_entity_offset(ent, size);
624       size += get_type_size_bytes(ent_ty);
625
626       DBG(("  member %s %s -> (size: %u, align: %u)\n",
627             get_type_name(ent_ty), get_entity_name(ent),
628             get_type_size_bytes(ent_ty), get_type_alignment_bytes(ent_ty)));
629     }
630     if (align_all > 0 && size % align_all) {
631        DBG(("align of the struct member: %u, type size: %d\n", align_all, size));
632        size += align_all - (size % align_all);
633        DBG(("correcting type-size to %d\n", size));
634     }
635     set_type_alignment_bytes(ty, align_all);
636     set = 1;
637     break;
638
639   case tpo_union:
640     for (i = 0, n = get_union_n_members(ty); i < n; ++i) {
641       ir_entity *ent = get_union_member(ty, i);
642
643       if (! compute_type_size(get_entity_type(ent)))
644         return 0;
645       s = get_type_size_bytes(get_entity_type(ent));
646
647       set_entity_offset(ent, 0);
648       size = (s > size ? s : size);
649     }
650     set = 1;
651     break;
652
653   case tpo_array:
654     dims = get_array_n_dimensions(ty);
655
656     if (! compute_type_size(get_array_element_type(ty)))
657       return 0;
658
659     size = 1;
660
661     save_optimization_state(&state);
662     set_optimize(1);
663     set_opt_constant_folding(1);
664
665     for (i = 0; i < dims; ++i) {
666       ir_node *lower   = get_array_lower_bound(ty, i);
667       ir_node *upper   = get_array_upper_bound(ty, i);
668       ir_graph *rem    = current_ir_graph;
669       tarval  *tv_lower, *tv_upper;
670       long     val_lower, val_upper;
671
672       current_ir_graph = get_const_code_irg();
673       local_optimize_node(lower);
674       local_optimize_node(upper);
675       current_ir_graph = rem;
676
677       tv_lower = computed_value(lower);
678       tv_upper = computed_value(upper);
679
680       if (tv_lower == tarval_bad || tv_upper == tarval_bad) {
681         /*
682          * we cannot calculate the size of this array yet, it
683          * even might be unknown until the end, like argv[]
684          */
685         restore_optimization_state(&state);
686         return 0;
687       }
688
689       val_upper = get_tarval_long(tv_upper);
690       val_lower = get_tarval_long(tv_lower);
691       size     *= val_upper - val_lower;
692     }
693     restore_optimization_state(&state);
694
695     DBG(("array %s -> (elements: %d, element type size: %d)\n",
696           get_type_name(ty),
697           size, get_type_size_bytes(get_array_element_type(ty))));
698     size *= get_type_size_bytes(get_array_element_type(ty));
699     set = 1;
700     break;
701
702   default:
703     break;
704   }
705
706   if (set) {
707     set_type_size_bytes(ty, size);
708     set_type_state(ty, layout_fixed);
709   }
710
711   DBG(("size: %d\n", get_type_size_bytes(ty)));
712
713   return set;
714 }  /* compute_type_size */
715
716 /**
717  * layout all types of the Firm graph
718  */
719 static void compute_type_sizes(void)
720 {
721   int i;
722   ir_type *tp;
723   ir_graph *irg;
724
725   /* all frame types */
726   for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
727     irg = get_irp_irg(i);
728     /* do not optimize away variables in debug mode */
729     if (firm_opt.debug_mode == DBG_MODE_NONE)
730       opt_frame_irg(irg);
731     compute_type_size(get_irg_frame_type(irg));
732   }
733
734   /* all other types */
735   for (i = get_irp_n_types() - 1; i >= 0; --i) {
736     tp = get_irp_type(i);
737     compute_type_size(tp);
738
739     if (is_Method_type(tp)) {
740       tp = get_method_value_res_type(tp);
741
742       if (tp) {
743         /* we have a value result type for this method, lower */
744         compute_type_size(tp);
745       }
746     }
747   }
748 }  /* compute_type_sizes */
749
750 /**
751  * do Firm lowering
752  *
753  * @param input_filename  the name of the (main) source file
754  */
755 static void do_firm_lowering(const char *input_filename)
756 {
757   int i;
758
759   /* do class lowering and vtbl creation */
760 //  lower_classes_to_struct("vtbl", "m");
761
762 #if 0
763   timer_push(TV_LOWER);
764   lower_highlevel();
765   timer_pop();
766 #endif
767
768   if (firm_opt.lower_ll) {
769     lwrdw_param_t init = {
770       1,
771       1,
772       mode_Ls, mode_Lu,
773       mode_Is, mode_Iu,
774       def_create_intrinsic_fkt,
775       NULL
776     };
777
778
779     if (arch_create_intrinsic) {
780       init.create_intrinsic = arch_create_intrinsic;
781       init.ctx              = create_intrinsic_ctx;
782     }
783     timer_push(TV_DW_LOWER);
784       lower_dw_ops(&init);
785       DUMP_ALL(firm_dump.ir_graph, "-dw");
786     timer_pop();
787   }
788
789   if (firm_dump.statistic & STAT_AFTER_LOWER)
790     stat_dump_snapshot(input_filename, "low");
791
792   /* verify lowered graphs */
793   timer_push(TV_VERIFY);
794   for (i = get_irp_n_irgs() - 1; i >= 0; --i)
795     irg_verify(get_irp_irg(i), VRFY_ENFORCE_SSA);
796   timer_pop();
797
798   DUMP_ALL(firm_dump.ir_graph, "-low");
799
800   if (firm_opt.enabled) {
801     timer_start(TV_ALL_OPT);
802
803     /* run reassociation first on all graphs BEFORE the architecture dependent optimizations
804        are enabled */
805     for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
806       current_ir_graph = get_irp_irg(i);
807
808       timer_push(TV_REASSOCIATION);
809         optimize_reassociation(current_ir_graph);
810       timer_pop();
811       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, current_ir_graph, "reassoc");
812       CHECK_ONE(firm_opt.check_all, current_ir_graph);
813     }
814
815     for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
816       current_ir_graph = get_irp_irg(i);
817
818       if (firm_opt.code_place)
819         set_opt_global_cse(1);
820
821       timer_push(TV_LOCAL_OPT);
822         optimize_graph_df(current_ir_graph);
823       timer_pop();
824       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, current_ir_graph, "lopt");
825       if (! firm_opt.code_place)
826         CHECK_ONE(firm_opt.check_all, current_ir_graph);
827
828       if (firm_opt.code_place) {
829         timer_push(TV_CODE_PLACE);
830           place_code(current_ir_graph);
831           set_opt_global_cse(0);
832         timer_pop();
833         DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, current_ir_graph, "place");
834         CHECK_ONE(firm_opt.check_all, current_ir_graph);
835       }
836
837 //      set_opt_global_cse(0);
838       timer_push(TV_LOAD_STORE);
839         optimize_load_store(current_ir_graph);
840       timer_pop();
841       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, current_ir_graph, "ldst");
842       CHECK_ONE(firm_opt.check_all, current_ir_graph);
843
844
845       timer_push(TV_LOCAL_OPT);
846         optimize_graph_df(current_ir_graph);
847       timer_pop();
848       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, current_ir_graph, "lopt");
849
850       timer_push(TV_CF_OPT);
851         optimize_cf(current_ir_graph);
852       timer_pop();
853       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, current_ir_graph, "cf");
854       CHECK_ONE(firm_opt.check_all, current_ir_graph);
855
856       if (firm_opt.if_conversion) {
857         timer_push(TV_IF_CONV);
858           opt_if_conv(current_ir_graph, if_conv_info);
859         timer_pop();
860         DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, current_ir_graph, "if");
861         CHECK_ONE(firm_opt.check_all, current_ir_graph);
862
863         timer_push(TV_LOCAL_OPT);
864           optimize_graph_df(current_ir_graph);
865         timer_pop();
866         timer_push(TV_CF_OPT);
867           optimize_cf(current_ir_graph);
868         timer_pop();
869         DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, current_ir_graph, "after_if");
870         CHECK_ONE(firm_opt.check_all, current_ir_graph);
871       }
872     }
873     timer_stop(TV_ALL_OPT);
874
875     DUMP_ALL(firm_dump.ir_graph, "-low-opt");
876   }
877
878   if (firm_opt.cc_opt)
879     mark_private_methods();
880
881   /* set the phase to low */
882   for (i = get_irp_n_irgs() - 1; i >= 0; --i)
883     set_irg_phase_low(get_irp_irg(i));
884
885   /* all graphs are lowered, set the irp phase to low */
886   set_irp_phase_state(phase_low);
887
888   if (firm_dump.statistic & STAT_FINAL) {
889     stat_dump_snapshot(input_filename, "final");
890   }
891 }  /* do_firm_lowering */
892
893 /**
894  * Initialize for the Firm-generating back end.
895  */
896 void gen_firm_init(void)
897 {
898   firm_parameter_t params;
899   char             *dump_filter;
900   unsigned         pattern = 0;
901
902   /* the automatic state is only set if inlining is enabled */
903   firm_opt.auto_inline = firm_opt.do_inline;
904
905   if (firm_dump.stat_pattern)
906     pattern |= FIRMSTAT_PATTERN_ENABLED;
907
908   if (firm_dump.stat_dag)
909     pattern |= FIRMSTAT_COUNT_DAG;
910
911   memset(&params, 0, sizeof(params));
912   params.size                  = sizeof(params);
913   params.enable_statistics     = firm_dump.statistic == STAT_NONE ? 0 :
914     FIRMSTAT_ENABLED | FIRMSTAT_COUNT_STRONG_OP | FIRMSTAT_COUNT_CONSTS | pattern;
915   params.initialize_local_func = uninitialized_local_var;
916   params.cc_mask               = 0; /* no regparam, cdecl */
917   params.builtin_dbg           = NULL;
918
919 #ifdef FIRM_BACKEND
920   if (firm_be_opt.selection == BE_FIRM_BE) {
921     const backend_params *be_params = be_init();
922
923     firm_opt.lower_ll       = (a_byte) be_params->do_dw_lowering;
924     params.arch_op_settings = be_params->arch_op_settings;
925
926     arch_create_intrinsic   = be_params->arch_create_intrinsic_fkt;
927     create_intrinsic_ctx    = be_params->create_intrinsic_ctx;
928
929     ad_param                = be_params->dep_param;
930     if_conv_info            = be_params->if_conv_info;
931   }
932 #endif /* FIRM_BACKEND */
933
934 #ifdef FIRM_EXT_GRS
935   /* Activate Graph rewriting if SIMD optimization is turned on */
936   /* This has to be done before init_firm() is called! */
937   if (firm_ext_grs.simd_opt)
938           ext_grs_activate();
939 #endif
940
941   init_firm(&params);
942   dbg_init(NULL, NULL, dbg_snprint);
943   edges_init_dbg(firm_opt.vrfy_edges);
944   //cbackend_set_debug_retrieve(dbg_retrieve);
945
946   set_opt_precise_exc_context(firm_opt.precise_exc);
947   set_opt_fragile_ops(firm_opt.fragile_ops);
948
949   /* dynamic dispatch works currently only if whole world scenarios */
950   set_opt_dyn_meth_dispatch(0);
951
952   arch_dep_init(arch_factory);
953
954   /* do not run architecture dependent optimizations in building phase */
955   arch_dep_set_opts(arch_dep_none);
956
957   do_node_verification((firm_verification_t) firm_opt.vrfy);
958   if (firm_dump.filter)
959     only_dump_method_with_name(new_id_from_str(firm_dump.filter));
960
961   if (firm_opt.enabled) {
962     set_optimize(1);
963     set_opt_constant_folding(firm_opt.const_folding);
964     set_opt_cse(firm_opt.cse);
965     set_opt_global_cse (0);
966     set_opt_unreachable_code(1);
967     set_opt_control_flow(firm_opt.control_flow);
968     set_opt_control_flow_weak_simplification(1);
969     set_opt_control_flow_strong_simplification(1);
970   }
971   else
972     set_optimize(0);
973
974   dump_filter = getenv("FIRM_DUMP_FILTER");
975   if (dump_filter)
976     only_dump_method_with_name(new_id_from_str(dump_filter));
977
978   /* do not dump entity ld names */
979   dump_ld_names(0);
980
981 #if 0
982   /* init the ycomp debugger extension */
983   if (firm_opt.ycomp_dbg)
984     firm_init_ycomp_debugger(firm_opt.ycomp_host, firm_opt.ycomp_port);
985 #endif
986 }  /* gen_firm_init */
987
988 /**
989  * Called, after the Firm generation is completed,
990  * do all optimizations and backend call here.
991  *
992  * @param out                a file handle for the output, may be NULL
993  * @param input_filename     the name of the (main) source file
994  * @param c_mode             non-zero if "C" was compiled
995  * @param firm_const_exists  non-zero, if the const attribute was used on functions
996  */
997 void gen_firm_finish(FILE *out, const char *input_filename, int c_mode, int firm_const_exists)
998 {
999   int i;
1000
1001   /* the general for dumping option must be set, or the others will not work */
1002   firm_dump.ir_graph
1003       = (a_byte) (firm_dump.ir_graph | firm_dump.all_phases | firm_dump.extbb);
1004
1005   dump_keepalive_edges(1);
1006   dump_consts_local(1);
1007   dump_dominator_information(1);
1008   dump_loop_information(0);
1009
1010   if (!firm_dump.edge_labels)
1011     turn_off_edge_labels();
1012
1013   if (firm_dump.all_types) {
1014     dump_all_types("");
1015     if (! c_mode) {
1016       dump_class_hierarchy(0, "");
1017       dump_class_hierarchy(1, "-with-entities");
1018     }
1019   }
1020
1021   /* finalize all graphs */
1022   for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
1023     ir_graph *irg = get_irp_irg(i);
1024
1025     irg_finalize_cons(irg);
1026     DUMP_ONE(firm_dump.ir_graph, irg, "");
1027
1028     /* verify the graph */
1029     timer_push(TV_VERIFY);
1030       irg_verify(irg, VRFY_ENFORCE_SSA);
1031     timer_pop();
1032   }
1033
1034   timer_push(TV_VERIFY);
1035     tr_vrfy();
1036   timer_pop();
1037
1038   /* all graphs are finalized, set the irp phase to high */
1039   set_irp_phase_state(phase_high);
1040
1041   /* lower all compound call return values */
1042   lower_compound_params();
1043
1044   /* computes the sizes of all types that are still not computed */
1045   compute_type_sizes();
1046
1047   if (firm_dump.statistic & STAT_BEFORE_OPT) {
1048     stat_dump_snapshot(input_filename, "noopt");
1049   }
1050
1051   if (firm_opt.enabled)
1052     do_firm_optimizations(input_filename, firm_const_exists);
1053
1054   if (firm_dump.gen_firm_asm) {
1055     timer_push(TV_FIRM_ASM);
1056       gen_Firm_assembler(input_filename);
1057     timer_pop();
1058     return;
1059   }
1060
1061   if (firm_opt.lower)
1062     do_firm_lowering(input_filename);
1063
1064   /* set the phase to low */
1065   for (i = get_irp_n_irgs() - 1; i >= 0; --i)
1066     set_irg_phase_low(get_irp_irg(i));
1067
1068
1069 #ifdef FIRM_EXT_GRS
1070   /** SIMD Optimization  Extensions **/
1071
1072   /* Pattern creation step. No code has to be generated, so
1073      exit after pattern creation */
1074   if (firm_ext_grs.create_pattern) {
1075     ext_grs_create_pattern();
1076     exit(0);
1077   }
1078
1079   /* SIMD optimization step. Uses graph patterns to find
1080      rich instructions and rewrite */
1081   if (firm_ext_grs.simd_opt)
1082     ext_grs_simd_opt();
1083 #endif
1084
1085   /* enable architecture dependent optimizations */
1086   arch_dep_set_opts((arch_dep_opts_t)
1087                     ((firm_opt.muls ? arch_dep_mul_to_shift : arch_dep_none) |
1088                     (firm_opt.divs ? arch_dep_div_by_const : arch_dep_none) |
1089                     (firm_opt.mods ? arch_dep_mod_by_const : arch_dep_none) ));
1090
1091
1092   if (firm_dump.statistic & STAT_FINAL_IR)
1093     stat_dump_snapshot(input_filename, "final-ir");
1094
1095   /* run the code generator */
1096   if (firm_be_opt.selection != BE_NONE)
1097     do_codegen(out, input_filename);
1098
1099   if (firm_dump.statistic & STAT_FINAL)
1100     stat_dump_snapshot(input_filename, "final");
1101
1102 #if 0
1103   if (firm_opt.ycomp_dbg)
1104     firm_finish_ycomp_debugger();
1105 #endif
1106 }  /* gen_firm_finish */
1107
1108 /**
1109  * Do very early initializations
1110  */
1111 void firm_early_init(void) {
1112 #ifdef FIRM_BACKEND
1113   /* arg: need this here for command line options */
1114   be_opt_register();
1115 #endif
1116   firm_init_options(NULL, 0, NULL);
1117 }  /* firm_early_init */