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