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