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