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