add missing FP_USED()
[libfirm] / ir / be / ia32 / ia32_optimize.c
1 #ifdef HAVE_CONFIG_H
2 #include "config.h"
3 #endif
4
5 #include "irnode.h"
6 #include "irprog_t.h"
7 #include "ircons.h"
8 #include "firm_types.h"
9 #include "iredges.h"
10 #include "tv.h"
11 #include "irgmod.h"
12
13 #include "../be_t.h"
14 #include "../beabi.h"
15 #include "../benode_t.h"
16 #include "../besched_t.h"
17
18 #include "ia32_new_nodes.h"
19 #include "bearch_ia32_t.h"
20 #include "gen_ia32_regalloc_if.h"     /* the generated interface (register type and class defenitions) */
21 #include "ia32_transform.h"
22
23 /*----*/
24
25 #include "irhooks.h"
26 #include "dbginfo_t.h"
27 #include "firmstat.h"
28
29 /**
30  * Merge the debug info due to a LEA creation.
31  *
32  * @param oldn  the node
33  * @param n     the new constant holding the value
34  */
35 #define DBG_OPT_LEA(oldn, n)                                \
36   do {                                                          \
37           hook_merge_nodes(&n, 1, &oldn, 1, FS_BE_IA32_LEA);      \
38     __dbg_info_merge_pair(n, oldn, dbg_backend);                  \
39   } while(0)
40
41
42 #undef is_NoMem
43 #define is_NoMem(irn) (get_irn_op(irn) == op_NoMem)
44
45 typedef int is_op_func_t(const ir_node *n);
46
47 /**
48  * checks if a node represents the NOREG value
49  */
50 static int be_is_NoReg(ia32_code_gen_t *cg, const ir_node *irn) {
51   be_abi_irg_t *babi = cg->birg->abi;
52         const arch_register_t *fp_noreg = USE_SSE2(cg) ?
53                 &ia32_xmm_regs[REG_XMM_NOREG] : &ia32_vfp_regs[REG_VFP_NOREG];
54
55         return (be_abi_get_callee_save_irn(babi, &ia32_gp_regs[REG_GP_NOREG]) == irn) ||
56                (be_abi_get_callee_save_irn(babi, fp_noreg) == irn);
57 }
58
59
60
61 /*************************************************
62  *   _____                _              _
63  *  / ____|              | |            | |
64  * | |     ___  _ __  ___| |_ __ _ _ __ | |_ ___
65  * | |    / _ \| '_ \/ __| __/ _` | '_ \| __/ __|
66  * | |___| (_) | | | \__ \ || (_| | | | | |_\__ \
67  *  \_____\___/|_| |_|___/\__\__,_|_| |_|\__|___/
68  *
69  *************************************************/
70
71 /**
72  * creates a unique ident by adding a number to a tag
73  *
74  * @param tag   the tag string, must contain a %d if a number
75  *              should be added
76  */
77 static ident *unique_id(const char *tag)
78 {
79         static unsigned id = 0;
80         char str[256];
81
82         snprintf(str, sizeof(str), tag, ++id);
83         return new_id_from_str(str);
84 }
85
86
87
88 /**
89  * Transforms a SymConst.
90  *
91  * @param mod     the debug module
92  * @param block   the block the new node should belong to
93  * @param node    the ir SymConst node
94  * @param mode    mode of the SymConst
95  * @return the created ia32 Const node
96  */
97 static ir_node *gen_SymConst(ia32_transform_env_t *env) {
98         ir_node  *cnst;
99         dbg_info *dbg   = env->dbg;
100         ir_mode  *mode  = env->mode;
101         ir_graph *irg   = env->irg;
102         ir_node  *block = env->block;
103
104         if (mode_is_float(mode)) {
105                 if (USE_SSE2(env->cg))
106                         cnst = new_rd_ia32_fConst(dbg, irg, block, mode);
107                 else
108                         cnst = new_rd_ia32_vfConst(dbg, irg, block, mode);
109         }
110         else {
111                 cnst = new_rd_ia32_Const(dbg, irg, block, mode);
112         }
113         set_ia32_Const_attr(cnst, env->irn);
114         return cnst;
115 }
116
117 /**
118  * Get a primitive type for a mode.
119  */
120 static ir_type *get_prim_type(pmap *types, ir_mode *mode)
121 {
122         pmap_entry *e = pmap_find(types, mode);
123         ir_type *res;
124
125         if (! e) {
126                 char buf[64];
127                 snprintf(buf, sizeof(buf), "prim_type_%s", get_mode_name(mode));
128                 res = new_type_primitive(new_id_from_str(buf), mode);
129                 pmap_insert(types, mode, res);
130         }
131         else
132                 res = e->value;
133         return res;
134 }
135
136 /**
137  * Get an entity that is initialized with a tarval
138  */
139 static entity *get_entity_for_tv(ia32_code_gen_t *cg, ir_node *cnst)
140 {
141         tarval *tv    = get_Const_tarval(cnst);
142         pmap_entry *e = pmap_find(cg->isa->tv_ent, tv);
143         entity *res;
144         ir_graph *rem;
145
146         if (! e) {
147                 ir_mode *mode = get_irn_mode(cnst);
148                 ir_type *tp = get_Const_type(cnst);
149                 if (tp == firm_unknown_type)
150                         tp = get_prim_type(cg->isa->types, mode);
151
152                 res = new_entity(get_glob_type(), unique_id("ia32FloatCnst_%u"), tp);
153
154                 set_entity_ld_ident(res, get_entity_ident(res));
155                 set_entity_visibility(res, visibility_local);
156                 set_entity_variability(res, variability_constant);
157                 set_entity_allocation(res, allocation_static);
158
159                  /* we create a new entity here: It's initialization must resist on the
160                     const code irg */
161                 rem = current_ir_graph;
162                 current_ir_graph = get_const_code_irg();
163                 set_atomic_ent_value(res, new_Const_type(tv, tp));
164                 current_ir_graph = rem;
165
166                 pmap_insert(cg->isa->tv_ent, tv, res);
167         }
168         else
169                 res = e->value;
170         return res;
171 }
172
173 /**
174  * Transforms a Const.
175  *
176  * @param mod     the debug module
177  * @param block   the block the new node should belong to
178  * @param node    the ir Const node
179  * @param mode    mode of the Const
180  * @return the created ia32 Const node
181  */
182 static ir_node *gen_Const(ia32_transform_env_t *env) {
183         ir_node *cnst;
184         symconst_symbol sym;
185         ir_graph *irg   = env->irg;
186         ir_node  *block = env->block;
187         ir_node  *node  = env->irn;
188         dbg_info *dbg   = env->dbg;
189         ir_mode  *mode  = env->mode;
190
191         if (mode_is_float(mode)) {
192                 FP_USED(env->cg);
193                 if (! USE_SSE2(env->cg)) {
194                         cnst_classify_t clss = classify_Const(node);
195
196                         if (clss == CNST_NULL)
197                                 return new_rd_ia32_vfldz(dbg, irg, block, mode);
198                         else if (clss == CNST_ONE)
199                                 return new_rd_ia32_vfld1(dbg, irg, block, mode);
200                 }
201                 sym.entity_p = get_entity_for_tv(env->cg, node);
202
203                 cnst = new_rd_SymConst(dbg, irg, block, sym, symconst_addr_ent);
204                 env->irn = cnst;
205                 cnst = gen_SymConst(env);
206         }
207         else {
208                 cnst = new_rd_ia32_Const(dbg, irg, block, get_irn_mode(node));
209                 set_ia32_Const_attr(cnst, node);
210         }
211         return cnst;
212 }
213
214
215
216 /**
217  * Transforms (all) Const's into ia32_Const and places them in the
218  * block where they are used (or in the cfg-pred Block in case of Phi's).
219  * Additionally all reference nodes are changed into mode_Is nodes.
220  */
221 void ia32_place_consts_set_modes(ir_node *irn, void *env) {
222         ia32_code_gen_t      *cg = env;
223         ia32_transform_env_t  tenv;
224         ir_mode              *mode;
225         ir_node              *pred, *cnst;
226         int                   i;
227         opcode                opc;
228
229         if (is_Block(irn))
230                 return;
231
232         mode = get_irn_mode(irn);
233
234         /* transform all reference nodes into mode_Is nodes */
235         if (mode_is_reference(mode)) {
236                 mode = mode_Is;
237                 set_irn_mode(irn, mode);
238         }
239
240         tenv.block    = get_nodes_block(irn);
241         tenv.cg       = cg;
242         tenv.irg      = cg->irg;
243         DEBUG_ONLY(tenv.mod      = cg->mod;)
244
245         /* Loop over all predecessors and check for Sym/Const nodes */
246         for (i = get_irn_arity(irn) - 1; i >= 0; --i) {
247                 pred      = get_irn_n(irn, i);
248                 cnst      = NULL;
249                 opc       = get_irn_opcode(pred);
250                 tenv.irn  = pred;
251                 tenv.mode = get_irn_mode(pred);
252                 tenv.dbg  = get_irn_dbg_info(pred);
253
254                 /* If it's a Phi, then we need to create the */
255                 /* new Const in it's predecessor block       */
256                 if (is_Phi(irn)) {
257                         tenv.block = get_Block_cfgpred_block(get_nodes_block(irn), i);
258                 }
259
260                 /* put the const into the block where the original const was */
261                 if (! cg->opt.placecnst) {
262                         tenv.block = get_nodes_block(pred);
263                 }
264
265                 switch (opc) {
266                         case iro_Const:
267                                 cnst = gen_Const(&tenv);
268                                 break;
269                         case iro_SymConst:
270                                 cnst = gen_SymConst(&tenv);
271                                 break;
272                         default:
273                                 break;
274                 }
275
276                 /* if we found a const, then set it */
277                 if (cnst) {
278                         set_irn_n(irn, i, cnst);
279                 }
280         }
281 }
282
283
284
285 /********************************************************************************************************
286  *  _____                _           _         ____        _   _           _          _   _
287  * |  __ \              | |         | |       / __ \      | | (_)         (_)        | | (_)
288  * | |__) |__  ___ _ __ | |__   ___ | | ___  | |  | |_ __ | |_ _ _ __ ___  _ ______ _| |_ _  ___  _ __
289  * |  ___/ _ \/ _ \ '_ \| '_ \ / _ \| |/ _ \ | |  | | '_ \| __| | '_ ` _ \| |_  / _` | __| |/ _ \| '_ \
290  * | |  |  __/  __/ |_) | | | | (_) | |  __/ | |__| | |_) | |_| | | | | | | |/ / (_| | |_| | (_) | | | |
291  * |_|   \___|\___| .__/|_| |_|\___/|_|\___|  \____/| .__/ \__|_|_| |_| |_|_/___\__,_|\__|_|\___/|_| |_|
292  *                | |                               | |
293  *                |_|                               |_|
294  ********************************************************************************************************/
295
296 /**
297  * NOTE: THESE PEEPHOLE OPTIMIZATIONS MUST BE CALLED AFTER SCHEDULING AND REGISTER ALLOCATION.
298  */
299
300 static int ia32_cnst_compare(ir_node *n1, ir_node *n2) {
301         return get_ia32_id_cnst(n1) == get_ia32_id_cnst(n2);
302 }
303
304 /**
305  * Checks for potential CJmp/CJmpAM optimization candidates.
306  */
307 static ir_node *ia32_determine_cjmp_cand(ir_node *irn, is_op_func_t *is_op_func) {
308         ir_node *cand = NULL;
309         ir_node *prev = sched_prev(irn);
310
311         if (is_Block(prev)) {
312                 if (get_Block_n_cfgpreds(prev) == 1)
313                         prev = get_Block_cfgpred(prev, 0);
314                 else
315                         prev = NULL;
316         }
317
318         /* The predecessor must be a ProjX. */
319         if (prev && is_Proj(prev) && get_irn_mode(prev) == mode_X) {
320                 prev = get_Proj_pred(prev);
321
322                 if (is_op_func(prev))
323                         cand = prev;
324         }
325
326         return cand;
327 }
328
329 static int is_TestJmp_cand(const ir_node *irn) {
330         return is_ia32_TestJmp(irn) || is_ia32_And(irn);
331 }
332
333 /**
334  * Checks if two consecutive arguments of cand matches
335  * the two arguments of irn (TestJmp).
336  */
337 static int is_TestJmp_replacement(ir_node *cand, ir_node *irn) {
338         ir_node *in1       = get_irn_n(irn, 0);
339         ir_node *in2       = get_irn_n(irn, 1);
340         int      i, n      = get_irn_arity(cand);
341         int      same_args = 0;
342
343         for (i = 0; i < n - 1; i++) {
344                 if (get_irn_n(cand, i)     == in1 &&
345                         get_irn_n(cand, i + 1) == in2)
346                 {
347                         same_args = 1;
348                         break;
349                 }
350         }
351
352         if (same_args)
353                 return ia32_cnst_compare(cand, irn);
354
355         return 0;
356 }
357
358 /**
359  * Tries to replace a TestJmp by a CJmp or CJmpAM (in case of And)
360  */
361 static void ia32_optimize_TestJmp(ir_node *irn, ia32_code_gen_t *cg) {
362         ir_node *cand    = ia32_determine_cjmp_cand(irn, is_TestJmp_cand);
363         int      replace = 0;
364
365         /* we found a possible candidate */
366         replace = cand ? is_TestJmp_replacement(cand, irn) : 0;
367
368         if (replace) {
369                 DBG((cg->mod, LEVEL_1, "replacing %+F by ", irn));
370
371                 if (is_ia32_And(cand))
372                         set_irn_op(irn, op_ia32_CJmpAM);
373                 else
374                         set_irn_op(irn, op_ia32_CJmp);
375
376                 DB((cg->mod, LEVEL_1, "%+F\n", irn));
377         }
378 }
379
380 static int is_CondJmp_cand(const ir_node *irn) {
381         return is_ia32_CondJmp(irn) || is_ia32_Sub(irn);
382 }
383
384 /**
385  * Checks if the arguments of cand are the same of irn.
386  */
387 static int is_CondJmp_replacement(ir_node *cand, ir_node *irn) {
388         int i, n      = get_irn_arity(cand);
389         int same_args = 1;
390
391         for (i = 0; i < n; i++) {
392                 if (get_irn_n(cand, i) == get_irn_n(irn, i)) {
393                         same_args = 0;
394                         break;
395                 }
396         }
397
398         if (same_args)
399                 return ia32_cnst_compare(cand, irn);
400
401         return 0;
402 }
403
404 /**
405  * Tries to replace a CondJmp by a CJmpAM
406  */
407 static void ia32_optimize_CondJmp(ir_node *irn, ia32_code_gen_t *cg) {
408         ir_node *cand    = ia32_determine_cjmp_cand(irn, is_CondJmp_cand);
409         int      replace = 0;
410
411         /* we found a possible candidate */
412         replace = cand ? is_CondJmp_replacement(cand, irn) : 0;
413
414         if (replace) {
415                 DBG((cg->mod, LEVEL_1, "replacing %+F by ", irn));
416
417                 set_irn_op(irn, op_ia32_CJmp);
418
419                 DB((cg->mod, LEVEL_1, "%+F\n", irn));
420         }
421 }
422
423 /**
424  * Tries to optimize two following IncSP.
425  */
426 static void ia32_optimize_IncSP(ir_node *irn, ia32_code_gen_t *cg) {
427         ir_node *prev = be_get_IncSP_pred(irn);
428         int real_uses = get_irn_n_edges(prev);
429
430         if (be_is_IncSP(prev) && real_uses == 1) {
431                 /* first IncSP has only one IncSP user, kill the first one */
432                 unsigned       prev_offs = be_get_IncSP_offset(prev);
433                 be_stack_dir_t prev_dir  = be_get_IncSP_direction(prev);
434                 unsigned       curr_offs = be_get_IncSP_offset(irn);
435                 be_stack_dir_t curr_dir  = be_get_IncSP_direction(irn);
436
437                 int new_ofs = prev_offs * (prev_dir == be_stack_dir_expand ? -1 : +1) +
438                                     curr_offs * (curr_dir == be_stack_dir_expand ? -1 : +1);
439
440                 if (new_ofs < 0) {
441                         new_ofs  = -new_ofs;
442                         curr_dir = be_stack_dir_expand;
443                 }
444                 else
445                         curr_dir = be_stack_dir_shrink;
446                 be_set_IncSP_offset(prev, 0);
447                 be_set_IncSP_offset(irn, (unsigned)new_ofs);
448                 be_set_IncSP_direction(irn, curr_dir);
449         }
450 }
451
452 /**
453  * Performs Peephole Optimizations.
454  */
455 void ia32_peephole_optimization(ir_node *irn, void *env) {
456         ia32_code_gen_t *cg = env;
457
458         if (is_ia32_TestJmp(irn))
459                 ia32_optimize_TestJmp(irn, cg);
460         else if (is_ia32_CondJmp(irn))
461                 ia32_optimize_CondJmp(irn, cg);
462         else if (be_is_IncSP(irn))
463                 ia32_optimize_IncSP(irn, cg);
464 }
465
466
467
468 /******************************************************************
469  *              _     _                   __  __           _
470  *     /\      | |   | |                 |  \/  |         | |
471  *    /  \   __| | __| |_ __ ___  ___ ___| \  / | ___   __| | ___
472  *   / /\ \ / _` |/ _` | '__/ _ \/ __/ __| |\/| |/ _ \ / _` |/ _ \
473  *  / ____ \ (_| | (_| | | |  __/\__ \__ \ |  | | (_) | (_| |  __/
474  * /_/    \_\__,_|\__,_|_|  \___||___/___/_|  |_|\___/ \__,_|\___|
475  *
476  ******************************************************************/
477
478 static int node_is_ia32_comm(const ir_node *irn) {
479         return is_ia32_irn(irn) ? is_ia32_commutative(irn) : 0;
480 }
481
482 static int ia32_get_irn_n_edges(const ir_node *irn) {
483         const ir_edge_t *edge;
484         int cnt = 0;
485
486         foreach_out_edge(irn, edge) {
487                 cnt++;
488         }
489
490         return cnt;
491 }
492
493 /**
494  * Returns the first mode_M Proj connected to irn.
495  */
496 static ir_node *get_mem_proj(const ir_node *irn) {
497         const ir_edge_t *edge;
498         ir_node         *src;
499
500         assert(get_irn_mode(irn) == mode_T && "expected mode_T node");
501
502         foreach_out_edge(irn, edge) {
503                 src = get_edge_src_irn(edge);
504
505                 assert(is_Proj(src) && "Proj expected");
506
507                 if (get_irn_mode(src) == mode_M)
508                         return src;
509         }
510
511         return NULL;
512 }
513
514 /**
515  * Returns the first Proj with mode != mode_M connected to irn.
516  */
517 static ir_node *get_res_proj(const ir_node *irn) {
518         const ir_edge_t *edge;
519         ir_node         *src;
520
521         assert(get_irn_mode(irn) == mode_T && "expected mode_T node");
522
523         foreach_out_edge(irn, edge) {
524                 src = get_edge_src_irn(edge);
525
526                 assert(is_Proj(src) && "Proj expected");
527
528                 if (get_irn_mode(src) != mode_M)
529                         return src;
530         }
531
532         return NULL;
533 }
534
535 /**
536  * Determines if pred is a Proj and if is_op_func returns true for it's predecessor.
537  *
538  * @param pred       The node to be checked
539  * @param is_op_func The check-function
540  * @return 1 if conditions are fulfilled, 0 otherwise
541  */
542 static int pred_is_specific_node(const ir_node *pred, is_op_func_t *is_op_func) {
543         if (is_Proj(pred) && is_op_func(get_Proj_pred(pred))) {
544                 return 1;
545         }
546
547         return 0;
548 }
549
550 /**
551  * Determines if pred is a Proj and if is_op_func returns true for it's predecessor
552  * and if the predecessor is in block bl.
553  *
554  * @param bl         The block
555  * @param pred       The node to be checked
556  * @param is_op_func The check-function
557  * @return 1 if conditions are fulfilled, 0 otherwise
558  */
559 static int pred_is_specific_nodeblock(const ir_node *bl, const ir_node *pred,
560         int (*is_op_func)(const ir_node *n))
561 {
562         if (is_Proj(pred)) {
563                 pred = get_Proj_pred(pred);
564                 if ((bl == get_nodes_block(pred)) && is_op_func(pred)) {
565                         return 1;
566                 }
567         }
568
569         return 0;
570 }
571
572
573
574 /**
575  * Checks if irn is a candidate for address calculation or address mode.
576  *
577  * address calculation (AC):
578  * - none of the operand must be a Load  within the same block OR
579  * - all Loads must have more than one user                    OR
580  * - the irn has a frame entity (it's a former FrameAddr)
581  *
582  * address mode (AM):
583  * - at least one operand has to be a Load within the same block AND
584  * - the load must not have other users than the irn             AND
585  * - the irn must not have a frame entity set
586  *
587  * @param block       The block the Loads must/not be in
588  * @param irn         The irn to check
589  * @param check_addr  1 if to check for address calculation, 0 otherwise
590  * return 1 if irn is a candidate for AC or AM, 0 otherwise
591  */
592 static int is_candidate(const ir_node *block, const ir_node *irn, int check_addr) {
593         ir_node *in;
594         int      n, is_cand = check_addr;
595
596         in = get_irn_n(irn, 2);
597
598         if (pred_is_specific_nodeblock(block, in, is_ia32_Ld)) {
599                 n         = ia32_get_irn_n_edges(in);
600                 is_cand   = check_addr ? (n == 1 ? 0 : is_cand) : (n == 1 ? 1 : is_cand);
601         }
602
603         in = get_irn_n(irn, 3);
604
605         if (pred_is_specific_nodeblock(block, in, is_ia32_Ld)) {
606                 n         = ia32_get_irn_n_edges(in);
607                 is_cand   = check_addr ? (n == 1 ? 0 : is_cand) : (n == 1 ? 1 : is_cand);
608         }
609
610         is_cand = get_ia32_frame_ent(irn) ? (check_addr ? 1 : 0) : is_cand;
611
612         return is_cand;
613 }
614
615 /**
616  * Compares the base and index addr and the load/store entities
617  * and returns 1 if they are equal.
618  */
619 static int load_store_addr_is_equal(const ir_node *load, const ir_node *store,
620                                                                         const ir_node *addr_b, const ir_node *addr_i)
621 {
622         int     is_equal = (addr_b == get_irn_n(load, 0)) && (addr_i == get_irn_n(load, 1));
623         entity *lent     = get_ia32_frame_ent(load);
624         entity *sent     = get_ia32_frame_ent(store);
625         ident  *lid      = get_ia32_am_sc(load);
626         ident  *sid      = get_ia32_am_sc(store);
627         char   *loffs    = get_ia32_am_offs(load);
628         char   *soffs    = get_ia32_am_offs(store);
629
630         /* are both entities set and equal? */
631         if (is_equal && (lent || sent))
632                 is_equal = lent && sent && (lent == sent);
633
634         /* are address mode idents set and equal? */
635         if (is_equal && (lid || sid))
636                 is_equal = lid && sid && (lid == sid);
637
638         /* are offsets set and equal */
639         if (is_equal && (loffs || soffs))
640                 is_equal = loffs && soffs && strcmp(loffs, soffs) == 0;
641
642         /* are the load and the store of the same mode? */
643         is_equal = is_equal ? get_ia32_ls_mode(load) == get_ia32_ls_mode(store) : 0;
644
645         return is_equal;
646 }
647
648
649
650 /**
651  * Folds Add or Sub to LEA if possible
652  */
653 static ir_node *fold_addr(ia32_code_gen_t *cg, ir_node *irn, ir_node *noreg) {
654         ir_graph   *irg        = get_irn_irg(irn);
655         dbg_info   *dbg        = get_irn_dbg_info(irn);
656         ir_node    *block      = get_nodes_block(irn);
657         ir_node    *res        = irn;
658         char       *offs       = NULL;
659         const char *offs_cnst  = NULL;
660         char       *offs_lea   = NULL;
661         int         scale      = 0;
662         int         isadd      = 0;
663         int         dolea      = 0;
664         int         have_am_sc = 0;
665         int         am_sc_sign = 0;
666         ident      *am_sc      = NULL;
667         ir_node    *left, *right, *temp;
668         ir_node    *base, *index;
669         ia32_am_flavour_t am_flav;
670         DEBUG_ONLY(firm_dbg_module_t *mod = cg->mod;)
671
672         if (is_ia32_Add(irn))
673                 isadd = 1;
674
675         left  = get_irn_n(irn, 2);
676         right = get_irn_n(irn, 3);
677
678         /* "normalize" arguments in case of add with two operands */
679         if  (isadd && ! be_is_NoReg(cg, right)) {
680                 /* put LEA == ia32_am_O as right operand */
681                 if (is_ia32_Lea(left) && get_ia32_am_flavour(left) == ia32_am_O) {
682                         set_irn_n(irn, 2, right);
683                         set_irn_n(irn, 3, left);
684                         temp  = left;
685                         left  = right;
686                         right = temp;
687                 }
688
689                 /* put LEA != ia32_am_O as left operand */
690                 if (is_ia32_Lea(right) && get_ia32_am_flavour(right) != ia32_am_O) {
691                         set_irn_n(irn, 2, right);
692                         set_irn_n(irn, 3, left);
693                         temp  = left;
694                         left  = right;
695                         right = temp;
696                 }
697
698                 /* put SHL as left operand iff left is NOT a LEA */
699                 if (! is_ia32_Lea(left) && pred_is_specific_node(right, is_ia32_Shl)) {
700                         set_irn_n(irn, 2, right);
701                         set_irn_n(irn, 3, left);
702                         temp  = left;
703                         left  = right;
704                         right = temp;
705                 }
706         }
707
708         base    = left;
709         index   = noreg;
710         offs    = NULL;
711         scale   = 0;
712         am_flav = 0;
713
714         /* check for operation with immediate */
715         if (is_ia32_ImmConst(irn)) {
716                 DBG((mod, LEVEL_1, "\tfound op with imm const"));
717
718                 offs_cnst = get_ia32_cnst(irn);
719                 dolea     = 1;
720         }
721         else if (is_ia32_ImmSymConst(irn)) {
722                 DBG((mod, LEVEL_1, "\tfound op with imm symconst"));
723
724                 have_am_sc = 1;
725                 dolea      = 1;
726                 am_sc      = get_ia32_id_cnst(irn);
727                 am_sc_sign = is_ia32_am_sc_sign(irn);
728         }
729
730         /* determine the operand which needs to be checked */
731         if (be_is_NoReg(cg, right)) {
732                 temp = left;
733         }
734         else {
735                 temp = right;
736         }
737
738         /* check if right operand is AMConst (LEA with ia32_am_O)  */
739         /* but we can only eat it up if there is no other symconst */
740         /* because the linker won't accept two symconsts           */
741         if (! have_am_sc && is_ia32_Lea(temp) && get_ia32_am_flavour(temp) == ia32_am_O) {
742                 DBG((mod, LEVEL_1, "\tgot op with LEA am_O"));
743
744                 offs_lea   = get_ia32_am_offs(temp);
745                 am_sc      = get_ia32_am_sc(temp);
746                 am_sc_sign = is_ia32_am_sc_sign(temp);
747                 have_am_sc = 1;
748                 dolea      = 1;
749         }
750
751         if (isadd) {
752                 /* default for add -> make right operand to index */
753                 index = right;
754                 dolea = 1;
755
756                 DBG((mod, LEVEL_1, "\tgot LEA candidate with index %+F\n", index));
757
758                 /* determine the operand which needs to be checked */
759                 temp = left;
760                 if (is_ia32_Lea(left)) {
761                         temp = right;
762                 }
763
764                 /* check for SHL 1,2,3 */
765                 if (pred_is_specific_node(temp, is_ia32_Shl)) {
766                         temp = get_Proj_pred(temp);
767
768                         if (get_ia32_Immop_tarval(temp)) {
769                                 scale = get_tarval_long(get_ia32_Immop_tarval(temp));
770
771                                 if (scale <= 3) {
772                                         index = get_irn_n(temp, 2);
773
774                                         DBG((mod, LEVEL_1, "\tgot scaled index %+F\n", index));
775                                 }
776                         }
777                 }
778
779                 /* fix base */
780                 if (! be_is_NoReg(cg, index)) {
781                         /* if we have index, but left == right -> no base */
782                         if (left == right) {
783                                 base = noreg;
784                         }
785                         else if (! is_ia32_Lea(left) && (index != right)) {
786                                 /* index != right -> we found a good Shl           */
787                                 /* left  != LEA   -> this Shl was the left operand */
788                                 /* -> base is right operand                        */
789                                 base = right;
790                         }
791                 }
792         }
793
794         /* Try to assimilate a LEA as left operand */
795         if (is_ia32_Lea(left) && (get_ia32_am_flavour(left) != ia32_am_O)) {
796                 ir_node *assim_lea_idx, *assim_lea_base;
797
798                 am_flav        = get_ia32_am_flavour(left);
799                 assim_lea_base = get_irn_n(left, 0);
800                 assim_lea_idx  = get_irn_n(left, 1);
801
802
803                 /* If we have an Add with a real right operand (not NoReg) and  */
804                 /* the LEA contains already an index calculation then we create */
805                 /* a new LEA.                                                   */
806                 /* If the LEA contains already a frame_entity then we also      */
807                 /* create a new one  otherwise we would loose it.               */
808                 if ((isadd && ! be_is_NoReg(cg, index) && (am_flav & ia32_I)) || /* no new LEA if index already set */
809                         get_ia32_frame_ent(left)                                  || /* no new LEA if stack access */
810                         (have_am_sc && get_ia32_am_sc(left))                      || /* no new LEA if AM symconst already present */
811                         /* at least on of the LEA operands must be NOREG */
812                         (!be_is_NoReg(cg, assim_lea_base) && !be_is_NoReg(cg, assim_lea_idx)))
813                 {
814                         DBG((mod, LEVEL_1, "\tleave old LEA, creating new one\n"));
815                 }
816                 else {
817                         DBG((mod, LEVEL_1, "\tgot LEA as left operand ... assimilating\n"));
818                         offs       = get_ia32_am_offs(left);
819                         am_sc      = have_am_sc ? am_sc : get_ia32_am_sc(left);
820                         have_am_sc = am_sc ? 1 : 0;
821                         am_sc_sign = is_ia32_am_sc_sign(left);
822                         scale      = get_ia32_am_scale(left);
823
824                         if (be_is_NoReg(cg, assim_lea_base) && ! be_is_NoReg(cg, assim_lea_idx)) {
825                                 /* assimilate index */
826                                 assert(be_is_NoReg(cg, index) && ! be_is_NoReg(cg, base) && "operand mismatch for LEA assimilation");
827                                 index = assim_lea_idx;
828                         }
829                         else if (! be_is_NoReg(cg, assim_lea_base) && be_is_NoReg(cg, assim_lea_idx)) {
830                                 /* assimilate base */
831                                 assert(! be_is_NoReg(cg, index) && (base == left) && "operand mismatch for LEA assimilation");
832                                 base = assim_lea_base;
833                         }
834                 }
835         }
836
837         /* ok, we can create a new LEA */
838         if (dolea) {
839                 res = new_rd_ia32_Lea(dbg, irg, block, base, index, mode_Is);
840
841                 /* add the old offset of a previous LEA */
842                 if (offs) {
843                         add_ia32_am_offs(res, offs);
844                 }
845
846                 /* add the new offset */
847                 if (isadd) {
848                         if (offs_cnst) {
849                                 add_ia32_am_offs(res, offs_cnst);
850                         }
851                         if (offs_lea) {
852                                 add_ia32_am_offs(res, offs_lea);
853                         }
854                 }
855                 else {
856                         /* either lea_O-cnst, -cnst or -lea_O  */
857                         if (offs_cnst) {
858                                 if (offs_lea) {
859                                         add_ia32_am_offs(res, offs_lea);
860                                 }
861
862                                 sub_ia32_am_offs(res, offs_cnst);
863                         }
864                         else {
865                                 sub_ia32_am_offs(res, offs_lea);
866                         }
867                 }
868
869                 /* set the address mode symconst */
870                 if (have_am_sc) {
871                         set_ia32_am_sc(res, am_sc);
872                         if (am_sc_sign)
873                                 set_ia32_am_sc_sign(res);
874                 }
875
876                 /* copy the frame entity (could be set in case of Add */
877                 /* which was a FrameAddr) */
878                 set_ia32_frame_ent(res, get_ia32_frame_ent(irn));
879
880                 if (is_ia32_use_frame(irn))
881                         set_ia32_use_frame(res);
882
883                 /* set scale */
884                 set_ia32_am_scale(res, scale);
885
886                 am_flav = ia32_am_N;
887                 /* determine new am flavour */
888                 if (offs || offs_cnst || offs_lea) {
889                         am_flav |= ia32_O;
890                 }
891                 if (! be_is_NoReg(cg, base)) {
892                         am_flav |= ia32_B;
893                 }
894                 if (! be_is_NoReg(cg, index)) {
895                         am_flav |= ia32_I;
896                 }
897                 if (scale > 0) {
898                         am_flav |= ia32_S;
899                 }
900                 set_ia32_am_flavour(res, am_flav);
901
902                 set_ia32_op_type(res, ia32_AddrModeS);
903
904                 SET_IA32_ORIG_NODE(res, ia32_get_old_node_name(cg, irn));
905
906                 DBG((mod, LEVEL_1, "\tLEA [%+F + %+F * %d + %s]\n", base, index, scale, get_ia32_am_offs(res)));
907
908                 /* we will exchange it, report here before the Proj is created */
909                 DBG_OPT_LEA(irn, res);
910
911                 /* get the result Proj of the Add/Sub */
912                 irn = get_res_proj(irn);
913
914                 assert(irn && "Couldn't find result proj");
915
916                 /* exchange the old op with the new LEA */
917                 exchange(irn, res);
918         }
919
920         return res;
921 }
922
923 /**
924  * Optimizes a pattern around irn to address mode if possible.
925  */
926 void ia32_optimize_am(ir_node *irn, void *env) {
927         ia32_code_gen_t   *cg   = env;
928         ir_node           *res  = irn;
929         dbg_info          *dbg;
930         ir_mode           *mode;
931         ir_node           *block, *noreg_gp, *noreg_fp;
932         ir_node           *left, *right, *temp;
933         ir_node           *store, *load, *mem_proj;
934         ir_node           *succ, *addr_b, *addr_i;
935         int                check_am_src = 0;
936         DEBUG_ONLY(firm_dbg_module_t *mod = cg->mod;)
937
938         if (! is_ia32_irn(irn))
939                 return;
940
941         dbg      = get_irn_dbg_info(irn);
942         mode     = get_irn_mode(irn);
943         block    = get_nodes_block(irn);
944         noreg_gp = ia32_new_NoReg_gp(cg);
945         noreg_fp = ia32_new_NoReg_fp(cg);
946
947         DBG((mod, LEVEL_1, "checking for AM\n"));
948
949         /* 1st part: check for address calculations and transform the into Lea */
950
951         /* Following cases can occur:                                  */
952         /* - Sub (l, imm) -> LEA [base - offset]                       */
953         /* - Sub (l, r == LEA with ia32_am_O)   -> LEA [base - offset] */
954         /* - Add (l, imm) -> LEA [base + offset]                       */
955         /* - Add (l, r == LEA with ia32_am_O)  -> LEA [base + offset]  */
956         /* - Add (l == LEA with ia32_am_O, r)  -> LEA [base + offset]  */
957         /* - Add (l, r) -> LEA [base + index * scale]                  */
958         /*              with scale > 1 iff l/r == shl (1,2,3)          */
959
960         if (is_ia32_Sub(irn) || is_ia32_Add(irn)) {
961                 left  = get_irn_n(irn, 2);
962                 right = get_irn_n(irn, 3);
963
964             /* Do not try to create a LEA if one of the operands is a Load. */
965                 /* check is irn is a candidate for address calculation */
966                 if (is_candidate(block, irn, 1)) {
967                         DBG((mod, LEVEL_1, "\tfound address calculation candidate %+F ... ", irn));
968                         res = fold_addr(cg, irn, noreg_gp);
969
970                         if (res == irn)
971                                 DB((mod, LEVEL_1, "transformed into %+F\n", res));
972                         else
973                                 DB((mod, LEVEL_1, "not transformed\n"));
974                 }
975         }
976
977         /* 2nd part: fold following patterns:                                               */
978         /* - Load  -> LEA into Load  } TODO: If the LEA is used by more than one Load/Store */
979         /* - Store -> LEA into Store }       it might be better to keep the LEA             */
980         /* - op -> Load into AMop with am_Source                                            */
981         /*   conditions:                                                                    */
982         /*     - op is am_Source capable AND                                                */
983         /*     - the Load is only used by this op AND                                       */
984         /*     - the Load is in the same block                                              */
985         /* - Store -> op -> Load  into AMop with am_Dest                                    */
986         /*   conditions:                                                                    */
987         /*     - op is am_Dest capable AND                                                  */
988         /*     - the Store uses the same address as the Load AND                            */
989         /*     - the Load is only used by this op AND                                       */
990         /*     - the Load and Store are in the same block AND                               */
991         /*     - nobody else uses the result of the op                                      */
992
993         if ((res == irn) && (get_ia32_am_support(irn) != ia32_am_None) && !is_ia32_Lea(irn)) {
994                 /* 1st: check for Load/Store -> LEA   */
995                 if (is_ia32_Ld(irn) || is_ia32_St(irn) || is_ia32_Store8Bit(irn)) {
996                         left = get_irn_n(irn, 0);
997
998                         if (is_ia32_Lea(left)) {
999                                 DBG((mod, LEVEL_1, "\nmerging %+F into %+F\n", left, irn));
1000
1001                                 /* get the AM attributes from the LEA */
1002                                 add_ia32_am_offs(irn, get_ia32_am_offs(left));
1003                                 set_ia32_am_scale(irn, get_ia32_am_scale(left));
1004                                 set_ia32_am_flavour(irn, get_ia32_am_flavour(left));
1005
1006                                 set_ia32_am_sc(irn, get_ia32_am_sc(left));
1007                                 if (is_ia32_am_sc_sign(left))
1008                                         set_ia32_am_sc_sign(irn);
1009
1010                                 set_ia32_op_type(irn, is_ia32_Ld(irn) ? ia32_AddrModeS : ia32_AddrModeD);
1011
1012                                 /* set base and index */
1013                                 set_irn_n(irn, 0, get_irn_n(left, 0));
1014                                 set_irn_n(irn, 1, get_irn_n(left, 1));
1015
1016                                 /* clear remat flag */
1017                                 set_ia32_flags(irn, get_ia32_flags(irn) & ~arch_irn_flags_rematerializable);
1018                         }
1019                 }
1020                 /* check if the node is an address mode candidate */
1021                 else if (is_candidate(block, irn, 0)) {
1022                         DBG((mod, LEVEL_1, "\tfound address mode candidate %+F ... ", irn));
1023
1024                         left  = get_irn_n(irn, 2);
1025                         if (get_irn_arity(irn) == 4) {
1026                                 /* it's an "unary" operation */
1027                                 right = left;
1028                         }
1029                         else {
1030                                 right = get_irn_n(irn, 3);
1031                         }
1032
1033                         /* normalize commutative ops */
1034                         if (node_is_ia32_comm(irn)) {
1035                                 /* Assure that right operand is always a Load if there is one    */
1036                                 /* because non-commutative ops can only use Dest AM if the right */
1037                                 /* operand is a load, so we only need to check right operand.    */
1038                                 if (pred_is_specific_nodeblock(block, left, is_ia32_Ld))
1039                                 {
1040                                         set_irn_n(irn, 2, right);
1041                                         set_irn_n(irn, 3, left);
1042
1043                                         temp  = left;
1044                                         left  = right;
1045                                         right = temp;
1046                                 }
1047                         }
1048
1049                         /* check for Store -> op -> Load */
1050
1051                         /* Store -> op -> Load optimization is only possible if supported by op */
1052                         /* and if right operand is a Load                                       */
1053                         if ((get_ia32_am_support(irn) & ia32_am_Dest) &&
1054                                  pred_is_specific_nodeblock(block, right, is_ia32_Ld))
1055                         {
1056
1057                                 /* An address mode capable op always has a result Proj.                  */
1058                                 /* If this Proj is used by more than one other node, we don't need to    */
1059                                 /* check further, otherwise we check for Store and remember the address, */
1060                                 /* the Store points to. */
1061
1062                                 succ = get_res_proj(irn);
1063                                 assert(succ && "Couldn't find result proj");
1064
1065                                 addr_b = NULL;
1066                                 addr_i = NULL;
1067                                 store  = NULL;
1068
1069                                 /* now check for users and Store */
1070                                 if (ia32_get_irn_n_edges(succ) == 1) {
1071                                         succ = get_edge_src_irn(get_irn_out_edge_first(succ));
1072
1073                                         if (is_ia32_fStore(succ) || is_ia32_Store(succ)) {
1074                                                 store  = succ;
1075                                                 addr_b = get_irn_n(store, 0);
1076
1077                                                 /* Could be that the Store is connected to the address    */
1078                                                 /* calculating LEA while the Load is already transformed. */
1079                                                 if (is_ia32_Lea(addr_b)) {
1080                                                         succ   = addr_b;
1081                                                         addr_b = get_irn_n(succ, 0);
1082                                                         addr_i = get_irn_n(succ, 1);
1083                                                 }
1084                                                 else {
1085                                                         addr_i = noreg_gp;
1086                                                 }
1087                                         }
1088                                 }
1089
1090                                 if (store) {
1091                                         /* we found a Store as single user: Now check for Load */
1092
1093                                         /* Extra check for commutative ops with two Loads */
1094                                         /* -> put the interesting Load right              */
1095                                         if (node_is_ia32_comm(irn) &&
1096                                                 pred_is_specific_nodeblock(block, left, is_ia32_Ld))
1097                                         {
1098                                                 if ((addr_b == get_irn_n(get_Proj_pred(left), 0)) &&
1099                                                         (addr_i == get_irn_n(get_Proj_pred(left), 1)))
1100                                                 {
1101                                                         /* We exchange left and right, so it's easier to kill     */
1102                                                         /* the correct Load later and to handle unary operations. */
1103                                                         set_irn_n(irn, 2, right);
1104                                                         set_irn_n(irn, 3, left);
1105
1106                                                         temp  = left;
1107                                                         left  = right;
1108                                                         right = temp;
1109                                                 }
1110                                         }
1111
1112                                         /* skip the Proj for easier access */
1113                                         load = get_Proj_pred(right);
1114
1115                                         /* Compare Load and Store address */
1116                                         if (load_store_addr_is_equal(load, store, addr_b, addr_i)) {
1117                                                 /* Right Load is from same address, so we can */
1118                                                 /* disconnect the Load and Store here        */
1119
1120                                                 /* set new base, index and attributes */
1121                                                 set_irn_n(irn, 0, addr_b);
1122                                                 set_irn_n(irn, 1, addr_i);
1123                                                 add_ia32_am_offs(irn, get_ia32_am_offs(load));
1124                                                 set_ia32_am_scale(irn, get_ia32_am_scale(load));
1125                                                 set_ia32_am_flavour(irn, get_ia32_am_flavour(load));
1126                                                 set_ia32_op_type(irn, ia32_AddrModeD);
1127                                                 set_ia32_frame_ent(irn, get_ia32_frame_ent(load));
1128                                                 set_ia32_ls_mode(irn, get_ia32_ls_mode(load));
1129
1130                                                 set_ia32_am_sc(irn, get_ia32_am_sc(load));
1131                                                 if (is_ia32_am_sc_sign(load))
1132                                                         set_ia32_am_sc_sign(irn);
1133
1134                                                 if (is_ia32_use_frame(load))
1135                                                         set_ia32_use_frame(irn);
1136
1137                                                 /* connect to Load memory and disconnect Load */
1138                                                 if (get_irn_arity(irn) == 5) {
1139                                                         /* binary AMop */
1140                                                         set_irn_n(irn, 4, get_irn_n(load, 2));
1141                                                         set_irn_n(irn, 3, noreg_gp);
1142                                                 }
1143                                                 else {
1144                                                         /* unary AMop */
1145                                                         set_irn_n(irn, 3, get_irn_n(load, 2));
1146                                                         set_irn_n(irn, 2, noreg_gp);
1147                                                 }
1148
1149                                                 /* connect the memory Proj of the Store to the op */
1150                                                 mem_proj = get_mem_proj(store);
1151                                                 set_Proj_pred(mem_proj, irn);
1152                                                 set_Proj_proj(mem_proj, 1);
1153
1154                                                 /* clear remat flag */
1155                                                 set_ia32_flags(irn, get_ia32_flags(irn) & ~arch_irn_flags_rematerializable);
1156
1157                                                 DB((mod, LEVEL_1, "merged with %+F and %+F into dest AM\n", load, store));
1158                                         }
1159                                 } /* if (store) */
1160                                 else if (get_ia32_am_support(irn) & ia32_am_Source) {
1161                                         /* There was no store, check if we still can optimize for source address mode */
1162                                         check_am_src = 1;
1163                                 }
1164                         } /* if (support AM Dest) */
1165                         else if (get_ia32_am_support(irn) & ia32_am_Source) {
1166                                 /* op doesn't support am AM Dest -> check for AM Source */
1167                                 check_am_src = 1;
1168                         }
1169
1170                         /* normalize commutative ops */
1171                         if (node_is_ia32_comm(irn)) {
1172                                 /* Assure that left operand is always a Load if there is one */
1173                                 /* because non-commutative ops can only use Source AM if the */
1174                                 /* left operand is a Load, so we only need to check the left */
1175                                 /* operand afterwards.                                       */
1176                                 if (pred_is_specific_nodeblock(block, right, is_ia32_Ld))       {
1177                                         set_irn_n(irn, 2, right);
1178                                         set_irn_n(irn, 3, left);
1179
1180                                         temp  = left;
1181                                         left  = right;
1182                                         right = temp;
1183                                 }
1184                         }
1185
1186                         /* optimize op -> Load iff Load is only used by this op   */
1187                         /* and left operand is a Load which only used by this irn */
1188                         if (check_am_src                                        &&
1189                                 pred_is_specific_nodeblock(block, left, is_ia32_Ld) &&
1190                                 (ia32_get_irn_n_edges(left) == 1))
1191                         {
1192                                 left = get_Proj_pred(left);
1193
1194                                 addr_b = get_irn_n(left, 0);
1195                                 addr_i = get_irn_n(left, 1);
1196
1197                                 /* set new base, index and attributes */
1198                                 set_irn_n(irn, 0, addr_b);
1199                                 set_irn_n(irn, 1, addr_i);
1200                                 add_ia32_am_offs(irn, get_ia32_am_offs(left));
1201                                 set_ia32_am_scale(irn, get_ia32_am_scale(left));
1202                                 set_ia32_am_flavour(irn, get_ia32_am_flavour(left));
1203                                 set_ia32_op_type(irn, ia32_AddrModeS);
1204                                 set_ia32_frame_ent(irn, get_ia32_frame_ent(left));
1205                                 set_ia32_ls_mode(irn, get_ia32_ls_mode(left));
1206
1207                                 set_ia32_am_sc(irn, get_ia32_am_sc(left));
1208                                 if (is_ia32_am_sc_sign(left))
1209                                         set_ia32_am_sc_sign(irn);
1210
1211                                 /* clear remat flag */
1212                                 set_ia32_flags(irn, get_ia32_flags(irn) & ~arch_irn_flags_rematerializable);
1213
1214                                 if (is_ia32_use_frame(left))
1215                                         set_ia32_use_frame(irn);
1216
1217                                 /* connect to Load memory */
1218                                 if (get_irn_arity(irn) == 5) {
1219                                         /* binary AMop */
1220                                         set_irn_n(irn, 4, get_irn_n(left, 2));
1221                                 }
1222                                 else {
1223                                         /* unary AMop */
1224                                         set_irn_n(irn, 3, get_irn_n(left, 2));
1225                                 }
1226
1227                                 /* disconnect from Load */
1228                                 set_irn_n(irn, 2, noreg_gp);
1229
1230                                 /* If Load has a memory Proj, connect it to the op */
1231                                 mem_proj = get_mem_proj(left);
1232                                 if (mem_proj) {
1233                                         set_Proj_pred(mem_proj, irn);
1234                                         set_Proj_proj(mem_proj, 1);
1235                                 }
1236
1237                                 DB((mod, LEVEL_1, "merged with %+F into source AM\n", left));
1238                         }
1239                 }
1240         }
1241 }