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