handle the new overflow_unsafe_transform option right; synchronize with edgfe
[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   /* Overflow unsafe transformation can be enabled here if OSR is disabled, else
304      must be disabled until OSR finished. */
305   set_opt_overflow_unsafe_transform(firm_opt.strength_red == FALSE);
306
307   aa_opt = aa_opt_no_opt;
308   if (firm_opt.strict_alias)
309     aa_opt |= aa_opt_type_based | aa_opt_byte_type_may_alias;
310   if (firm_opt.no_alias)
311     aa_opt = aa_opt_no_alias;
312
313   set_irp_memory_disambiguator_options(aa_opt);
314
315   timer_start(TV_ALL_OPT);
316
317   if (firm_opt.remove_unused) {
318         ir_entity **keep_methods;
319         int         arr_len;
320
321     /* Analysis that finds the free methods,
322        i.e. methods that are dereferenced.
323        Optimizes polymorphic calls :-). */
324     cgana(&arr_len, &keep_methods);
325
326     /* Remove methods that are never called. */
327     gc_irgs(arr_len, keep_methods);
328
329     free(keep_methods);
330   }
331
332   if (! firm_opt.freestanding) {
333     rts_map();
334     DUMP_ALL_C(firm_dump.ir_graph && firm_dump.all_phases, "rts");
335     CHECK_ALL(firm_opt.check_all);
336   }
337
338   if (firm_opt.tail_rec) {
339     timer_push(TV_TAIL_REC);
340       opt_tail_recursion();
341     timer_pop();
342
343     DUMP_ALL_C(firm_dump.ir_graph && firm_dump.all_phases, "tail_rec");
344     CHECK_ALL(firm_opt.check_all);
345   }
346
347   if (firm_opt.func_calls) {
348     timer_push(TV_REAL_FUNC_CALL);
349       optimize_funccalls(firm_const_exists, NULL);
350     timer_pop();
351     DUMP_ALL_C(firm_dump.ir_graph && firm_dump.all_phases, "func_call");
352     CHECK_ALL(firm_opt.check_all);
353   }
354
355   if (firm_opt.do_inline) {
356     timer_push(TV_INLINE);
357       inline_leave_functions(500, 80, 30, FALSE);
358     timer_pop();
359     DUMP_ALL_C(firm_dump.ir_graph && firm_dump.all_phases, "inl");
360     CHECK_ALL(firm_opt.check_all);
361   }
362
363   /* do lowering on the const code irg */
364   lower_const_code();
365
366   for (i = 0; i < get_irp_n_irgs(); i++) {
367     irg = current_ir_graph = get_irp_irg(i);
368
369
370 #ifdef FIRM_EXT_GRS
371   /* If SIMD optimization is on, make sure we have only 1 return */
372   if (firm_ext_grs.create_pattern || firm_ext_grs.simd_opt)
373     normalize_one_return(irg);
374 #endif
375
376
377 #if 0
378     if (firm_opt.modes) {
379       /* convert all modes into integer if possible */
380       arch_mode_conversion(irg, predefs.mode_uint);
381     }
382 #endif
383     timer_push(TV_SCALAR_REPLACE);
384       scalar_replacement_opt(irg);
385     timer_pop();
386     DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "scalar");
387     CHECK_ONE(firm_opt.check_all, irg);
388
389     timer_push(TV_LOCAL_OPT);
390       optimize_graph_df(irg);
391     timer_pop();
392     DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "lopt");
393     CHECK_ONE(firm_opt.check_all, irg);
394
395     timer_push(TV_REASSOCIATION);
396       optimize_reassociation(irg);
397     timer_pop();
398     DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "reassoc");
399     CHECK_ONE(firm_opt.check_all, irg);
400
401     if (firm_opt.confirm) {
402       /* Confirm construction currently can only handle blocks with only one control
403          flow predecessor. Calling optimize_cf here removes Bad predecessors and help
404          the optimization of switch constructs. */
405       timer_push(TV_CF_OPT);
406         optimize_cf(irg);
407       timer_pop();
408       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "cfopt");
409       CHECK_ONE(firm_opt.check_all, irg);
410       timer_push(TV_CONFIRM_CREATE);
411         construct_confirms(irg);
412       timer_pop();
413       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "confirms");
414       CHECK_ONE(firm_opt.check_all, irg);
415     }
416
417     timer_push(TV_LOCAL_OPT);
418       optimize_graph_df(irg);
419     timer_pop();
420     DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "lopt");
421     CHECK_ONE(firm_opt.check_all, irg);
422
423     compute_doms(irg);
424     CHECK_ONE(firm_opt.check_all, irg);
425
426     if (firm_opt.code_place) {
427       timer_push(TV_CODE_PLACE);
428         set_opt_global_cse(1);
429         optimize_graph_df(irg);
430         place_code(irg);
431         set_opt_global_cse(0);
432       timer_pop();
433       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "place");
434       CHECK_ONE(firm_opt.check_all, irg);
435     }
436
437     if (firm_opt.luffig) {
438       opt_ldst2(irg);
439       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "ldst2");
440       CHECK_ONE(firm_opt.check_all, irg);
441     }
442
443     timer_push(TV_CF_OPT);
444       optimize_cf(irg);
445     timer_pop();
446     DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "cfopt");
447     CHECK_ONE(firm_opt.check_all, irg);
448
449     /* should we really remove the Confirm here? */
450     if (firm_opt.confirm) {
451       timer_push(TV_CONFIRM_CREATE);
452         remove_confirms(irg);
453       timer_pop();
454     }
455
456     irg_verify(irg, VRFY_ENFORCE_SSA);
457     if (firm_opt.gvn_pre) {
458       do_gvn_pre(irg);
459       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "pre");
460       CHECK_ONE(firm_opt.check_all, irg);
461       irg_verify(irg, VRFY_ENFORCE_SSA);
462     }
463
464     if (firm_opt.loop_unrolling) {
465       timer_push(TV_LOOP_UNROLL);
466         optimize_loop_unrolling(irg);
467       timer_pop();
468       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "loop");
469       CHECK_ONE(firm_opt.check_all, irg);
470         }
471
472     if (firm_opt.load_store) {
473       timer_push(TV_LOAD_STORE);
474         optimize_load_store(irg);
475       timer_pop();
476       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "ldst");
477       CHECK_ONE(firm_opt.check_all, irg);
478         }
479
480     lower_highlevel_graph(irg, firm_opt.lower_bitfields);
481
482     if (firm_opt.deconv) {
483       timer_push(TV_DECONV);
484         conv_opt(irg);
485       timer_pop();
486       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "deconv");
487       CHECK_ONE(firm_opt.check_all, irg);
488     }
489
490     if (firm_opt.cond_eval) {
491       timer_push(TV_COND_EVAL);
492         opt_cond_eval(irg);
493       timer_pop();
494       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "cond_eval");
495       CHECK_ONE(firm_opt.check_all, irg);
496     }
497
498     compute_doms(irg);
499     compute_postdoms(irg);
500     DUMP_ONE_CFG_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "dom");
501     CHECK_ONE(firm_opt.check_all, irg);
502
503     construct_backedges(irg);
504
505     timer_push(TV_CF_OPT);
506       optimize_cf(irg);
507     timer_pop();
508     DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "cfopt");
509     CHECK_ONE(firm_opt.check_all, irg);
510
511     if (firm_opt.if_conversion) {
512       timer_push(TV_IF_CONV);
513         opt_if_conv(current_ir_graph, if_conv_info);
514       timer_pop();
515       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "if");
516       CHECK_ONE(firm_opt.check_all, current_ir_graph);
517
518       timer_push(TV_LOCAL_OPT);
519         optimize_graph_df(current_ir_graph);
520       timer_pop();
521       timer_push(TV_CF_OPT);
522         optimize_cf(current_ir_graph);
523       timer_pop();
524       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "after_if");
525       CHECK_ONE(firm_opt.check_all, current_ir_graph);
526     }
527
528     if (firm_opt.bool_opt) {
529       opt_bool(irg);
530       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "bool");
531       CHECK_ONE(firm_opt.check_all, irg);
532     }
533
534     timer_push(TV_OSR);
535       opt_osr(current_ir_graph, osr_flag_default | osr_flag_keep_reg_pressure | osr_flag_ignore_x86_shift);
536           /* now it is safe to enable overflow unsafe transformations */
537           set_opt_overflow_unsafe_transform(1);
538     timer_pop();
539     DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "stred");
540     CHECK_ONE(firm_opt.check_all, irg);
541
542     timer_push(TV_LOCAL_OPT);
543       optimize_graph_df(irg);
544     timer_pop();
545     DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "lopt");
546     CHECK_ONE(firm_opt.check_all, irg);
547
548     edges_deactivate(irg);
549     timer_push(TV_DEAD_NODE);
550       dead_node_elimination(irg);
551     timer_pop();
552     DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, irg, "dead");
553     CHECK_ONE(firm_opt.check_all, irg);
554   }
555
556   if (firm_opt.cloning) {
557     proc_cloning((float)firm_opt.clone_threshold);
558     DUMP_ALL_C(firm_dump.ir_graph && firm_dump.all_phases, "clone");
559     CHECK_ALL(firm_opt.check_all);
560   }
561
562   if (firm_dump.ir_graph) {
563     /* recompute backedges for nicer dumps */
564     for (i = 0; i < get_irp_n_irgs(); i++)
565       construct_cf_backedges(get_irp_irg(i));
566   }
567
568   if (firm_opt.remove_unused) {
569     ir_entity **keep_methods;
570     int arr_len;
571
572     /* Analysis that finds the free methods,
573        i.e. methods that are dereferenced.
574        Optimizes polymorphic calls :-). */
575     cgana(&arr_len, &keep_methods);
576
577     /* Remove methods that are never called. */
578     gc_irgs(arr_len, keep_methods);
579
580     free(keep_methods);
581   }
582
583
584   DUMP_ALL(firm_dump.ir_graph, "-opt");
585
586   /* verify optimized graphs */
587   for (i = get_irp_n_irgs() - 1; i >= 0; --i)
588     irg_verify(get_irp_irg(i), VRFY_ENFORCE_SSA);
589
590   if (firm_dump.statistic & STAT_AFTER_OPT)
591     stat_dump_snapshot(input_filename, "opt");
592
593   timer_stop(TV_ALL_OPT);
594 }  /* do_firm_optimizations */
595
596 /**
597  * compute the size of a type (do implicit lowering)
598  *
599  * @param ty   a Firm type
600  */
601 static int compute_type_size(ir_type *ty)
602 {
603   optimization_state_t state;
604   unsigned             align_all = 1;
605   int                  n, size = 0, set = 0;
606   int                  i, dims, s;
607
608   if (get_type_state(ty) == layout_fixed) {
609     /* do not layout already layouted types again */
610     return 1;
611   }
612
613   if (is_Method_type(ty) || ty == get_glob_type()) {
614     /* no need for size calculation for method types or the global type */
615     return 1;
616   }
617
618   DBG(("compute type size visiting: %s\n", get_type_name(ty)));
619
620   switch (get_type_tpop_code(ty)) {
621   case tpo_class:
622   case tpo_struct:
623     for (i = 0, n = get_compound_n_members(ty); i < n; ++i) {
624       ir_entity *ent  = get_compound_member(ty, i);
625       ir_type *ent_ty = get_entity_type(ent);
626       unsigned align, misalign;
627
628       /* compute member types */
629       if (! compute_type_size(ent_ty))
630         return 0;
631
632       align     = get_type_alignment_bytes(ent_ty);
633       align_all = align > align_all ? align : align_all;
634       misalign  = (align ? size % align : 0);
635       size     += (misalign ? align - misalign : 0);
636
637       set_entity_offset(ent, size);
638       size += get_type_size_bytes(ent_ty);
639
640       DBG(("  member %s %s -> (size: %u, align: %u)\n",
641             get_type_name(ent_ty), get_entity_name(ent),
642             get_type_size_bytes(ent_ty), get_type_alignment_bytes(ent_ty)));
643     }
644     if (align_all > 0 && size % align_all) {
645        DBG(("align of the struct member: %u, type size: %d\n", align_all, size));
646        size += align_all - (size % align_all);
647        DBG(("correcting type-size to %d\n", size));
648     }
649     set_type_alignment_bytes(ty, align_all);
650     set = 1;
651     break;
652
653   case tpo_union:
654     for (i = 0, n = get_union_n_members(ty); i < n; ++i) {
655       ir_entity *ent = get_union_member(ty, i);
656
657       if (! compute_type_size(get_entity_type(ent)))
658         return 0;
659       s = get_type_size_bytes(get_entity_type(ent));
660
661       set_entity_offset(ent, 0);
662       size = (s > size ? s : size);
663     }
664     set = 1;
665     break;
666
667   case tpo_array:
668     dims = get_array_n_dimensions(ty);
669
670     if (! compute_type_size(get_array_element_type(ty)))
671       return 0;
672
673     size = 1;
674
675     save_optimization_state(&state);
676     set_optimize(1);
677     set_opt_constant_folding(1);
678
679     for (i = 0; i < dims; ++i) {
680       ir_node *lower   = get_array_lower_bound(ty, i);
681       ir_node *upper   = get_array_upper_bound(ty, i);
682       ir_graph *rem    = current_ir_graph;
683       tarval  *tv_lower, *tv_upper;
684       long     val_lower, val_upper;
685
686       current_ir_graph = get_const_code_irg();
687       local_optimize_node(lower);
688       local_optimize_node(upper);
689       current_ir_graph = rem;
690
691       tv_lower = computed_value(lower);
692       tv_upper = computed_value(upper);
693
694       if (tv_lower == tarval_bad || tv_upper == tarval_bad) {
695         /*
696          * we cannot calculate the size of this array yet, it
697          * even might be unknown until the end, like argv[]
698          */
699         restore_optimization_state(&state);
700         return 0;
701       }
702
703       val_upper = get_tarval_long(tv_upper);
704       val_lower = get_tarval_long(tv_lower);
705       size     *= val_upper - val_lower;
706     }
707     restore_optimization_state(&state);
708
709     DBG(("array %s -> (elements: %d, element type size: %d)\n",
710           get_type_name(ty),
711           size, get_type_size_bytes(get_array_element_type(ty))));
712     size *= get_type_size_bytes(get_array_element_type(ty));
713     set = 1;
714     break;
715
716   default:
717     break;
718   }
719
720   if (set) {
721     set_type_size_bytes(ty, size);
722     set_type_state(ty, layout_fixed);
723   }
724
725   DBG(("size: %d\n", get_type_size_bytes(ty)));
726
727   return set;
728 }  /* compute_type_size */
729
730 /**
731  * layout all types of the Firm graph
732  */
733 static void compute_type_sizes(void)
734 {
735   int i;
736   ir_type *tp;
737   ir_graph *irg;
738
739   /* all frame types */
740   for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
741     irg = get_irp_irg(i);
742     /* do not optimize away variables in debug mode */
743     if (firm_opt.debug_mode == DBG_MODE_NONE)
744       opt_frame_irg(irg);
745     compute_type_size(get_irg_frame_type(irg));
746   }
747
748   /* all other types */
749   for (i = get_irp_n_types() - 1; i >= 0; --i) {
750     tp = get_irp_type(i);
751     compute_type_size(tp);
752
753     if (is_Method_type(tp)) {
754       tp = get_method_value_res_type(tp);
755
756       if (tp) {
757         /* we have a value result type for this method, lower */
758         compute_type_size(tp);
759       }
760     }
761   }
762 }  /* compute_type_sizes */
763
764 /**
765  * do Firm lowering
766  *
767  * @param input_filename  the name of the (main) source file
768  */
769 static void do_firm_lowering(const char *input_filename)
770 {
771   int i;
772
773   /* do class lowering and vtbl creation */
774 //  lower_classes_to_struct("vtbl", "m");
775
776 #if 0
777   timer_push(TV_LOWER);
778   lower_highlevel();
779   timer_pop();
780 #endif
781
782   if (firm_opt.lower_ll) {
783     lwrdw_param_t init = {
784       1,
785       1,
786       mode_Ls, mode_Lu,
787       mode_Is, mode_Iu,
788       def_create_intrinsic_fkt,
789       NULL
790     };
791
792
793     if (arch_create_intrinsic) {
794       init.create_intrinsic = arch_create_intrinsic;
795       init.ctx              = create_intrinsic_ctx;
796     }
797     timer_push(TV_DW_LOWER);
798       lower_dw_ops(&init);
799       DUMP_ALL(firm_dump.ir_graph, "-dw");
800     timer_pop();
801   }
802
803   if (firm_dump.statistic & STAT_AFTER_LOWER)
804     stat_dump_snapshot(input_filename, "low");
805
806   /* verify lowered graphs */
807   timer_push(TV_VERIFY);
808   for (i = get_irp_n_irgs() - 1; i >= 0; --i)
809     irg_verify(get_irp_irg(i), VRFY_ENFORCE_SSA);
810   timer_pop();
811
812   DUMP_ALL(firm_dump.ir_graph, "-low");
813
814   if (firm_opt.enabled) {
815     timer_start(TV_ALL_OPT);
816
817     /* run reassociation first on all graphs BEFORE the architecture dependent optimizations
818        are enabled */
819     for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
820       current_ir_graph = get_irp_irg(i);
821
822       timer_push(TV_REASSOCIATION);
823         optimize_reassociation(current_ir_graph);
824       timer_pop();
825       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, current_ir_graph, "reassoc");
826       CHECK_ONE(firm_opt.check_all, current_ir_graph);
827     }
828
829     for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
830       current_ir_graph = get_irp_irg(i);
831
832       if (firm_opt.code_place)
833         set_opt_global_cse(1);
834
835       timer_push(TV_LOCAL_OPT);
836         optimize_graph_df(current_ir_graph);
837       timer_pop();
838       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, current_ir_graph, "lopt");
839       if (! firm_opt.code_place)
840         CHECK_ONE(firm_opt.check_all, current_ir_graph);
841
842       if (firm_opt.code_place) {
843         timer_push(TV_CODE_PLACE);
844           place_code(current_ir_graph);
845           set_opt_global_cse(0);
846         timer_pop();
847         DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, current_ir_graph, "place");
848         CHECK_ONE(firm_opt.check_all, current_ir_graph);
849       }
850
851 //      set_opt_global_cse(0);
852       timer_push(TV_LOAD_STORE);
853         optimize_load_store(current_ir_graph);
854       timer_pop();
855       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, current_ir_graph, "ldst");
856       CHECK_ONE(firm_opt.check_all, current_ir_graph);
857
858
859       timer_push(TV_LOCAL_OPT);
860         optimize_graph_df(current_ir_graph);
861       timer_pop();
862       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, current_ir_graph, "lopt");
863
864       timer_push(TV_CF_OPT);
865         optimize_cf(current_ir_graph);
866       timer_pop();
867       DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, current_ir_graph, "cf");
868       CHECK_ONE(firm_opt.check_all, current_ir_graph);
869
870       if (firm_opt.if_conversion) {
871         timer_push(TV_IF_CONV);
872           opt_if_conv(current_ir_graph, if_conv_info);
873         timer_pop();
874         DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, current_ir_graph, "if");
875         CHECK_ONE(firm_opt.check_all, current_ir_graph);
876
877         timer_push(TV_LOCAL_OPT);
878           optimize_graph_df(current_ir_graph);
879         timer_pop();
880         timer_push(TV_CF_OPT);
881           optimize_cf(current_ir_graph);
882         timer_pop();
883         DUMP_ONE_C(firm_dump.ir_graph && firm_dump.all_phases, current_ir_graph, "after_if");
884         CHECK_ONE(firm_opt.check_all, current_ir_graph);
885       }
886     }
887     timer_stop(TV_ALL_OPT);
888
889     DUMP_ALL(firm_dump.ir_graph, "-low-opt");
890   }
891
892   if (firm_opt.cc_opt)
893     mark_private_methods();
894
895   /* set the phase to low */
896   for (i = get_irp_n_irgs() - 1; i >= 0; --i)
897     set_irg_phase_low(get_irp_irg(i));
898
899   /* all graphs are lowered, set the irp phase to low */
900   set_irp_phase_state(phase_low);
901
902   if (firm_dump.statistic & STAT_FINAL) {
903     stat_dump_snapshot(input_filename, "final");
904   }
905 }  /* do_firm_lowering */
906
907 /**
908  * Initialize for the Firm-generating back end.
909  */
910 void gen_firm_init(void)
911 {
912   firm_parameter_t params;
913   char             *dump_filter;
914   unsigned         pattern = 0;
915
916   /* the automatic state is only set if inlining is enabled */
917   firm_opt.auto_inline = firm_opt.do_inline;
918
919   if (firm_dump.stat_pattern)
920     pattern |= FIRMSTAT_PATTERN_ENABLED;
921
922   if (firm_dump.stat_dag)
923     pattern |= FIRMSTAT_COUNT_DAG;
924
925   memset(&params, 0, sizeof(params));
926   params.size                  = sizeof(params);
927   params.enable_statistics     = firm_dump.statistic == STAT_NONE ? 0 :
928     FIRMSTAT_ENABLED | FIRMSTAT_COUNT_STRONG_OP | FIRMSTAT_COUNT_CONSTS | pattern;
929   params.initialize_local_func = uninitialized_local_var;
930   params.cc_mask               = 0; /* no regparam, cdecl */
931   params.builtin_dbg           = NULL;
932
933 #ifdef FIRM_BACKEND
934   if (firm_be_opt.selection == BE_FIRM_BE) {
935     const backend_params *be_params = be_init();
936
937     firm_opt.lower_ll       = (a_byte) be_params->do_dw_lowering;
938     params.arch_op_settings = be_params->arch_op_settings;
939
940     arch_create_intrinsic   = be_params->arch_create_intrinsic_fkt;
941     create_intrinsic_ctx    = be_params->create_intrinsic_ctx;
942
943     ad_param                = be_params->dep_param;
944     if_conv_info            = be_params->if_conv_info;
945   }
946 #endif /* FIRM_BACKEND */
947
948 #ifdef FIRM_EXT_GRS
949   /* Activate Graph rewriting if SIMD optimization is turned on */
950   /* This has to be done before init_firm() is called! */
951   if (firm_ext_grs.simd_opt)
952           ext_grs_activate();
953 #endif
954
955   init_firm(&params);
956   dbg_init(NULL, NULL, dbg_snprint);
957   edges_init_dbg(firm_opt.vrfy_edges);
958   //cbackend_set_debug_retrieve(dbg_retrieve);
959
960   set_opt_precise_exc_context(firm_opt.precise_exc);
961   set_opt_fragile_ops(firm_opt.fragile_ops);
962
963   /* dynamic dispatch works currently only if whole world scenarios */
964   set_opt_dyn_meth_dispatch(0);
965
966   arch_dep_init(arch_factory);
967
968   /* do not run architecture dependent optimizations in building phase */
969   arch_dep_set_opts(arch_dep_none);
970
971   do_node_verification((firm_verification_t) firm_opt.vrfy);
972   if (firm_dump.filter)
973     only_dump_method_with_name(new_id_from_str(firm_dump.filter));
974
975   if (firm_opt.enabled) {
976     set_optimize(1);
977     set_opt_constant_folding(firm_opt.const_folding);
978     set_opt_cse(firm_opt.cse);
979     set_opt_global_cse (0);
980     set_opt_unreachable_code(1);
981     set_opt_control_flow(firm_opt.control_flow);
982     set_opt_control_flow_weak_simplification(1);
983     set_opt_control_flow_strong_simplification(1);
984   }
985   else
986     set_optimize(0);
987
988   dump_filter = getenv("FIRM_DUMP_FILTER");
989   if (dump_filter)
990     only_dump_method_with_name(new_id_from_str(dump_filter));
991
992   /* do not dump entity ld names */
993   dump_ld_names(0);
994
995 #if 0
996   /* init the ycomp debugger extension */
997   if (firm_opt.ycomp_dbg)
998     firm_init_ycomp_debugger(firm_opt.ycomp_host, firm_opt.ycomp_port);
999 #endif
1000 }  /* gen_firm_init */
1001
1002 /**
1003  * Called, after the Firm generation is completed,
1004  * do all optimizations and backend call here.
1005  *
1006  * @param out                a file handle for the output, may be NULL
1007  * @param input_filename     the name of the (main) source file
1008  * @param c_mode             non-zero if "C" was compiled
1009  * @param firm_const_exists  non-zero, if the const attribute was used on functions
1010  */
1011 void gen_firm_finish(FILE *out, const char *input_filename, int c_mode, int firm_const_exists)
1012 {
1013   int i;
1014
1015   /* the general for dumping option must be set, or the others will not work */
1016   firm_dump.ir_graph
1017       = (a_byte) (firm_dump.ir_graph | firm_dump.all_phases | firm_dump.extbb);
1018
1019   dump_keepalive_edges(1);
1020   dump_consts_local(1);
1021   dump_dominator_information(1);
1022   dump_loop_information(0);
1023
1024   if (!firm_dump.edge_labels)
1025     turn_off_edge_labels();
1026
1027   if (firm_dump.all_types) {
1028     dump_all_types("");
1029     if (! c_mode) {
1030       dump_class_hierarchy(0, "");
1031       dump_class_hierarchy(1, "-with-entities");
1032     }
1033   }
1034
1035   /* finalize all graphs */
1036   for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
1037     ir_graph *irg = get_irp_irg(i);
1038
1039     irg_finalize_cons(irg);
1040     DUMP_ONE(firm_dump.ir_graph, irg, "");
1041
1042     /* verify the graph */
1043     timer_push(TV_VERIFY);
1044       irg_verify(irg, VRFY_ENFORCE_SSA);
1045     timer_pop();
1046   }
1047
1048   timer_push(TV_VERIFY);
1049     tr_vrfy();
1050   timer_pop();
1051
1052   /* all graphs are finalized, set the irp phase to high */
1053   set_irp_phase_state(phase_high);
1054
1055   /* lower all compound call return values */
1056   lower_compound_params();
1057
1058   /* computes the sizes of all types that are still not computed */
1059   compute_type_sizes();
1060
1061   if (firm_dump.statistic & STAT_BEFORE_OPT) {
1062     stat_dump_snapshot(input_filename, "noopt");
1063   }
1064
1065   if (firm_opt.enabled)
1066     do_firm_optimizations(input_filename, firm_const_exists);
1067
1068   if (firm_dump.gen_firm_asm) {
1069     timer_push(TV_FIRM_ASM);
1070       gen_Firm_assembler(input_filename);
1071     timer_pop();
1072     return;
1073   }
1074
1075   if (firm_opt.lower)
1076     do_firm_lowering(input_filename);
1077
1078   /* set the phase to low */
1079   for (i = get_irp_n_irgs() - 1; i >= 0; --i)
1080     set_irg_phase_low(get_irp_irg(i));
1081
1082
1083 #ifdef FIRM_EXT_GRS
1084   /** SIMD Optimization  Extensions **/
1085
1086   /* Pattern creation step. No code has to be generated, so
1087      exit after pattern creation */
1088   if (firm_ext_grs.create_pattern) {
1089     ext_grs_create_pattern();
1090     exit(0);
1091   }
1092
1093   /* SIMD optimization step. Uses graph patterns to find
1094      rich instructions and rewrite */
1095   if (firm_ext_grs.simd_opt)
1096     ext_grs_simd_opt();
1097 #endif
1098
1099   /* enable architecture dependent optimizations */
1100   arch_dep_set_opts((arch_dep_opts_t)
1101                     ((firm_opt.muls ? arch_dep_mul_to_shift : arch_dep_none) |
1102                     (firm_opt.divs ? arch_dep_div_by_const : arch_dep_none) |
1103                     (firm_opt.mods ? arch_dep_mod_by_const : arch_dep_none) ));
1104
1105
1106   if (firm_dump.statistic & STAT_FINAL_IR)
1107     stat_dump_snapshot(input_filename, "final-ir");
1108
1109   /* run the code generator */
1110   if (firm_be_opt.selection != BE_NONE)
1111     do_codegen(out, input_filename);
1112
1113   if (firm_dump.statistic & STAT_FINAL)
1114     stat_dump_snapshot(input_filename, "final");
1115
1116 #if 0
1117   if (firm_opt.ycomp_dbg)
1118     firm_finish_ycomp_debugger();
1119 #endif
1120 }  /* gen_firm_finish */
1121
1122 /**
1123  * Do very early initializations
1124  */
1125 void firm_early_init(void) {
1126 #ifdef FIRM_BACKEND
1127   /* arg: need this here for command line options */
1128   be_opt_register();
1129 #endif
1130   firm_init_options(NULL, 0, NULL);
1131 }  /* firm_early_init */