e7a94f280f76a692f83a6c585df8dae3a106fb58
[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 #include "adt/util.h"
24
25 /* optimization settings */
26 struct a_firm_opt {
27         bool     const_folding;   /**< enable constant folding */
28         bool     cse;             /**< enable common-subexpression elimination */
29         bool     confirm;         /**< enable Confirm optimization */
30         bool     muls;            /**< enable architecture dependent mul optimization */
31         bool     divs;            /**< enable architecture dependent div optimization */
32         bool     mods;            /**< enable architecture dependent mod optimization */
33         bool     alias_analysis;  /**< enable Alias Analysis */
34         bool     strict_alias;    /**< enable strict Alias Analysis (using type based AA) */
35         bool     no_alias;        /**< no aliasing possible. */
36         bool     verify;          /**< Firm verifier setting */
37         bool     check_all;       /**< enable checking all Firm phases */
38         int      clone_threshold; /**< The threshold value for procedure cloning. */
39         unsigned inline_maxsize;  /**< Maximum function size for inlining. */
40         unsigned inline_threshold;/**< Inlining benefice threshold. */
41         bool     verify_edges;    /**< verify edges */
42 };
43
44 /** statistic options */
45 typedef enum a_firmstat_selection_tag {
46         STAT_NONE        = 0x00000000,
47         STAT_BEFORE_OPT  = 0x00000001,
48         STAT_AFTER_OPT   = 0x00000002,
49         STAT_AFTER_LOWER = 0x00000004,
50         STAT_FINAL_IR    = 0x00000008,
51         STAT_FINAL       = 0x00000010,
52 } a_firmstat_selection;
53
54 /* dumping options */
55 struct a_firm_dump {
56         bool debug_print;   /**< enable debug print */
57         bool all_types;     /**< dump the All_types graph */
58         bool no_blocks;     /**< dump non-blocked graph */
59         bool extbb;         /**< dumps extended basic blocks */
60         bool ir_graph;      /**< dump all graphs */
61         bool all_phases;    /**< dump the IR graph after all phases */
62         bool statistic;     /**< Firm statistic setting */
63         bool stat_pattern;  /**< enable Firm statistic pattern */
64         bool stat_dag;      /**< enable Firm DAG statistic */
65 };
66
67 struct a_firm_be_opt {
68         bool selection;
69         bool node_stat;
70 };
71
72 /* optimization settings */
73 static struct a_firm_opt firm_opt = {
74         .const_folding    =  true,
75         .cse              =  true,
76         .confirm          =  true,
77         .muls             =  true,
78         .divs             =  true,
79         .mods             =  true,
80         .alias_analysis   =  true,
81         .strict_alias     =  false,
82         .no_alias         =  false,
83         .verify           =  FIRM_VERIFICATION_ON,
84         .check_all        =  true,
85         .clone_threshold  =  DEFAULT_CLONE_THRESHOLD,
86         .inline_maxsize   =  750,
87         .inline_threshold =  0,
88         .verify_edges     =  false,
89 };
90
91 /* dumping options */
92 static struct a_firm_dump firm_dump = {
93         .debug_print  = false,
94         .all_types    = false,
95         .no_blocks    = false,
96         .extbb        = false,
97         .ir_graph     = false,
98         .all_phases   = false,
99         .statistic    = STAT_NONE,
100         .stat_pattern = 0,
101         .stat_dag     = 0,
102 };
103
104 #define X(a)  a, sizeof(a)-1
105
106 /** Parameter description structure */
107 static const struct params {
108   const char *option;      /**< name of the option */
109   size_t     opt_len;      /**< length of the option string */
110   bool       *flag;        /**< address of variable to set/reset */
111   bool       set;          /**< iff true, variable will be set, else reset */
112   const char *description; /**< description of this option */
113 } firm_options[] = {
114   /* firm optimization options */
115   { X("no-opt"),                 NULL,                       0, "disable all FIRM optimizations" },
116   { X("cse"),                    &firm_opt.cse,              1, "enable common subexpression elimination" },
117   { X("no-cse"),                 &firm_opt.cse,              0, "disable common subexpression elimination" },
118   { X("const-fold"),             &firm_opt.const_folding,    1, "enable constant folding" },
119   { X("no-const-fold"),          &firm_opt.const_folding,    0, "disable constant folding" },
120   { X("inline-max-size=<size>"), NULL,                       0, "set maximum size for function inlining" },
121   { X("inline-threshold=<size>"),NULL,                       0, "set benefice threshold for function inlining" },
122   { X("confirm"),                &firm_opt.confirm,          1, "enable Confirm optimization" },
123   { X("no-confirm"),             &firm_opt.confirm,          0, "disable Confirm optimization" },
124   { X("opt-mul"),                &firm_opt.muls,             0, "enable multiplication optimization" },
125   { X("no-opt-mul"),             &firm_opt.muls,             0, "disable multiplication optimization" },
126   { X("opt-div"),                &firm_opt.divs,             0, "enable division optimization" },
127   { X("no-opt-div"),             &firm_opt.divs,             0, "disable division optimization" },
128   { X("opt-mod"),                &firm_opt.mods,             0, "enable remainder optimization" },
129   { X("no-opt-mod"),             &firm_opt.mods,             0, "disable remainder optimization" },
130   { X("opt-alias"),              &firm_opt.alias_analysis,   1, "enable alias analysis" },
131   { X("no-opt-alias"),           &firm_opt.alias_analysis,   0, "disable alias analysis" },
132   { X("alias"),                  &firm_opt.no_alias,         0, "aliasing occurs" },
133   { X("no-alias"),               &firm_opt.no_alias,         1, "no aliasing occurs" },
134   { X("strict-aliasing"),        &firm_opt.strict_alias,     1, "strict alias rules" },
135   { X("no-strict-aliasing"),     &firm_opt.strict_alias,     0, "strict alias rules" },
136   { X("clone-threshold=<value>"),NULL,                       0, "set clone threshold to <value>" },
137
138   /* other firm regarding options */
139   { X("verify-off"),             &firm_opt.verify,           FIRM_VERIFICATION_OFF,    "disable node verification" },
140   { X("verify-on"),              &firm_opt.verify,           FIRM_VERIFICATION_ON,     "enable node verification" },
141   { X("verify-report"),          &firm_opt.verify,           FIRM_VERIFICATION_REPORT, "node verification, report only" },
142   { X("check-all"),              &firm_opt.check_all,        1, "enable checking all Firm phases" },
143   { X("no-check-all"),           &firm_opt.check_all,        0, "disable checking all Firm phases" },
144   { X("verify-edges-on"),        &firm_opt.verify_edges,     1, "enable out edge verification" },
145   { X("verify-edges-off"),       &firm_opt.verify_edges,     0, "disable out edge verification" },
146
147   /* dumping */
148   { X("dump-ir"),                &firm_dump.ir_graph,        1, "dump IR graph" },
149   { X("dump-all-types"),         &firm_dump.all_types,       1, "dump graph of all types" },
150   { X("dump-no-blocks"),         &firm_dump.no_blocks,       1, "dump non-blocked graph" },
151   { X("dump-extbb"),             &firm_dump.extbb,           1, "dump extended basic blocks" },
152   { X("dump-all-phases"),        &firm_dump.all_phases,      1, "dump graphs for all optimization phases" },
153   { X("dump-filter=<string>"),   NULL,                       0, "set dumper filter" },
154
155   /* misc */
156   { X("stat-before-opt"),        &firm_dump.statistic,       STAT_BEFORE_OPT,  "Firm statistic output before optimizations" },
157   { X("stat-after-opt"),         &firm_dump.statistic,       STAT_AFTER_OPT,   "Firm statistic output after optimizations" },
158   { X("stat-after-lower"),       &firm_dump.statistic,       STAT_AFTER_LOWER, "Firm statistic output after lowering" },
159   { X("stat-final-ir"),          &firm_dump.statistic,       STAT_FINAL_IR,    "Firm statistic after final optimization" },
160   { X("stat-final"),             &firm_dump.statistic,       STAT_FINAL,       "Firm statistic after code generation" },
161   { X("stat-pattern"),           &firm_dump.stat_pattern,    1, "Firm statistic calculates most used pattern" },
162   { X("stat-dag"),               &firm_dump.stat_dag,        1, "Firm calculates DAG statistics" },
163 };
164
165 #undef X
166
167 static ir_timer_t *t_vcg_dump;
168 static ir_timer_t *t_verify;
169 static ir_timer_t *t_all_opt;
170 static bool do_irg_opt(ir_graph *irg, const char *name);
171
172 /** dump all the graphs depending on cond */
173
174 static void dump_all(const char *suffix)
175 {
176         if (!firm_dump.ir_graph)
177                 return;
178
179         timer_push(t_vcg_dump);
180         dump_all_ir_graphs(suffix);
181         timer_pop(t_vcg_dump);
182 }
183
184 /* entities of runtime functions */
185 ir_entity_ptr rts_entities[rts_max];
186
187 /**
188  * Map runtime functions.
189  */
190 static void rts_map(void)
191 {
192         static const struct {
193                 ir_entity_ptr *ent; /**< address of the rts entity */
194                 i_mapper_func func; /**< mapper function. */
195         } mapper[] = {
196                 /* integer */
197                 { &rts_entities[rts_abs],     i_mapper_abs },
198                 { &rts_entities[rts_labs],    i_mapper_abs },
199                 { &rts_entities[rts_llabs],   i_mapper_abs },
200                 { &rts_entities[rts_imaxabs], i_mapper_abs },
201
202                 /* double -> double */
203                 { &rts_entities[rts_fabs],    i_mapper_abs },
204                 { &rts_entities[rts_sqrt],    i_mapper_sqrt },
205                 { &rts_entities[rts_cbrt],    i_mapper_cbrt },
206                 { &rts_entities[rts_pow],     i_mapper_pow },
207                 { &rts_entities[rts_exp],     i_mapper_exp },
208                 { &rts_entities[rts_exp2],    i_mapper_exp },
209                 { &rts_entities[rts_exp10],   i_mapper_exp },
210                 { &rts_entities[rts_log],     i_mapper_log },
211                 { &rts_entities[rts_log2],    i_mapper_log2 },
212                 { &rts_entities[rts_log10],   i_mapper_log10 },
213                 { &rts_entities[rts_sin],     i_mapper_sin },
214                 { &rts_entities[rts_cos],     i_mapper_cos },
215                 { &rts_entities[rts_tan],     i_mapper_tan },
216                 { &rts_entities[rts_asin],    i_mapper_asin },
217                 { &rts_entities[rts_acos],    i_mapper_acos },
218                 { &rts_entities[rts_atan],    i_mapper_atan },
219                 { &rts_entities[rts_sinh],    i_mapper_sinh },
220                 { &rts_entities[rts_cosh],    i_mapper_cosh },
221                 { &rts_entities[rts_tanh],    i_mapper_tanh },
222
223                 /* float -> float */
224                 { &rts_entities[rts_fabsf],   i_mapper_abs },
225                 { &rts_entities[rts_sqrtf],   i_mapper_sqrt },
226                 { &rts_entities[rts_cbrtf],   i_mapper_cbrt },
227                 { &rts_entities[rts_powf],    i_mapper_pow },
228                 { &rts_entities[rts_expf],    i_mapper_exp },
229                 { &rts_entities[rts_exp2f],   i_mapper_exp },
230                 { &rts_entities[rts_exp10f],  i_mapper_exp },
231                 { &rts_entities[rts_logf],    i_mapper_log },
232                 { &rts_entities[rts_log2f],   i_mapper_log2 },
233                 { &rts_entities[rts_log10f],  i_mapper_log10 },
234                 { &rts_entities[rts_sinf],    i_mapper_sin },
235                 { &rts_entities[rts_cosf],    i_mapper_cos },
236                 { &rts_entities[rts_tanf],    i_mapper_tan },
237                 { &rts_entities[rts_asinf],   i_mapper_asin },
238                 { &rts_entities[rts_acosf],   i_mapper_acos },
239                 { &rts_entities[rts_atanf],   i_mapper_atan },
240                 { &rts_entities[rts_sinhf],   i_mapper_sinh },
241                 { &rts_entities[rts_coshf],   i_mapper_cosh },
242                 { &rts_entities[rts_tanhf],   i_mapper_tanh },
243
244                 /* long double -> long double */
245                 { &rts_entities[rts_fabsl],   i_mapper_abs },
246                 { &rts_entities[rts_sqrtl],   i_mapper_sqrt },
247                 { &rts_entities[rts_cbrtl],   i_mapper_cbrt },
248                 { &rts_entities[rts_powl],    i_mapper_pow },
249                 { &rts_entities[rts_expl],    i_mapper_exp },
250                 { &rts_entities[rts_exp2l],   i_mapper_exp },
251                 { &rts_entities[rts_exp10l],  i_mapper_exp },
252                 { &rts_entities[rts_logl],    i_mapper_log },
253                 { &rts_entities[rts_log2l],   i_mapper_log2 },
254                 { &rts_entities[rts_log10l],  i_mapper_log10 },
255                 { &rts_entities[rts_sinl],    i_mapper_sin },
256                 { &rts_entities[rts_cosl],    i_mapper_cos },
257                 { &rts_entities[rts_tanl],    i_mapper_tan },
258                 { &rts_entities[rts_asinl],   i_mapper_asin },
259                 { &rts_entities[rts_acosl],   i_mapper_acos },
260                 { &rts_entities[rts_atanl],   i_mapper_atan },
261                 { &rts_entities[rts_sinhl],   i_mapper_sinh },
262                 { &rts_entities[rts_coshl],   i_mapper_cosh },
263                 { &rts_entities[rts_tanhl],   i_mapper_tanh },
264
265                 /* string */
266                 { &rts_entities[rts_strcmp],  i_mapper_strcmp },
267                 { &rts_entities[rts_strncmp], i_mapper_strncmp },
268                 { &rts_entities[rts_strcpy],  i_mapper_strcpy },
269                 { &rts_entities[rts_strlen],  i_mapper_strlen },
270                 { &rts_entities[rts_memcpy],  i_mapper_memcpy },
271                 { &rts_entities[rts_mempcpy], i_mapper_mempcpy },
272                 { &rts_entities[rts_memmove], i_mapper_memmove },
273                 { &rts_entities[rts_memset],  i_mapper_memset },
274                 { &rts_entities[rts_memcmp],  i_mapper_memcmp }
275         };
276         i_record rec[sizeof(mapper)/sizeof(mapper[0])];
277         unsigned i, n_map;
278
279         for (i = n_map = 0; i < sizeof(mapper)/sizeof(mapper[0]); ++i) {
280                 if (*mapper[i].ent != NULL) {
281                         rec[n_map].i_call.kind     = INTRINSIC_CALL;
282                         rec[n_map].i_call.i_ent    = *mapper[i].ent;
283                         rec[n_map].i_call.i_mapper = mapper[i].func;
284                         rec[n_map].i_call.ctx      = NULL;
285                         rec[n_map].i_call.link     = NULL;
286                         ++n_map;
287                 }
288         }
289
290         if (n_map > 0)
291                 lower_intrinsics(rec, n_map, /* part_block_used=*/0);
292 }
293
294 static int *irg_dump_no;
295
296 static void do_stred(ir_graph *irg)
297 {
298         opt_osr(irg, osr_flag_default | osr_flag_keep_reg_pressure | osr_flag_ignore_x86_shift);
299 }
300
301 static void after_inline_opt(ir_graph *irg)
302 {
303         do_irg_opt(irg, "scalar-replace");
304         do_irg_opt(irg, "local");
305         do_irg_opt(irg, "control-flow");
306         do_irg_opt(irg, "combo");
307 }
308
309 static void do_inline(void)
310 {
311         inline_functions(firm_opt.inline_maxsize, firm_opt.inline_threshold,
312                          after_inline_opt);
313 }
314
315 static void do_cloning(void)
316 {
317         proc_cloning((float) firm_opt.clone_threshold);
318 }
319
320 static void do_lower_mux(ir_graph *irg)
321 {
322         lower_mux(irg, NULL);
323 }
324
325 static void do_gcse(ir_graph *irg)
326 {
327         set_opt_global_cse(1);
328         optimize_graph_df(irg);
329         set_opt_global_cse(0);
330 }
331
332 static void lower_blockcopy(ir_graph *irg)
333 {
334         lower_CopyB(irg, 128, 4);
335 }
336
337 typedef enum opt_target {
338         OPT_TARGET_IRG, /**< optimization function works on a single graph */
339         OPT_TARGET_IRP  /**< optimization function works on the complete program */
340 } opt_target_t;
341
342 typedef enum opt_flags {
343         OPT_FLAG_NONE         = 0,
344         OPT_FLAG_ENABLED      = 1 << 0, /**< enable the optimization */
345         OPT_FLAG_NO_DUMP      = 1 << 1, /**< don't dump after transformation */
346         OPT_FLAG_NO_VERIFY    = 1 << 2, /**< don't verify after transformation */
347         OPT_FLAG_HIDE_OPTIONS = 1 << 3, /**< do not automatically process
348                                              -foptions for this transformation */
349         OPT_FLAG_ESSENTIAL    = 1 << 4, /**< output won't work without this pass
350                                              so we need it even with -O0 */
351 } opt_flags_t;
352
353 typedef void (*transform_irg_func)(ir_graph *irg);
354 typedef void (*transform_irp_func)(void);
355
356 typedef struct {
357         opt_target_t  target;
358         const char   *name;
359         union {
360                 transform_irg_func transform_irg;
361                 transform_irp_func transform_irp;
362         } u;
363         const char   *description;
364         opt_flags_t   flags;
365         ir_timer_t   *timer;
366 } opt_config_t;
367
368 static opt_config_t opts[] = {
369 #define IRG(a, b, c, d) { OPT_TARGET_IRG, a, .u.transform_irg = (transform_irg_func)b, c, d }
370 #define IRP(a, b, c, d) { OPT_TARGET_IRP, a, .u.transform_irp = b,                     c, d }
371         IRG("bool",              opt_bool,                 "bool simplification",                                   OPT_FLAG_NONE),
372         IRG("combo",             combo,                    "combined CCE, UCE and GVN",                             OPT_FLAG_NONE),
373         IRG("confirm",           construct_confirms,       "confirm optimization",                                  OPT_FLAG_HIDE_OPTIONS),
374         IRG("control-flow",      optimize_cf,              "optimization of control-flow",                          OPT_FLAG_HIDE_OPTIONS),
375         IRG("dead",              dead_node_elimination,    "dead node elimination",                                 OPT_FLAG_HIDE_OPTIONS | OPT_FLAG_NO_DUMP | OPT_FLAG_NO_VERIFY),
376         IRG("deconv",            conv_opt,                 "conv node elimination",                                 OPT_FLAG_NONE),
377         IRG("fp-vrp",            fixpoint_vrp,             "fixpoint value range propagation",                      OPT_FLAG_NONE),
378         IRG("frame",             opt_frame_irg,            "remove unused frame entities",                          OPT_FLAG_NONE),
379         IRG("gvn-pre",           do_gvn_pre,               "global value numbering partial redundancy elimination", OPT_FLAG_NONE),
380         IRG("if-conversion",     opt_if_conv,              "if-conversion",                                         OPT_FLAG_NONE),
381         IRG("invert-loops",      do_loop_inversion,        "loop inversion",                                        OPT_FLAG_NONE),
382         IRG("ivopts",            do_stred,                 "induction variable strength reduction",                 OPT_FLAG_NONE),
383         IRG("local",             optimize_graph_df,        "local graph optimizations",                             OPT_FLAG_HIDE_OPTIONS),
384         IRG("lower",             lower_highlevel_graph,    "lowering",                                              OPT_FLAG_HIDE_OPTIONS | OPT_FLAG_ESSENTIAL),
385         IRG("lower-mux",         do_lower_mux,             "mux lowering",                                          OPT_FLAG_NONE),
386         IRG("opt-load-store",    optimize_load_store,      "load store optimization",                               OPT_FLAG_NONE),
387         IRG("opt-tail-rec",      opt_tail_rec_irg,         "tail-recursion eliminiation",                           OPT_FLAG_NONE),
388         IRG("parallelize-mem",   opt_parallelize_mem,      "parallelize memory",                                    OPT_FLAG_NONE),
389         IRG("gcse",              do_gcse,                  "global common subexpression eliminiation",              OPT_FLAG_NONE),
390         IRG("place",             place_code,               "code placement",                                        OPT_FLAG_NONE),
391         IRG("reassociation",     optimize_reassociation,   "reassociation",                                         OPT_FLAG_NONE),
392         IRG("remove-confirms",   remove_confirms,          "confirm removal",                                       OPT_FLAG_HIDE_OPTIONS | OPT_FLAG_NO_DUMP | OPT_FLAG_NO_VERIFY),
393         IRG("remove-phi-cycles", remove_phi_cycles,        "removal of phi cycles",                                 OPT_FLAG_HIDE_OPTIONS),
394         IRG("scalar-replace",    scalar_replacement_opt,   "scalar replacement",                                    OPT_FLAG_NONE),
395         IRG("shape-blocks",      shape_blocks,             "block shaping",                                         OPT_FLAG_NONE),
396         IRG("thread-jumps",      opt_jumpthreading,        "path-sensitive jumpthreading",                          OPT_FLAG_NONE),
397         IRG("unroll-loops",      do_loop_unrolling,        "loop unrolling",                                        OPT_FLAG_NONE),
398         IRG("vrp",               set_vrp_data,             "value range propagation",                               OPT_FLAG_NONE),
399         IRP("inline",            do_inline,                "inlining",                                              OPT_FLAG_NONE),
400         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),
401         IRG("lower-blockcopy",   lower_blockcopy,          "replace small block copies with load/store sequences",  OPT_FLAG_NO_DUMP),
402         IRP("target-lowering",   be_lower_for_target,      "lowering necessary for target architecture",            OPT_FLAG_HIDE_OPTIONS | OPT_FLAG_ESSENTIAL),
403         IRP("opt-func-call",     optimize_funccalls,       "function call optimization",                            OPT_FLAG_NONE),
404         IRP("opt-proc-clone",    do_cloning,               "procedure cloning",                                     OPT_FLAG_NONE),
405         IRP("remove-unused",     garbage_collect_entities, "removal of unused functions/variables",                 OPT_FLAG_NO_DUMP | OPT_FLAG_NO_VERIFY),
406         IRP("rts",               rts_map,                  "optimization of known library functions",               OPT_FLAG_NONE),
407         IRP("opt-cc",            mark_private_methods,     "calling conventions optimization",                      OPT_FLAG_NONE),
408 #undef IRP
409 #undef IRG
410 };
411
412 #define FOR_EACH_OPT(i) for (opt_config_t *i = opts; i != endof(opts); ++i)
413
414 static opt_config_t *get_opt(const char *name)
415 {
416         FOR_EACH_OPT(config) {
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
738         FOR_EACH_OPT(i) {
739                 i->timer = ir_timer_new();
740                 timer_register(i->timer, i->description);
741         }
742         t_verify = ir_timer_new();
743         timer_register(t_verify, "Firm: verify pass");
744         t_vcg_dump = ir_timer_new();
745         timer_register(t_vcg_dump, "Firm: vcg dumping");
746         t_all_opt = ir_timer_new();
747         timer_register(t_all_opt, "Firm: all optimizations");
748
749         if (firm_dump.stat_pattern)
750                 pattern |= FIRMSTAT_PATTERN_ENABLED;
751
752         if (firm_dump.stat_dag)
753                 pattern |= FIRMSTAT_COUNT_DAG;
754
755         ir_init(NULL);
756         firm_init_stat(firm_dump.statistic == STAT_NONE ?
757                         0 : FIRMSTAT_ENABLED | FIRMSTAT_COUNT_STRONG_OP
758                         | FIRMSTAT_COUNT_CONSTS | pattern);
759
760         edges_init_dbg(firm_opt.verify_edges);
761
762         /* Sel node cannot produce NULL pointers */
763         set_opt_sel_based_null_check_elim(1);
764
765         /* dynamic dispatch works currently only if whole world scenarios */
766         set_opt_dyn_meth_dispatch(0);
767
768         /* do not run architecture dependent optimizations in building phase */
769         arch_dep_set_opts(arch_dep_none);
770
771         do_node_verification((firm_verification_t) firm_opt.verify);
772         if (firm_dump.extbb)
773                 ir_add_dump_flags(ir_dump_flag_group_extbb);
774         if (firm_dump.no_blocks)
775                 ir_remove_dump_flags(ir_dump_flag_blocks_as_subgraphs);
776
777         set_optimize(1);
778         set_opt_constant_folding(firm_opt.const_folding);
779         set_opt_algebraic_simplification(firm_opt.const_folding);
780         set_opt_cse(firm_opt.cse);
781         set_opt_global_cse(0);
782         set_opt_unreachable_code(1);
783 }
784
785 /**
786  * Called, after the Firm generation is completed,
787  * do all optimizations and backend call here.
788  *
789  * @param out                a file handle for the output, may be NULL
790  * @param input_filename     the name of the (main) source file
791  * @param c_mode             non-zero if "C" was compiled
792  */
793 void gen_firm_finish(FILE *out, const char *input_filename)
794 {
795         int i;
796
797         /* the general for dumping option must be set, or the others will not work*/
798         firm_dump.ir_graph
799                 = (bool) (firm_dump.ir_graph | firm_dump.all_phases | firm_dump.extbb);
800
801         ir_add_dump_flags(ir_dump_flag_keepalive_edges
802                         | ir_dump_flag_consts_local | ir_dump_flag_dominance);
803         ir_remove_dump_flags(ir_dump_flag_loops | ir_dump_flag_ld_names);
804
805         /* FIXME: cloning might ADD new graphs. */
806         irg_dump_no = calloc(get_irp_last_idx(), sizeof(*irg_dump_no));
807
808         if (firm_dump.all_types) {
809                 dump_ir_prog_ext(dump_typegraph, "types.vcg");
810         }
811
812         /* finalize all graphs */
813         for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
814                 ir_graph *irg = get_irp_irg(i);
815                 irg_finalize_cons(irg);
816         }
817         dump_all("");
818
819         timer_push(t_verify);
820         tr_verify();
821         timer_pop(t_verify);
822
823         /* all graphs are finalized, set the irp phase to high */
824         set_irp_phase_state(phase_high);
825
826         /* BEWARE: kill unreachable code before doing compound lowering */
827         for (i = get_irp_n_irgs() - 1; i >= 0; --i) {
828                 ir_graph *irg = get_irp_irg(i);
829                 do_irg_opt(irg, "control-flow");
830                 do_irg_opt(irg, "lower-blockcopy");
831         }
832
833         if (firm_dump.statistic & STAT_BEFORE_OPT) {
834                 stat_dump_snapshot(input_filename, "noopt");
835         }
836
837         do_firm_optimizations(input_filename);
838         do_firm_lowering(input_filename);
839
840         /* set the phase to low */
841         for (i = get_irp_n_irgs() - 1; i >= 0; --i)
842                 set_irg_phase_state(get_irp_irg(i), phase_low);
843
844         if (firm_dump.statistic & STAT_FINAL_IR)
845                 stat_dump_snapshot(input_filename, "final-ir");
846
847         /* run the code generator */
848         ir_timer_t *timer = ir_timer_new();
849         timer_register(timer, "Firm: backend");
850         timer_start(timer);
851         be_main(out, input_filename);
852         timer_stop(timer);
853
854         if (firm_dump.statistic & STAT_FINAL)
855                 stat_dump_snapshot(input_filename, "final");
856 }
857
858 static void disable_all_opts(void)
859 {
860         firm_opt.cse             = false;
861         firm_opt.confirm         = false;
862         firm_opt.muls            = false;
863         firm_opt.divs            = false;
864         firm_opt.mods            = false;
865         firm_opt.alias_analysis  = false;
866         firm_opt.strict_alias    = false;
867         firm_opt.no_alias        = false;
868
869         FOR_EACH_OPT(config) {
870                 if (config->flags & OPT_FLAG_ESSENTIAL) {
871                         config->flags |= OPT_FLAG_ENABLED;
872                 } else {
873                         config->flags &= ~OPT_FLAG_ENABLED;
874                 }
875         }
876 }
877
878 static bool firm_opt_option(const char *opt)
879 {
880         bool enable = true;
881         if (strncmp(opt, "no-", 3) == 0) {
882                 enable = false;
883                 opt = opt + 3;
884         }
885
886         opt_config_t *config = get_opt(opt);
887         if (config == NULL || (config->flags & OPT_FLAG_HIDE_OPTIONS))
888                 return false;
889
890         config->flags &= ~OPT_FLAG_ENABLED;
891         config->flags |= enable ? OPT_FLAG_ENABLED : 0;
892         return true;
893 }
894
895 void firm_option_help(print_option_help_func print_option_help)
896 {
897         print_option_help(firm_options[0].option, firm_options[0].description);
898
899         FOR_EACH_OPT(config) {
900                 char buf[1024];
901                 char buf2[1024];
902
903                 if (config->flags & OPT_FLAG_HIDE_OPTIONS)
904                         continue;
905
906                 snprintf(buf, sizeof(buf), "-f%s", config->name);
907                 snprintf(buf2, sizeof(buf2), "enable %s", config->description);
908                 print_option_help(buf, buf2);
909                 snprintf(buf, sizeof(buf), "-fno-%s", config->name);
910                 snprintf(buf2, sizeof(buf2), "disable %s", config->description);
911                 print_option_help(buf, buf2);
912         }
913
914         size_t const n_options = sizeof(firm_options)/sizeof(firm_options[0]);
915         for (size_t k = 0; k < n_options; ++k) {
916                 char buf[1024];
917                 char buf2[1024];
918                 snprintf(buf, sizeof(buf), "-f%s", firm_options[k].option);
919                 snprintf(buf2, sizeof(buf2), "%s", firm_options[k].description);
920                 print_option_help(buf, buf2);
921         }
922 }
923
924 int firm_option(const char *const opt)
925 {
926         char const* val;
927         if ((val = strstart(opt, "dump-filter="))) {
928                 ir_set_dump_filter(val);
929                 return 1;
930         } else if ((val = strstart(opt, "clone-threshold="))) {
931                 sscanf(val, "%d", &firm_opt.clone_threshold);
932                 return 1;
933         } else if ((val = strstart(opt, "inline-max-size="))) {
934                 sscanf(val, "%u", &firm_opt.inline_maxsize);
935                 return 1;
936         } else if ((val = strstart(opt, "inline-threshold="))) {
937                 sscanf(val, "%u", &firm_opt.inline_threshold);
938                 return 1;
939         } else if (streq(opt, "no-opt")) {
940                 disable_all_opts();
941                 return 1;
942         }
943
944         size_t const len = strlen(opt);
945         size_t const n_options = sizeof(firm_options)/sizeof(firm_options[0]);
946         for (size_t i = n_options; i != 0;) {
947                 struct params const* const o = &firm_options[--i];
948                 if (len == o->opt_len && strncmp(opt, o->option, len) == 0) {
949                         /* statistic options do accumulate */
950                         if (o->flag == &firm_dump.statistic)
951                                 *o->flag = (bool) (*o->flag | o->set);
952                         else
953                                 *o->flag = o->set;
954
955                         return 1;
956                 }
957         }
958
959         /* maybe this enables/disables optimizations */
960         if (firm_opt_option(opt))
961                 return 1;
962
963         return 0;
964 }
965
966 static void set_be_option(const char *arg)
967 {
968         int res = be_parse_arg(arg);
969         (void) res;
970         assert(res);
971 }
972
973 static void set_option(const char *arg)
974 {
975         int res = firm_option(arg);
976         (void) res;
977         assert(res);
978 }
979
980 void choose_optimization_pack(int level)
981 {
982         /* apply optimization level */
983         switch(level) {
984         case 0:
985                 set_option("no-opt");
986                 break;
987         case 1:
988                 set_option("no-inline");
989                 break;
990         default:
991         case 4:
992                 /* use_builtins = true; */
993                 /* fallthrough */
994         case 3:
995                 set_option("thread-jumps");
996                 set_option("if-conversion");
997                 /* fallthrough */
998         case 2:
999                 set_option("strict-aliasing");
1000                 set_option("inline");
1001                 set_option("fp-vrp");
1002                 set_option("deconv");
1003                 set_be_option("omitfp");
1004                 break;
1005         }
1006 }
1007
1008 /**
1009  * Do very early initializations
1010  */
1011 void firm_early_init(void)
1012 {
1013         /* arg: need this here for command line options */
1014         be_opt_register();
1015
1016         enable_safe_defaults();
1017 }