Merge timers[] into opts[].
[cparser] / driver / firm_opt.c
1 /**
2  *
3  * @file firm_opt.c -- Firm-generating back end optimizations.
4  *
5  * (C) 2005-2010  Michael Beck   beck@ipd.info.uni-karlsruhe.de
6  *
7  * $Id$
8  */
9
10 #include <config.h>
11
12 #include <stdbool.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <stdbool.h>
16 #include <assert.h>
17 #include <libfirm/firm.h>
18
19 #include "firm_opt.h"
20 #include "firm_timing.h"
21 #include "ast2firm.h"
22 #include "adt/strutil.h"
23
24 /* optimization settings */
25 struct a_firm_opt {
26         bool     const_folding;   /**< enable constant folding */
27         bool     cse;             /**< enable common-subexpression elimination */
28         bool     confirm;         /**< enable Confirm optimization */
29         bool     muls;            /**< enable architecture dependent mul optimization */
30         bool     divs;            /**< enable architecture dependent div optimization */
31         bool     mods;            /**< enable architecture dependent mod optimization */
32         bool     alias_analysis;  /**< enable Alias Analysis */
33         bool     strict_alias;    /**< enable strict Alias Analysis (using type based AA) */
34         bool     no_alias;        /**< no aliasing possible. */
35         bool     verify;          /**< Firm verifier setting */
36         bool     check_all;       /**< enable checking all Firm phases */
37         int      clone_threshold; /**< The threshold value for procedure cloning. */
38         unsigned inline_maxsize;  /**< Maximum function size for inlining. */
39         unsigned inline_threshold;/**< Inlining benefice threshold. */
40         bool     verify_edges;    /**< verify edges */
41 };
42
43 /** statistic options */
44 typedef enum a_firmstat_selection_tag {
45         STAT_NONE        = 0x00000000,
46         STAT_BEFORE_OPT  = 0x00000001,
47         STAT_AFTER_OPT   = 0x00000002,
48         STAT_AFTER_LOWER = 0x00000004,
49         STAT_FINAL_IR    = 0x00000008,
50         STAT_FINAL       = 0x00000010,
51 } a_firmstat_selection;
52
53 /* dumping options */
54 struct a_firm_dump {
55         bool debug_print;   /**< enable debug print */
56         bool all_types;     /**< dump the All_types graph */
57         bool no_blocks;     /**< dump non-blocked graph */
58         bool extbb;         /**< dumps extended basic blocks */
59         bool ir_graph;      /**< dump all graphs */
60         bool all_phases;    /**< dump the IR graph after all phases */
61         bool statistic;     /**< Firm statistic setting */
62         bool stat_pattern;  /**< enable Firm statistic pattern */
63         bool stat_dag;      /**< enable Firm DAG statistic */
64 };
65
66 struct a_firm_be_opt {
67         bool selection;
68         bool node_stat;
69 };
70
71 /* optimization settings */
72 static struct a_firm_opt firm_opt = {
73         .const_folding    =  true,
74         .cse              =  true,
75         .confirm          =  true,
76         .muls             =  true,
77         .divs             =  true,
78         .mods             =  true,
79         .alias_analysis   =  true,
80         .strict_alias     =  false,
81         .no_alias         =  false,
82         .verify           =  FIRM_VERIFICATION_ON,
83         .check_all        =  true,
84         .clone_threshold  =  DEFAULT_CLONE_THRESHOLD,
85         .inline_maxsize   =  750,
86         .inline_threshold =  0,
87         .verify_edges     =  false,
88 };
89
90 /* dumping options */
91 static struct a_firm_dump firm_dump = {
92         .debug_print  = false,
93         .all_types    = false,
94         .no_blocks    = false,
95         .extbb        = false,
96         .ir_graph     = false,
97         .all_phases   = false,
98         .statistic    = STAT_NONE,
99         .stat_pattern = 0,
100         .stat_dag     = 0,
101 };
102
103 #define X(a)  a, sizeof(a)-1
104
105 /** Parameter description structure */
106 static const struct params {
107   const char *option;      /**< name of the option */
108   size_t     opt_len;      /**< length of the option string */
109   bool       *flag;        /**< address of variable to set/reset */
110   bool       set;          /**< iff true, variable will be set, else reset */
111   const char *description; /**< description of this option */
112 } firm_options[] = {
113   /* firm optimization options */
114   { X("no-opt"),                 NULL,                       0, "disable all FIRM optimizations" },
115   { X("cse"),                    &firm_opt.cse,              1, "enable common subexpression elimination" },
116   { X("no-cse"),                 &firm_opt.cse,              0, "disable common subexpression elimination" },
117   { X("const-fold"),             &firm_opt.const_folding,    1, "enable constant folding" },
118   { X("no-const-fold"),          &firm_opt.const_folding,    0, "disable constant folding" },
119   { X("inline-max-size=<size>"), NULL,                       0, "set maximum size for function inlining" },
120   { X("inline-threshold=<size>"),NULL,                       0, "set benefice threshold for function inlining" },
121   { X("confirm"),                &firm_opt.confirm,          1, "enable Confirm optimization" },
122   { X("no-confirm"),             &firm_opt.confirm,          0, "disable Confirm optimization" },
123   { X("opt-mul"),                &firm_opt.muls,             0, "enable multiplication optimization" },
124   { X("no-opt-mul"),             &firm_opt.muls,             0, "disable multiplication optimization" },
125   { X("opt-div"),                &firm_opt.divs,             0, "enable division optimization" },
126   { X("no-opt-div"),             &firm_opt.divs,             0, "disable division optimization" },
127   { X("opt-mod"),                &firm_opt.mods,             0, "enable remainder optimization" },
128   { X("no-opt-mod"),             &firm_opt.mods,             0, "disable remainder optimization" },
129   { X("opt-alias"),              &firm_opt.alias_analysis,   1, "enable alias analysis" },
130   { X("no-opt-alias"),           &firm_opt.alias_analysis,   0, "disable alias analysis" },
131   { X("alias"),                  &firm_opt.no_alias,         0, "aliasing occurs" },
132   { X("no-alias"),               &firm_opt.no_alias,         1, "no aliasing occurs" },
133   { X("strict-aliasing"),        &firm_opt.strict_alias,     1, "strict alias rules" },
134   { X("no-strict-aliasing"),     &firm_opt.strict_alias,     0, "strict alias rules" },
135   { X("clone-threshold=<value>"),NULL,                       0, "set clone threshold to <value>" },
136
137   /* other firm regarding options */
138   { X("verify-off"),             &firm_opt.verify,           FIRM_VERIFICATION_OFF,    "disable node verification" },
139   { X("verify-on"),              &firm_opt.verify,           FIRM_VERIFICATION_ON,     "enable node verification" },
140   { X("verify-report"),          &firm_opt.verify,           FIRM_VERIFICATION_REPORT, "node verification, report only" },
141   { X("check-all"),              &firm_opt.check_all,        1, "enable checking all Firm phases" },
142   { X("no-check-all"),           &firm_opt.check_all,        0, "disable checking all Firm phases" },
143   { X("verify-edges-on"),        &firm_opt.verify_edges,     1, "enable out edge verification" },
144   { X("verify-edges-off"),       &firm_opt.verify_edges,     0, "disable out edge verification" },
145
146   /* dumping */
147   { X("dump-ir"),                &firm_dump.ir_graph,        1, "dump IR graph" },
148   { X("dump-all-types"),         &firm_dump.all_types,       1, "dump graph of all types" },
149   { X("dump-no-blocks"),         &firm_dump.no_blocks,       1, "dump non-blocked graph" },
150   { X("dump-extbb"),             &firm_dump.extbb,           1, "dump extended basic blocks" },
151   { X("dump-all-phases"),        &firm_dump.all_phases,      1, "dump graphs for all optimization phases" },
152   { X("dump-filter=<string>"),   NULL,                       0, "set dumper filter" },
153
154   /* misc */
155   { X("stat-before-opt"),        &firm_dump.statistic,       STAT_BEFORE_OPT,  "Firm statistic output before optimizations" },
156   { X("stat-after-opt"),         &firm_dump.statistic,       STAT_AFTER_OPT,   "Firm statistic output after optimizations" },
157   { X("stat-after-lower"),       &firm_dump.statistic,       STAT_AFTER_LOWER, "Firm statistic output after lowering" },
158   { X("stat-final-ir"),          &firm_dump.statistic,       STAT_FINAL_IR,    "Firm statistic after final optimization" },
159   { X("stat-final"),             &firm_dump.statistic,       STAT_FINAL,       "Firm statistic after code generation" },
160   { X("stat-pattern"),           &firm_dump.stat_pattern,    1, "Firm statistic calculates most used pattern" },
161   { X("stat-dag"),               &firm_dump.stat_dag,        1, "Firm calculates DAG statistics" },
162 };
163
164 #undef X
165
166 static ir_timer_t *t_vcg_dump;
167 static ir_timer_t *t_verify;
168 static ir_timer_t *t_all_opt;
169 static bool do_irg_opt(ir_graph *irg, const char *name);
170
171 /** dump all the graphs depending on cond */
172
173 static void dump_all(const char *suffix)
174 {
175         if (!firm_dump.ir_graph)
176                 return;
177
178         timer_push(t_vcg_dump);
179         dump_all_ir_graphs(suffix);
180         timer_pop(t_vcg_dump);
181 }
182
183 /* entities of runtime functions */
184 ir_entity_ptr rts_entities[rts_max];
185
186 /**
187  * Map runtime functions.
188  */
189 static void rts_map(void)
190 {
191         static const struct {
192                 ir_entity_ptr *ent; /**< address of the rts entity */
193                 i_mapper_func func; /**< mapper function. */
194         } mapper[] = {
195                 /* integer */
196                 { &rts_entities[rts_abs],     i_mapper_abs },
197                 { &rts_entities[rts_labs],    i_mapper_abs },
198                 { &rts_entities[rts_llabs],   i_mapper_abs },
199                 { &rts_entities[rts_imaxabs], i_mapper_abs },
200
201                 /* double -> double */
202                 { &rts_entities[rts_fabs],    i_mapper_abs },
203                 { &rts_entities[rts_sqrt],    i_mapper_sqrt },
204                 { &rts_entities[rts_cbrt],    i_mapper_cbrt },
205                 { &rts_entities[rts_pow],     i_mapper_pow },
206                 { &rts_entities[rts_exp],     i_mapper_exp },
207                 { &rts_entities[rts_exp2],    i_mapper_exp },
208                 { &rts_entities[rts_exp10],   i_mapper_exp },
209                 { &rts_entities[rts_log],     i_mapper_log },
210                 { &rts_entities[rts_log2],    i_mapper_log2 },
211                 { &rts_entities[rts_log10],   i_mapper_log10 },
212                 { &rts_entities[rts_sin],     i_mapper_sin },
213                 { &rts_entities[rts_cos],     i_mapper_cos },
214                 { &rts_entities[rts_tan],     i_mapper_tan },
215                 { &rts_entities[rts_asin],    i_mapper_asin },
216                 { &rts_entities[rts_acos],    i_mapper_acos },
217                 { &rts_entities[rts_atan],    i_mapper_atan },
218                 { &rts_entities[rts_sinh],    i_mapper_sinh },
219                 { &rts_entities[rts_cosh],    i_mapper_cosh },
220                 { &rts_entities[rts_tanh],    i_mapper_tanh },
221
222                 /* float -> float */
223                 { &rts_entities[rts_fabsf],   i_mapper_abs },
224                 { &rts_entities[rts_sqrtf],   i_mapper_sqrt },
225                 { &rts_entities[rts_cbrtf],   i_mapper_cbrt },
226                 { &rts_entities[rts_powf],    i_mapper_pow },
227                 { &rts_entities[rts_expf],    i_mapper_exp },
228                 { &rts_entities[rts_exp2f],   i_mapper_exp },
229                 { &rts_entities[rts_exp10f],  i_mapper_exp },
230                 { &rts_entities[rts_logf],    i_mapper_log },
231                 { &rts_entities[rts_log2f],   i_mapper_log2 },
232                 { &rts_entities[rts_log10f],  i_mapper_log10 },
233                 { &rts_entities[rts_sinf],    i_mapper_sin },
234                 { &rts_entities[rts_cosf],    i_mapper_cos },
235                 { &rts_entities[rts_tanf],    i_mapper_tan },
236                 { &rts_entities[rts_asinf],   i_mapper_asin },
237                 { &rts_entities[rts_acosf],   i_mapper_acos },
238                 { &rts_entities[rts_atanf],   i_mapper_atan },
239                 { &rts_entities[rts_sinhf],   i_mapper_sinh },
240                 { &rts_entities[rts_coshf],   i_mapper_cosh },
241                 { &rts_entities[rts_tanhf],   i_mapper_tanh },
242
243                 /* long double -> long double */
244                 { &rts_entities[rts_fabsl],   i_mapper_abs },
245                 { &rts_entities[rts_sqrtl],   i_mapper_sqrt },
246                 { &rts_entities[rts_cbrtl],   i_mapper_cbrt },
247                 { &rts_entities[rts_powl],    i_mapper_pow },
248                 { &rts_entities[rts_expl],    i_mapper_exp },
249                 { &rts_entities[rts_exp2l],   i_mapper_exp },
250                 { &rts_entities[rts_exp10l],  i_mapper_exp },
251                 { &rts_entities[rts_logl],    i_mapper_log },
252                 { &rts_entities[rts_log2l],   i_mapper_log2 },
253                 { &rts_entities[rts_log10l],  i_mapper_log10 },
254                 { &rts_entities[rts_sinl],    i_mapper_sin },
255                 { &rts_entities[rts_cosl],    i_mapper_cos },
256                 { &rts_entities[rts_tanl],    i_mapper_tan },
257                 { &rts_entities[rts_asinl],   i_mapper_asin },
258                 { &rts_entities[rts_acosl],   i_mapper_acos },
259                 { &rts_entities[rts_atanl],   i_mapper_atan },
260                 { &rts_entities[rts_sinhl],   i_mapper_sinh },
261                 { &rts_entities[rts_coshl],   i_mapper_cosh },
262                 { &rts_entities[rts_tanhl],   i_mapper_tanh },
263
264                 /* string */
265                 { &rts_entities[rts_strcmp],  i_mapper_strcmp },
266                 { &rts_entities[rts_strncmp], i_mapper_strncmp },
267                 { &rts_entities[rts_strcpy],  i_mapper_strcpy },
268                 { &rts_entities[rts_strlen],  i_mapper_strlen },
269                 { &rts_entities[rts_memcpy],  i_mapper_memcpy },
270                 { &rts_entities[rts_mempcpy], i_mapper_mempcpy },
271                 { &rts_entities[rts_memmove], i_mapper_memmove },
272                 { &rts_entities[rts_memset],  i_mapper_memset },
273                 { &rts_entities[rts_memcmp],  i_mapper_memcmp }
274         };
275         i_record rec[sizeof(mapper)/sizeof(mapper[0])];
276         unsigned i, n_map;
277
278         for (i = n_map = 0; i < sizeof(mapper)/sizeof(mapper[0]); ++i) {
279                 if (*mapper[i].ent != NULL) {
280                         rec[n_map].i_call.kind     = INTRINSIC_CALL;
281                         rec[n_map].i_call.i_ent    = *mapper[i].ent;
282                         rec[n_map].i_call.i_mapper = mapper[i].func;
283                         rec[n_map].i_call.ctx      = NULL;
284                         rec[n_map].i_call.link     = NULL;
285                         ++n_map;
286                 }
287         }
288
289         if (n_map > 0)
290                 lower_intrinsics(rec, n_map, /* part_block_used=*/0);
291 }
292
293 static int *irg_dump_no;
294
295 static void do_stred(ir_graph *irg)
296 {
297         opt_osr(irg, osr_flag_default | osr_flag_keep_reg_pressure | osr_flag_ignore_x86_shift);
298 }
299
300 static void after_inline_opt(ir_graph *irg)
301 {
302         do_irg_opt(irg, "scalar-replace");
303         do_irg_opt(irg, "local");
304         do_irg_opt(irg, "control-flow");
305         do_irg_opt(irg, "combo");
306 }
307
308 static void do_inline(void)
309 {
310         inline_functions(firm_opt.inline_maxsize, firm_opt.inline_threshold,
311                          after_inline_opt);
312 }
313
314 static void do_cloning(void)
315 {
316         proc_cloning((float) firm_opt.clone_threshold);
317 }
318
319 static void do_lower_mux(ir_graph *irg)
320 {
321         lower_mux(irg, NULL);
322 }
323
324 static void do_gcse(ir_graph *irg)
325 {
326         set_opt_global_cse(1);
327         optimize_graph_df(irg);
328         set_opt_global_cse(0);
329 }
330
331 static void lower_blockcopy(ir_graph *irg)
332 {
333         lower_CopyB(irg, 128, 4);
334 }
335
336 typedef enum opt_target {
337         OPT_TARGET_IRG, /**< optimization function works on a single graph */
338         OPT_TARGET_IRP  /**< optimization function works on the complete program */
339 } opt_target_t;
340
341 typedef enum opt_flags {
342         OPT_FLAG_NONE         = 0,
343         OPT_FLAG_ENABLED      = 1 << 0, /**< enable the optimization */
344         OPT_FLAG_NO_DUMP      = 1 << 1, /**< don't dump after transformation */
345         OPT_FLAG_NO_VERIFY    = 1 << 2, /**< don't verify after transformation */
346         OPT_FLAG_HIDE_OPTIONS = 1 << 3, /**< do not automatically process
347                                              -foptions for this transformation */
348         OPT_FLAG_ESSENTIAL    = 1 << 4, /**< output won't work without this pass
349                                              so we need it even with -O0 */
350 } opt_flags_t;
351
352 typedef void (*transform_irg_func)(ir_graph *irg);
353 typedef void (*transform_irp_func)(void);
354
355 typedef struct {
356         opt_target_t  target;
357         const char   *name;
358         union {
359                 transform_irg_func transform_irg;
360                 transform_irp_func transform_irp;
361         } u;
362         const char   *description;
363         opt_flags_t   flags;
364         ir_timer_t   *timer;
365 } opt_config_t;
366
367 static opt_config_t opts[] = {
368 #define IRG(a, b, c, d) { OPT_TARGET_IRG, a, .u.transform_irg = (transform_irg_func)b, c, d }
369 #define IRP(a, b, c, d) { OPT_TARGET_IRP, a, .u.transform_irp = b,                     c, d }
370         IRG("bool",              opt_bool,                 "bool simplification",                                   OPT_FLAG_NONE),
371         IRG("combo",             combo,                    "combined CCE, UCE and GVN",                             OPT_FLAG_NONE),
372         IRG("confirm",           construct_confirms,       "confirm optimization",                                  OPT_FLAG_HIDE_OPTIONS),
373         IRG("control-flow",      optimize_cf,              "optimization of control-flow",                          OPT_FLAG_HIDE_OPTIONS),
374         IRG("dead",              dead_node_elimination,    "dead node elimination",                                 OPT_FLAG_HIDE_OPTIONS | OPT_FLAG_NO_DUMP | OPT_FLAG_NO_VERIFY),
375         IRG("deconv",            conv_opt,                 "conv node elimination",                                 OPT_FLAG_NONE),
376         IRG("fp-vrp",            fixpoint_vrp,             "fixpoint value range propagation",                      OPT_FLAG_NONE),
377         IRG("frame",             opt_frame_irg,            "remove unused frame entities",                          OPT_FLAG_NONE),
378         IRG("gvn-pre",           do_gvn_pre,               "global value numbering partial redundancy elimination", OPT_FLAG_NONE),
379         IRG("if-conversion",     opt_if_conv,              "if-conversion",                                         OPT_FLAG_NONE),
380         IRG("invert-loops",      do_loop_inversion,        "loop inversion",                                        OPT_FLAG_NONE),
381         IRG("ivopts",            do_stred,                 "induction variable strength reduction",                 OPT_FLAG_NONE),
382         IRG("local",             optimize_graph_df,        "local graph optimizations",                             OPT_FLAG_HIDE_OPTIONS),
383         IRG("lower",             lower_highlevel_graph,    "lowering",                                              OPT_FLAG_HIDE_OPTIONS | OPT_FLAG_ESSENTIAL),
384         IRG("lower-mux",         do_lower_mux,             "mux lowering",                                          OPT_FLAG_NONE),
385         IRG("opt-load-store",    optimize_load_store,      "load store optimization",                               OPT_FLAG_NONE),
386         IRG("opt-tail-rec",      opt_tail_rec_irg,         "tail-recursion eliminiation",                           OPT_FLAG_NONE),
387         IRG("parallelize-mem",   opt_parallelize_mem,      "parallelize memory",                                    OPT_FLAG_NONE),
388         IRG("gcse",              do_gcse,                  "global common subexpression eliminiation",              OPT_FLAG_NONE),
389         IRG("place",             place_code,               "code placement",                                        OPT_FLAG_NONE),
390         IRG("reassociation",     optimize_reassociation,   "reassociation",                                         OPT_FLAG_NONE),
391         IRG("remove-confirms",   remove_confirms,          "confirm removal",                                       OPT_FLAG_HIDE_OPTIONS | OPT_FLAG_NO_DUMP | OPT_FLAG_NO_VERIFY),
392         IRG("remove-phi-cycles", remove_phi_cycles,        "removal of phi cycles",                                 OPT_FLAG_HIDE_OPTIONS),
393         IRG("scalar-replace",    scalar_replacement_opt,   "scalar replacement",                                    OPT_FLAG_NONE),
394         IRG("shape-blocks",      shape_blocks,             "block shaping",                                         OPT_FLAG_NONE),
395         IRG("thread-jumps",      opt_jumpthreading,        "path-sensitive jumpthreading",                          OPT_FLAG_NONE),
396         IRG("unroll-loops",      do_loop_unrolling,        "loop unrolling",                                        OPT_FLAG_NONE),
397         IRG("vrp",               set_vrp_data,             "value range propagation",                               OPT_FLAG_NONE),
398         IRP("inline",            do_inline,                "inlining",                                              OPT_FLAG_NONE),
399         IRP("lower-const",       lower_const_code,         "lowering of constant code",                             OPT_FLAG_HIDE_OPTIONS | OPT_FLAG_NO_DUMP | OPT_FLAG_NO_VERIFY | OPT_FLAG_ESSENTIAL),
400         IRG("lower-blockcopy",   lower_blockcopy,          "replace small block copies with load/store sequences",  OPT_FLAG_NO_DUMP),
401         IRP("target-lowering",   be_lower_for_target,      "lowering necessary for target architecture",            OPT_FLAG_HIDE_OPTIONS | OPT_FLAG_ESSENTIAL),
402         IRP("opt-func-call",     optimize_funccalls,       "function call optimization",                            OPT_FLAG_NONE),
403         IRP("opt-proc-clone",    do_cloning,               "procedure cloning",                                     OPT_FLAG_NONE),
404         IRP("remove-unused",     garbage_collect_entities, "removal of unused functions/variables",                 OPT_FLAG_NO_DUMP | OPT_FLAG_NO_VERIFY),
405         IRP("rts",               rts_map,                  "optimization of known library functions",               OPT_FLAG_NONE),
406         IRP("opt-cc",            mark_private_methods,     "calling conventions optimization",                      OPT_FLAG_NONE),
407 #undef IRP
408 #undef IRG
409 };
410 static const int n_opts = sizeof(opts) / sizeof(opts[0]);
411
412 static opt_config_t *get_opt(const char *name)
413 {
414         int i;
415         for (i = 0; i < n_opts; ++i) {
416                 opt_config_t *config = &opts[i];
417                 if (strcmp(config->name, name) == 0)
418                         return config;
419         }
420
421         return NULL;
422 }
423
424 static void set_opt_enabled(const char *name, bool enabled)
425 {
426         opt_config_t *config = get_opt(name);
427         config->flags = (config->flags & ~OPT_FLAG_ENABLED)
428                 | (enabled ? OPT_FLAG_ENABLED : 0);
429 }
430
431 static bool get_opt_enabled(const char *name)
432 {
433         opt_config_t *config = get_opt(name);
434         return (config->flags & OPT_FLAG_ENABLED) != 0;
435 }
436
437 /**
438  * perform an optimization on a single graph
439  *
440  * @return  true if something changed, false otherwise
441  */
442 static bool do_irg_opt(ir_graph *irg, const char *name)
443 {
444         opt_config_t *const config = get_opt(name);
445         assert(config != NULL);
446         assert(config->target == OPT_TARGET_IRG);
447         if (! (config->flags & OPT_FLAG_ENABLED))
448                 return false;
449
450         ir_graph *const old_irg = current_ir_graph;
451         current_ir_graph = irg;
452
453         timer_push(config->timer);
454         config->u.transform_irg(irg);
455         timer_pop(config->timer);
456
457         if (firm_dump.all_phases && firm_dump.ir_graph) {
458                 dump_ir_graph(irg, name);
459         }
460
461         if (firm_opt.check_all) {
462                 timer_push(t_verify);
463                 irg_verify(irg, VERIFY_ENFORCE_SSA);
464                 timer_pop(t_verify);
465         }
466
467         current_ir_graph = old_irg;
468         return true;
469 }
470
471 static void do_irp_opt(const char *name)
472 {
473         opt_config_t *const config = get_opt(name);
474         assert(config->target == OPT_TARGET_IRP);
475         if (! (config->flags & OPT_FLAG_ENABLED))
476                 return;
477
478         timer_push(config->timer);
479         config->u.transform_irp();
480         timer_pop(config->timer);
481
482         if (firm_dump.ir_graph && firm_dump.all_phases) {
483                 int i;
484                 for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
485                         ir_graph *irg = get_irp_irg(i);
486                         dump_ir_graph(irg, name);
487                 }
488         }
489
490         if (firm_opt.check_all) {
491                 int i;
492                 timer_push(t_verify);
493                 for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
494                         irg_verify(get_irp_irg(i), VERIFY_ENFORCE_SSA);
495                 }
496                 timer_pop(t_verify);
497         }
498 }
499
500 /**
501  * Enable transformations which should be always safe (and cheap) to perform
502  */
503 static void enable_safe_defaults(void)
504 {
505         set_opt_enabled("remove-unused", true);
506         set_opt_enabled("opt-tail-rec", true);
507         set_opt_enabled("opt-func-call", true);
508         set_opt_enabled("reassociation", true);
509         set_opt_enabled("control-flow", true);
510         set_opt_enabled("local", true);
511         set_opt_enabled("lower-const", true);
512         set_opt_enabled("scalar-replace", true);
513         set_opt_enabled("place", true);
514         set_opt_enabled("gcse", true);
515         set_opt_enabled("confirm", true);
516         set_opt_enabled("opt-load-store", true);
517         set_opt_enabled("lower", true);
518         set_opt_enabled("lower-blockcopy", true);
519         set_opt_enabled("deconv", true);
520         set_opt_enabled("remove-confirms", true);
521         set_opt_enabled("ivopts", true);
522         set_opt_enabled("dead", true);
523         set_opt_enabled("remove-phi-cycles", true);
524         set_opt_enabled("frame", true);
525         set_opt_enabled("combo", true);
526         set_opt_enabled("invert-loops", true);
527         set_opt_enabled("target-lowering", true);
528         set_opt_enabled("rts", true);
529         set_opt_enabled("parallelize-mem", true);
530         set_opt_enabled("opt-cc", true);
531 }
532
533 /**
534  * run all the Firm optimizations
535  *
536  * @param input_filename     the name of the (main) source file
537  */
538 static void do_firm_optimizations(const char *input_filename)
539 {
540         size_t   i;
541         unsigned aa_opt;
542
543         set_opt_alias_analysis(firm_opt.alias_analysis);
544
545         aa_opt = aa_opt_no_opt;
546         if (firm_opt.strict_alias)
547                 aa_opt |= aa_opt_type_based | aa_opt_byte_type_may_alias;
548         if (firm_opt.no_alias)
549                 aa_opt = aa_opt_no_alias;
550
551         set_irp_memory_disambiguator_options(aa_opt);
552
553         /* parameter passing code should set them directly sometime... */
554         set_opt_enabled("confirm", firm_opt.confirm);
555         set_opt_enabled("remove-confirms", firm_opt.confirm);
556
557         /* osr supersedes remove_phi_cycles */
558         if (get_opt_enabled("ivopts"))
559                 set_opt_enabled("remove-phi-cycles", false);
560
561         timer_start(t_all_opt);
562
563         do_irp_opt("rts");
564
565         /* first step: kill dead code */
566         for (i = 0; i < get_irp_n_irgs(); i++) {
567                 ir_graph *irg = get_irp_irg(i);
568                 do_irg_opt(irg, "combo");
569                 do_irg_opt(irg, "local");
570                 do_irg_opt(irg, "control-flow");
571         }
572
573         do_irp_opt("remove-unused");
574         for (i = 0; i < get_irp_n_irgs(); ++i) {
575                 ir_graph *irg = get_irp_irg(i);
576                 do_irg_opt(irg, "opt-tail-rec");
577         }
578         do_irp_opt("opt-func-call");
579         do_irp_opt("lower-const");
580
581         for (i = 0; i < get_irp_n_irgs(); i++) {
582                 ir_graph *irg = get_irp_irg(i);
583
584                 do_irg_opt(irg, "scalar-replace");
585                 do_irg_opt(irg, "invert-loops");
586                 do_irg_opt(irg, "unroll-loops");
587                 do_irg_opt(irg, "local");
588                 do_irg_opt(irg, "reassociation");
589                 do_irg_opt(irg, "local");
590                 do_irg_opt(irg, "gcse");
591                 do_irg_opt(irg, "place");
592
593                 if (firm_opt.confirm) {
594                         /* Confirm construction currently can only handle blocks with only
595                            one control flow predecessor. Calling optimize_cf here removes
596                            Bad predecessors and help the optimization of switch constructs.
597                          */
598                         do_irg_opt(irg, "control-flow");
599                         do_irg_opt(irg, "confirm");
600                         do_irg_opt(irg, "vrp");
601                         do_irg_opt(irg, "local");
602                 }
603
604                 do_irg_opt(irg, "control-flow");
605                 do_irg_opt(irg, "opt-load-store");
606                 do_irg_opt(irg, "fp-vrp");
607                 do_irg_opt(irg, "lower");
608                 do_irg_opt(irg, "deconv");
609                 do_irg_opt(irg, "thread-jumps");
610                 do_irg_opt(irg, "remove-confirms");
611                 do_irg_opt(irg, "gvn-pre");
612                 do_irg_opt(irg, "gcse");
613                 do_irg_opt(irg, "place");
614                 do_irg_opt(irg, "control-flow");
615
616                 if (do_irg_opt(irg, "if-conversion")) {
617                         do_irg_opt(irg, "local");
618                         do_irg_opt(irg, "control-flow");
619                 }
620                 /* this doesn't make too much sense but tests the mux destruction... */
621                 do_irg_opt(irg, "lower-mux");
622
623                 do_irg_opt(irg, "bool");
624                 do_irg_opt(irg, "shape-blocks");
625                 do_irg_opt(irg, "ivopts");
626                 do_irg_opt(irg, "local");
627                 do_irg_opt(irg, "dead");
628         }
629
630         do_irp_opt("inline");
631         do_irp_opt("opt-proc-clone");
632
633         for (i = 0; i < get_irp_n_irgs(); i++) {
634                 ir_graph *irg = get_irp_irg(i);
635                 do_irg_opt(irg, "local");
636                 do_irg_opt(irg, "control-flow");
637                 do_irg_opt(irg, "thread-jumps");
638                 do_irg_opt(irg, "local");
639                 do_irg_opt(irg, "control-flow");
640
641                 if( do_irg_opt(irg, "vrp") ) { // if vrp is enabled
642                         do_irg_opt(irg, "local");
643                         do_irg_opt(irg, "vrp");
644                         do_irg_opt(irg, "local");
645                         do_irg_opt(irg, "vrp");
646                 }
647         }
648
649         if (firm_dump.ir_graph) {
650                 /* recompute backedges for nicer dumps */
651                 for (i = 0; i < get_irp_n_irgs(); i++)
652                         construct_cf_backedges(get_irp_irg(i));
653         }
654
655         dump_all("opt");
656
657         if (firm_dump.statistic & STAT_AFTER_OPT)
658                 stat_dump_snapshot(input_filename, "opt");
659
660         timer_stop(t_all_opt);
661 }
662
663 /**
664  * do Firm lowering
665  *
666  * @param input_filename  the name of the (main) source file
667  */
668 static void do_firm_lowering(const char *input_filename)
669 {
670         int i;
671
672         /* enable architecture dependent optimizations */
673         arch_dep_set_opts((arch_dep_opts_t)
674                         ((firm_opt.muls ? arch_dep_mul_to_shift : arch_dep_none) |
675                          (firm_opt.divs ? arch_dep_div_by_const : arch_dep_none) |
676                          (firm_opt.mods ? arch_dep_mod_by_const : arch_dep_none) ));
677         for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
678                 ir_graph *irg = get_irp_irg(i);
679                 do_irg_opt(irg, "reassociation");
680                 do_irg_opt(irg, "local");
681         }
682
683         do_irp_opt("target-lowering");
684
685         if (firm_dump.statistic & STAT_AFTER_LOWER)
686                 stat_dump_snapshot(input_filename, "low");
687
688         timer_start(t_all_opt);
689
690         for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
691                 ir_graph *irg = get_irp_irg(i);
692
693                 do_irg_opt(irg, "lower-blockcopy");
694                 do_irg_opt(irg, "local");
695                 do_irg_opt(irg, "deconv");
696                 do_irg_opt(irg, "control-flow");
697                 do_irg_opt(irg, "opt-load-store");
698                 do_irg_opt(irg, "gcse");
699                 do_irg_opt(irg, "place");
700                 do_irg_opt(irg, "control-flow");
701
702                 if (do_irg_opt(irg, "vrp")) {
703                         do_irg_opt(irg, "local");
704                         do_irg_opt(irg, "control-flow");
705                         do_irg_opt(irg, "vrp");
706                         do_irg_opt(irg, "local");
707                         do_irg_opt(irg, "control-flow");
708                 }
709
710                 if (do_irg_opt(irg, "if-conversion")) {
711                         do_irg_opt(irg, "local");
712                         do_irg_opt(irg, "control-flow");
713                 }
714
715                 set_irg_state(irg, IR_GRAPH_STATE_NORMALISATION2);
716                 do_irg_opt(irg, "local");
717
718                 do_irg_opt(irg, "parallelize-mem");
719                 do_irg_opt(irg, "frame");
720         }
721         do_irp_opt("remove-unused");
722         do_irp_opt("opt-cc");
723         timer_stop(t_all_opt);
724         dump_all("low-opt");
725
726         if (firm_dump.statistic & STAT_FINAL) {
727                 stat_dump_snapshot(input_filename, "final");
728         }
729 }
730
731 /**
732  * Initialize for the Firm-generating back end.
733  */
734 void gen_firm_init(void)
735 {
736         unsigned pattern = 0;
737         int      i;
738
739         for (i = 0; i < n_opts; ++i) {
740                 opts[i].timer = ir_timer_new();
741                 timer_register(opts[i].timer, opts[i].description);
742         }
743         t_verify = ir_timer_new();
744         timer_register(t_verify, "Firm: verify pass");
745         t_vcg_dump = ir_timer_new();
746         timer_register(t_vcg_dump, "Firm: vcg dumping");
747         t_all_opt = ir_timer_new();
748         timer_register(t_all_opt, "Firm: all optimizations");
749
750         if (firm_dump.stat_pattern)
751                 pattern |= FIRMSTAT_PATTERN_ENABLED;
752
753         if (firm_dump.stat_dag)
754                 pattern |= FIRMSTAT_COUNT_DAG;
755
756         ir_init(NULL);
757         firm_init_stat(firm_dump.statistic == STAT_NONE ?
758                         0 : FIRMSTAT_ENABLED | FIRMSTAT_COUNT_STRONG_OP
759                         | FIRMSTAT_COUNT_CONSTS | pattern);
760
761         edges_init_dbg(firm_opt.verify_edges);
762
763         /* Sel node cannot produce NULL pointers */
764         set_opt_sel_based_null_check_elim(1);
765
766         /* dynamic dispatch works currently only if whole world scenarios */
767         set_opt_dyn_meth_dispatch(0);
768
769         /* do not run architecture dependent optimizations in building phase */
770         arch_dep_set_opts(arch_dep_none);
771
772         do_node_verification((firm_verification_t) firm_opt.verify);
773         if (firm_dump.extbb)
774                 ir_add_dump_flags(ir_dump_flag_group_extbb);
775         if (firm_dump.no_blocks)
776                 ir_remove_dump_flags(ir_dump_flag_blocks_as_subgraphs);
777
778         set_optimize(1);
779         set_opt_constant_folding(firm_opt.const_folding);
780         set_opt_algebraic_simplification(firm_opt.const_folding);
781         set_opt_cse(firm_opt.cse);
782         set_opt_global_cse(0);
783         set_opt_unreachable_code(1);
784 }
785
786 /**
787  * Called, after the Firm generation is completed,
788  * do all optimizations and backend call here.
789  *
790  * @param out                a file handle for the output, may be NULL
791  * @param input_filename     the name of the (main) source file
792  * @param c_mode             non-zero if "C" was compiled
793  */
794 void gen_firm_finish(FILE *out, const char *input_filename)
795 {
796         int i;
797
798         /* the general for dumping option must be set, or the others will not work*/
799         firm_dump.ir_graph
800                 = (bool) (firm_dump.ir_graph | firm_dump.all_phases | firm_dump.extbb);
801
802         ir_add_dump_flags(ir_dump_flag_keepalive_edges
803                         | ir_dump_flag_consts_local | ir_dump_flag_dominance);
804         ir_remove_dump_flags(ir_dump_flag_loops | ir_dump_flag_ld_names);
805
806         /* FIXME: cloning might ADD new graphs. */
807         irg_dump_no = calloc(get_irp_last_idx(), sizeof(*irg_dump_no));
808
809         if (firm_dump.all_types) {
810                 dump_ir_prog_ext(dump_typegraph, "types.vcg");
811         }
812
813         /* finalize all graphs */
814         for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
815                 ir_graph *irg = get_irp_irg(i);
816                 irg_finalize_cons(irg);
817         }
818         dump_all("");
819
820         timer_push(t_verify);
821         tr_verify();
822         timer_pop(t_verify);
823
824         /* all graphs are finalized, set the irp phase to high */
825         set_irp_phase_state(phase_high);
826
827         /* BEWARE: kill unreachable code before doing compound lowering */
828         for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
829                 ir_graph *irg = get_irp_irg(i);
830                 do_irg_opt(irg, "control-flow");
831                 do_irg_opt(irg, "lower-blockcopy");
832         }
833
834         if (firm_dump.statistic & STAT_BEFORE_OPT) {
835                 stat_dump_snapshot(input_filename, "noopt");
836         }
837
838         do_firm_optimizations(input_filename);
839         do_firm_lowering(input_filename);
840
841         /* set the phase to low */
842         for (i = get_irp_n_irgs() - 1; i >= 0; --i)
843                 set_irg_phase_state(get_irp_irg(i), phase_low);
844
845         if (firm_dump.statistic & STAT_FINAL_IR)
846                 stat_dump_snapshot(input_filename, "final-ir");
847
848         /* run the code generator */
849         ir_timer_t *timer = ir_timer_new();
850         timer_register(timer, "Firm: backend");
851         timer_start(timer);
852         be_main(out, input_filename);
853         timer_stop(timer);
854
855         if (firm_dump.statistic & STAT_FINAL)
856                 stat_dump_snapshot(input_filename, "final");
857 }
858
859 static void disable_all_opts(void)
860 {
861         firm_opt.cse             = false;
862         firm_opt.confirm         = false;
863         firm_opt.muls            = false;
864         firm_opt.divs            = false;
865         firm_opt.mods            = false;
866         firm_opt.alias_analysis  = false;
867         firm_opt.strict_alias    = false;
868         firm_opt.no_alias        = false;
869
870         for (int i = 0; i < n_opts; ++i) {
871                 opt_config_t *config = &opts[i];
872                 if (config->flags & OPT_FLAG_ESSENTIAL) {
873                         config->flags |= OPT_FLAG_ENABLED;
874                 } else {
875                         config->flags &= ~OPT_FLAG_ENABLED;
876                 }
877         }
878 }
879
880 static bool firm_opt_option(const char *opt)
881 {
882         bool enable = true;
883         if (strncmp(opt, "no-", 3) == 0) {
884                 enable = false;
885                 opt = opt + 3;
886         }
887
888         opt_config_t *config = get_opt(opt);
889         if (config == NULL || (config->flags & OPT_FLAG_HIDE_OPTIONS))
890                 return false;
891
892         config->flags &= ~OPT_FLAG_ENABLED;
893         config->flags |= enable ? OPT_FLAG_ENABLED : 0;
894         return true;
895 }
896
897 void firm_option_help(print_option_help_func print_option_help)
898 {
899         print_option_help(firm_options[0].option, firm_options[0].description);
900
901         for (int i = 0; i < n_opts; ++i) {
902                 char buf[1024];
903                 char buf2[1024];
904
905                 const opt_config_t *config = &opts[i];
906                 if (config->flags & OPT_FLAG_HIDE_OPTIONS)
907                         continue;
908
909                 snprintf(buf, sizeof(buf), "-f%s", config->name);
910                 snprintf(buf2, sizeof(buf2), "enable %s", config->description);
911                 print_option_help(buf, buf2);
912                 snprintf(buf, sizeof(buf), "-fno-%s", config->name);
913                 snprintf(buf2, sizeof(buf2), "disable %s", config->description);
914                 print_option_help(buf, buf2);
915         }
916
917         size_t const n_options = sizeof(firm_options)/sizeof(firm_options[0]);
918         for (size_t k = 0; k < n_options; ++k) {
919                 char buf[1024];
920                 char buf2[1024];
921                 snprintf(buf, sizeof(buf), "-f%s", firm_options[k].option);
922                 snprintf(buf2, sizeof(buf2), "%s", firm_options[k].description);
923                 print_option_help(buf, buf2);
924         }
925 }
926
927 int firm_option(const char *const opt)
928 {
929         char const* val;
930         if ((val = strstart(opt, "dump-filter="))) {
931                 ir_set_dump_filter(val);
932                 return 1;
933         } else if ((val = strstart(opt, "clone-threshold="))) {
934                 sscanf(val, "%d", &firm_opt.clone_threshold);
935                 return 1;
936         } else if ((val = strstart(opt, "inline-max-size="))) {
937                 sscanf(val, "%u", &firm_opt.inline_maxsize);
938                 return 1;
939         } else if ((val = strstart(opt, "inline-threshold="))) {
940                 sscanf(val, "%u", &firm_opt.inline_threshold);
941                 return 1;
942         } else if (streq(opt, "no-opt")) {
943                 disable_all_opts();
944                 return 1;
945         }
946
947         size_t const len = strlen(opt);
948         size_t const n_options = sizeof(firm_options)/sizeof(firm_options[0]);
949         for (size_t i = n_options; i != 0;) {
950                 struct params const* const o = &firm_options[--i];
951                 if (len == o->opt_len && strncmp(opt, o->option, len) == 0) {
952                         /* statistic options do accumulate */
953                         if (o->flag == &firm_dump.statistic)
954                                 *o->flag = (bool) (*o->flag | o->set);
955                         else
956                                 *o->flag = o->set;
957
958                         return 1;
959                 }
960         }
961
962         /* maybe this enables/disables optimizations */
963         if (firm_opt_option(opt))
964                 return 1;
965
966         return 0;
967 }
968
969 static void set_be_option(const char *arg)
970 {
971         int res = be_parse_arg(arg);
972         (void) res;
973         assert(res);
974 }
975
976 static void set_option(const char *arg)
977 {
978         int res = firm_option(arg);
979         (void) res;
980         assert(res);
981 }
982
983 void choose_optimization_pack(int level)
984 {
985         /* apply optimization level */
986         switch(level) {
987         case 0:
988                 set_option("no-opt");
989                 break;
990         case 1:
991                 set_option("no-inline");
992                 break;
993         default:
994         case 4:
995                 /* use_builtins = true; */
996                 /* fallthrough */
997         case 3:
998                 set_option("thread-jumps");
999                 set_option("if-conversion");
1000                 /* fallthrough */
1001         case 2:
1002                 set_option("strict-aliasing");
1003                 set_option("inline");
1004                 set_option("fp-vrp");
1005                 set_option("deconv");
1006                 set_be_option("omitfp");
1007                 break;
1008         }
1009 }
1010
1011 /**
1012  * Do very early initializations
1013  */
1014 void firm_early_init(void)
1015 {
1016         /* arg: need this here for command line options */
1017         be_opt_register();
1018
1019         enable_safe_defaults();
1020 }