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