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