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