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