6d7c40fe6cb3431f0156b4480f863682aecd2165
[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         DEBUG_ONLY(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  * Tries to optimize two following IncSP.
402  */
403 static void ia32_optimize_IncSP(ir_node *irn, ia32_code_gen_t *cg) {
404         ir_node *prev = be_get_IncSP_pred(irn);
405         int real_uses = get_irn_n_edges(prev);
406
407         if (real_uses != 1) {
408                 /*
409                    This is a hack that should be removed if be_abi_fix_stack_nodes()
410                    is fixed. Currently it leaves some IncSP's outside the chain ...
411                    The previous IncSp is NOT our prev, but directly scheduled before ...
412                          Impossible in a bug-free implementation :-)
413                  */
414                 prev = sched_prev(irn);
415                 real_uses = 1;
416         }
417
418         if (be_is_IncSP(prev) && real_uses == 1) {
419                 /* first IncSP has only one IncSP user, kill the first one */
420                 unsigned       prev_offs = be_get_IncSP_offset(prev);
421                 be_stack_dir_t prev_dir  = be_get_IncSP_direction(prev);
422                 unsigned       curr_offs = be_get_IncSP_offset(irn);
423                 be_stack_dir_t curr_dir  = be_get_IncSP_direction(irn);
424
425                 int new_ofs = prev_offs * (prev_dir == be_stack_dir_expand ? -1 : +1) +
426                                     curr_offs * (curr_dir == be_stack_dir_expand ? -1 : +1);
427
428                 if (new_ofs < 0) {
429                         new_ofs  = -new_ofs;
430                         curr_dir = be_stack_dir_expand;
431                 }
432                 else
433                         curr_dir = be_stack_dir_shrink;
434                 be_set_IncSP_offset(prev, 0);
435                 be_set_IncSP_offset(irn, (unsigned)new_ofs);
436                 be_set_IncSP_direction(irn, curr_dir);
437         }
438 }
439
440 /**
441  * Performs Peephole Optimizations.
442  */
443 void ia32_peephole_optimization(ir_node *irn, void *env) {
444         ia32_code_gen_t *cg = env;
445
446         if (is_ia32_TestJmp(irn))
447                 ia32_optimize_TestJmp(irn, cg);
448         else if (is_ia32_CondJmp(irn))
449                 ia32_optimize_CondJmp(irn, cg);
450         else if (be_is_IncSP(irn))
451                 ia32_optimize_IncSP(irn, cg);
452 }
453
454
455
456 /******************************************************************
457  *              _     _                   __  __           _
458  *     /\      | |   | |                 |  \/  |         | |
459  *    /  \   __| | __| |_ __ ___  ___ ___| \  / | ___   __| | ___
460  *   / /\ \ / _` |/ _` | '__/ _ \/ __/ __| |\/| |/ _ \ / _` |/ _ \
461  *  / ____ \ (_| | (_| | | |  __/\__ \__ \ |  | | (_) | (_| |  __/
462  * /_/    \_\__,_|\__,_|_|  \___||___/___/_|  |_|\___/ \__,_|\___|
463  *
464  ******************************************************************/
465
466 static int node_is_ia32_comm(const ir_node *irn) {
467         return is_ia32_irn(irn) ? is_ia32_commutative(irn) : 0;
468 }
469
470 static int ia32_get_irn_n_edges(const ir_node *irn) {
471         const ir_edge_t *edge;
472         int cnt = 0;
473
474         foreach_out_edge(irn, edge) {
475                 cnt++;
476         }
477
478         return cnt;
479 }
480
481 /**
482  * Returns the first mode_M Proj connected to irn.
483  */
484 static ir_node *get_mem_proj(const ir_node *irn) {
485         const ir_edge_t *edge;
486         ir_node         *src;
487
488         assert(get_irn_mode(irn) == mode_T && "expected mode_T node");
489
490         foreach_out_edge(irn, edge) {
491                 src = get_edge_src_irn(edge);
492
493                 assert(is_Proj(src) && "Proj expected");
494
495                 if (get_irn_mode(src) == mode_M)
496                         return src;
497         }
498
499         return NULL;
500 }
501
502 /**
503  * Returns the first Proj with mode != mode_M connected to irn.
504  */
505 static ir_node *get_res_proj(const ir_node *irn) {
506         const ir_edge_t *edge;
507         ir_node         *src;
508
509         assert(get_irn_mode(irn) == mode_T && "expected mode_T node");
510
511         foreach_out_edge(irn, edge) {
512                 src = get_edge_src_irn(edge);
513
514                 assert(is_Proj(src) && "Proj expected");
515
516                 if (get_irn_mode(src) != mode_M)
517                         return src;
518         }
519
520         return NULL;
521 }
522
523 /**
524  * Determines if pred is a Proj and if is_op_func returns true for it's predecessor.
525  *
526  * @param pred       The node to be checked
527  * @param is_op_func The check-function
528  * @return 1 if conditions are fulfilled, 0 otherwise
529  */
530 static int pred_is_specific_node(const ir_node *pred, is_op_func_t *is_op_func) {
531         if (is_Proj(pred) && is_op_func(get_Proj_pred(pred))) {
532                 return 1;
533         }
534
535         return 0;
536 }
537
538 /**
539  * Determines if pred is a Proj and if is_op_func returns true for it's predecessor
540  * and if the predecessor is in block bl.
541  *
542  * @param bl         The block
543  * @param pred       The node to be checked
544  * @param is_op_func The check-function
545  * @return 1 if conditions are fulfilled, 0 otherwise
546  */
547 static int pred_is_specific_nodeblock(const ir_node *bl, const ir_node *pred,
548         int (*is_op_func)(const ir_node *n))
549 {
550         if (is_Proj(pred)) {
551                 pred = get_Proj_pred(pred);
552                 if ((bl == get_nodes_block(pred)) && is_op_func(pred)) {
553                         return 1;
554                 }
555         }
556
557         return 0;
558 }
559
560
561
562 /**
563  * Checks if irn is a candidate for address calculation or address mode.
564  *
565  * address calculation (AC):
566  * - none of the operand must be a Load  within the same block OR
567  * - all Loads must have more than one user                    OR
568  * - the irn has a frame entity (it's a former FrameAddr)
569  *
570  * address mode (AM):
571  * - at least one operand has to be a Load within the same block AND
572  * - the load must not have other users than the irn             AND
573  * - the irn must not have a frame entity set
574  *
575  * @param block       The block the Loads must/not be in
576  * @param irn         The irn to check
577  * @param check_addr  1 if to check for address calculation, 0 otherwise
578  * return 1 if irn is a candidate for AC or AM, 0 otherwise
579  */
580 static int is_candidate(const ir_node *block, const ir_node *irn, int check_addr) {
581         ir_node *in;
582         int      n, is_cand = check_addr;
583
584         in = get_irn_n(irn, 2);
585
586         if (pred_is_specific_nodeblock(block, in, is_ia32_Ld)) {
587                 n         = ia32_get_irn_n_edges(in);
588                 is_cand   = check_addr ? (n == 1 ? 0 : is_cand) : (n == 1 ? 1 : is_cand);
589         }
590
591         in = get_irn_n(irn, 3);
592
593         if (pred_is_specific_nodeblock(block, in, is_ia32_Ld)) {
594                 n         = ia32_get_irn_n_edges(in);
595                 is_cand   = check_addr ? (n == 1 ? 0 : is_cand) : (n == 1 ? 1 : is_cand);
596         }
597
598         is_cand = get_ia32_frame_ent(irn) ? (check_addr ? 1 : 0) : is_cand;
599
600         return is_cand;
601 }
602
603 /**
604  * Compares the base and index addr and the load/store entities
605  * and returns 1 if they are equal.
606  */
607 static int load_store_addr_is_equal(const ir_node *load, const ir_node *store,
608                                                                         const ir_node *addr_b, const ir_node *addr_i)
609 {
610         int     is_equal = (addr_b == get_irn_n(load, 0)) && (addr_i == get_irn_n(load, 1));
611         entity *lent     = get_ia32_frame_ent(load);
612         entity *sent     = get_ia32_frame_ent(store);
613         ident  *lid      = get_ia32_am_sc(load);
614         ident  *sid      = get_ia32_am_sc(store);
615         char   *loffs    = get_ia32_am_offs(load);
616         char   *soffs    = get_ia32_am_offs(store);
617
618         /* are both entities set and equal? */
619         if (is_equal && (lent || sent))
620                 is_equal = lent && sent && (lent == sent);
621
622         /* are address mode idents set and equal? */
623         if (is_equal && (lid || sid))
624                 is_equal = lid && sid && (lid == sid);
625
626         /* are offsets set and equal */
627         if (is_equal && (loffs || soffs))
628                 is_equal = loffs && soffs && strcmp(loffs, soffs) == 0;
629
630         /* are the load and the store of the same mode? */
631         is_equal = is_equal ? get_ia32_ls_mode(load) == get_ia32_ls_mode(store) : 0;
632
633         return is_equal;
634 }
635
636
637
638 /**
639  * Folds Add or Sub to LEA if possible
640  */
641 static ir_node *fold_addr(ia32_code_gen_t *cg, ir_node *irn, ir_node *noreg) {
642         ir_graph   *irg        = get_irn_irg(irn);
643         dbg_info   *dbg        = get_irn_dbg_info(irn);
644         ir_node    *block      = get_nodes_block(irn);
645         ir_node    *res        = irn;
646         char       *offs       = NULL;
647         const char *offs_cnst  = NULL;
648         char       *offs_lea   = NULL;
649         int         scale      = 0;
650         int         isadd      = 0;
651         int         dolea      = 0;
652         int         have_am_sc = 0;
653         int         am_sc_sign = 0;
654         ident      *am_sc      = NULL;
655         ir_node    *left, *right, *temp;
656         ir_node    *base, *index;
657         ia32_am_flavour_t am_flav;
658         DEBUG_ONLY(firm_dbg_module_t *mod = cg->mod;)
659
660         if (is_ia32_Add(irn))
661                 isadd = 1;
662
663         left  = get_irn_n(irn, 2);
664         right = get_irn_n(irn, 3);
665
666         /* "normalize" arguments in case of add with two operands */
667         if  (isadd && ! be_is_NoReg(cg, right)) {
668                 /* put LEA == ia32_am_O as right operand */
669                 if (is_ia32_Lea(left) && get_ia32_am_flavour(left) == ia32_am_O) {
670                         set_irn_n(irn, 2, right);
671                         set_irn_n(irn, 3, left);
672                         temp  = left;
673                         left  = right;
674                         right = temp;
675                 }
676
677                 /* put LEA != ia32_am_O as left operand */
678                 if (is_ia32_Lea(right) && get_ia32_am_flavour(right) != ia32_am_O) {
679                         set_irn_n(irn, 2, right);
680                         set_irn_n(irn, 3, left);
681                         temp  = left;
682                         left  = right;
683                         right = temp;
684                 }
685
686                 /* put SHL as left operand iff left is NOT a LEA */
687                 if (! is_ia32_Lea(left) && pred_is_specific_node(right, is_ia32_Shl)) {
688                         set_irn_n(irn, 2, right);
689                         set_irn_n(irn, 3, left);
690                         temp  = left;
691                         left  = right;
692                         right = temp;
693                 }
694         }
695
696         base    = left;
697         index   = noreg;
698         offs    = NULL;
699         scale   = 0;
700         am_flav = 0;
701
702         /* check for operation with immediate */
703         if (is_ia32_ImmConst(irn)) {
704                 DBG((mod, LEVEL_1, "\tfound op with imm const"));
705
706                 offs_cnst = get_ia32_cnst(irn);
707                 dolea     = 1;
708         }
709         else if (is_ia32_ImmSymConst(irn)) {
710                 DBG((mod, LEVEL_1, "\tfound op with imm symconst"));
711
712                 have_am_sc = 1;
713                 dolea      = 1;
714                 am_sc      = get_ia32_id_cnst(irn);
715                 am_sc_sign = is_ia32_am_sc_sign(irn);
716         }
717
718         /* determine the operand which needs to be checked */
719         if (be_is_NoReg(cg, right)) {
720                 temp = left;
721         }
722         else {
723                 temp = right;
724         }
725
726         /* check if right operand is AMConst (LEA with ia32_am_O)  */
727         /* but we can only eat it up if there is no other symconst */
728         /* because the linker won't accept two symconsts           */
729         if (! have_am_sc && is_ia32_Lea(temp) && get_ia32_am_flavour(temp) == ia32_am_O) {
730                 DBG((mod, LEVEL_1, "\tgot op with LEA am_O"));
731
732                 offs_lea   = get_ia32_am_offs(temp);
733                 am_sc      = get_ia32_am_sc(temp);
734                 am_sc_sign = is_ia32_am_sc_sign(temp);
735                 have_am_sc = 1;
736                 dolea      = 1;
737         }
738
739         if (isadd) {
740                 /* default for add -> make right operand to index */
741                 index = right;
742                 dolea = 1;
743
744                 DBG((mod, LEVEL_1, "\tgot LEA candidate with index %+F\n", index));
745
746                 /* determine the operand which needs to be checked */
747                 temp = left;
748                 if (is_ia32_Lea(left)) {
749                         temp = right;
750                 }
751
752                 /* check for SHL 1,2,3 */
753                 if (pred_is_specific_node(temp, is_ia32_Shl)) {
754                         temp = get_Proj_pred(temp);
755
756                         if (get_ia32_Immop_tarval(temp)) {
757                                 scale = get_tarval_long(get_ia32_Immop_tarval(temp));
758
759                                 if (scale <= 3) {
760                                         index = get_irn_n(temp, 2);
761
762                                         DBG((mod, LEVEL_1, "\tgot scaled index %+F\n", index));
763                                 }
764                         }
765                 }
766
767                 /* fix base */
768                 if (! be_is_NoReg(cg, index)) {
769                         /* if we have index, but left == right -> no base */
770                         if (left == right) {
771                                 base = noreg;
772                         }
773                         else if (! is_ia32_Lea(left) && (index != right)) {
774                                 /* index != right -> we found a good Shl           */
775                                 /* left  != LEA   -> this Shl was the left operand */
776                                 /* -> base is right operand                        */
777                                 base = right;
778                         }
779                 }
780         }
781
782         /* Try to assimilate a LEA as left operand */
783         if (is_ia32_Lea(left) && (get_ia32_am_flavour(left) != ia32_am_O)) {
784                 am_flav = get_ia32_am_flavour(left);
785
786                 /* If we have an Add with a real right operand (not NoReg) and  */
787                 /* the LEA contains already an index calculation then we create */
788                 /* a new LEA.                                                   */
789                 /* If the LEA contains already a frame_entity then we also      */
790                 /* create a new one  otherwise we would loose it.               */
791                 if ((isadd && !be_is_NoReg(cg, index) && (am_flav & ia32_am_I)) || /* no new LEA if index already set */
792                         get_ia32_frame_ent(left)                                    || /* no new LEA if stack access */
793                         (have_am_sc && get_ia32_am_sc(left)))                          /* no new LEA if AM symconst already present */
794                 {
795                         DBG((mod, LEVEL_1, "\tleave old LEA, creating new one\n"));
796                 }
797                 else {
798                         DBG((mod, LEVEL_1, "\tgot LEA as left operand ... assimilating\n"));
799                         offs       = get_ia32_am_offs(left);
800                         am_sc      = have_am_sc ? am_sc : get_ia32_am_sc(left);
801                         have_am_sc = am_sc ? 1 : 0;
802                         am_sc_sign = is_ia32_am_sc_sign(left);
803                         base       = get_irn_n(left, 0);
804                         index      = get_irn_n(left, 1);
805                         scale      = get_ia32_am_scale(left);
806                 }
807         }
808
809         /* ok, we can create a new LEA */
810         if (dolea) {
811                 res = new_rd_ia32_Lea(dbg, irg, block, base, index, mode_Is);
812
813                 /* add the old offset of a previous LEA */
814                 if (offs) {
815                         add_ia32_am_offs(res, offs);
816                 }
817
818                 /* add the new offset */
819                 if (isadd) {
820                         if (offs_cnst) {
821                                 add_ia32_am_offs(res, offs_cnst);
822                         }
823                         if (offs_lea) {
824                                 add_ia32_am_offs(res, offs_lea);
825                         }
826                 }
827                 else {
828                         /* either lea_O-cnst, -cnst or -lea_O  */
829                         if (offs_cnst) {
830                                 if (offs_lea) {
831                                         add_ia32_am_offs(res, offs_lea);
832                                 }
833
834                                 sub_ia32_am_offs(res, offs_cnst);
835                         }
836                         else {
837                                 sub_ia32_am_offs(res, offs_lea);
838                         }
839                 }
840
841                 /* set the address mode symconst */
842                 if (have_am_sc) {
843                         set_ia32_am_sc(res, am_sc);
844                         if (am_sc_sign)
845                                 set_ia32_am_sc_sign(res);
846                 }
847
848                 /* copy the frame entity (could be set in case of Add */
849                 /* which was a FrameAddr) */
850                 set_ia32_frame_ent(res, get_ia32_frame_ent(irn));
851
852                 if (is_ia32_use_frame(irn))
853                         set_ia32_use_frame(res);
854
855                 /* set scale */
856                 set_ia32_am_scale(res, scale);
857
858                 am_flav = ia32_am_N;
859                 /* determine new am flavour */
860                 if (offs || offs_cnst || offs_lea) {
861                         am_flav |= ia32_O;
862                 }
863                 if (! be_is_NoReg(cg, base)) {
864                         am_flav |= ia32_B;
865                 }
866                 if (! be_is_NoReg(cg, index)) {
867                         am_flav |= ia32_I;
868                 }
869                 if (scale > 0) {
870                         am_flav |= ia32_S;
871                 }
872                 set_ia32_am_flavour(res, am_flav);
873
874                 set_ia32_op_type(res, ia32_AddrModeS);
875
876                 DBG((mod, LEVEL_1, "\tLEA [%+F + %+F * %d + %s]\n", base, index, scale, get_ia32_am_offs(res)));
877
878                 /* get the result Proj of the Add/Sub */
879                 irn = get_res_proj(irn);
880
881                 assert(irn && "Couldn't find result proj");
882
883                 /* exchange the old op with the new LEA */
884                 exchange(irn, res);
885         }
886
887         return res;
888 }
889
890 /**
891  * Optimizes a pattern around irn to address mode if possible.
892  */
893 void ia32_optimize_am(ir_node *irn, void *env) {
894         ia32_code_gen_t   *cg   = env;
895         ir_node           *res  = irn;
896         dbg_info          *dbg;
897         ir_mode           *mode;
898         ir_node           *block, *noreg_gp, *noreg_fp;
899         ir_node           *left, *right, *temp;
900         ir_node           *store, *load, *mem_proj;
901         ir_node           *succ, *addr_b, *addr_i;
902         int                check_am_src = 0;
903         DEBUG_ONLY(firm_dbg_module_t *mod = cg->mod;)
904
905         if (! is_ia32_irn(irn))
906                 return;
907
908         dbg      = get_irn_dbg_info(irn);
909         mode     = get_irn_mode(irn);
910         block    = get_nodes_block(irn);
911         noreg_gp = ia32_new_NoReg_gp(cg);
912         noreg_fp = ia32_new_NoReg_fp(cg);
913
914         DBG((mod, LEVEL_1, "checking for AM\n"));
915
916         /* 1st part: check for address calculations and transform the into Lea */
917
918         /* Following cases can occur:                                  */
919         /* - Sub (l, imm) -> LEA [base - offset]                       */
920         /* - Sub (l, r == LEA with ia32_am_O)   -> LEA [base - offset] */
921         /* - Add (l, imm) -> LEA [base + offset]                       */
922         /* - Add (l, r == LEA with ia32_am_O)  -> LEA [base + offset]  */
923         /* - Add (l == LEA with ia32_am_O, r)  -> LEA [base + offset]  */
924         /* - Add (l, r) -> LEA [base + index * scale]                  */
925         /*              with scale > 1 iff l/r == shl (1,2,3)          */
926
927         if (is_ia32_Sub(irn) || is_ia32_Add(irn)) {
928                 left  = get_irn_n(irn, 2);
929                 right = get_irn_n(irn, 3);
930
931             /* Do not try to create a LEA if one of the operands is a Load. */
932                 /* check is irn is a candidate for address calculation */
933                 if (is_candidate(block, irn, 1)) {
934                         DBG((mod, LEVEL_1, "\tfound address calculation candidate %+F ... ", irn));
935                         res = fold_addr(cg, irn, noreg_gp);
936
937                         if (res == irn)
938                                 DB((mod, LEVEL_1, "transformed into %+F\n", res));
939                         else
940                                 DB((mod, LEVEL_1, "not transformed\n"));
941                 }
942         }
943
944         /* 2nd part: fold following patterns:                                               */
945         /* - Load  -> LEA into Load  } TODO: If the LEA is used by more than one Load/Store */
946         /* - Store -> LEA into Store }       it might be better to keep the LEA             */
947         /* - op -> Load into AMop with am_Source                                            */
948         /*   conditions:                                                                    */
949         /*     - op is am_Source capable AND                                                */
950         /*     - the Load is only used by this op AND                                       */
951         /*     - the Load is in the same block                                              */
952         /* - Store -> op -> Load  into AMop with am_Dest                                    */
953         /*   conditions:                                                                    */
954         /*     - op is am_Dest capable AND                                                  */
955         /*     - the Store uses the same address as the Load AND                            */
956         /*     - the Load is only used by this op AND                                       */
957         /*     - the Load and Store are in the same block AND                               */
958         /*     - nobody else uses the result of the op                                      */
959
960         if ((res == irn) && (get_ia32_am_support(irn) != ia32_am_None) && !is_ia32_Lea(irn)) {
961                 /* 1st: check for Load/Store -> LEA   */
962                 if (is_ia32_Ld(irn) || is_ia32_St(irn) || is_ia32_Store8Bit(irn)) {
963                         left = get_irn_n(irn, 0);
964
965                         if (is_ia32_Lea(left)) {
966                                 DBG((mod, LEVEL_1, "\nmerging %+F into %+F\n", left, irn));
967
968                                 /* get the AM attributes from the LEA */
969                                 add_ia32_am_offs(irn, get_ia32_am_offs(left));
970                                 set_ia32_am_scale(irn, get_ia32_am_scale(left));
971                                 set_ia32_am_flavour(irn, get_ia32_am_flavour(left));
972
973                                 set_ia32_am_sc(irn, get_ia32_am_sc(left));
974                                 if (is_ia32_am_sc_sign(left))
975                                         set_ia32_am_sc_sign(irn);
976
977                                 set_ia32_op_type(irn, is_ia32_Ld(irn) ? ia32_AddrModeS : ia32_AddrModeD);
978
979                                 /* set base and index */
980                                 set_irn_n(irn, 0, get_irn_n(left, 0));
981                                 set_irn_n(irn, 1, get_irn_n(left, 1));
982
983                                 /* clear remat flag */
984                                 set_ia32_flags(irn, get_ia32_flags(irn) & ~arch_irn_flags_rematerializable);
985                         }
986                 }
987                 /* check if the node is an address mode candidate */
988                 else if (is_candidate(block, irn, 0)) {
989                         DBG((mod, LEVEL_1, "\tfound address mode candidate %+F ... ", irn));
990
991                         left  = get_irn_n(irn, 2);
992                         if (get_irn_arity(irn) == 4) {
993                                 /* it's an "unary" operation */
994                                 right = left;
995                         }
996                         else {
997                                 right = get_irn_n(irn, 3);
998                         }
999
1000                         /* normalize commutative ops */
1001                         if (node_is_ia32_comm(irn)) {
1002                                 /* Assure that right operand is always a Load if there is one    */
1003                                 /* because non-commutative ops can only use Dest AM if the right */
1004                                 /* operand is a load, so we only need to check right operand.    */
1005                                 if (pred_is_specific_nodeblock(block, left, is_ia32_Ld))
1006                                 {
1007                                         set_irn_n(irn, 2, right);
1008                                         set_irn_n(irn, 3, left);
1009
1010                                         temp  = left;
1011                                         left  = right;
1012                                         right = temp;
1013                                 }
1014                         }
1015
1016                         /* check for Store -> op -> Load */
1017
1018                         /* Store -> op -> Load optimization is only possible if supported by op */
1019                         /* and if right operand is a Load                                       */
1020                         if ((get_ia32_am_support(irn) & ia32_am_Dest) &&
1021                                  pred_is_specific_nodeblock(block, right, is_ia32_Ld))
1022                         {
1023
1024                                 /* An address mode capable op always has a result Proj.                  */
1025                                 /* If this Proj is used by more than one other node, we don't need to    */
1026                                 /* check further, otherwise we check for Store and remember the address, */
1027                                 /* the Store points to. */
1028
1029                                 succ = get_res_proj(irn);
1030                                 assert(succ && "Couldn't find result proj");
1031
1032                                 addr_b = NULL;
1033                                 addr_i = NULL;
1034                                 store  = NULL;
1035
1036                                 /* now check for users and Store */
1037                                 if (ia32_get_irn_n_edges(succ) == 1) {
1038                                         succ = get_edge_src_irn(get_irn_out_edge_first(succ));
1039
1040                                         if (is_ia32_fStore(succ) || is_ia32_Store(succ)) {
1041                                                 store  = succ;
1042                                                 addr_b = get_irn_n(store, 0);
1043
1044                                                 /* Could be that the Store is connected to the address    */
1045                                                 /* calculating LEA while the Load is already transformed. */
1046                                                 if (is_ia32_Lea(addr_b)) {
1047                                                         succ   = addr_b;
1048                                                         addr_b = get_irn_n(succ, 0);
1049                                                         addr_i = get_irn_n(succ, 1);
1050                                                 }
1051                                                 else {
1052                                                         addr_i = noreg_gp;
1053                                                 }
1054                                         }
1055                                 }
1056
1057                                 if (store) {
1058                                         /* we found a Store as single user: Now check for Load */
1059
1060                                         /* Extra check for commutative ops with two Loads */
1061                                         /* -> put the interesting Load right              */
1062                                         if (node_is_ia32_comm(irn) &&
1063                                                 pred_is_specific_nodeblock(block, left, is_ia32_Ld))
1064                                         {
1065                                                 if ((addr_b == get_irn_n(get_Proj_pred(left), 0)) &&
1066                                                         (addr_i == get_irn_n(get_Proj_pred(left), 1)))
1067                                                 {
1068                                                         /* We exchange left and right, so it's easier to kill     */
1069                                                         /* the correct Load later and to handle unary operations. */
1070                                                         set_irn_n(irn, 2, right);
1071                                                         set_irn_n(irn, 3, left);
1072
1073                                                         temp  = left;
1074                                                         left  = right;
1075                                                         right = temp;
1076                                                 }
1077                                         }
1078
1079                                         /* skip the Proj for easier access */
1080                                         load = get_Proj_pred(right);
1081
1082                                         /* Compare Load and Store address */
1083                                         if (load_store_addr_is_equal(load, store, addr_b, addr_i)) {
1084                                                 /* Right Load is from same address, so we can */
1085                                                 /* disconnect the Load and Store here        */
1086
1087                                                 /* set new base, index and attributes */
1088                                                 set_irn_n(irn, 0, addr_b);
1089                                                 set_irn_n(irn, 1, addr_i);
1090                                                 add_ia32_am_offs(irn, get_ia32_am_offs(load));
1091                                                 set_ia32_am_scale(irn, get_ia32_am_scale(load));
1092                                                 set_ia32_am_flavour(irn, get_ia32_am_flavour(load));
1093                                                 set_ia32_op_type(irn, ia32_AddrModeD);
1094                                                 set_ia32_frame_ent(irn, get_ia32_frame_ent(load));
1095                                                 set_ia32_ls_mode(irn, get_ia32_ls_mode(load));
1096
1097                                                 set_ia32_am_sc(irn, get_ia32_am_sc(load));
1098                                                 if (is_ia32_am_sc_sign(load))
1099                                                         set_ia32_am_sc_sign(irn);
1100
1101                                                 if (is_ia32_use_frame(load))
1102                                                         set_ia32_use_frame(irn);
1103
1104                                                 /* connect to Load memory and disconnect Load */
1105                                                 if (get_irn_arity(irn) == 5) {
1106                                                         /* binary AMop */
1107                                                         set_irn_n(irn, 4, get_irn_n(load, 2));
1108                                                         set_irn_n(irn, 3, noreg_gp);
1109                                                 }
1110                                                 else {
1111                                                         /* unary AMop */
1112                                                         set_irn_n(irn, 3, get_irn_n(load, 2));
1113                                                         set_irn_n(irn, 2, noreg_gp);
1114                                                 }
1115
1116                                                 /* connect the memory Proj of the Store to the op */
1117                                                 mem_proj = get_mem_proj(store);
1118                                                 set_Proj_pred(mem_proj, irn);
1119                                                 set_Proj_proj(mem_proj, 1);
1120
1121                                                 /* clear remat flag */
1122                                                 set_ia32_flags(irn, get_ia32_flags(irn) & ~arch_irn_flags_rematerializable);
1123
1124                                                 DB((mod, LEVEL_1, "merged with %+F and %+F into dest AM\n", load, store));
1125                                         }
1126                                 } /* if (store) */
1127                                 else if (get_ia32_am_support(irn) & ia32_am_Source) {
1128                                         /* There was no store, check if we still can optimize for source address mode */
1129                                         check_am_src = 1;
1130                                 }
1131                         } /* if (support AM Dest) */
1132                         else if (get_ia32_am_support(irn) & ia32_am_Source) {
1133                                 /* op doesn't support am AM Dest -> check for AM Source */
1134                                 check_am_src = 1;
1135                         }
1136
1137                         /* normalize commutative ops */
1138                         if (node_is_ia32_comm(irn)) {
1139                                 /* Assure that left operand is always a Load if there is one */
1140                                 /* because non-commutative ops can only use Source AM if the */
1141                                 /* left operand is a Load, so we only need to check the left */
1142                                 /* operand afterwards.                                       */
1143                                 if (pred_is_specific_nodeblock(block, right, is_ia32_Ld))       {
1144                                         set_irn_n(irn, 2, right);
1145                                         set_irn_n(irn, 3, left);
1146
1147                                         temp  = left;
1148                                         left  = right;
1149                                         right = temp;
1150                                 }
1151                         }
1152
1153                         /* optimize op -> Load iff Load is only used by this op   */
1154                         /* and left operand is a Load which only used by this irn */
1155                         if (check_am_src                                        &&
1156                                 pred_is_specific_nodeblock(block, left, is_ia32_Ld) &&
1157                                 (ia32_get_irn_n_edges(left) == 1))
1158                         {
1159                                 left = get_Proj_pred(left);
1160
1161                                 addr_b = get_irn_n(left, 0);
1162                                 addr_i = get_irn_n(left, 1);
1163
1164                                 /* set new base, index and attributes */
1165                                 set_irn_n(irn, 0, addr_b);
1166                                 set_irn_n(irn, 1, addr_i);
1167                                 add_ia32_am_offs(irn, get_ia32_am_offs(left));
1168                                 set_ia32_am_scale(irn, get_ia32_am_scale(left));
1169                                 set_ia32_am_flavour(irn, get_ia32_am_flavour(left));
1170                                 set_ia32_op_type(irn, ia32_AddrModeS);
1171                                 set_ia32_frame_ent(irn, get_ia32_frame_ent(left));
1172                                 set_ia32_ls_mode(irn, get_ia32_ls_mode(left));
1173
1174                                 set_ia32_am_sc(irn, get_ia32_am_sc(left));
1175                                 if (is_ia32_am_sc_sign(left))
1176                                         set_ia32_am_sc_sign(irn);
1177
1178                                 /* clear remat flag */
1179                                 set_ia32_flags(irn, get_ia32_flags(irn) & ~arch_irn_flags_rematerializable);
1180
1181                                 if (is_ia32_use_frame(left))
1182                                         set_ia32_use_frame(irn);
1183
1184                                 /* connect to Load memory */
1185                                 if (get_irn_arity(irn) == 5) {
1186                                         /* binary AMop */
1187                                         set_irn_n(irn, 4, get_irn_n(left, 2));
1188                                 }
1189                                 else {
1190                                         /* unary AMop */
1191                                         set_irn_n(irn, 3, get_irn_n(left, 2));
1192                                 }
1193
1194                                 /* disconnect from Load */
1195                                 set_irn_n(irn, 2, noreg_gp);
1196
1197                                 /* If Load has a memory Proj, connect it to the op */
1198                                 mem_proj = get_mem_proj(left);
1199                                 if (mem_proj) {
1200                                         set_Proj_pred(mem_proj, irn);
1201                                         set_Proj_proj(mem_proj, 1);
1202                                 }
1203
1204                                 DB((mod, LEVEL_1, "merged with %+F into source AM\n", left));
1205                         }
1206                 }
1207         }
1208 }