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