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