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