added 8Bit Conv_I2I node
[libfirm] / ir / be / ia32 / ia32_optimize.c
1 #ifdef HAVE_CONFIG_H
2 #include "config.h"
3 #endif
4
5 #include "irnode.h"
6 #include "irprog_t.h"
7 #include "ircons.h"
8 #include "firm_types.h"
9 #include "iredges.h"
10 #include "tv.h"
11 #include "irgmod.h"
12
13 #include "../be_t.h"
14 #include "../beabi.h"
15 #include "../benode_t.h"
16 #include "../besched_t.h"
17
18 #include "ia32_new_nodes.h"
19 #include "bearch_ia32_t.h"
20 #include "gen_ia32_regalloc_if.h"     /* the generated interface (register type and class defenitions) */
21
22 #undef is_NoMem
23 #define is_NoMem(irn) (get_irn_op(irn) == op_NoMem)
24
25 typedef int is_op_func_t(const ir_node *n);
26
27 static int be_is_NoReg(be_abi_irg_t *babi, const ir_node *irn) {
28         if (be_abi_get_callee_save_irn(babi, &ia32_gp_regs[REG_XXX]) == irn ||
29                 be_abi_get_callee_save_irn(babi, &ia32_fp_regs[REG_XXXX]) == irn)
30         {
31                 return 1;
32         }
33
34         return 0;
35 }
36
37
38
39 /*************************************************
40  *   _____                _              _
41  *  / ____|              | |            | |
42  * | |     ___  _ __  ___| |_ __ _ _ __ | |_ ___
43  * | |    / _ \| '_ \/ __| __/ _` | '_ \| __/ __|
44  * | |___| (_) | | | \__ \ || (_| | | | | |_\__ \
45  *  \_____\___/|_| |_|___/\__\__,_|_| |_|\__|___/
46  *
47  *************************************************/
48
49 /**
50  * creates a unique ident by adding a number to a tag
51  *
52  * @param tag   the tag string, must contain a %d if a number
53  *              should be added
54  */
55 static ident *unique_id(const char *tag)
56 {
57         static unsigned id = 0;
58         char str[256];
59
60         snprintf(str, sizeof(str), tag, ++id);
61         return new_id_from_str(str);
62 }
63
64
65
66 /**
67  * Transforms a SymConst.
68  *
69  * @param mod     the debug module
70  * @param block   the block the new node should belong to
71  * @param node    the ir SymConst node
72  * @param mode    mode of the SymConst
73  * @return the created ia32 Const node
74  */
75 static ir_node *gen_SymConst(ia32_transform_env_t *env) {
76         ir_node  *cnst;
77         dbg_info *dbg   = env->dbg;
78         ir_mode  *mode  = env->mode;
79         ir_graph *irg   = env->irg;
80         ir_node  *block = env->block;
81
82         if (mode_is_float(mode)) {
83                 cnst = new_rd_ia32_fConst(dbg, irg, block, mode);
84         }
85         else {
86                 cnst = new_rd_ia32_Const(dbg, irg, block, mode);
87         }
88         set_ia32_Const_attr(cnst, env->irn);
89         return cnst;
90 }
91
92 /**
93  * Get a primitive type for a mode.
94  */
95 static ir_type *get_prim_type(pmap *types, ir_mode *mode)
96 {
97         pmap_entry *e = pmap_find(types, mode);
98         ir_type *res;
99
100         if (! e) {
101                 char buf[64];
102                 snprintf(buf, sizeof(buf), "prim_type_%s", get_mode_name(mode));
103                 res = new_type_primitive(new_id_from_str(buf), mode);
104                 pmap_insert(types, mode, res);
105         }
106         else
107                 res = e->value;
108         return res;
109 }
110
111 /**
112  * Get an entity that is initialized with a tarval
113  */
114 static entity *get_entity_for_tv(ia32_code_gen_t *cg, ir_node *cnst)
115 {
116         tarval *tv    = get_Const_tarval(cnst);
117         pmap_entry *e = pmap_find(cg->tv_ent, tv);
118         entity *res;
119         ir_graph *rem;
120
121         if (! e) {
122                 ir_mode *mode = get_irn_mode(cnst);
123                 ir_type *tp = get_Const_type(cnst);
124                 if (tp == firm_unknown_type)
125                         tp = get_prim_type(cg->types, mode);
126
127                 res = new_entity(get_glob_type(), unique_id("ia32FloatCnst_%u"), tp);
128
129                 set_entity_ld_ident(res, get_entity_ident(res));
130                 set_entity_visibility(res, visibility_local);
131                 set_entity_variability(res, variability_constant);
132                 set_entity_allocation(res, allocation_static);
133
134                  /* we create a new entity here: It's initialization must resist on the
135                     const code irg */
136                 rem = current_ir_graph;
137                 current_ir_graph = get_const_code_irg();
138                 set_atomic_ent_value(res, new_Const_type(tv, tp));
139                 current_ir_graph = rem;
140         }
141         else
142                 res = e->value;
143         return res;
144 }
145
146 /**
147  * Transforms a Const.
148  *
149  * @param mod     the debug module
150  * @param block   the block the new node should belong to
151  * @param node    the ir Const node
152  * @param mode    mode of the Const
153  * @return the created ia32 Const node
154  */
155 static ir_node *gen_Const(ia32_transform_env_t *env) {
156         ir_node *cnst;
157         symconst_symbol sym;
158         ir_graph *irg   = env->irg;
159         ir_node  *block = env->block;
160         ir_node  *node  = env->irn;
161         dbg_info *dbg   = env->dbg;
162         ir_mode  *mode  = env->mode;
163
164         if (mode_is_float(mode)) {
165                 sym.entity_p = get_entity_for_tv(env->cg, node);
166
167                 cnst = new_rd_SymConst(dbg, irg, block, sym, symconst_addr_ent);
168                 env->irn = cnst;
169                 cnst = gen_SymConst(env);
170         }
171         else {
172                 cnst = new_rd_ia32_Const(dbg, irg, block, get_irn_mode(node));
173                 set_ia32_Const_attr(cnst, node);
174         }
175         return cnst;
176 }
177
178
179
180 /**
181  * Transforms (all) Const's into ia32_Const and places them in the
182  * block where they are used (or in the cfg-pred Block in case of Phi's).
183  * Additionally all reference nodes are changed into mode_Is nodes.
184  */
185 void ia32_place_consts_set_modes(ir_node *irn, void *env) {
186         ia32_code_gen_t      *cg = env;
187         ia32_transform_env_t  tenv;
188         ir_mode              *mode;
189         ir_node              *pred, *cnst;
190         int                   i;
191         opcode                opc;
192
193         if (is_Block(irn))
194                 return;
195
196         mode = get_irn_mode(irn);
197
198         /* transform all reference nodes into mode_Is nodes */
199         if (mode_is_reference(mode)) {
200                 mode = mode_Is;
201                 set_irn_mode(irn, mode);
202         }
203
204         tenv.block    = get_nodes_block(irn);
205         tenv.cg       = cg;
206         tenv.irg      = cg->irg;
207         tenv.mod      = cg->mod;
208
209         /* Loop over all predecessors and check for Sym/Const nodes */
210         for (i = get_irn_arity(irn) - 1; i >= 0; --i) {
211                 pred      = get_irn_n(irn, i);
212                 cnst      = NULL;
213                 opc       = get_irn_opcode(pred);
214                 tenv.irn  = pred;
215                 tenv.mode = get_irn_mode(pred);
216                 tenv.dbg  = get_irn_dbg_info(pred);
217
218                 /* If it's a Phi, then we need to create the */
219                 /* new Const in it's predecessor block       */
220                 if (is_Phi(irn)) {
221                         tenv.block = get_Block_cfgpred_block(get_nodes_block(irn), i);
222                 }
223
224                 /* put the const into the block where the original const was */
225                 if (! cg->opt.placecnst) {
226                         tenv.block = get_nodes_block(pred);
227                 }
228
229                 switch (opc) {
230                         case iro_Const:
231                                 cnst = gen_Const(&tenv);
232                                 break;
233                         case iro_SymConst:
234                                 cnst = gen_SymConst(&tenv);
235                                 break;
236                         default:
237                                 break;
238                 }
239
240                 /* if we found a const, then set it */
241                 if (cnst) {
242                         set_irn_n(irn, i, cnst);
243                 }
244         }
245 }
246
247
248
249 /********************************************************************************************************
250  *  _____                _           _         ____        _   _           _          _   _
251  * |  __ \              | |         | |       / __ \      | | (_)         (_)        | | (_)
252  * | |__) |__  ___ _ __ | |__   ___ | | ___  | |  | |_ __ | |_ _ _ __ ___  _ ______ _| |_ _  ___  _ __
253  * |  ___/ _ \/ _ \ '_ \| '_ \ / _ \| |/ _ \ | |  | | '_ \| __| | '_ ` _ \| |_  / _` | __| |/ _ \| '_ \
254  * | |  |  __/  __/ |_) | | | | (_) | |  __/ | |__| | |_) | |_| | | | | | | |/ / (_| | |_| | (_) | | | |
255  * |_|   \___|\___| .__/|_| |_|\___/|_|\___|  \____/| .__/ \__|_|_| |_| |_|_/___\__,_|\__|_|\___/|_| |_|
256  *                | |                               | |
257  *                |_|                               |_|
258  ********************************************************************************************************/
259
260 /**
261  * NOTE: THESE PEEPHOLE OPTIMIZATIONS MUST BE CALLED AFTER SCHEDULING AND REGISTER ALLOCATION.
262  */
263
264 static int ia32_cnst_compare(ir_node *n1, ir_node *n2) {
265         char *c1 = get_ia32_cnst(n1);
266         char *c2 = get_ia32_cnst(n2);
267
268         if (c1 && c2)                    /* both consts are set -> compare */
269                 return strcmp(c1, c2) == 0;
270         else if (!c1 && !c2)             /* both consts are not set -> true */
271                 return 1;
272
273         return 0;
274 }
275
276 /**
277  * Checks for potential CJmp/CJmpAM optimization candidates.
278  */
279 static ir_node *ia32_determine_cjmp_cand(ir_node *irn, is_op_func_t *is_op_func) {
280         ir_node *cand = NULL;
281         ir_node *prev = sched_prev(irn);
282
283         if (is_Block(prev)) {
284                 if (get_Block_n_cfgpreds(prev) == 1)
285                         prev = get_Block_cfgpred(prev, 0);
286                 else
287                         prev = NULL;
288         }
289
290         /* The predecessor must be a ProjX. */
291         if (prev && is_Proj(prev) && get_irn_mode(prev) == mode_X) {
292                 prev = get_Proj_pred(prev);
293
294                 if (is_op_func(prev))
295                         cand = prev;
296         }
297
298         return cand;
299 }
300
301 static int is_TestJmp_cand(const ir_node *irn) {
302         return is_ia32_TestJmp(irn) || is_ia32_And(irn);
303 }
304
305 /**
306  * Checks if two consecutive arguments of cand matches
307  * the two arguments of irn (TestJmp).
308  */
309 static int is_TestJmp_replacement(ir_node *cand, ir_node *irn) {
310         ir_node *in1       = get_irn_n(irn, 0);
311         ir_node *in2       = get_irn_n(irn, 1);
312         int      i, n      = get_irn_arity(cand);
313         int      same_args = 0;
314
315         for (i = 0; i < n - 1; i++) {
316                 if (get_irn_n(cand, i)     == in1 &&
317                         get_irn_n(cand, i + 1) == in2)
318                 {
319                         same_args = 1;
320                         break;
321                 }
322         }
323
324         if (same_args)
325                 return ia32_cnst_compare(cand, irn);
326
327         return 0;
328 }
329
330 /**
331  * Tries to replace a TestJmp by a CJmp or CJmpAM (in case of And)
332  */
333 static void ia32_optimize_TestJmp(ir_node *irn, ia32_code_gen_t *cg) {
334         ir_node *cand    = ia32_determine_cjmp_cand(irn, is_TestJmp_cand);
335         int      replace = 0;
336
337         /* we found a possible candidate */
338         replace = cand ? is_TestJmp_replacement(cand, irn) : 0;
339
340         if (replace) {
341                 DBG((cg->mod, LEVEL_1, "replacing %+F by ", irn));
342
343                 if (is_ia32_And(cand))
344                         set_irn_op(irn, op_ia32_CJmpAM);
345                 else
346                         set_irn_op(irn, op_ia32_CJmp);
347
348                 DB((cg->mod, LEVEL_1, "%+F\n", irn));
349         }
350 }
351
352 static int is_CondJmp_cand(const ir_node *irn) {
353         return is_ia32_CondJmp(irn) || is_ia32_Sub(irn);
354 }
355
356 /**
357  * Checks if the arguments of cand are the same of irn.
358  */
359 static int is_CondJmp_replacement(ir_node *cand, ir_node *irn) {
360         int i, n      = get_irn_arity(cand);
361         int same_args = 0;
362
363         for (i = 0; i < n; i++) {
364                 if (get_irn_n(cand, i) == get_irn_n(irn, i)) {
365                         same_args = 1;
366                         break;
367                 }
368         }
369
370         if (same_args)
371                 return ia32_cnst_compare(cand, irn);
372
373         return 0;
374 }
375
376 /**
377  * Tries to replace a CondJmp by a CJmpAM
378  */
379 static void ia32_optimize_CondJmp(ir_node *irn, ia32_code_gen_t *cg) {
380         ir_node *cand    = ia32_determine_cjmp_cand(irn, is_CondJmp_cand);
381         int      replace = 0;
382
383         /* we found a possible candidate */
384         replace = cand ? is_CondJmp_replacement(cand, irn) : 0;
385
386         if (replace) {
387                 DBG((cg->mod, LEVEL_1, "replacing %+F by ", irn));
388
389                 set_irn_op(irn, op_ia32_CJmp);
390
391                 DB((cg->mod, LEVEL_1, "%+F\n", irn));
392         }
393 }
394
395 /**
396  * Performs Peephole Optimizations
397  */
398 void ia32_peephole_optimization(ir_node *irn, void *env) {
399         if (is_ia32_TestJmp(irn)) {
400                 ia32_optimize_TestJmp(irn, env);
401         }
402         else if (is_ia32_CondJmp(irn)) {
403                 ia32_optimize_CondJmp(irn, env);
404         }
405 }
406
407
408
409 /******************************************************************
410  *              _     _                   __  __           _
411  *     /\      | |   | |                 |  \/  |         | |
412  *    /  \   __| | __| |_ __ ___  ___ ___| \  / | ___   __| | ___
413  *   / /\ \ / _` |/ _` | '__/ _ \/ __/ __| |\/| |/ _ \ / _` |/ _ \
414  *  / ____ \ (_| | (_| | | |  __/\__ \__ \ |  | | (_) | (_| |  __/
415  * /_/    \_\__,_|\__,_|_|  \___||___/___/_|  |_|\___/ \__,_|\___|
416  *
417  ******************************************************************/
418
419 static int node_is_comm(const ir_node *irn) {
420         return is_ia32_irn(irn) ? is_ia32_commutative(irn) : 0;
421 }
422
423 static int ia32_get_irn_n_edges(const ir_node *irn) {
424         const ir_edge_t *edge;
425         int cnt = 0;
426
427         foreach_out_edge(irn, edge) {
428                 cnt++;
429         }
430
431         return cnt;
432 }
433
434 /**
435  * Returns the first mode_M Proj connected to irn.
436  */
437 static ir_node *get_mem_proj(const ir_node *irn) {
438         const ir_edge_t *edge;
439         ir_node         *src;
440
441         assert(get_irn_mode(irn) == mode_T && "expected mode_T node");
442
443         foreach_out_edge(irn, edge) {
444                 src = get_edge_src_irn(edge);
445
446                 assert(is_Proj(src) && "Proj expected");
447
448                 if (get_irn_mode(src) == mode_M)
449                         return src;
450         }
451
452         return NULL;
453 }
454
455 /**
456  * Returns the first Proj with mode != mode_M connected to irn.
457  */
458 static ir_node *get_res_proj(const ir_node *irn) {
459         const ir_edge_t *edge;
460         ir_node         *src;
461
462         assert(get_irn_mode(irn) == mode_T && "expected mode_T node");
463
464         foreach_out_edge(irn, edge) {
465                 src = get_edge_src_irn(edge);
466
467                 assert(is_Proj(src) && "Proj expected");
468
469                 if (get_irn_mode(src) != mode_M)
470                         return src;
471         }
472
473         return NULL;
474 }
475
476 /**
477  * Determines if pred is a Proj and if is_op_func returns true for it's predecessor.
478  *
479  * @param pred       The node to be checked
480  * @param is_op_func The check-function
481  * @return 1 if conditions are fulfilled, 0 otherwise
482  */
483 static int pred_is_specific_node(const ir_node *pred, is_op_func_t *is_op_func) {
484         if (is_Proj(pred) && is_op_func(get_Proj_pred(pred))) {
485                 return 1;
486         }
487
488         return 0;
489 }
490
491 /**
492  * Determines if pred is a Proj and if is_op_func returns true for it's predecessor
493  * and if the predecessor is in block bl.
494  *
495  * @param bl         The block
496  * @param pred       The node to be checked
497  * @param is_op_func The check-function
498  * @return 1 if conditions are fulfilled, 0 otherwise
499  */
500 static int pred_is_specific_nodeblock(const ir_node *bl, const ir_node *pred,
501         int (*is_op_func)(const ir_node *n))
502 {
503         if (is_Proj(pred)) {
504                 pred = get_Proj_pred(pred);
505                 if ((bl == get_nodes_block(pred)) && is_op_func(pred)) {
506                         return 1;
507                 }
508         }
509
510         return 0;
511 }
512
513
514
515 /**
516  * Checks if irn is a candidate for address calculation or address mode.
517  *
518  * address calculation (AC):
519  * - none of the operand must be a Load  within the same block OR
520  * - all Loads must have more than one user                    OR
521  * - the irn has a frame entity (it's a former FrameAddr)
522  *
523  * address mode (AM):
524  * - at least one operand has to be a Load within the same block AND
525  * - the load must not have other users than the irn             AND
526  * - the irn must not have a frame entity set
527  *
528  * @param block       The block the Loads must/not be in
529  * @param irn         The irn to check
530  * @param check_addr  1 if to check for address calculation, 0 otherwise
531  * return 1 if irn is a candidate for AC or AM, 0 otherwise
532  */
533 static int is_candidate(const ir_node *block, const ir_node *irn, int check_addr) {
534         ir_node *in;
535         int      n, is_cand = check_addr;
536
537         in = get_irn_n(irn, 2);
538
539         if (pred_is_specific_nodeblock(block, in, is_ia32_Ld)) {
540                 n         = ia32_get_irn_n_edges(in);
541                 is_cand   = check_addr ? (n == 1 ? 0 : is_cand) : (n == 1 ? 1 : is_cand);
542         }
543
544         in = get_irn_n(irn, 3);
545
546         if (pred_is_specific_nodeblock(block, in, is_ia32_Ld)) {
547                 n         = ia32_get_irn_n_edges(in);
548                 is_cand   = check_addr ? (n == 1 ? 0 : is_cand) : (n == 1 ? 1 : is_cand);
549         }
550
551         is_cand = get_ia32_frame_ent(irn) ? (check_addr ? 1 : 0) : is_cand;
552
553         return is_cand;
554 }
555
556 /**
557  * Compares the base and index addr and the load/store entities
558  * and returns 1 if they are equal.
559  */
560 static int load_store_addr_is_equal(const ir_node *load, const ir_node *store,
561                                                                         const ir_node *addr_b, const ir_node *addr_i)
562 {
563         int     is_equal = (addr_b == get_irn_n(load, 0)) && (addr_i == get_irn_n(load, 1));
564         entity *lent     = get_ia32_frame_ent(load);
565         entity *sent     = get_ia32_frame_ent(store);
566
567         /* are both entities set and equal? */
568         is_equal = lent && sent && (lent == sent);
569
570         /* are the load and the store of the same mode? */
571         is_equal = get_ia32_ls_mode(load) == get_ia32_ls_mode(store);
572
573         return is_equal;
574 }
575
576
577
578 /**
579  * Folds Add or Sub to LEA if possible
580  */
581 static ir_node *fold_addr(be_abi_irg_t *babi, ir_node *irn, firm_dbg_module_t *mod, ir_node *noreg) {
582         ir_graph *irg       = get_irn_irg(irn);
583         dbg_info *dbg       = get_irn_dbg_info(irn);
584         ir_node  *block     = get_nodes_block(irn);
585         ir_node  *res       = irn;
586         char     *offs      = NULL;
587         char     *offs_cnst = NULL;
588         char     *offs_lea  = NULL;
589         int       scale     = 0;
590         int       isadd     = 0;
591         int       dolea     = 0;
592         ir_node  *left, *right, *temp;
593         ir_node  *base, *index;
594         ia32_am_flavour_t am_flav;
595
596         if (is_ia32_Add(irn))
597                 isadd = 1;
598
599         left  = get_irn_n(irn, 2);
600         right = get_irn_n(irn, 3);
601
602         /* "normalize" arguments in case of add with two operands */
603         if  (isadd && ! be_is_NoReg(babi, right)) {
604                 /* put LEA == ia32_am_O as right operand */
605                 if (is_ia32_Lea(left) && get_ia32_am_flavour(left) == ia32_am_O) {
606                         set_irn_n(irn, 2, right);
607                         set_irn_n(irn, 3, left);
608                         temp  = left;
609                         left  = right;
610                         right = temp;
611                 }
612
613                 /* put LEA != ia32_am_O as left operand */
614                 if (is_ia32_Lea(right) && get_ia32_am_flavour(right) != ia32_am_O) {
615                         set_irn_n(irn, 2, right);
616                         set_irn_n(irn, 3, left);
617                         temp  = left;
618                         left  = right;
619                         right = temp;
620                 }
621
622                 /* put SHL as left operand iff left is NOT a LEA */
623                 if (! is_ia32_Lea(left) && pred_is_specific_node(right, is_ia32_Shl)) {
624                         set_irn_n(irn, 2, right);
625                         set_irn_n(irn, 3, left);
626                         temp  = left;
627                         left  = right;
628                         right = temp;
629                 }
630         }
631
632         base    = left;
633         index   = noreg;
634         offs    = NULL;
635         scale   = 0;
636         am_flav = 0;
637
638         /* check if operand is either const */
639         if (get_ia32_cnst(irn)) {
640                 DBG((mod, LEVEL_1, "\tfound op with imm"));
641
642                 offs_cnst = get_ia32_cnst(irn);
643                 dolea     = 1;
644         }
645
646         /* determine the operand which needs to be checked */
647         if (be_is_NoReg(babi, right)) {
648                 temp = left;
649         }
650         else {
651                 temp = right;
652         }
653
654         /* check if right operand is AMConst (LEA with ia32_am_O) */
655         if (is_ia32_Lea(temp) && get_ia32_am_flavour(temp) == ia32_am_O) {
656                 DBG((mod, LEVEL_1, "\tgot op with LEA am_O"));
657
658                 offs_lea = get_ia32_am_offs(temp);
659                 dolea    = 1;
660         }
661
662         if (isadd) {
663                 /* default for add -> make right operand to index */
664                 index = right;
665                 dolea = 1;
666
667                 DBG((mod, LEVEL_1, "\tgot LEA candidate with index %+F\n", index));
668
669                 /* determine the operand which needs to be checked */
670                 temp = left;
671                 if (is_ia32_Lea(left)) {
672                         temp = right;
673                 }
674
675                 /* check for SHL 1,2,3 */
676                 if (pred_is_specific_node(temp, is_ia32_Shl)) {
677                         temp = get_Proj_pred(temp);
678
679                         if (get_ia32_Immop_tarval(temp)) {
680                                 scale = get_tarval_long(get_ia32_Immop_tarval(temp));
681
682                                 if (scale <= 3) {
683                                         index = get_irn_n(temp, 2);
684
685                                         DBG((mod, LEVEL_1, "\tgot scaled index %+F\n", index));
686                                 }
687                         }
688                 }
689
690                 /* fix base */
691                 if (! be_is_NoReg(babi, index)) {
692                         /* if we have index, but left == right -> no base */
693                         if (left == right) {
694                                 base = noreg;
695                         }
696                         else if (! is_ia32_Lea(left) && (index != right)) {
697                                 /* index != right -> we found a good Shl           */
698                                 /* left  != LEA   -> this Shl was the left operand */
699                                 /* -> base is right operand                        */
700                                 base = right;
701                         }
702                 }
703         }
704
705         /* Try to assimilate a LEA as left operand */
706         if (is_ia32_Lea(left) && (get_ia32_am_flavour(left) != ia32_am_O)) {
707                 am_flav = get_ia32_am_flavour(left);
708
709                 /* If we have an Add with a real right operand (not NoReg) and  */
710                 /* the LEA contains already an index calculation then we create */
711                 /* a new LEA.                                                   */
712                 /* If the LEA contains already a frame_entity then we also      */
713                 /* create a new one  otherwise we would loose it.               */
714                 if ((isadd && !be_is_NoReg(babi, index) && (am_flav & ia32_am_I)) ||
715                         get_ia32_frame_ent(left))
716                 {
717                         DBG((mod, LEVEL_1, "\tleave old LEA, creating new one\n"));
718                 }
719                 else {
720                         DBG((mod, LEVEL_1, "\tgot LEA as left operand ... assimilating\n"));
721                         offs  = get_ia32_am_offs(left);
722                         base  = get_irn_n(left, 0);
723                         index = get_irn_n(left, 1);
724                         scale = get_ia32_am_scale(left);
725                 }
726         }
727
728         /* ok, we can create a new LEA */
729         if (dolea) {
730                 res = new_rd_ia32_Lea(dbg, irg, block, base, index, mode_Is);
731
732                 /* add the old offset of a previous LEA */
733                 if (offs) {
734                         add_ia32_am_offs(res, offs);
735                 }
736
737                 /* add the new offset */
738                 if (isadd) {
739                         if (offs_cnst) {
740                                 add_ia32_am_offs(res, offs_cnst);
741                         }
742                         if (offs_lea) {
743                                 add_ia32_am_offs(res, offs_lea);
744                         }
745                 }
746                 else {
747                         /* either lea_O-cnst, -cnst or -lea_O  */
748                         if (offs_cnst) {
749                                 if (offs_lea) {
750                                         add_ia32_am_offs(res, offs_lea);
751                                 }
752
753                                 sub_ia32_am_offs(res, offs_cnst);
754                         }
755                         else {
756                                 sub_ia32_am_offs(res, offs_lea);
757                         }
758                 }
759
760                 /* copy the frame entity (could be set in case of Add */
761                 /* which was a FrameAddr) */
762                 set_ia32_frame_ent(res, get_ia32_frame_ent(irn));
763
764                 if (is_ia32_use_frame(irn))
765                         set_ia32_use_frame(res);
766
767                 /* set scale */
768                 set_ia32_am_scale(res, scale);
769
770                 am_flav = ia32_am_N;
771                 /* determine new am flavour */
772                 if (offs || offs_cnst || offs_lea) {
773                         am_flav |= ia32_O;
774                 }
775                 if (! be_is_NoReg(babi, base)) {
776                         am_flav |= ia32_B;
777                 }
778                 if (! be_is_NoReg(babi, index)) {
779                         am_flav |= ia32_I;
780                 }
781                 if (scale > 0) {
782                         am_flav |= ia32_S;
783                 }
784                 set_ia32_am_flavour(res, am_flav);
785
786                 set_ia32_op_type(res, ia32_AddrModeS);
787
788                 DBG((mod, LEVEL_1, "\tLEA [%+F + %+F * %d + %s]\n", base, index, scale, get_ia32_am_offs(res)));
789
790                 /* get the result Proj of the Add/Sub */
791                 irn = get_res_proj(irn);
792
793                 assert(irn && "Couldn't find result proj");
794
795                 /* exchange the old op with the new LEA */
796                 exchange(irn, res);
797         }
798
799         return res;
800 }
801
802 /**
803  * Optimizes a pattern around irn to address mode if possible.
804  */
805 void ia32_optimize_am(ir_node *irn, void *env) {
806         ia32_code_gen_t   *cg   = env;
807         firm_dbg_module_t *mod  = cg->mod;
808         ir_node           *res  = irn;
809         be_abi_irg_t      *babi = cg->birg->abi;
810         dbg_info          *dbg;
811         ir_mode           *mode;
812         ir_node           *block, *noreg_gp, *noreg_fp;
813         ir_node           *left, *right, *temp;
814         ir_node           *store, *load, *mem_proj;
815         ir_node           *succ, *addr_b, *addr_i;
816         int                check_am_src = 0;
817
818         if (! is_ia32_irn(irn))
819                 return;
820
821         dbg      = get_irn_dbg_info(irn);
822         mode     = get_irn_mode(irn);
823         block    = get_nodes_block(irn);
824         noreg_gp = ia32_new_NoReg_gp(cg);
825         noreg_fp = ia32_new_NoReg_fp(cg);
826
827         DBG((mod, LEVEL_1, "checking for AM\n"));
828
829         /* 1st part: check for address calculations and transform the into Lea */
830
831         /* Following cases can occur:                                  */
832         /* - Sub (l, imm) -> LEA [base - offset]                       */
833         /* - Sub (l, r == LEA with ia32_am_O)   -> LEA [base - offset] */
834         /* - Add (l, imm) -> LEA [base + offset]                       */
835         /* - Add (l, r == LEA with ia32_am_O)  -> LEA [base + offset]  */
836         /* - Add (l == LEA with ia32_am_O, r)  -> LEA [base + offset]  */
837         /* - Add (l, r) -> LEA [base + index * scale]                  */
838         /*              with scale > 1 iff l/r == shl (1,2,3)          */
839
840         if (is_ia32_Sub(irn) || is_ia32_Add(irn)) {
841                 left  = get_irn_n(irn, 2);
842                 right = get_irn_n(irn, 3);
843
844             /* Do not try to create a LEA if one of the operands is a Load. */
845                 /* check is irn is a candidate for address calculation */
846                 if (is_candidate(block, irn, 1)) {
847                         DBG((mod, LEVEL_1, "\tfound address calculation candidate %+F ... ", irn));
848                         res = fold_addr(babi, irn, mod, noreg_gp);
849
850                         if (res == irn)
851                                 DB((mod, LEVEL_1, "transformed into %+F\n", res));
852                         else
853                                 DB((mod, LEVEL_1, "not transformed\n"));
854                 }
855         }
856
857         /* 2nd part: fold following patterns:                                               */
858         /* - Load  -> LEA into Load  } TODO: If the LEA is used by more than one Load/Store */
859         /* - Store -> LEA into Store }       it might be better to keep the LEA             */
860         /* - op -> Load into AMop with am_Source                                            */
861         /*   conditions:                                                                    */
862         /*     - op is am_Source capable AND                                                */
863         /*     - the Load is only used by this op AND                                       */
864         /*     - the Load is in the same block                                              */
865         /* - Store -> op -> Load  into AMop with am_Dest                                    */
866         /*   conditions:                                                                    */
867         /*     - op is am_Dest capable AND                                                  */
868         /*     - the Store uses the same address as the Load AND                            */
869         /*     - the Load is only used by this op AND                                       */
870         /*     - the Load and Store are in the same block AND                               */
871         /*     - nobody else uses the result of the op                                      */
872
873         if ((res == irn) && (get_ia32_am_support(irn) != ia32_am_None) && !is_ia32_Lea(irn)) {
874                 /* 1st: check for Load/Store -> LEA   */
875                 if (is_ia32_Ld(irn) || is_ia32_St(irn) || is_ia32_Store8Bit(irn)) {
876                         left = get_irn_n(irn, 0);
877
878                         if (is_ia32_Lea(left)) {
879                                 DBG((mod, LEVEL_1, "\nmerging %+F into %+F\n", left, irn));
880
881                                 /* get the AM attributes from the LEA */
882                                 add_ia32_am_offs(irn, get_ia32_am_offs(left));
883                                 set_ia32_am_scale(irn, get_ia32_am_scale(left));
884                                 set_ia32_am_flavour(irn, get_ia32_am_flavour(left));
885
886                                 set_ia32_op_type(irn, is_ia32_Ld(irn) ? ia32_AddrModeS : ia32_AddrModeD);
887
888                                 /* set base and index */
889                                 set_irn_n(irn, 0, get_irn_n(left, 0));
890                                 set_irn_n(irn, 1, get_irn_n(left, 1));
891
892                                 /* clear remat flag */
893                                 set_ia32_flags(irn, get_ia32_flags(irn) & ~arch_irn_flags_rematerializable);
894                         }
895                 }
896                 /* check if the node is an address mode candidate */
897                 else if (is_candidate(block, irn, 0)) {
898                         DBG((mod, LEVEL_1, "\tfound address mode candidate %+F ... ", irn));
899
900                         left  = get_irn_n(irn, 2);
901                         if (get_irn_arity(irn) == 4) {
902                                 /* it's an "unary" operation */
903                                 right = left;
904                         }
905                         else {
906                                 right = get_irn_n(irn, 3);
907                         }
908
909                         /* normalize commutative ops */
910                         if (node_is_comm(irn)) {
911                                 /* Assure that right operand is always a Load if there is one    */
912                                 /* because non-commutative ops can only use Dest AM if the right */
913                                 /* operand is a load, so we only need to check right operand.    */
914                                 if (pred_is_specific_nodeblock(block, left, is_ia32_Ld))
915                                 {
916                                         set_irn_n(irn, 2, right);
917                                         set_irn_n(irn, 3, left);
918
919                                         temp  = left;
920                                         left  = right;
921                                         right = temp;
922                                 }
923                         }
924
925                         /* check for Store -> op -> Load */
926
927                         /* Store -> op -> Load optimization is only possible if supported by op */
928                         /* and if right operand is a Load                                       */
929                         if ((get_ia32_am_support(irn) & ia32_am_Dest) &&
930                                  pred_is_specific_nodeblock(block, right, is_ia32_Ld))
931                         {
932
933                                 /* An address mode capable op always has a result Proj.                  */
934                                 /* If this Proj is used by more than one other node, we don't need to    */
935                                 /* check further, otherwise we check for Store and remember the address, */
936                                 /* the Store points to. */
937
938                                 succ = get_res_proj(irn);
939                                 assert(succ && "Couldn't find result proj");
940
941                                 addr_b = NULL;
942                                 addr_i = NULL;
943                                 store  = NULL;
944
945                                 /* now check for users and Store */
946                                 if (ia32_get_irn_n_edges(succ) == 1) {
947                                         succ = get_edge_src_irn(get_irn_out_edge_first(succ));
948
949                                         if (is_ia32_fStore(succ) || is_ia32_Store(succ)) {
950                                                 store  = succ;
951                                                 addr_b = get_irn_n(store, 0);
952
953                                                 /* Could be that the Store is connected to the address    */
954                                                 /* calculating LEA while the Load is already transformed. */
955                                                 if (is_ia32_Lea(addr_b)) {
956                                                         succ   = addr_b;
957                                                         addr_b = get_irn_n(succ, 0);
958                                                         addr_i = get_irn_n(succ, 1);
959                                                 }
960                                                 else {
961                                                         addr_i = noreg_gp;
962                                                 }
963                                         }
964                                 }
965
966                                 if (store) {
967                                         /* we found a Store as single user: Now check for Load */
968
969                                         /* Extra check for commutative ops with two Loads */
970                                         /* -> put the interesting Load right              */
971                                         if (node_is_comm(irn) &&
972                                                 pred_is_specific_nodeblock(block, left, is_ia32_Ld))
973                                         {
974                                                 if ((addr_b == get_irn_n(get_Proj_pred(left), 0)) &&
975                                                         (addr_i == get_irn_n(get_Proj_pred(left), 1)))
976                                                 {
977                                                         /* We exchange left and right, so it's easier to kill     */
978                                                         /* the correct Load later and to handle unary operations. */
979                                                         set_irn_n(irn, 2, right);
980                                                         set_irn_n(irn, 3, left);
981
982                                                         temp  = left;
983                                                         left  = right;
984                                                         right = temp;
985                                                 }
986                                         }
987
988                                         /* skip the Proj for easier access */
989                                         load = get_Proj_pred(right);
990
991                                         /* Compare Load and Store address */
992                                         if (load_store_addr_is_equal(load, store, addr_b, addr_i)) {
993                                                 /* Right Load is from same address, so we can */
994                                                 /* disconnect the Load and Store here        */
995
996                                                 /* set new base, index and attributes */
997                                                 set_irn_n(irn, 0, addr_b);
998                                                 set_irn_n(irn, 1, addr_i);
999                                                 add_ia32_am_offs(irn, get_ia32_am_offs(load));
1000                                                 set_ia32_am_scale(irn, get_ia32_am_scale(load));
1001                                                 set_ia32_am_flavour(irn, get_ia32_am_flavour(load));
1002                                                 set_ia32_op_type(irn, ia32_AddrModeD);
1003                                                 set_ia32_frame_ent(irn, get_ia32_frame_ent(load));
1004                                                 set_ia32_ls_mode(irn, get_ia32_ls_mode(load));
1005
1006                                                 if (is_ia32_use_frame(load))
1007                                                         set_ia32_use_frame(irn);
1008
1009                                                 /* connect to Load memory and disconnect Load */
1010                                                 if (get_irn_arity(irn) == 5) {
1011                                                         /* binary AMop */
1012                                                         set_irn_n(irn, 4, get_irn_n(load, 2));
1013                                                         set_irn_n(irn, 3, noreg_gp);
1014                                                 }
1015                                                 else {
1016                                                         /* unary AMop */
1017                                                         set_irn_n(irn, 3, get_irn_n(load, 2));
1018                                                         set_irn_n(irn, 2, noreg_gp);
1019                                                 }
1020
1021                                                 /* connect the memory Proj of the Store to the op */
1022                                                 mem_proj = get_mem_proj(store);
1023                                                 set_Proj_pred(mem_proj, irn);
1024                                                 set_Proj_proj(mem_proj, 1);
1025
1026                                                 /* clear remat flag */
1027                                                 set_ia32_flags(irn, get_ia32_flags(irn) & ~arch_irn_flags_rematerializable);
1028
1029                                                 DB((mod, LEVEL_1, "merged with %+F and %+F into dest AM\n", load, store));
1030                                         }
1031                                 } /* if (store) */
1032                                 else if (get_ia32_am_support(irn) & ia32_am_Source) {
1033                                         /* There was no store, check if we still can optimize for source address mode */
1034                                         check_am_src = 1;
1035                                 }
1036                         } /* if (support AM Dest) */
1037                         else if (get_ia32_am_support(irn) & ia32_am_Source) {
1038                                 /* op doesn't support am AM Dest -> check for AM Source */
1039                                 check_am_src = 1;
1040                         }
1041
1042                         /* normalize commutative ops */
1043                         if (node_is_comm(irn)) {
1044                                 /* Assure that left operand is always a Load if there is one */
1045                                 /* because non-commutative ops can only use Source AM if the */
1046                                 /* left operand is a Load, so we only need to check the left */
1047                                 /* operand afterwards.                                       */
1048                                 if (pred_is_specific_nodeblock(block, right, is_ia32_Ld))       {
1049                                         set_irn_n(irn, 2, right);
1050                                         set_irn_n(irn, 3, left);
1051
1052                                         temp  = left;
1053                                         left  = right;
1054                                         right = temp;
1055                                 }
1056                         }
1057
1058                         /* optimize op -> Load iff Load is only used by this op   */
1059                         /* and left operand is a Load which only used by this irn */
1060                         if (check_am_src                                        &&
1061                                 pred_is_specific_nodeblock(block, left, is_ia32_Ld) &&
1062                                 (ia32_get_irn_n_edges(left) == 1))
1063                         {
1064                                 left = get_Proj_pred(left);
1065
1066                                 addr_b = get_irn_n(left, 0);
1067                                 addr_i = get_irn_n(left, 1);
1068
1069                                 /* set new base, index and attributes */
1070                                 set_irn_n(irn, 0, addr_b);
1071                                 set_irn_n(irn, 1, addr_i);
1072                                 add_ia32_am_offs(irn, get_ia32_am_offs(left));
1073                                 set_ia32_am_scale(irn, get_ia32_am_scale(left));
1074                                 set_ia32_am_flavour(irn, get_ia32_am_flavour(left));
1075                                 set_ia32_op_type(irn, ia32_AddrModeS);
1076                                 set_ia32_frame_ent(irn, get_ia32_frame_ent(left));
1077                                 set_ia32_ls_mode(irn, get_ia32_ls_mode(left));
1078
1079                                 /* clear remat flag */
1080                                 set_ia32_flags(irn, get_ia32_flags(irn) & ~arch_irn_flags_rematerializable);
1081
1082                                 if (is_ia32_use_frame(left))
1083                                         set_ia32_use_frame(irn);
1084
1085                                 /* connect to Load memory */
1086                                 if (get_irn_arity(irn) == 5) {
1087                                         /* binary AMop */
1088                                         set_irn_n(irn, 4, get_irn_n(left, 2));
1089                                 }
1090                                 else {
1091                                         /* unary AMop */
1092                                         set_irn_n(irn, 3, get_irn_n(left, 2));
1093                                 }
1094
1095                                 /* disconnect from Load */
1096                                 set_irn_n(irn, 2, noreg_gp);
1097
1098                                 /* If Load has a memory Proj, connect it to the op */
1099                                 mem_proj = get_mem_proj(left);
1100                                 if (mem_proj) {
1101                                         set_Proj_pred(mem_proj, irn);
1102                                         set_Proj_proj(mem_proj, 1);
1103                                 }
1104
1105                                 DB((mod, LEVEL_1, "merged with %+F into source AM\n", left));
1106                         }
1107                 }
1108         }
1109 }