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