made address mode optimizer more modular
[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 #include "irgwalk.h"
13
14 #include "../be_t.h"
15 #include "../beabi.h"
16 #include "../benode_t.h"
17 #include "../besched_t.h"
18
19 #include "ia32_new_nodes.h"
20 #include "bearch_ia32_t.h"
21 #include "gen_ia32_regalloc_if.h"     /* the generated interface (register type and class defenitions) */
22 #include "ia32_transform.h"
23 #include "ia32_dbg_stat.h"
24
25 #undef is_NoMem
26 #define is_NoMem(irn) (get_irn_op(irn) == op_NoMem)
27
28 typedef int is_op_func_t(const ir_node *n);
29
30 /**
31  * checks if a node represents the NOREG value
32  */
33 static int be_is_NoReg(ia32_code_gen_t *cg, const ir_node *irn) {
34   be_abi_irg_t *babi = cg->birg->abi;
35         const arch_register_t *fp_noreg = USE_SSE2(cg) ?
36                 &ia32_xmm_regs[REG_XMM_NOREG] : &ia32_vfp_regs[REG_VFP_NOREG];
37
38         return (be_abi_get_callee_save_irn(babi, &ia32_gp_regs[REG_GP_NOREG]) == irn) ||
39                (be_abi_get_callee_save_irn(babi, fp_noreg) == irn);
40 }
41
42
43
44 /*************************************************
45  *   _____                _              _
46  *  / ____|              | |            | |
47  * | |     ___  _ __  ___| |_ __ _ _ __ | |_ ___
48  * | |    / _ \| '_ \/ __| __/ _` | '_ \| __/ __|
49  * | |___| (_) | | | \__ \ || (_| | | | | |_\__ \
50  *  \_____\___/|_| |_|___/\__\__,_|_| |_|\__|___/
51  *
52  *************************************************/
53
54 /**
55  * creates a unique ident by adding a number to a tag
56  *
57  * @param tag   the tag string, must contain a %d if a number
58  *              should be added
59  */
60 static ident *unique_id(const char *tag)
61 {
62         static unsigned id = 0;
63         char str[256];
64
65         snprintf(str, sizeof(str), tag, ++id);
66         return new_id_from_str(str);
67 }
68
69
70
71 /**
72  * Transforms a SymConst.
73  *
74  * @param mod     the debug module
75  * @param block   the block the new node should belong to
76  * @param node    the ir SymConst node
77  * @param mode    mode of the SymConst
78  * @return the created ia32 Const node
79  */
80 static ir_node *gen_SymConst(ia32_transform_env_t *env) {
81         ir_node  *cnst;
82         dbg_info *dbg   = env->dbg;
83         ir_mode  *mode  = env->mode;
84         ir_graph *irg   = env->irg;
85         ir_node  *block = env->block;
86
87         if (mode_is_float(mode)) {
88                 FP_USED(env->cg);
89                 if (USE_SSE2(env->cg))
90                         cnst = new_rd_ia32_xConst(dbg, irg, block, get_irg_no_mem(irg), mode);
91                 else
92                         cnst = new_rd_ia32_vfConst(dbg, irg, block, get_irg_no_mem(irg), mode);
93         }
94         else
95                 cnst = new_rd_ia32_Const(dbg, irg, block, get_irg_no_mem(irg), mode);
96
97         set_ia32_Const_attr(cnst, env->irn);
98
99         return cnst;
100 }
101
102 /**
103  * Get a primitive type for a mode.
104  */
105 static ir_type *get_prim_type(pmap *types, ir_mode *mode)
106 {
107         pmap_entry *e = pmap_find(types, mode);
108         ir_type *res;
109
110         if (! e) {
111                 char buf[64];
112                 snprintf(buf, sizeof(buf), "prim_type_%s", get_mode_name(mode));
113                 res = new_type_primitive(new_id_from_str(buf), mode);
114                 pmap_insert(types, mode, res);
115         }
116         else
117                 res = e->value;
118         return res;
119 }
120
121 /**
122  * Get an entity that is initialized with a tarval
123  */
124 static entity *get_entity_for_tv(ia32_code_gen_t *cg, ir_node *cnst)
125 {
126         tarval *tv    = get_Const_tarval(cnst);
127         pmap_entry *e = pmap_find(cg->isa->tv_ent, tv);
128         entity *res;
129         ir_graph *rem;
130
131         if (! e) {
132                 ir_mode *mode = get_irn_mode(cnst);
133                 ir_type *tp = get_Const_type(cnst);
134                 if (tp == firm_unknown_type)
135                         tp = get_prim_type(cg->isa->types, mode);
136
137                 res = new_entity(get_glob_type(), unique_id("ia32FloatCnst_%u"), tp);
138
139                 set_entity_ld_ident(res, get_entity_ident(res));
140                 set_entity_visibility(res, visibility_local);
141                 set_entity_variability(res, variability_constant);
142                 set_entity_allocation(res, allocation_static);
143
144                  /* we create a new entity here: It's initialization must resist on the
145                     const code irg */
146                 rem = current_ir_graph;
147                 current_ir_graph = get_const_code_irg();
148                 set_atomic_ent_value(res, new_Const_type(tv, tp));
149                 current_ir_graph = rem;
150
151                 pmap_insert(cg->isa->tv_ent, tv, res);
152         }
153         else
154                 res = e->value;
155         return res;
156 }
157
158 /**
159  * Transforms a Const.
160  *
161  * @param mod     the debug module
162  * @param block   the block the new node should belong to
163  * @param node    the ir Const node
164  * @param mode    mode of the Const
165  * @return the created ia32 Const node
166  */
167 static ir_node *gen_Const(ia32_transform_env_t *env) {
168         ir_node *cnst;
169         symconst_symbol sym;
170         ir_graph *irg   = env->irg;
171         ir_node  *block = env->block;
172         ir_node  *node  = env->irn;
173         dbg_info *dbg   = env->dbg;
174         ir_mode  *mode  = env->mode;
175
176         if (mode_is_float(mode)) {
177                 FP_USED(env->cg);
178                 if (! USE_SSE2(env->cg)) {
179                         cnst_classify_t clss = classify_Const(node);
180
181                         if (clss == CNST_NULL)
182                                 return new_rd_ia32_vfldz(dbg, irg, block, mode);
183                         else if (clss == CNST_ONE)
184                                 return new_rd_ia32_vfld1(dbg, irg, block, mode);
185                 }
186                 sym.entity_p = get_entity_for_tv(env->cg, node);
187
188                 cnst = new_rd_SymConst(dbg, irg, block, sym, symconst_addr_ent);
189                 env->irn = cnst;
190                 cnst = gen_SymConst(env);
191         }
192         else {
193                 cnst = new_rd_ia32_Const(dbg, irg, block, get_irg_no_mem(irg), get_irn_mode(node));
194                 set_ia32_Const_attr(cnst, node);
195         }
196         return cnst;
197 }
198
199
200
201 /**
202  * Transforms (all) Const's into ia32_Const and places them in the
203  * block where they are used (or in the cfg-pred Block in case of Phi's).
204  * Additionally all reference nodes are changed into mode_Is nodes.
205  */
206 void ia32_place_consts_set_modes(ir_node *irn, void *env) {
207         ia32_code_gen_t      *cg = env;
208         ia32_transform_env_t  tenv;
209         ir_mode              *mode;
210         ir_node              *pred, *cnst;
211         int                   i;
212         opcode                opc;
213
214         if (is_Block(irn))
215                 return;
216
217         mode = get_irn_mode(irn);
218
219         /* transform all reference nodes into mode_Is nodes */
220         if (mode_is_reference(mode)) {
221                 mode = mode_Is;
222                 set_irn_mode(irn, mode);
223         }
224
225         tenv.block    = get_nodes_block(irn);
226         tenv.cg       = cg;
227         tenv.irg      = cg->irg;
228         DEBUG_ONLY(tenv.mod      = cg->mod;)
229
230         /* Loop over all predecessors and check for Sym/Const nodes */
231         for (i = get_irn_arity(irn) - 1; i >= 0; --i) {
232                 pred      = get_irn_n(irn, i);
233                 cnst      = NULL;
234                 opc       = get_irn_opcode(pred);
235                 tenv.irn  = pred;
236                 tenv.mode = get_irn_mode(pred);
237                 tenv.dbg  = get_irn_dbg_info(pred);
238
239                 /* If it's a Phi, then we need to create the */
240                 /* new Const in it's predecessor block       */
241                 if (is_Phi(irn)) {
242                         tenv.block = get_Block_cfgpred_block(get_nodes_block(irn), i);
243                 }
244
245                 /* put the const into the block where the original const was */
246                 if (! (cg->opt & IA32_OPT_PLACECNST)) {
247                         tenv.block = get_nodes_block(pred);
248                 }
249
250                 switch (opc) {
251                         case iro_Const:
252                                 cnst = gen_Const(&tenv);
253                                 break;
254                         case iro_SymConst:
255                                 cnst = gen_SymConst(&tenv);
256                                 break;
257                         default:
258                                 break;
259                 }
260
261                 /* if we found a const, then set it */
262                 if (cnst) {
263                         set_irn_n(irn, i, cnst);
264                 }
265         }
266 }
267
268
269
270 /********************************************************************************************************
271  *  _____                _           _         ____        _   _           _          _   _
272  * |  __ \              | |         | |       / __ \      | | (_)         (_)        | | (_)
273  * | |__) |__  ___ _ __ | |__   ___ | | ___  | |  | |_ __ | |_ _ _ __ ___  _ ______ _| |_ _  ___  _ __
274  * |  ___/ _ \/ _ \ '_ \| '_ \ / _ \| |/ _ \ | |  | | '_ \| __| | '_ ` _ \| |_  / _` | __| |/ _ \| '_ \
275  * | |  |  __/  __/ |_) | | | | (_) | |  __/ | |__| | |_) | |_| | | | | | | |/ / (_| | |_| | (_) | | | |
276  * |_|   \___|\___| .__/|_| |_|\___/|_|\___|  \____/| .__/ \__|_|_| |_| |_|_/___\__,_|\__|_|\___/|_| |_|
277  *                | |                               | |
278  *                |_|                               |_|
279  ********************************************************************************************************/
280
281 /**
282  * NOTE: THESE PEEPHOLE OPTIMIZATIONS MUST BE CALLED AFTER SCHEDULING AND REGISTER ALLOCATION.
283  */
284
285 static int ia32_cnst_compare(ir_node *n1, ir_node *n2) {
286         return get_ia32_id_cnst(n1) == get_ia32_id_cnst(n2);
287 }
288
289 /**
290  * Checks for potential CJmp/CJmpAM optimization candidates.
291  */
292 static ir_node *ia32_determine_cjmp_cand(ir_node *irn, is_op_func_t *is_op_func) {
293         ir_node *cand = NULL;
294         ir_node *prev = sched_prev(irn);
295
296         if (is_Block(prev)) {
297                 if (get_Block_n_cfgpreds(prev) == 1)
298                         prev = get_Block_cfgpred(prev, 0);
299                 else
300                         prev = NULL;
301         }
302
303         /* The predecessor must be a ProjX. */
304         if (prev && is_Proj(prev) && get_irn_mode(prev) == mode_X) {
305                 prev = get_Proj_pred(prev);
306
307                 if (is_op_func(prev))
308                         cand = prev;
309         }
310
311         return cand;
312 }
313
314 static int is_TestJmp_cand(const ir_node *irn) {
315         return is_ia32_TestJmp(irn) || is_ia32_And(irn);
316 }
317
318 /**
319  * Checks if two consecutive arguments of cand matches
320  * the two arguments of irn (TestJmp).
321  */
322 static int is_TestJmp_replacement(ir_node *cand, ir_node *irn) {
323         ir_node *in1       = get_irn_n(irn, 0);
324         ir_node *in2       = get_irn_n(irn, 1);
325         int      i, n      = get_irn_arity(cand);
326         int      same_args = 0;
327
328         for (i = 0; i < n - 1; i++) {
329                 if (get_irn_n(cand, i)     == in1 &&
330                         get_irn_n(cand, i + 1) == in2)
331                 {
332                         same_args = 1;
333                         break;
334                 }
335         }
336
337         if (same_args)
338                 return ia32_cnst_compare(cand, irn);
339
340         return 0;
341 }
342
343 /**
344  * Tries to replace a TestJmp by a CJmp or CJmpAM (in case of And)
345  */
346 static void ia32_optimize_TestJmp(ir_node *irn, ia32_code_gen_t *cg) {
347         ir_node *cand    = ia32_determine_cjmp_cand(irn, is_TestJmp_cand);
348         int      replace = 0;
349
350         /* we found a possible candidate */
351         replace = cand ? is_TestJmp_replacement(cand, irn) : 0;
352
353         if (replace) {
354                 DBG((cg->mod, LEVEL_1, "replacing %+F by ", irn));
355
356                 if (is_ia32_And(cand))
357                         set_irn_op(irn, op_ia32_CJmpAM);
358                 else
359                         set_irn_op(irn, op_ia32_CJmp);
360
361                 DB((cg->mod, LEVEL_1, "%+F\n", irn));
362         }
363 }
364
365 static int is_CondJmp_cand(const ir_node *irn) {
366         return is_ia32_CondJmp(irn) || is_ia32_Sub(irn);
367 }
368
369 /**
370  * Checks if the arguments of cand are the same of irn.
371  */
372 static int is_CondJmp_replacement(ir_node *cand, ir_node *irn) {
373         int i, n      = get_irn_arity(cand);
374         int same_args = 1;
375
376         for (i = 0; i < n; i++) {
377                 if (get_irn_n(cand, i) != get_irn_n(irn, i)) {
378                         same_args = 0;
379                         break;
380                 }
381         }
382
383         if (same_args)
384                 return ia32_cnst_compare(cand, irn);
385
386         return 0;
387 }
388
389 /**
390  * Tries to replace a CondJmp by a CJmpAM
391  */
392 static void ia32_optimize_CondJmp(ir_node *irn, ia32_code_gen_t *cg) {
393         ir_node *cand    = ia32_determine_cjmp_cand(irn, is_CondJmp_cand);
394         int      replace = 0;
395
396         /* we found a possible candidate */
397         replace = cand ? is_CondJmp_replacement(cand, irn) : 0;
398
399         if (replace) {
400                 DBG((cg->mod, LEVEL_1, "replacing %+F by ", irn));
401                 DBG_OPT_CJMP(irn);
402
403                 set_irn_op(irn, op_ia32_CJmpAM);
404
405                 DB((cg->mod, LEVEL_1, "%+F\n", irn));
406         }
407 }
408
409 /**
410  * Creates a Push from Store(IncSP(gp_reg_size))
411  */
412 static void ia32_create_Push(ir_node *irn, ia32_code_gen_t *cg) {
413         ir_node *sp  = get_irn_n(irn, 0);
414         ir_node *val, *next, *push, *bl, *proj_M, *proj_res, *old_proj_M;
415         const ir_edge_t *edge;
416
417         if (get_ia32_am_offs(irn) || !be_is_IncSP(sp))
418                 return;
419
420         if (arch_get_irn_register(cg->arch_env, get_irn_n(irn, 1)) !=
421                 &ia32_gp_regs[REG_GP_NOREG])
422                 return;
423
424         val = get_irn_n(irn, 2);
425         if (mode_is_float(get_irn_mode(val)))
426                 return;
427
428         if (be_get_IncSP_direction(sp) != be_stack_dir_expand ||
429                 be_get_IncSP_offset(sp) != get_mode_size_bytes(ia32_reg_classes[CLASS_ia32_gp].mode))
430                 return;
431
432         /* ok, translate into Push */
433         edge = get_irn_out_edge_first(irn);
434         old_proj_M = get_edge_src_irn(edge);
435
436         next = sched_next(irn);
437         sched_remove(irn);
438         sched_remove(sp);
439
440         bl   = get_nodes_block(irn);
441         push = new_rd_ia32_Push(NULL, current_ir_graph, bl,
442                 be_get_IncSP_pred(sp), val, be_get_IncSP_mem(sp));
443         proj_res = new_r_Proj(current_ir_graph, bl, push, get_irn_mode(sp), pn_ia32_Push_stack);
444         proj_M   = new_r_Proj(current_ir_graph, bl, push, mode_M, pn_ia32_Push_M);
445
446         /* copy a possible constant from the store */
447         set_ia32_id_cnst(push, get_ia32_id_cnst(irn));
448         set_ia32_immop_type(push, get_ia32_immop_type(irn));
449
450         /* the push must have SP out register */
451         arch_set_irn_register(cg->arch_env, push, arch_get_irn_register(cg->arch_env, sp));
452
453         exchange(old_proj_M, proj_M);
454         exchange(sp, proj_res);
455         sched_add_before(next, push);
456         sched_add_after(push, proj_res);
457 }
458
459 /**
460  * Creates a Pop from IncSP(Load(sp))
461  */
462 static void ia32_create_Pop(ir_node *irn, ia32_code_gen_t *cg) {
463         ir_node *old_proj_M = be_get_IncSP_mem(irn);
464         ir_node *load = skip_Proj(old_proj_M);
465         ir_node *old_proj_res = NULL;
466         ir_node *bl, *pop, *next, *proj_res, *proj_sp, *proj_M;
467         const ir_edge_t *edge;
468         const arch_register_t *reg, *sp;
469
470         if (! is_ia32_Load(load) || get_ia32_am_offs(load))
471                 return;
472
473         if (arch_get_irn_register(cg->arch_env, get_irn_n(load, 1)) !=
474                 &ia32_gp_regs[REG_GP_NOREG])
475                 return;
476         if (arch_get_irn_register(cg->arch_env, get_irn_n(load, 0)) != cg->isa->arch_isa.sp)
477                 return;
478
479         /* ok, translate into pop */
480         foreach_out_edge(load, edge) {
481                 ir_node *succ = get_edge_src_irn(edge);
482                 if (succ != old_proj_M) {
483                         old_proj_res = succ;
484                         break;
485                 }
486         }
487         if (! old_proj_res) {
488                 assert(0);
489                 return; /* should not happen */
490         }
491
492         bl = get_nodes_block(load);
493
494         /* IncSP is typically scheduled after the load, so remove it first */
495         sched_remove(irn);
496         next = sched_next(old_proj_res);
497         sched_remove(old_proj_res);
498         sched_remove(load);
499
500         reg = arch_get_irn_register(cg->arch_env, load);
501         sp  = arch_get_irn_register(cg->arch_env, irn);
502
503         pop      = new_rd_ia32_Pop(NULL, current_ir_graph, bl, get_irn_n(irn, 0), get_irn_n(load, 2));
504         proj_res = new_r_Proj(current_ir_graph, bl, pop, get_irn_mode(old_proj_res), pn_ia32_Pop_res);
505         proj_sp  = new_r_Proj(current_ir_graph, bl, pop, get_irn_mode(irn), pn_ia32_Pop_stack);
506         proj_M   = new_r_Proj(current_ir_graph, bl, pop, mode_M, pn_ia32_Pop_M);
507
508         exchange(old_proj_M, proj_M);
509         exchange(old_proj_res, proj_res);
510         exchange(irn, proj_sp);
511
512         arch_set_irn_register(cg->arch_env, proj_res, reg);
513         arch_set_irn_register(cg->arch_env, proj_sp, sp);
514
515         sched_add_before(next, proj_sp);
516         sched_add_before(proj_sp, proj_res);
517         sched_add_before(proj_res,pop);
518 }
519
520 /**
521  * Tries to optimize two following IncSP.
522  */
523 static void ia32_optimize_IncSP(ir_node *irn, ia32_code_gen_t *cg) {
524         ir_node *prev = be_get_IncSP_pred(irn);
525         int real_uses = get_irn_n_edges(prev);
526
527         if (be_is_IncSP(prev) && real_uses == 1) {
528                 /* first IncSP has only one IncSP user, kill the first one */
529                 unsigned       prev_offs = be_get_IncSP_offset(prev);
530                 be_stack_dir_t prev_dir  = be_get_IncSP_direction(prev);
531                 unsigned       curr_offs = be_get_IncSP_offset(irn);
532                 be_stack_dir_t curr_dir  = be_get_IncSP_direction(irn);
533
534                 int new_ofs = prev_offs * (prev_dir == be_stack_dir_expand ? -1 : +1) +
535                                     curr_offs * (curr_dir == be_stack_dir_expand ? -1 : +1);
536
537                 if (new_ofs < 0) {
538                         new_ofs  = -new_ofs;
539                         curr_dir = be_stack_dir_expand;
540                 }
541                 else
542                         curr_dir = be_stack_dir_shrink;
543                 be_set_IncSP_offset(prev, 0);
544                 be_set_IncSP_offset(irn, (unsigned)new_ofs);
545                 be_set_IncSP_direction(irn, curr_dir);
546
547                 /* Omit the optimized IncSP */
548                 be_set_IncSP_pred(irn, be_get_IncSP_pred(prev));
549         }
550 }
551
552 /**
553  * Performs Peephole Optimizations.
554  */
555 void ia32_peephole_optimization(ir_node *irn, void *env) {
556         ia32_code_gen_t *cg = env;
557
558         if (is_ia32_TestJmp(irn))
559                 ia32_optimize_TestJmp(irn, cg);
560         else if (is_ia32_CondJmp(irn))
561                 ia32_optimize_CondJmp(irn, cg);
562         /* seems to be buggy when using Pushes */
563 //      else if (be_is_IncSP(irn))
564 //              ia32_optimize_IncSP(irn, cg);
565         else if (is_ia32_Store(irn))
566                 ia32_create_Push(irn, cg);
567 }
568
569
570
571 /******************************************************************
572  *              _     _                   __  __           _
573  *     /\      | |   | |                 |  \/  |         | |
574  *    /  \   __| | __| |_ __ ___  ___ ___| \  / | ___   __| | ___
575  *   / /\ \ / _` |/ _` | '__/ _ \/ __/ __| |\/| |/ _ \ / _` |/ _ \
576  *  / ____ \ (_| | (_| | | |  __/\__ \__ \ |  | | (_) | (_| |  __/
577  * /_/    \_\__,_|\__,_|_|  \___||___/___/_|  |_|\___/ \__,_|\___|
578  *
579  ******************************************************************/
580
581 static int node_is_ia32_comm(const ir_node *irn) {
582         return is_ia32_irn(irn) ? is_ia32_commutative(irn) : 0;
583 }
584
585 static int ia32_get_irn_n_edges(const ir_node *irn) {
586         const ir_edge_t *edge;
587         int cnt = 0;
588
589         foreach_out_edge(irn, edge) {
590                 cnt++;
591         }
592
593         return cnt;
594 }
595
596 /**
597  * Returns the first mode_M Proj connected to irn.
598  */
599 static ir_node *get_mem_proj(const ir_node *irn) {
600         const ir_edge_t *edge;
601         ir_node         *src;
602
603         assert(get_irn_mode(irn) == mode_T && "expected mode_T node");
604
605         foreach_out_edge(irn, edge) {
606                 src = get_edge_src_irn(edge);
607
608                 assert(is_Proj(src) && "Proj expected");
609
610                 if (get_irn_mode(src) == mode_M)
611                         return src;
612         }
613
614         return NULL;
615 }
616
617 /**
618  * Returns the first Proj with mode != mode_M connected to irn.
619  */
620 static ir_node *get_res_proj(const ir_node *irn) {
621         const ir_edge_t *edge;
622         ir_node         *src;
623
624         assert(get_irn_mode(irn) == mode_T && "expected mode_T node");
625
626         foreach_out_edge(irn, edge) {
627                 src = get_edge_src_irn(edge);
628
629                 assert(is_Proj(src) && "Proj expected");
630
631                 if (get_irn_mode(src) != mode_M)
632                         return src;
633         }
634
635         return NULL;
636 }
637
638 /**
639  * Determines if pred is a Proj and if is_op_func returns true for it's predecessor.
640  *
641  * @param pred       The node to be checked
642  * @param is_op_func The check-function
643  * @return 1 if conditions are fulfilled, 0 otherwise
644  */
645 static int pred_is_specific_node(const ir_node *pred, is_op_func_t *is_op_func) {
646         if (is_Proj(pred) && is_op_func(get_Proj_pred(pred))) {
647                 return 1;
648         }
649
650         return 0;
651 }
652
653 /**
654  * Determines if pred is a Proj and if is_op_func returns true for it's predecessor
655  * and if the predecessor is in block bl.
656  *
657  * @param bl         The block
658  * @param pred       The node to be checked
659  * @param is_op_func The check-function
660  * @return 1 if conditions are fulfilled, 0 otherwise
661  */
662 static int pred_is_specific_nodeblock(const ir_node *bl, const ir_node *pred,
663         int (*is_op_func)(const ir_node *n))
664 {
665         if (is_Proj(pred)) {
666                 pred = get_Proj_pred(pred);
667                 if ((bl == get_nodes_block(pred)) && is_op_func(pred)) {
668                         return 1;
669                 }
670         }
671
672         return 0;
673 }
674
675
676
677 /**
678  * Checks if irn is a candidate for address calculation or address mode.
679  *
680  * address calculation (AC):
681  * - none of the operand must be a Load  within the same block OR
682  * - all Loads must have more than one user                    OR
683  * - the irn has a frame entity (it's a former FrameAddr)
684  *
685  * address mode (AM):
686  * - at least one operand has to be a Load within the same block AND
687  * - the load must not have other users than the irn             AND
688  * - the irn must not have a frame entity set
689  *
690  * @param block       The block the Loads must/not be in
691  * @param irn         The irn to check
692  * @param check_addr  1 if to check for address calculation, 0 otherwise
693  * return 1 if irn is a candidate for AC or AM, 0 otherwise
694  */
695 static int is_candidate(const ir_node *block, const ir_node *irn, int check_addr) {
696         ir_node *in;
697         int      n, is_cand = check_addr;
698
699         in = get_irn_n(irn, 2);
700
701         if (pred_is_specific_nodeblock(block, in, is_ia32_Ld)) {
702                 n         = ia32_get_irn_n_edges(in);
703                 is_cand   = check_addr ? (n == 1 ? 0 : is_cand) : (n == 1 ? 1 : is_cand);
704         }
705
706         in = get_irn_n(irn, 3);
707
708         if (pred_is_specific_nodeblock(block, in, is_ia32_Ld)) {
709                 n         = ia32_get_irn_n_edges(in);
710                 is_cand   = check_addr ? (n == 1 ? 0 : is_cand) : (n == 1 ? 1 : is_cand);
711         }
712
713         is_cand = get_ia32_frame_ent(irn) ? (check_addr ? 1 : 0) : is_cand;
714
715         return is_cand;
716 }
717
718 /**
719  * Compares the base and index addr and the load/store entities
720  * and returns 1 if they are equal.
721  */
722 static int load_store_addr_is_equal(const ir_node *load, const ir_node *store,
723                                                                         const ir_node *addr_b, const ir_node *addr_i)
724 {
725         int     is_equal = (addr_b == get_irn_n(load, 0)) && (addr_i == get_irn_n(load, 1));
726         entity *lent     = get_ia32_frame_ent(load);
727         entity *sent     = get_ia32_frame_ent(store);
728         ident  *lid      = get_ia32_am_sc(load);
729         ident  *sid      = get_ia32_am_sc(store);
730         char   *loffs    = get_ia32_am_offs(load);
731         char   *soffs    = get_ia32_am_offs(store);
732
733         /* are both entities set and equal? */
734         if (is_equal && (lent || sent))
735                 is_equal = lent && sent && (lent == sent);
736
737         /* are address mode idents set and equal? */
738         if (is_equal && (lid || sid))
739                 is_equal = lid && sid && (lid == sid);
740
741         /* are offsets set and equal */
742         if (is_equal && (loffs || soffs))
743                 is_equal = loffs && soffs && strcmp(loffs, soffs) == 0;
744
745         /* are the load and the store of the same mode? */
746         is_equal = is_equal ? get_ia32_ls_mode(load) == get_ia32_ls_mode(store) : 0;
747
748         return is_equal;
749 }
750
751 typedef enum _ia32_take_lea_attr {
752         IA32_LEA_ATTR_NONE  = 0,
753         IA32_LEA_ATTR_BASE  = (1 << 0),
754         IA32_LEA_ATTR_INDEX = (1 << 1),
755         IA32_LEA_ATTR_OFFS  = (1 << 2),
756         IA32_LEA_ATTR_SCALE = (1 << 3),
757         IA32_LEA_ATTR_AMSC  = (1 << 4),
758         IA32_LEA_ATTR_FENT  = (1 << 5)
759 } ia32_take_lea_attr;
760
761 /**
762  * Decides if we have to keep the LEA operand or if we can assimilate it.
763  */
764 static int do_new_lea(ir_node *irn, ir_node *base, ir_node *index, ir_node *lea,
765                 int have_am_sc, ia32_code_gen_t *cg)
766 {
767         ir_node *lea_base = get_irn_n(lea, 0);
768         ir_node *lea_idx  = get_irn_n(lea, 1);
769         entity  *irn_ent  = get_ia32_frame_ent(irn);
770         entity  *lea_ent  = get_ia32_frame_ent(lea);
771         int      ret_val  = 0;
772         int      is_noreg_base  = be_is_NoReg(cg, base);
773         int      is_noreg_index = be_is_NoReg(cg, index);
774         ia32_am_flavour_t am_flav = get_ia32_am_flavour(lea);
775
776         /* If the Add and the LEA both have a different frame entity set: keep */
777         if (irn_ent && lea_ent && (irn_ent != lea_ent))
778                 return IA32_LEA_ATTR_NONE;
779         else if (! irn_ent && lea_ent)
780                 ret_val |= IA32_LEA_ATTR_FENT;
781
782         /* If the Add and the LEA both have already an address mode symconst: keep */
783         if (have_am_sc && get_ia32_am_sc(lea))
784                 return IA32_LEA_ATTR_NONE;
785         else if (get_ia32_am_sc(lea))
786                 ret_val |= IA32_LEA_ATTR_AMSC;
787
788         /* Check the different base-index combinations */
789
790         if (! is_noreg_base && ! is_noreg_index) {
791                 /* Assimilate if base is the lea and the LEA is just a Base + Offset calculation */
792                 if ((base == lea) && ! (am_flav & ia32_I ? 1 : 0)) {
793                         if (am_flav & ia32_O)
794                                 ret_val |= IA32_LEA_ATTR_OFFS;
795
796                         ret_val |= IA32_LEA_ATTR_BASE;
797                 }
798                 else
799                         return IA32_LEA_ATTR_NONE;
800         }
801         else if (! is_noreg_base && is_noreg_index) {
802                 /* Base is set but index not */
803                 if (base == lea) {
804                         /* Base points to LEA: assimilate everything */
805                         if (am_flav & ia32_O)
806                                 ret_val |= IA32_LEA_ATTR_OFFS;
807                         if (am_flav & ia32_S)
808                                 ret_val |= IA32_LEA_ATTR_SCALE;
809                         if (am_flav & ia32_I)
810                                 ret_val |= IA32_LEA_ATTR_INDEX;
811
812                         ret_val |= IA32_LEA_ATTR_BASE;
813                 }
814                 else if (am_flav & ia32_B ? 0 : 1) {
815                         /* Base is not the LEA but the LEA is an index only calculation: assimilate */
816                         if (am_flav & ia32_O)
817                                 ret_val |= IA32_LEA_ATTR_OFFS;
818                         if (am_flav & ia32_S)
819                                 ret_val |= IA32_LEA_ATTR_SCALE;
820
821                         ret_val |= IA32_LEA_ATTR_INDEX;
822                 }
823                 else
824                         return IA32_LEA_ATTR_NONE;
825         }
826         else if (is_noreg_base && ! is_noreg_index) {
827                 /* Index is set but not base */
828                 if (index == lea) {
829                         /* Index points to LEA: assimilate everything */
830                         if (am_flav & ia32_O)
831                                 ret_val |= IA32_LEA_ATTR_OFFS;
832                         if (am_flav & ia32_S)
833                                 ret_val |= IA32_LEA_ATTR_SCALE;
834                         if (am_flav & ia32_B)
835                                 ret_val |= IA32_LEA_ATTR_BASE;
836
837                         ret_val |= IA32_LEA_ATTR_INDEX;
838                 }
839                 else if (am_flav & ia32_I ? 0 : 1) {
840                         /* Index is not the LEA but the LEA is a base only calculation: assimilate */
841                         if (am_flav & ia32_O)
842                                 ret_val |= IA32_LEA_ATTR_OFFS;
843                         if (am_flav & ia32_S)
844                                 ret_val |= IA32_LEA_ATTR_SCALE;
845
846                         ret_val |= IA32_LEA_ATTR_BASE;
847                 }
848                 else
849                         return IA32_LEA_ATTR_NONE;
850         }
851         else {
852                 assert(0 && "There must have been set base or index");
853         }
854
855         return ret_val;
856 }
857
858
859 /**
860  * Folds Add or Sub to LEA if possible
861  */
862 static ir_node *fold_addr(ia32_code_gen_t *cg, ir_node *irn, ir_node *noreg) {
863         ir_graph   *irg        = get_irn_irg(irn);
864         dbg_info   *dbg        = get_irn_dbg_info(irn);
865         ir_node    *block      = get_nodes_block(irn);
866         ir_node    *res        = irn;
867         ir_node    *shift      = NULL;
868         ir_node    *lea_o      = NULL;
869         ir_node    *lea        = NULL;
870         char       *offs       = NULL;
871         const char *offs_cnst  = NULL;
872         char       *offs_lea   = NULL;
873         int         scale      = 0;
874         int         isadd      = 0;
875         int         dolea      = 0;
876         int         have_am_sc = 0;
877         int         am_sc_sign = 0;
878         ident      *am_sc      = NULL;
879         entity     *lea_ent    = NULL;
880         ir_node    *left, *right, *temp;
881         ir_node    *base, *index;
882         ia32_am_flavour_t am_flav;
883         DEBUG_ONLY(firm_dbg_module_t *mod = cg->mod;)
884
885         if (is_ia32_Add(irn))
886                 isadd = 1;
887
888         left  = get_irn_n(irn, 2);
889         right = get_irn_n(irn, 3);
890
891         /* "normalize" arguments in case of add with two operands */
892         if  (isadd && ! be_is_NoReg(cg, right)) {
893                 /* put LEA == ia32_am_O as right operand */
894                 if (is_ia32_Lea(left) && get_ia32_am_flavour(left) == ia32_am_O) {
895                         set_irn_n(irn, 2, right);
896                         set_irn_n(irn, 3, left);
897                         temp  = left;
898                         left  = right;
899                         right = temp;
900                 }
901
902                 /* put LEA != ia32_am_O as left operand */
903                 if (is_ia32_Lea(right) && get_ia32_am_flavour(right) != ia32_am_O) {
904                         set_irn_n(irn, 2, right);
905                         set_irn_n(irn, 3, left);
906                         temp  = left;
907                         left  = right;
908                         right = temp;
909                 }
910
911                 /* put SHL as left operand iff left is NOT a LEA */
912                 if (! is_ia32_Lea(left) && pred_is_specific_node(right, is_ia32_Shl)) {
913                         set_irn_n(irn, 2, right);
914                         set_irn_n(irn, 3, left);
915                         temp  = left;
916                         left  = right;
917                         right = temp;
918                 }
919         }
920
921         base    = left;
922         index   = noreg;
923         offs    = NULL;
924         scale   = 0;
925         am_flav = 0;
926
927         /* check for operation with immediate */
928         if (is_ia32_ImmConst(irn)) {
929                 DBG((mod, LEVEL_1, "\tfound op with imm const"));
930
931                 offs_cnst = get_ia32_cnst(irn);
932                 dolea     = 1;
933         }
934         else if (is_ia32_ImmSymConst(irn)) {
935                 DBG((mod, LEVEL_1, "\tfound op with imm symconst"));
936
937                 have_am_sc = 1;
938                 dolea      = 1;
939                 am_sc      = get_ia32_id_cnst(irn);
940                 am_sc_sign = is_ia32_am_sc_sign(irn);
941         }
942
943         /* determine the operand which needs to be checked */
944         if (be_is_NoReg(cg, right)) {
945                 temp = left;
946         }
947         else {
948                 temp = right;
949         }
950
951         /* check if right operand is AMConst (LEA with ia32_am_O)  */
952         /* but we can only eat it up if there is no other symconst */
953         /* because the linker won't accept two symconsts           */
954         if (! have_am_sc && is_ia32_Lea(temp) && get_ia32_am_flavour(temp) == ia32_am_O) {
955                 DBG((mod, LEVEL_1, "\tgot op with LEA am_O"));
956
957                 offs_lea   = get_ia32_am_offs(temp);
958                 am_sc      = get_ia32_am_sc(temp);
959                 am_sc_sign = is_ia32_am_sc_sign(temp);
960                 have_am_sc = 1;
961                 dolea      = 1;
962                 lea_o      = temp;
963         }
964
965         if (isadd) {
966                 /* default for add -> make right operand to index */
967                 index = right;
968                 dolea = 1;
969
970                 DBG((mod, LEVEL_1, "\tgot LEA candidate with index %+F\n", index));
971
972                 /* determine the operand which needs to be checked */
973                 temp = left;
974                 if (is_ia32_Lea(left)) {
975                         temp = right;
976                 }
977
978                 /* check for SHL 1,2,3 */
979                 if (pred_is_specific_node(temp, is_ia32_Shl)) {
980                         temp  = get_Proj_pred(temp);
981                         shift = temp;
982
983                         if (get_ia32_Immop_tarval(temp)) {
984                                 scale = get_tarval_long(get_ia32_Immop_tarval(temp));
985
986                                 if (scale <= 3) {
987                                         index = get_irn_n(temp, 2);
988
989                                         DBG((mod, LEVEL_1, "\tgot scaled index %+F\n", index));
990                                 }
991                                 else {
992                                         scale = 0;
993                                         shift = NULL;
994                                 }
995                         }
996                 }
997
998                 /* fix base */
999                 if (! be_is_NoReg(cg, index)) {
1000                         /* if we have index, but left == right -> no base */
1001                         if (left == right) {
1002                                 base = noreg;
1003                         }
1004                         else if (! is_ia32_Lea(left) && (index != right)) {
1005                                 /* index != right -> we found a good Shl           */
1006                                 /* left  != LEA   -> this Shl was the left operand */
1007                                 /* -> base is right operand                        */
1008                                 base = right;
1009                         }
1010                 }
1011         }
1012
1013         /* Try to assimilate a LEA as left operand */
1014         if (is_ia32_Lea(left) && (get_ia32_am_flavour(left) != ia32_am_O)) {
1015                 /* check if we can assimilate the LEA */
1016                 int take_attr = do_new_lea(irn, base, index, left, have_am_sc, cg);
1017
1018                 if (take_attr == IA32_LEA_ATTR_NONE) {
1019                         DBG((mod, LEVEL_1, "\tleave old LEA, creating new one\n"));
1020                 }
1021                 else {
1022                         DBG((mod, LEVEL_1, "\tgot LEA as left operand ... assimilating\n"));
1023                         lea = left; /* for statistics */
1024
1025                         if (take_attr & IA32_LEA_ATTR_OFFS)
1026                                 offs = get_ia32_am_offs(left);
1027
1028                         if (take_attr & IA32_LEA_ATTR_AMSC) {
1029                                 am_sc      = get_ia32_am_sc(left);
1030                                 have_am_sc = 1;
1031                                 am_sc_sign = is_ia32_am_sc_sign(left);
1032                         }
1033
1034                         if (take_attr & IA32_LEA_ATTR_SCALE)
1035                                 scale = get_ia32_am_scale(left);
1036
1037                         if (take_attr & IA32_LEA_ATTR_BASE)
1038                                 base = get_irn_n(left, 0);
1039
1040                         if (take_attr & IA32_LEA_ATTR_INDEX)
1041                                 index = get_irn_n(left, 1);
1042
1043                         if (take_attr & IA32_LEA_ATTR_FENT)
1044                                 lea_ent = get_ia32_frame_ent(left);
1045                 }
1046         }
1047
1048         /* ok, we can create a new LEA */
1049         if (dolea) {
1050                 res = new_rd_ia32_Lea(dbg, irg, block, base, index, mode_Is);
1051
1052                 /* add the old offset of a previous LEA */
1053                 if (offs) {
1054                         add_ia32_am_offs(res, offs);
1055                 }
1056
1057                 /* add the new offset */
1058                 if (isadd) {
1059                         if (offs_cnst) {
1060                                 add_ia32_am_offs(res, offs_cnst);
1061                         }
1062                         if (offs_lea) {
1063                                 add_ia32_am_offs(res, offs_lea);
1064                         }
1065                 }
1066                 else {
1067                         /* either lea_O-cnst, -cnst or -lea_O  */
1068                         if (offs_cnst) {
1069                                 if (offs_lea) {
1070                                         add_ia32_am_offs(res, offs_lea);
1071                                 }
1072
1073                                 sub_ia32_am_offs(res, offs_cnst);
1074                         }
1075                         else {
1076                                 sub_ia32_am_offs(res, offs_lea);
1077                         }
1078                 }
1079
1080                 /* set the address mode symconst */
1081                 if (have_am_sc) {
1082                         set_ia32_am_sc(res, am_sc);
1083                         if (am_sc_sign)
1084                                 set_ia32_am_sc_sign(res);
1085                 }
1086
1087                 /* copy the frame entity (could be set in case of Add */
1088                 /* which was a FrameAddr) */
1089                 if (lea_ent)
1090                         set_ia32_frame_ent(res, lea_ent);
1091                 else
1092                         set_ia32_frame_ent(res, get_ia32_frame_ent(irn));
1093
1094                 if (get_ia32_frame_ent(res))
1095                         set_ia32_use_frame(res);
1096
1097                 /* set scale */
1098                 set_ia32_am_scale(res, scale);
1099
1100                 am_flav = ia32_am_N;
1101                 /* determine new am flavour */
1102                 if (offs || offs_cnst || offs_lea) {
1103                         am_flav |= ia32_O;
1104                 }
1105                 if (! be_is_NoReg(cg, base)) {
1106                         am_flav |= ia32_B;
1107                 }
1108                 if (! be_is_NoReg(cg, index)) {
1109                         am_flav |= ia32_I;
1110                 }
1111                 if (scale > 0) {
1112                         am_flav |= ia32_S;
1113                 }
1114                 set_ia32_am_flavour(res, am_flav);
1115
1116                 set_ia32_op_type(res, ia32_AddrModeS);
1117
1118                 SET_IA32_ORIG_NODE(res, ia32_get_old_node_name(cg, irn));
1119
1120                 DBG((mod, LEVEL_1, "\tLEA [%+F + %+F * %d + %s]\n", base, index, scale, get_ia32_am_offs(res)));
1121
1122                 /* we will exchange it, report here before the Proj is created */
1123                 if (shift && lea && lea_o)
1124                         DBG_OPT_LEA4(irn, lea_o, lea, shift, res);
1125                 else if (shift && lea)
1126                         DBG_OPT_LEA3(irn, lea, shift, res);
1127                 else if (shift && lea_o)
1128                         DBG_OPT_LEA3(irn, lea_o, shift, res);
1129                 else if (lea && lea_o)
1130                         DBG_OPT_LEA3(irn, lea_o, lea, res);
1131                 else if (shift)
1132                         DBG_OPT_LEA2(irn, shift, res);
1133                 else if (lea)
1134                         DBG_OPT_LEA2(irn, lea, res);
1135                 else if (lea_o)
1136                         DBG_OPT_LEA2(irn, lea_o, res);
1137                 else
1138                         DBG_OPT_LEA1(irn, res);
1139
1140                 /* get the result Proj of the Add/Sub */
1141                 irn = get_res_proj(irn);
1142
1143                 assert(irn && "Couldn't find result proj");
1144
1145                 /* exchange the old op with the new LEA */
1146                 exchange(irn, res);
1147         }
1148
1149         return res;
1150 }
1151
1152
1153 /**
1154  * Merges a Load/Store node with a LEA.
1155  * @param irn The Load/Store node
1156  * @param lea The LEA
1157  */
1158 static void merge_loadstore_lea(ir_node *irn, ir_node *lea) {
1159         entity *irn_ent = get_ia32_frame_ent(irn);
1160         entity *lea_ent = get_ia32_frame_ent(lea);
1161
1162         /* If the irn and the LEA both have a different frame entity set: do not merge */
1163         if (irn_ent && lea_ent && (irn_ent != lea_ent))
1164                 return;
1165         else if (! irn_ent && lea_ent) {
1166                 set_ia32_frame_ent(irn, lea_ent);
1167                 set_ia32_use_frame(irn);
1168         }
1169
1170         /* get the AM attributes from the LEA */
1171         add_ia32_am_offs(irn, get_ia32_am_offs(lea));
1172         set_ia32_am_scale(irn, get_ia32_am_scale(lea));
1173         set_ia32_am_flavour(irn, get_ia32_am_flavour(lea));
1174
1175         set_ia32_am_sc(irn, get_ia32_am_sc(lea));
1176         if (is_ia32_am_sc_sign(lea))
1177                 set_ia32_am_sc_sign(irn);
1178
1179         set_ia32_op_type(irn, is_ia32_Ld(irn) ? ia32_AddrModeS : ia32_AddrModeD);
1180
1181         /* set base and index */
1182         set_irn_n(irn, 0, get_irn_n(lea, 0));
1183         set_irn_n(irn, 1, get_irn_n(lea, 1));
1184
1185         /* clear remat flag */
1186         set_ia32_flags(irn, get_ia32_flags(irn) & ~arch_irn_flags_rematerializable);
1187
1188         if (is_ia32_Ld(irn))
1189                 DBG_OPT_LOAD_LEA(lea, irn);
1190         else
1191                 DBG_OPT_STORE_LEA(lea, irn);
1192
1193 }
1194
1195 /**
1196  * Sets new_right index of irn to right and new_left index to left.
1197  * Also exchange left and right
1198  */
1199 static void exchange_left_right(ir_node *irn, ir_node **left, ir_node **right, int new_left, int new_right) {
1200         ir_node *temp;
1201
1202         set_irn_n(irn, new_right, *right);
1203         set_irn_n(irn, new_left, *left);
1204
1205         temp   = *left;
1206         *left  = *right;
1207         *right = temp;
1208
1209         /* this is only needed for Compares, but currently ALL nodes
1210          * have this attribute :-) */
1211         set_ia32_pncode(irn, get_inversed_pnc(get_ia32_pncode(irn)));
1212 }
1213
1214 /**
1215  * Performs address calculation optimization (create LEAs if possible)
1216  * @return 1 if performed optimization, 0 otherwise
1217  */
1218 static int optimize_address_calculation(ir_node *irn, void *env) {
1219         ia32_code_gen_t *cg  = env;
1220         int              ret = 0;
1221         ir_node         *block, *noreg_gp, *left, *right;
1222
1223         if (! is_ia32_irn(irn))
1224                 return ret;
1225
1226         /* Following cases can occur:                                  */
1227         /* - Sub (l, imm) -> LEA [base - offset]                       */
1228         /* - Sub (l, r == LEA with ia32_am_O)   -> LEA [base - offset] */
1229         /* - Add (l, imm) -> LEA [base + offset]                       */
1230         /* - Add (l, r == LEA with ia32_am_O)  -> LEA [base + offset]  */
1231         /* - Add (l == LEA with ia32_am_O, r)  -> LEA [base + offset]  */
1232         /* - Add (l, r) -> LEA [base + index * scale]                  */
1233         /*              with scale > 1 iff l/r == shl (1,2,3)          */
1234
1235         if (is_ia32_Sub(irn) || is_ia32_Add(irn)) {
1236                 left     = get_irn_n(irn, 2);
1237                 right    = get_irn_n(irn, 3);
1238                 block    = get_nodes_block(irn);
1239                 noreg_gp = ia32_new_NoReg_gp(cg);
1240
1241             /* Do not try to create a LEA if one of the operands is a Load. */
1242                 /* check is irn is a candidate for address calculation */
1243                 if (is_candidate(block, irn, 1)) {
1244                         ir_node *res;
1245
1246                         DBG((cg->mod, LEVEL_1, "\tfound address calculation candidate %+F ... ", irn));
1247                         res = fold_addr(cg, irn, noreg_gp);
1248                         ret = (res != irn);
1249
1250                         if (ret)
1251                                 DB((cg->mod, LEVEL_1, "transformed into %+F\n", res));
1252                         else
1253                                 DB((cg->mod, LEVEL_1, "not transformed\n"));
1254                 }
1255         }
1256         else if (is_ia32_Ld(irn) || is_ia32_St(irn) || is_ia32_Store8Bit(irn)) {
1257                 /* - Load  -> LEA into Load  } TODO: If the LEA is used by more than one Load/Store */
1258                 /* - Store -> LEA into Store }       it might be better to keep the LEA             */
1259                 left = get_irn_n(irn, 0);
1260
1261                 if (is_ia32_Lea(left)) {
1262                         const ir_edge_t *edge, *ne;
1263                         ir_node *src;
1264
1265                         /* merge all Loads/Stores connected to this LEA with the LEA */
1266                         foreach_out_edge_safe(left, edge, ne) {
1267                                 src = get_edge_src_irn(edge);
1268
1269                                 if (src && (is_ia32_Ld(src) || is_ia32_St(src) || is_ia32_Store8Bit(src))) {
1270                                         DBG((cg->mod, LEVEL_1, "\nmerging %+F into %+F\n", left, irn));
1271                                         merge_loadstore_lea(src, left);
1272                                         ret = 1;
1273                                 }
1274                         }
1275                 }
1276         }
1277
1278         return ret;
1279 }
1280
1281
1282 /**
1283  * Checks for address mode patterns and performs the
1284  * necessary transformations.
1285  * This function is called by a walker.
1286  */
1287 static void optimize_am(ir_node *irn, void *env) {
1288         ia32_code_gen_t   *cg   = env;
1289         ir_node           *res  = irn;
1290         dbg_info          *dbg;
1291         ir_mode           *mode;
1292         ir_node           *block, *noreg_gp, *noreg_fp;
1293         ir_node           *left, *right, *temp;
1294         ir_node           *store, *load, *mem_proj;
1295         ir_node           *succ, *addr_b, *addr_i;
1296         int               check_am_src = 0;
1297         int               need_exchange_on_fail = 0;
1298         DEBUG_ONLY(firm_dbg_module_t *mod = cg->mod;)
1299
1300         if (! is_ia32_irn(irn))
1301                 return;
1302
1303         dbg      = get_irn_dbg_info(irn);
1304         mode     = get_irn_mode(irn);
1305         block    = get_nodes_block(irn);
1306         noreg_gp = ia32_new_NoReg_gp(cg);
1307         noreg_fp = ia32_new_NoReg_fp(cg);
1308
1309         DBG((mod, LEVEL_1, "checking for AM\n"));
1310
1311         /* fold following patterns:                                                         */
1312         /* - op -> Load into AMop with am_Source                                            */
1313         /*   conditions:                                                                    */
1314         /*     - op is am_Source capable AND                                                */
1315         /*     - the Load is only used by this op AND                                       */
1316         /*     - the Load is in the same block                                              */
1317         /* - Store -> op -> Load  into AMop with am_Dest                                    */
1318         /*   conditions:                                                                    */
1319         /*     - op is am_Dest capable AND                                                  */
1320         /*     - the Store uses the same address as the Load AND                            */
1321         /*     - the Load is only used by this op AND                                       */
1322         /*     - the Load and Store are in the same block AND                               */
1323         /*     - nobody else uses the result of the op                                      */
1324
1325         if ((get_ia32_am_support(irn) != ia32_am_None) && ! is_ia32_Lea(irn) && is_candidate(block, irn, 0)) {
1326                 DBG((mod, LEVEL_1, "\tfound address mode candidate %+F ... ", irn));
1327
1328                 left  = get_irn_n(irn, 2);
1329                 if (get_irn_arity(irn) == 4) {
1330                         /* it's an "unary" operation */
1331                         right = left;
1332                 }
1333                 else {
1334                         right = get_irn_n(irn, 3);
1335                 }
1336
1337                 /* normalize commutative ops */
1338                 if (node_is_ia32_comm(irn)) {
1339                         /* Assure that right operand is always a Load if there is one    */
1340                         /* because non-commutative ops can only use Dest AM if the right */
1341                         /* operand is a load, so we only need to check right operand.    */
1342                         if (pred_is_specific_nodeblock(block, left, is_ia32_Ld))
1343                         {
1344                                 exchange_left_right(irn, &left, &right, 3, 2);
1345                                 need_exchange_on_fail = 1;
1346                         }
1347                 }
1348
1349                 /* check for Store -> op -> Load */
1350
1351                 /* Store -> op -> Load optimization is only possible if supported by op */
1352                 /* and if right operand is a Load                                       */
1353                 if ((get_ia32_am_support(irn) & ia32_am_Dest) &&
1354                          pred_is_specific_nodeblock(block, right, is_ia32_Ld))
1355                 {
1356
1357                         /* An address mode capable op always has a result Proj.                  */
1358                         /* If this Proj is used by more than one other node, we don't need to    */
1359                         /* check further, otherwise we check for Store and remember the address, */
1360                         /* the Store points to. */
1361
1362                         succ = get_res_proj(irn);
1363                         assert(succ && "Couldn't find result proj");
1364
1365                         addr_b = NULL;
1366                         addr_i = NULL;
1367                         store  = NULL;
1368
1369                         /* now check for users and Store */
1370                         if (ia32_get_irn_n_edges(succ) == 1) {
1371                                 succ = get_edge_src_irn(get_irn_out_edge_first(succ));
1372
1373                                 if (is_ia32_xStore(succ) || is_ia32_Store(succ)) {
1374                                         store  = succ;
1375                                         addr_b = get_irn_n(store, 0);
1376                                         addr_i = get_irn_n(store, 1);
1377                                 }
1378                         }
1379
1380                         if (store) {
1381                                 /* we found a Store as single user: Now check for Load */
1382
1383                                 /* Extra check for commutative ops with two Loads */
1384                                 /* -> put the interesting Load right              */
1385                                 if (node_is_ia32_comm(irn) &&
1386                                         pred_is_specific_nodeblock(block, left, is_ia32_Ld))
1387                                 {
1388                                         if ((addr_b == get_irn_n(get_Proj_pred(left), 0)) &&
1389                                                 (addr_i == get_irn_n(get_Proj_pred(left), 1)))
1390                                         {
1391                                                 /* We exchange left and right, so it's easier to kill     */
1392                                                 /* the correct Load later and to handle unary operations. */
1393                                                 set_irn_n(irn, 2, right);
1394                                                 set_irn_n(irn, 3, left);
1395
1396                                                 temp  = left;
1397                                                 left  = right;
1398                                                 right = temp;
1399
1400                                                 /* this is only needed for Compares, but currently ALL nodes
1401                                                  * have this attribute :-) */
1402                                                 set_ia32_pncode(irn, get_inversed_pnc(get_ia32_pncode(irn)));
1403                                         }
1404                                 }
1405
1406                                 /* skip the Proj for easier access */
1407                                 load = get_Proj_pred(right);
1408
1409                                 /* Compare Load and Store address */
1410                                 if (load_store_addr_is_equal(load, store, addr_b, addr_i)) {
1411                                         /* Right Load is from same address, so we can */
1412                                         /* disconnect the Load and Store here        */
1413
1414                                         /* set new base, index and attributes */
1415                                         set_irn_n(irn, 0, addr_b);
1416                                         set_irn_n(irn, 1, addr_i);
1417                                         add_ia32_am_offs(irn, get_ia32_am_offs(load));
1418                                         set_ia32_am_scale(irn, get_ia32_am_scale(load));
1419                                         set_ia32_am_flavour(irn, get_ia32_am_flavour(load));
1420                                         set_ia32_op_type(irn, ia32_AddrModeD);
1421                                         set_ia32_frame_ent(irn, get_ia32_frame_ent(load));
1422                                         set_ia32_ls_mode(irn, get_ia32_ls_mode(load));
1423
1424                                         set_ia32_am_sc(irn, get_ia32_am_sc(load));
1425                                         if (is_ia32_am_sc_sign(load))
1426                                                 set_ia32_am_sc_sign(irn);
1427
1428                                         if (is_ia32_use_frame(load))
1429                                                 set_ia32_use_frame(irn);
1430
1431                                         /* connect to Load memory and disconnect Load */
1432                                         if (get_irn_arity(irn) == 5) {
1433                                                 /* binary AMop */
1434                                                 set_irn_n(irn, 4, get_irn_n(load, 2));
1435                                                 set_irn_n(irn, 3, noreg_gp);
1436                                         }
1437                                         else {
1438                                                 /* unary AMop */
1439                                                 set_irn_n(irn, 3, get_irn_n(load, 2));
1440                                                 set_irn_n(irn, 2, noreg_gp);
1441                                         }
1442
1443                                         /* connect the memory Proj of the Store to the op */
1444                                         mem_proj = get_mem_proj(store);
1445                                         set_Proj_pred(mem_proj, irn);
1446                                         set_Proj_proj(mem_proj, 1);
1447
1448                                         /* clear remat flag */
1449                                         set_ia32_flags(irn, get_ia32_flags(irn) & ~arch_irn_flags_rematerializable);
1450
1451                                         DBG_OPT_AM_D(load, store, irn);
1452
1453                                         DB((mod, LEVEL_1, "merged with %+F and %+F into dest AM\n", load, store));
1454                                 }
1455                         } /* if (store) */
1456                         else if (get_ia32_am_support(irn) & ia32_am_Source) {
1457                                 /* There was no store, check if we still can optimize for source address mode */
1458                                 check_am_src = 1;
1459                         }
1460                 } /* if (support AM Dest) */
1461                 else if (get_ia32_am_support(irn) & ia32_am_Source) {
1462                         /* op doesn't support am AM Dest -> check for AM Source */
1463                         check_am_src = 1;
1464                 }
1465
1466                 /* was exchanged but optimize failed: exchange back */
1467                 if (check_am_src && need_exchange_on_fail)
1468                         exchange_left_right(irn, &left, &right, 3, 2);
1469
1470                 need_exchange_on_fail = 0;
1471
1472                 /* normalize commutative ops */
1473                 if (check_am_src && node_is_ia32_comm(irn)) {
1474                         /* Assure that left operand is always a Load if there is one */
1475                         /* because non-commutative ops can only use Source AM if the */
1476                         /* left operand is a Load, so we only need to check the left */
1477                         /* operand afterwards.                                       */
1478                         if (pred_is_specific_nodeblock(block, right, is_ia32_Ld))       {
1479                                 exchange_left_right(irn, &left, &right, 3, 2);
1480                                 need_exchange_on_fail = 1;
1481                         }
1482                 }
1483
1484                 /* optimize op -> Load iff Load is only used by this op   */
1485                 /* and left operand is a Load which only used by this irn */
1486                 if (check_am_src                                        &&
1487                         pred_is_specific_nodeblock(block, left, is_ia32_Ld) &&
1488                         (ia32_get_irn_n_edges(left) == 1))
1489                 {
1490                         left = get_Proj_pred(left);
1491
1492                         addr_b = get_irn_n(left, 0);
1493                         addr_i = get_irn_n(left, 1);
1494
1495                         /* set new base, index and attributes */
1496                         set_irn_n(irn, 0, addr_b);
1497                         set_irn_n(irn, 1, addr_i);
1498                         add_ia32_am_offs(irn, get_ia32_am_offs(left));
1499                         set_ia32_am_scale(irn, get_ia32_am_scale(left));
1500                         set_ia32_am_flavour(irn, get_ia32_am_flavour(left));
1501                         set_ia32_op_type(irn, ia32_AddrModeS);
1502                         set_ia32_frame_ent(irn, get_ia32_frame_ent(left));
1503                         set_ia32_ls_mode(irn, get_ia32_ls_mode(left));
1504
1505                         set_ia32_am_sc(irn, get_ia32_am_sc(left));
1506                         if (is_ia32_am_sc_sign(left))
1507                                 set_ia32_am_sc_sign(irn);
1508
1509                         /* clear remat flag */
1510                         set_ia32_flags(irn, get_ia32_flags(irn) & ~arch_irn_flags_rematerializable);
1511
1512                         if (is_ia32_use_frame(left))
1513                                 set_ia32_use_frame(irn);
1514
1515                         /* connect to Load memory */
1516                         if (get_irn_arity(irn) == 5) {
1517                                 /* binary AMop */
1518                                 set_irn_n(irn, 4, get_irn_n(left, 2));
1519
1520                                 /* this is only needed for Compares, but currently ALL nodes
1521                                  * have this attribute :-) */
1522                                 set_ia32_pncode(irn, get_inversed_pnc(get_ia32_pncode(irn)));
1523
1524                                 /* disconnect from Load */
1525                                 /* (make second op -> first, set second in to noreg) */
1526                                 set_irn_n(irn, 2, get_irn_n(irn, 3));
1527                                 set_irn_n(irn, 3, noreg_gp);
1528                         }
1529                         else {
1530                                 /* unary AMop */
1531                                 set_irn_n(irn, 3, get_irn_n(left, 2));
1532
1533                                 /* disconnect from Load */
1534                                 set_irn_n(irn, 2, noreg_gp);
1535                         }
1536
1537                         DBG_OPT_AM_S(left, irn);
1538
1539                         /* If Load has a memory Proj, connect it to the op */
1540                         mem_proj = get_mem_proj(left);
1541                         if (mem_proj) {
1542                                 set_Proj_pred(mem_proj, irn);
1543                                 set_Proj_proj(mem_proj, 1);
1544                         }
1545
1546                         DB((mod, LEVEL_1, "merged with %+F into source AM\n", left));
1547                 }
1548                 else {
1549                         /* was exchanged but optimize failed: exchange back */
1550                         if (need_exchange_on_fail)
1551                                 exchange_left_right(irn, &left, &right, 3, 2);
1552                 }
1553         }
1554 }
1555
1556 /**
1557  * This function is called by a walker and performs LEA optimization only.
1558  * It's a wrapper for optimize_address_calculation because this one returns
1559  * the transformed irn (or NULL) which gives a type mismatch for walker
1560  * functions.
1561  */
1562 static void optimize_lea(ir_node *irn, void *env) {
1563         (void)optimize_address_calculation(irn, env);
1564 }
1565
1566 /**
1567  * This function first performs LEA optimization and if this failed
1568  * it performs address mode optimization.
1569  */
1570 static void optimize_all(ir_node *irn, void *env) {
1571         if (! optimize_address_calculation(irn, env)) {
1572                 /* irn was not transformed into LEA: check for am */
1573                 optimize_am(irn, env);
1574         }
1575 }
1576
1577 /**
1578  * Performs address mode optimization.
1579  */
1580 void ia32_optimize_addressmode(ia32_code_gen_t *cg) {
1581         /* if we are supposed to do AM or LEA optimization: recalculate edges */
1582         if (cg->opt & (IA32_OPT_DOAM | IA32_OPT_LEA)) {
1583                 edges_deactivate(cg->irg);
1584                 edges_activate(cg->irg);
1585         }
1586         else {
1587                 /* no optimizations at all */
1588                 return;
1589         }
1590
1591         if ((cg->opt & IA32_OPT_DOAM) && (cg->opt & IA32_OPT_LEA)) {
1592                 /* optimize AM and LEA */
1593                 irg_walk_blkwise_graph(cg->irg, NULL, optimize_all, cg);
1594         }
1595         else if (cg->opt & IA32_OPT_DOAM) {
1596                 /* optimize AM only */
1597                 irg_walk_blkwise_graph(cg->irg, NULL, optimize_am, cg);
1598         }
1599         else {
1600                 /* optimize LEA only */
1601                 irg_walk_blkwise_graph(cg->irg, NULL, optimize_lea, cg);
1602         }
1603 }