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