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