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