remove conv after load and before stores
[libfirm] / ir / be / ia32 / ia32_optimize.c
1 /*
2  * Copyright (C) 1995-2007 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief       Implements several optimizations for IA32.
23  * @author      Christian Wuerdig
24  * @version     $Id$
25  */
26 #ifdef HAVE_CONFIG_H
27 #include "config.h"
28 #endif
29
30 #include "irnode.h"
31 #include "irprog_t.h"
32 #include "ircons.h"
33 #include "firm_types.h"
34 #include "iredges.h"
35 #include "tv.h"
36 #include "irgmod.h"
37 #include "irgwalk.h"
38 #include "height.h"
39 #include "irbitset.h"
40
41 #include "../be_t.h"
42 #include "../beabi.h"
43 #include "../benode_t.h"
44 #include "../besched_t.h"
45
46 #include "ia32_new_nodes.h"
47 #include "bearch_ia32_t.h"
48 #include "gen_ia32_regalloc_if.h"     /* the generated interface (register type and class defenitions) */
49 #include "ia32_transform.h"
50 #include "ia32_dbg_stat.h"
51 #include "ia32_util.h"
52
53 DEBUG_ONLY(static firm_dbg_module_t *dbg = NULL;)
54
55 #define AGGRESSIVE_AM
56
57 typedef enum {
58         IA32_AM_CAND_NONE  = 0,  /**< no addressmode possible with irn inputs */
59         IA32_AM_CAND_LEFT  = 1,  /**< addressmode possible with left input */
60         IA32_AM_CAND_RIGHT = 2,  /**< addressmode possible with right input */
61         IA32_AM_CAND_BOTH  = 3   /**< addressmode possible with both inputs */
62 } ia32_am_cand_t;
63
64 typedef int is_op_func_t(const ir_node *n);
65 typedef ir_node *load_func_t(dbg_info *db, ir_graph *irg, ir_node *block, ir_node *base, ir_node *index, ir_node *mem);
66
67 /**
68  * checks if a node represents the NOREG value
69  */
70 static INLINE int be_is_NoReg(ia32_code_gen_t *cg, const ir_node *irn) {
71         return irn == cg->noreg_gp || irn == cg->noreg_xmm || irn == cg->noreg_vfp;
72 }
73
74 void ia32_pre_transform_phase(ia32_code_gen_t *cg) {
75         /*
76                 We need to transform the consts twice:
77                 - the psi condition tree transformer needs existing constants to be ia32 constants
78                 - the psi condition tree transformer inserts new firm constants which need to be transformed
79         */
80         //ia32_transform_all_firm_consts(cg);
81         irg_walk_graph(cg->irg, NULL, ia32_transform_psi_cond_tree, cg);
82         //ia32_transform_all_firm_consts(cg);
83 }
84
85 /********************************************************************************************************
86  *  _____                _           _         ____        _   _           _          _   _
87  * |  __ \              | |         | |       / __ \      | | (_)         (_)        | | (_)
88  * | |__) |__  ___ _ __ | |__   ___ | | ___  | |  | |_ __ | |_ _ _ __ ___  _ ______ _| |_ _  ___  _ __
89  * |  ___/ _ \/ _ \ '_ \| '_ \ / _ \| |/ _ \ | |  | | '_ \| __| | '_ ` _ \| |_  / _` | __| |/ _ \| '_ \
90  * | |  |  __/  __/ |_) | | | | (_) | |  __/ | |__| | |_) | |_| | | | | | | |/ / (_| | |_| | (_) | | | |
91  * |_|   \___|\___| .__/|_| |_|\___/|_|\___|  \____/| .__/ \__|_|_| |_| |_|_/___\__,_|\__|_|\___/|_| |_|
92  *                | |                               | |
93  *                |_|                               |_|
94  ********************************************************************************************************/
95
96 /**
97  * NOTE: THESE PEEPHOLE OPTIMIZATIONS MUST BE CALLED AFTER SCHEDULING AND REGISTER ALLOCATION.
98  */
99
100 static int ia32_const_equal(const ir_node *n1, const ir_node *n2) {
101         if(get_ia32_immop_type(n1) != get_ia32_immop_type(n2))
102                 return 0;
103
104         if(get_ia32_immop_type(n1) == ia32_ImmConst) {
105                 return get_ia32_Immop_tarval(n1) == get_ia32_Immop_tarval(n2);
106         } else if(get_ia32_immop_type(n1) == ia32_ImmSymConst) {
107                 return get_ia32_Immop_symconst(n1) == get_ia32_Immop_symconst(n2);
108         }
109
110         assert(get_ia32_immop_type(n1) == ia32_ImmNone);
111         return 1;
112 }
113
114 /**
115  * Checks for potential CJmp/CJmpAM optimization candidates.
116  */
117 static ir_node *ia32_determine_cjmp_cand(ir_node *irn, is_op_func_t *is_op_func) {
118         ir_node *cand = NULL;
119         ir_node *prev = sched_prev(irn);
120
121         if (is_Block(prev)) {
122                 if (get_Block_n_cfgpreds(prev) == 1)
123                         prev = get_Block_cfgpred(prev, 0);
124                 else
125                         prev = NULL;
126         }
127
128         /* The predecessor must be a ProjX. */
129         if (prev && is_Proj(prev) && get_irn_mode(prev) == mode_X) {
130                 prev = get_Proj_pred(prev);
131
132                 if (is_op_func(prev))
133                         cand = prev;
134         }
135
136         return cand;
137 }
138
139 static int is_TestJmp_cand(const ir_node *irn) {
140         return is_ia32_TestJmp(irn) || is_ia32_And(irn);
141 }
142
143 /**
144  * Checks if two consecutive arguments of cand matches
145  * the two arguments of irn (TestJmp).
146  */
147 static int is_TestJmp_replacement(ir_node *cand, ir_node *irn) {
148         ir_node *in1       = get_irn_n(irn, 0);
149         ir_node *in2       = get_irn_n(irn, 1);
150         int      i, n      = get_irn_arity(cand);
151         int      same_args = 0;
152
153         for (i = 0; i < n - 1; i++) {
154                 if (get_irn_n(cand, i)     == in1 &&
155                         get_irn_n(cand, i + 1) == in2)
156                 {
157                         same_args = 1;
158                         break;
159                 }
160         }
161
162         if (!same_args)
163                 return 0;
164
165         return ia32_const_equal(cand, irn);
166 }
167
168 /**
169  * Tries to replace a TestJmp by a CJmp or CJmpAM (in case of And)
170  */
171 static void ia32_optimize_TestJmp(ir_node *irn, ia32_code_gen_t *cg) {
172         ir_node *cand    = ia32_determine_cjmp_cand(irn, is_TestJmp_cand);
173         int      replace = 0;
174
175         /* we found a possible candidate */
176         replace = cand ? is_TestJmp_replacement(cand, irn) : 0;
177
178         if (replace) {
179                 DBG((dbg, LEVEL_1, "replacing %+F by ", irn));
180
181                 if (is_ia32_And(cand))
182                         set_irn_op(irn, op_ia32_CJmpAM);
183                 else
184                         set_irn_op(irn, op_ia32_CJmp);
185
186                 DB((dbg, LEVEL_1, "%+F\n", irn));
187         }
188 }
189
190 static int is_CondJmp_cand(const ir_node *irn) {
191         return is_ia32_CondJmp(irn) || is_ia32_Sub(irn);
192 }
193
194 /**
195  * Checks if the arguments of cand are the same of irn.
196  */
197 static int is_CondJmp_replacement(ir_node *cand, ir_node *irn) {
198         int i, arity;
199
200         arity = get_irn_arity(cand);
201         for (i = 0; i < arity; i++) {
202                 if (get_irn_n(cand, i) != get_irn_n(irn, i)) {
203                         return 0;
204                 }
205         }
206
207         return ia32_const_equal(cand, irn);
208 }
209
210 /**
211  * Tries to replace a CondJmp by a CJmpAM
212  */
213 static void ia32_optimize_CondJmp(ir_node *irn, ia32_code_gen_t *cg) {
214         ir_node *cand    = ia32_determine_cjmp_cand(irn, is_CondJmp_cand);
215         int      replace = 0;
216
217         /* we found a possible candidate */
218         replace = cand ? is_CondJmp_replacement(cand, irn) : 0;
219
220         if (replace) {
221                 DBG((dbg, LEVEL_1, "replacing %+F by ", irn));
222                 DBG_OPT_CJMP(irn);
223
224                 set_irn_op(irn, op_ia32_CJmpAM);
225
226                 DB((dbg, LEVEL_1, "%+F\n", irn));
227         }
228 }
229
230 // only optimize up to 48 stores behind IncSPs
231 #define MAXPUSH_OPTIMIZE        48
232
233 /**
234  * Tries to create pushs from IncSP,Store combinations
235  */
236 static void ia32_create_Pushs(ir_node *irn, ia32_code_gen_t *cg) {
237         int i;
238         int offset;
239         ir_node *node;
240         ir_node *stores[MAXPUSH_OPTIMIZE];
241         ir_node *block = get_nodes_block(irn);
242         ir_graph *irg = cg->irg;
243         ir_node *curr_sp;
244         ir_mode *spmode = get_irn_mode(irn);
245
246         memset(stores, 0, sizeof(stores));
247
248         assert(be_is_IncSP(irn));
249
250         offset = be_get_IncSP_offset(irn);
251         if(offset < 4)
252                 return;
253
254         /*
255          * We first walk the schedule after the IncSP node as long as we find
256          * suitable stores that could be transformed to a push.
257          * We save them into the stores array which is sorted by the frame offset/4
258          * attached to the node
259          */
260         for(node = sched_next(irn); !sched_is_end(node); node = sched_next(node)) {
261                 ir_node *mem;
262                 int offset;
263                 int storeslot;
264
265                 // it has to be a store
266                 if(!is_ia32_Store(node))
267                         break;
268
269                 // it has to use our sp value
270                 if(get_irn_n(node, 0) != irn)
271                         continue;
272                 // store has to be attached to NoMem
273                 mem = get_irn_n(node, 3);
274                 if(!is_NoMem(mem)) {
275                         continue;
276                 }
277
278                 if( (get_ia32_am_flavour(node) & ia32_am_IS) != 0)
279                         break;
280
281                 offset = get_ia32_am_offs_int(node);
282
283                 storeslot = offset / 4;
284                 if(storeslot >= MAXPUSH_OPTIMIZE)
285                         continue;
286
287                 // storing into the same slot twice is bad (and shouldn't happen...)
288                 if(stores[storeslot] != NULL)
289                         break;
290
291                 // storing at half-slots is bad
292                 if(offset % 4 != 0)
293                         break;
294
295                 stores[storeslot] = node;
296         }
297
298         curr_sp = get_irn_n(irn, 0);
299
300         // walk the stores in inverse order and create pushs for them
301         i = (offset / 4) - 1;
302         if(i >= MAXPUSH_OPTIMIZE) {
303                 i = MAXPUSH_OPTIMIZE - 1;
304         }
305
306         for( ; i >= 0; --i) {
307                 const arch_register_t *spreg;
308                 ir_node *push;
309                 ir_node *val, *mem, *mem_proj;
310                 ir_node *store = stores[i];
311                 ir_node *noreg = ia32_new_NoReg_gp(cg);
312
313                 if(store == NULL || is_Bad(store))
314                         break;
315
316                 val = get_irn_n(store, 2);
317                 mem = get_irn_n(store, 3);
318                 spreg = arch_get_irn_register(cg->arch_env, curr_sp);
319
320                 // create a push
321                 push = new_rd_ia32_Push(NULL, irg, block, noreg, noreg, val, curr_sp, mem);
322
323                 set_ia32_am_support(push, ia32_am_Source);
324                 copy_ia32_Immop_attr(push, store);
325
326                 sched_add_before(irn, push);
327
328                 // create stackpointer proj
329                 curr_sp = new_r_Proj(irg, block, push, spmode, pn_ia32_Push_stack);
330                 arch_set_irn_register(cg->arch_env, curr_sp, spreg);
331                 sched_add_before(irn, curr_sp);
332
333                 // create memory proj
334                 mem_proj = new_r_Proj(irg, block, push, mode_M, pn_ia32_Push_M);
335                 sched_add_before(irn, mem_proj);
336
337                 // use the memproj now
338                 exchange(store, mem_proj);
339
340                 // we can remove the store now
341                 sched_remove(store);
342
343                 offset -= 4;
344         }
345
346         be_set_IncSP_offset(irn, offset);
347
348         // can we remove the IncSP now?
349         if(offset == 0) {
350                 const ir_edge_t *edge, *next;
351
352                 foreach_out_edge_safe(irn, edge, next) {
353                         ir_node *arg = get_edge_src_irn(edge);
354                         int pos = get_edge_src_pos(edge);
355
356                         set_irn_n(arg, pos, curr_sp);
357                 }
358
359                 set_irn_n(irn, 0, new_Bad());
360                 sched_remove(irn);
361         } else {
362                 set_irn_n(irn, 0, curr_sp);
363         }
364 }
365
366 #if 0
367 /**
368  * Tries to optimize two following IncSP.
369  */
370 static void ia32_optimize_IncSP(ir_node *irn, ia32_code_gen_t *cg) {
371         ir_node *prev = be_get_IncSP_pred(irn);
372         int real_uses = get_irn_n_edges(prev);
373
374         if (be_is_IncSP(prev) && real_uses == 1) {
375                 /* first IncSP has only one IncSP user, kill the first one */
376                 int prev_offs = be_get_IncSP_offset(prev);
377                 int curr_offs = be_get_IncSP_offset(irn);
378
379                 be_set_IncSP_offset(prev, prev_offs + curr_offs);
380
381                 /* Omit the optimized IncSP */
382                 be_set_IncSP_pred(irn, be_get_IncSP_pred(prev));
383
384                 set_irn_n(prev, 0, new_Bad());
385                 sched_remove(prev);
386         }
387 }
388 #endif
389
390 /**
391  * Performs Peephole Optimizations.
392  */
393 static void ia32_peephole_optimize_node(ir_node *irn, void *env) {
394         ia32_code_gen_t *cg = env;
395
396         /* AMD CPUs want explicit compare before conditional jump  */
397         if (! ARCH_AMD(cg->opt_arch)) {
398                 if (is_ia32_TestJmp(irn))
399                         ia32_optimize_TestJmp(irn, cg);
400                 else if (is_ia32_CondJmp(irn))
401                         ia32_optimize_CondJmp(irn, cg);
402         }
403
404         if (be_is_IncSP(irn)) {
405                 // optimize_IncSP doesn't respect dependency edges yet...
406                 //ia32_optimize_IncSP(irn, cg);
407
408                 if (cg->opt & IA32_OPT_PUSHARGS)
409                         ia32_create_Pushs(irn, cg);
410         }
411 }
412
413 void ia32_peephole_optimization(ir_graph *irg, ia32_code_gen_t *cg) {
414         irg_walk_graph(irg, ia32_peephole_optimize_node, NULL, cg);
415 }
416
417 /******************************************************************
418  *              _     _                   __  __           _
419  *     /\      | |   | |                 |  \/  |         | |
420  *    /  \   __| | __| |_ __ ___  ___ ___| \  / | ___   __| | ___
421  *   / /\ \ / _` |/ _` | '__/ _ \/ __/ __| |\/| |/ _ \ / _` |/ _ \
422  *  / ____ \ (_| | (_| | | |  __/\__ \__ \ |  | | (_) | (_| |  __/
423  * /_/    \_\__,_|\__,_|_|  \___||___/___/_|  |_|\___/ \__,_|\___|
424  *
425  ******************************************************************/
426
427 typedef struct {
428         ia32_code_gen_t *cg;
429         heights_t       *h;
430 } ia32_am_opt_env_t;
431
432 static int node_is_ia32_comm(const ir_node *irn) {
433         return is_ia32_irn(irn) ? is_ia32_commutative(irn) : 0;
434 }
435
436 static int ia32_get_irn_n_edges(const ir_node *irn) {
437         const ir_edge_t *edge;
438         int cnt = 0;
439
440         foreach_out_edge(irn, edge) {
441                 cnt++;
442         }
443
444         return cnt;
445 }
446
447 /**
448  * Determines if pred is a Proj and if is_op_func returns true for it's predecessor.
449  *
450  * @param pred       The node to be checked
451  * @param is_op_func The check-function
452  * @return 1 if conditions are fulfilled, 0 otherwise
453  */
454 static int pred_is_specific_node(const ir_node *pred, is_op_func_t *is_op_func) {
455         return is_op_func(pred);
456 }
457
458 /**
459  * Determines if pred is a Proj and if is_op_func returns true for it's predecessor
460  * and if the predecessor is in block bl.
461  *
462  * @param bl         The block
463  * @param pred       The node to be checked
464  * @param is_op_func The check-function
465  * @return 1 if conditions are fulfilled, 0 otherwise
466  */
467 static int pred_is_specific_nodeblock(const ir_node *bl, const ir_node *pred,
468         int (*is_op_func)(const ir_node *n))
469 {
470         if (is_Proj(pred)) {
471                 pred = get_Proj_pred(pred);
472                 if ((bl == get_nodes_block(pred)) && is_op_func(pred)) {
473                         return 1;
474                 }
475         }
476
477         return 0;
478 }
479
480 /**
481  * Checks if irn is a candidate for address calculation. We avoid transforming
482  * adds to leas if they have a load as pred, because then we can use AM mode
483  * for the add later.
484  *
485  * - none of the operand must be a Load  within the same block OR
486  * - all Loads must have more than one user                    OR
487  *
488  * @param block   The block the Loads must/mustnot be in
489  * @param irn     The irn to check
490  * return 1 if irn is a candidate, 0 otherwise
491  */
492 static int is_addr_candidate(const ir_node *irn) {
493 #ifndef AGGRESSIVE_AM
494         const ir_node *block = get_nodes_block(irn);
495         ir_node *left, *right;
496         int      n;
497
498         left  = get_irn_n(irn, 2);
499         right = get_irn_n(irn, 3);
500
501         if (pred_is_specific_nodeblock(block, left, is_ia32_Ld)) {
502                 n         = ia32_get_irn_n_edges(left);
503                 /* load with only one user: don't create LEA */
504                 if(n == 1)
505                         return 0;
506         }
507
508         if (pred_is_specific_nodeblock(block, right, is_ia32_Ld)) {
509                 n         = ia32_get_irn_n_edges(right);
510                 if(n == 1)
511                         return 0;
512         }
513 #endif
514
515         return 1;
516 }
517
518 /**
519  * Checks if irn is a candidate for address mode.
520  *
521  * address mode (AM):
522  * - at least one operand has to be a Load within the same block AND
523  * - the load must not have other users than the irn             AND
524  * - the irn must not have a frame entity set
525  *
526  * @param cg          The ia32 code generator
527  * @param h           The height information of the irg
528  * @param block       The block the Loads must/mustnot be in
529  * @param irn         The irn to check
530  * return 0 if irn is no candidate, 1 if left load can be used, 2 if right one, 3 for both
531  */
532 static ia32_am_cand_t is_am_candidate(ia32_code_gen_t *cg, heights_t *h, const ir_node *block, ir_node *irn) {
533         ir_node *in, *load, *other, *left, *right;
534         int      is_cand = 0, cand;
535         int arity;
536
537         if (is_ia32_Ld(irn) || is_ia32_St(irn) || is_ia32_Store8Bit(irn) || is_ia32_vfild(irn) || is_ia32_vfist(irn) ||
538                 is_ia32_GetST0(irn) || is_ia32_SetST0(irn) || is_ia32_xStoreSimple(irn))
539                 return 0;
540
541         left  = get_irn_n(irn, 2);
542         arity = get_irn_arity(irn);
543         assert(arity == 5 || arity == 4);
544         if(arity == 5) {
545                 /* binary op */
546                 right = get_irn_n(irn, 3);
547         } else {
548                 /* unary op */
549                 right = left;
550         }
551
552         in = left;
553
554         if (pred_is_specific_nodeblock(block, in, is_ia32_Ld)) {
555 #ifndef AGGRESSIVE_AM
556                 int n;
557                 n         = ia32_get_irn_n_edges(in);
558                 is_cand   = (n == 1) ? 1 : is_cand;  /* load with more than one user: no AM */
559 #else
560                 is_cand   = 1;
561 #endif
562
563                 load  = get_Proj_pred(in);
564                 other = right;
565
566                 /* 8bit Loads are not supported (for binary ops),
567                  * they cannot be used with every register */
568                 if (get_irn_arity(irn) != 4 && get_mode_size_bits(get_ia32_ls_mode(load)) < 16) {
569                         assert(get_irn_arity(irn) == 5);
570                         is_cand = 0;
571                 }
572
573                 /* If there is a data dependency of other irn from load: cannot use AM */
574                 if (is_cand && get_nodes_block(other) == block) {
575                         other   = skip_Proj(other);
576                         is_cand = heights_reachable_in_block(h, other, load) ? 0 : is_cand;
577                         /* this could happen in loops */
578                         is_cand = heights_reachable_in_block(h, load, irn) ? 0 : is_cand;
579                 }
580         }
581
582         cand    = is_cand ? IA32_AM_CAND_LEFT : IA32_AM_CAND_NONE;
583         in      = right;
584         is_cand = 0;
585
586         if (pred_is_specific_nodeblock(block, in, is_ia32_Ld)) {
587 #ifndef AGGRESSIVE_AM
588                 int n;
589                 n         = ia32_get_irn_n_edges(in);
590                 is_cand   = (n == 1) ? 1 : is_cand;  /* load with more than one user: no AM */
591 #else
592                 is_cand = 1;
593 #endif
594
595                 load  = get_Proj_pred(in);
596                 other = left;
597
598                 /* 8bit Loads are not supported, they cannot be used with every register */
599                 if (get_mode_size_bits(get_ia32_ls_mode(load)) < 16)
600                         is_cand = 0;
601
602                 /* If there is a data dependency of other irn from load: cannot use load */
603                 if (is_cand && get_nodes_block(other) == block) {
604                         other   = skip_Proj(other);
605                         is_cand = heights_reachable_in_block(h, other, load) ? 0 : is_cand;
606                         /* this could happen in loops */
607                         is_cand = heights_reachable_in_block(h, load, irn) ? 0 : is_cand;
608                 }
609         }
610
611         cand = is_cand ? (cand | IA32_AM_CAND_RIGHT) : cand;
612
613         /* if the irn has a frame entity: we do not use address mode */
614         return get_ia32_frame_ent(irn) ? IA32_AM_CAND_NONE : cand;
615 }
616
617 /**
618  * Compares the base and index addr and the load/store entities
619  * and returns 1 if they are equal.
620  */
621 static int load_store_addr_is_equal(const ir_node *load, const ir_node *store,
622                                                                         const ir_node *addr_b, const ir_node *addr_i)
623 {
624         if(get_irn_n(load, 0) != addr_b)
625                 return 0;
626         if(get_irn_n(load, 1) != addr_i)
627                 return 0;
628
629         if(get_ia32_frame_ent(load) != get_ia32_frame_ent(store))
630                 return 0;
631
632         if(get_ia32_am_sc(load) != get_ia32_am_sc(store))
633                 return 0;
634         if(is_ia32_am_sc_sign(load) != is_ia32_am_sc_sign(store))
635                 return 0;
636         if(get_ia32_am_offs_int(load) != get_ia32_am_offs_int(store))
637                 return 0;
638         if(get_ia32_ls_mode(load) != get_ia32_ls_mode(store))
639                 return 0;
640
641         return 1;
642 }
643
644 typedef enum _ia32_take_lea_attr {
645         IA32_LEA_ATTR_NONE  = 0,
646         IA32_LEA_ATTR_BASE  = (1 << 0),
647         IA32_LEA_ATTR_INDEX = (1 << 1),
648         IA32_LEA_ATTR_OFFS  = (1 << 2),
649         IA32_LEA_ATTR_SCALE = (1 << 3),
650         IA32_LEA_ATTR_AMSC  = (1 << 4),
651         IA32_LEA_ATTR_FENT  = (1 << 5)
652 } ia32_take_lea_attr;
653
654 /**
655  * Decides if we have to keep the LEA operand or if we can assimilate it.
656  */
657 static int do_new_lea(ir_node *irn, ir_node *base, ir_node *index, ir_node *lea,
658                 int have_am_sc, ia32_code_gen_t *cg)
659 {
660         ir_entity *irn_ent  = get_ia32_frame_ent(irn);
661         ir_entity *lea_ent  = get_ia32_frame_ent(lea);
662         int        ret_val  = 0;
663         int        is_noreg_base  = be_is_NoReg(cg, base);
664         int        is_noreg_index = be_is_NoReg(cg, index);
665         ia32_am_flavour_t am_flav = get_ia32_am_flavour(lea);
666
667         /* If the Add and the LEA both have a different frame entity set: keep */
668         if (irn_ent && lea_ent && (irn_ent != lea_ent))
669                 return IA32_LEA_ATTR_NONE;
670         else if (! irn_ent && lea_ent)
671                 ret_val |= IA32_LEA_ATTR_FENT;
672
673         /* If the Add and the LEA both have already an address mode symconst: keep */
674         if (have_am_sc && get_ia32_am_sc(lea))
675                 return IA32_LEA_ATTR_NONE;
676         else if (get_ia32_am_sc(lea))
677                 ret_val |= IA32_LEA_ATTR_AMSC;
678
679         /* Check the different base-index combinations */
680
681         if (! is_noreg_base && ! is_noreg_index) {
682                 /* Assimilate if base is the lea and the LEA is just a Base + Offset calculation */
683                 if ((base == lea) && ! (am_flav & ia32_I ? 1 : 0)) {
684                         if (am_flav & ia32_O)
685                                 ret_val |= IA32_LEA_ATTR_OFFS;
686
687                         ret_val |= IA32_LEA_ATTR_BASE;
688                 }
689                 else
690                         return IA32_LEA_ATTR_NONE;
691         }
692         else if (! is_noreg_base && is_noreg_index) {
693                 /* Base is set but index not */
694                 if (base == lea) {
695                         /* Base points to LEA: assimilate everything */
696                         if (am_flav & ia32_O)
697                                 ret_val |= IA32_LEA_ATTR_OFFS;
698                         if (am_flav & ia32_S)
699                                 ret_val |= IA32_LEA_ATTR_SCALE;
700                         if (am_flav & ia32_I)
701                                 ret_val |= IA32_LEA_ATTR_INDEX;
702
703                         ret_val |= IA32_LEA_ATTR_BASE;
704                 }
705                 else if (am_flav & ia32_B ? 0 : 1) {
706                         /* Base is not the LEA but the LEA is an index only calculation: assimilate */
707                         if (am_flav & ia32_O)
708                                 ret_val |= IA32_LEA_ATTR_OFFS;
709                         if (am_flav & ia32_S)
710                                 ret_val |= IA32_LEA_ATTR_SCALE;
711
712                         ret_val |= IA32_LEA_ATTR_INDEX;
713                 }
714                 else
715                         return IA32_LEA_ATTR_NONE;
716         }
717         else if (is_noreg_base && ! is_noreg_index) {
718                 /* Index is set but not base */
719                 if (index == lea) {
720                         /* Index points to LEA: assimilate everything */
721                         if (am_flav & ia32_O)
722                                 ret_val |= IA32_LEA_ATTR_OFFS;
723                         if (am_flav & ia32_S)
724                                 ret_val |= IA32_LEA_ATTR_SCALE;
725                         if (am_flav & ia32_B)
726                                 ret_val |= IA32_LEA_ATTR_BASE;
727
728                         ret_val |= IA32_LEA_ATTR_INDEX;
729                 }
730                 else if (am_flav & ia32_I ? 0 : 1) {
731                         /* Index is not the LEA but the LEA is a base only calculation: assimilate */
732                         if (am_flav & ia32_O)
733                                 ret_val |= IA32_LEA_ATTR_OFFS;
734                         if (am_flav & ia32_S)
735                                 ret_val |= IA32_LEA_ATTR_SCALE;
736
737                         ret_val |= IA32_LEA_ATTR_BASE;
738                 }
739                 else
740                         return IA32_LEA_ATTR_NONE;
741         }
742         else {
743                 assert(0 && "There must have been set base or index");
744         }
745
746         return ret_val;
747 }
748
749 /**
750  * Adds res before irn into schedule if irn was scheduled.
751  * @param irn  The schedule point
752  * @param res  The node to be scheduled
753  */
754 static INLINE void try_add_to_sched(ir_node *irn, ir_node *res) {
755         if (sched_is_scheduled(irn))
756                 sched_add_before(irn, res);
757 }
758
759 /**
760  * Removes node from schedule if it is not used anymore. If irn is a mode_T node
761  * all it's Projs are removed as well.
762  * @param irn  The irn to be removed from schedule
763  */
764 static INLINE void try_remove_from_sched(ir_node *node) {
765         int i, arity;
766
767         if(get_irn_mode(node) == mode_T) {
768                 const ir_edge_t *edge;
769                 foreach_out_edge(node, edge) {
770                         ir_node *proj = get_edge_src_irn(edge);
771                         try_remove_from_sched(proj);
772                 }
773         }
774
775         if(get_irn_n_edges(node) != 0)
776                 return;
777
778         if (sched_is_scheduled(node)) {
779                 sched_remove(node);
780         }
781
782         arity = get_irn_arity(node);
783         for(i = 0; i < arity; ++i) {
784                 set_irn_n(node, i, new_Bad());
785         }
786 }
787
788 /**
789  * Folds Add or Sub to LEA if possible
790  */
791 static ir_node *fold_addr(ia32_code_gen_t *cg, ir_node *irn) {
792         ir_graph   *irg        = get_irn_irg(irn);
793         dbg_info   *dbg_info   = get_irn_dbg_info(irn);
794         ir_node    *block      = get_nodes_block(irn);
795         ir_node    *res        = irn;
796         ir_node    *shift      = NULL;
797         ir_node    *lea_o      = NULL;
798         ir_node    *lea        = NULL;
799         long        offs       = 0;
800         long        offs_cnst  = 0;
801         long        offs_lea   = 0;
802         int         scale      = 0;
803         int         isadd      = 0;
804         int         dolea      = 0;
805         int         have_am_sc = 0;
806         int         am_sc_sign = 0;
807         ir_entity  *am_sc      = NULL;
808         ir_entity  *lea_ent    = NULL;
809         ir_node    *noreg      = ia32_new_NoReg_gp(cg);
810         ir_node    *left, *right, *temp;
811         ir_node    *base, *index;
812         int consumed_left_shift;
813         ia32_am_flavour_t am_flav;
814
815         if (is_ia32_Add(irn))
816                 isadd = 1;
817
818         left  = get_irn_n(irn, 2);
819         right = get_irn_n(irn, 3);
820
821         /* "normalize" arguments in case of add with two operands */
822         if  (isadd && ! be_is_NoReg(cg, right)) {
823                 /* put LEA == ia32_am_O as right operand */
824                 if (is_ia32_Lea(left) && get_ia32_am_flavour(left) == ia32_am_O) {
825                         set_irn_n(irn, 2, right);
826                         set_irn_n(irn, 3, left);
827                         temp  = left;
828                         left  = right;
829                         right = temp;
830                 }
831
832                 /* put LEA != ia32_am_O as left operand */
833                 if (is_ia32_Lea(right) && get_ia32_am_flavour(right) != ia32_am_O) {
834                         set_irn_n(irn, 2, right);
835                         set_irn_n(irn, 3, left);
836                         temp  = left;
837                         left  = right;
838                         right = temp;
839                 }
840
841                 /* put SHL as left operand iff left is NOT a LEA */
842                 if (! is_ia32_Lea(left) && pred_is_specific_node(right, is_ia32_Shl)) {
843                         set_irn_n(irn, 2, right);
844                         set_irn_n(irn, 3, left);
845                         temp  = left;
846                         left  = right;
847                         right = temp;
848                 }
849         }
850
851         base    = left;
852         index   = noreg;
853         offs    = 0;
854         scale   = 0;
855         am_flav = 0;
856
857         /* check for operation with immediate */
858         if (is_ia32_ImmConst(irn)) {
859                 tarval *tv = get_ia32_Immop_tarval(irn);
860
861                 DBG((dbg, LEVEL_1, "\tfound op with imm const"));
862
863                 offs_cnst = get_tarval_long(tv);
864                 dolea     = 1;
865         }
866         else if (isadd && is_ia32_ImmSymConst(irn)) {
867                 DBG((dbg, LEVEL_1, "\tfound op with imm symconst"));
868
869                 have_am_sc = 1;
870                 dolea      = 1;
871                 am_sc      = get_ia32_Immop_symconst(irn);
872                 am_sc_sign = is_ia32_am_sc_sign(irn);
873         }
874
875         /* determine the operand which needs to be checked */
876         temp = be_is_NoReg(cg, right) ? left : right;
877
878         /* check if right operand is AMConst (LEA with ia32_am_O)  */
879         /* but we can only eat it up if there is no other symconst */
880         /* because the linker won't accept two symconsts           */
881         if (! have_am_sc && is_ia32_Lea(temp) && get_ia32_am_flavour(temp) == ia32_am_O) {
882                 DBG((dbg, LEVEL_1, "\tgot op with LEA am_O"));
883
884                 offs_lea   = get_ia32_am_offs_int(temp);
885                 am_sc      = get_ia32_am_sc(temp);
886                 am_sc_sign = is_ia32_am_sc_sign(temp);
887                 have_am_sc = 1;
888                 dolea      = 1;
889                 lea_o      = temp;
890
891                 if (temp == base)
892                         base = noreg;
893                 else if (temp == right)
894                         right = noreg;
895         }
896
897         if (isadd) {
898                 /* default for add -> make right operand to index */
899                 index               = right;
900                 dolea               = 1;
901                 consumed_left_shift = -1;
902
903                 DBG((dbg, LEVEL_1, "\tgot LEA candidate with index %+F\n", index));
904
905                 /* determine the operand which needs to be checked */
906                 temp = left;
907                 if (is_ia32_Lea(left)) {
908                         temp = right;
909                         consumed_left_shift = 0;
910                 }
911
912                 /* check for SHL 1,2,3 */
913                 if (pred_is_specific_node(temp, is_ia32_Shl)) {
914
915                         if (is_ia32_ImmConst(temp)) {
916                                 long shiftval = get_tarval_long(get_ia32_Immop_tarval(temp));
917
918                                 if (shiftval <= 3) {
919                                         index               = get_irn_n(temp, 2);
920                                         consumed_left_shift = consumed_left_shift < 0 ? 1 : 0;
921                                         shift = temp;
922                                         scale = shiftval;
923
924                                         DBG((dbg, LEVEL_1, "\tgot scaled index %+F\n", index));
925                                 }
926                         }
927                 }
928
929                 /* fix base */
930                 if (! be_is_NoReg(cg, index)) {
931                         /* if we have index, but left == right -> no base */
932                         if (left == right) {
933                                 base = noreg;
934                         }
935                         else if (consumed_left_shift == 1) {
936                                 /* -> base is right operand  */
937                                 base = (right == lea_o) ? noreg : right;
938                         }
939                 }
940         }
941
942         /* Try to assimilate a LEA as left operand */
943         if (is_ia32_Lea(left) && (get_ia32_am_flavour(left) != ia32_am_O)) {
944                 /* check if we can assimilate the LEA */
945                 int take_attr = do_new_lea(irn, base, index, left, have_am_sc, cg);
946
947                 if (take_attr == IA32_LEA_ATTR_NONE) {
948                         DBG((dbg, LEVEL_1, "\tleave old LEA, creating new one\n"));
949                 }
950                 else {
951                         DBG((dbg, LEVEL_1, "\tgot LEA as left operand ... assimilating\n"));
952                         lea = left; /* for statistics */
953
954                         if (take_attr & IA32_LEA_ATTR_OFFS)
955                                 offs = get_ia32_am_offs_int(left);
956
957                         if (take_attr & IA32_LEA_ATTR_AMSC) {
958                                 am_sc      = get_ia32_am_sc(left);
959                                 have_am_sc = 1;
960                                 am_sc_sign = is_ia32_am_sc_sign(left);
961                         }
962
963                         if (take_attr & IA32_LEA_ATTR_SCALE)
964                                 scale = get_ia32_am_scale(left);
965
966                         if (take_attr & IA32_LEA_ATTR_BASE)
967                                 base = get_irn_n(left, 0);
968
969                         if (take_attr & IA32_LEA_ATTR_INDEX)
970                                 index = get_irn_n(left, 1);
971
972                         if (take_attr & IA32_LEA_ATTR_FENT)
973                                 lea_ent = get_ia32_frame_ent(left);
974                 }
975         }
976
977         /* ok, we can create a new LEA */
978         if (dolea) {
979                 res = new_rd_ia32_Lea(dbg_info, irg, block, base, index);
980
981                 /* add the old offset of a previous LEA */
982                 add_ia32_am_offs_int(res, offs);
983
984                 /* add the new offset */
985                 if (isadd) {
986                         add_ia32_am_offs_int(res, offs_cnst);
987                         add_ia32_am_offs_int(res, offs_lea);
988                 } else {
989                         /* either lea_O-cnst, -cnst or -lea_O  */
990                         if (offs_cnst != 0) {
991                                 add_ia32_am_offs_int(res, offs_lea);
992                                 add_ia32_am_offs_int(res, -offs_cnst);
993                         } else {
994                                 add_ia32_am_offs_int(res, offs_lea);
995                         }
996                 }
997
998                 /* set the address mode symconst */
999                 if (have_am_sc) {
1000                         set_ia32_am_sc(res, am_sc);
1001                         if (am_sc_sign)
1002                                 set_ia32_am_sc_sign(res);
1003                 }
1004
1005                 /* copy the frame entity (could be set in case of Add */
1006                 /* which was a FrameAddr) */
1007                 if (lea_ent != NULL) {
1008                         set_ia32_frame_ent(res, lea_ent);
1009                         set_ia32_use_frame(res);
1010                 } else {
1011                         set_ia32_frame_ent(res, get_ia32_frame_ent(irn));
1012                         if(is_ia32_use_frame(irn))
1013                                 set_ia32_use_frame(res);
1014                 }
1015
1016                 /* set scale */
1017                 set_ia32_am_scale(res, scale);
1018
1019                 am_flav = ia32_am_N;
1020                 /* determine new am flavour */
1021                 if (offs || offs_cnst || offs_lea || have_am_sc) {
1022                         am_flav |= ia32_O;
1023                 }
1024                 if (! be_is_NoReg(cg, base)) {
1025                         am_flav |= ia32_B;
1026                 }
1027                 if (! be_is_NoReg(cg, index)) {
1028                         am_flav |= ia32_I;
1029                 }
1030                 if (scale > 0) {
1031                         am_flav |= ia32_S;
1032                 }
1033                 set_ia32_am_flavour(res, am_flav);
1034
1035                 set_ia32_op_type(res, ia32_AddrModeS);
1036
1037                 SET_IA32_ORIG_NODE(res, ia32_get_old_node_name(cg, irn));
1038
1039                 DBG((dbg, LEVEL_1, "\tLEA [%+F + %+F * %d + %d]\n", base, index, scale, get_ia32_am_offs_int(res)));
1040
1041                 assert(irn && "Couldn't find result proj");
1042
1043                 /* get the result Proj of the Add/Sub */
1044                 try_add_to_sched(irn, res);
1045
1046                 /* exchange the old op with the new LEA */
1047                 try_remove_from_sched(irn);
1048                 exchange(irn, res);
1049
1050                 /* we will exchange it, report here before the Proj is created */
1051                 if (shift && lea && lea_o) {
1052                         try_remove_from_sched(shift);
1053                         try_remove_from_sched(lea);
1054                         try_remove_from_sched(lea_o);
1055                         DBG_OPT_LEA4(irn, lea_o, lea, shift, res);
1056                 } else if (shift && lea) {
1057                         try_remove_from_sched(shift);
1058                         try_remove_from_sched(lea);
1059                         DBG_OPT_LEA3(irn, lea, shift, res);
1060                 } else if (shift && lea_o) {
1061                         try_remove_from_sched(shift);
1062                         try_remove_from_sched(lea_o);
1063                         DBG_OPT_LEA3(irn, lea_o, shift, res);
1064                 } else if (lea && lea_o) {
1065                         try_remove_from_sched(lea);
1066                         try_remove_from_sched(lea_o);
1067                         DBG_OPT_LEA3(irn, lea_o, lea, res);
1068                 } else if (shift) {
1069                         try_remove_from_sched(shift);
1070                         DBG_OPT_LEA2(irn, shift, res);
1071                 } else if (lea) {
1072                         try_remove_from_sched(lea);
1073                         DBG_OPT_LEA2(irn, lea, res);
1074                 } else if (lea_o) {
1075                         try_remove_from_sched(lea_o);
1076                         DBG_OPT_LEA2(irn, lea_o, res);
1077                 } else {
1078                         DBG_OPT_LEA1(irn, res);
1079                 }
1080         }
1081
1082         return res;
1083 }
1084
1085
1086 /**
1087  * Merges a Load/Store node with a LEA.
1088  * @param irn The Load/Store node
1089  * @param lea The LEA
1090  */
1091 static void merge_loadstore_lea(ir_node *irn, ir_node *lea) {
1092         ir_entity *irn_ent = get_ia32_frame_ent(irn);
1093         ir_entity *lea_ent = get_ia32_frame_ent(lea);
1094
1095         /* If the irn and the LEA both have a different frame entity set: do not merge */
1096         if (irn_ent != NULL && lea_ent != NULL && (irn_ent != lea_ent))
1097                 return;
1098         else if (irn_ent == NULL && lea_ent != NULL) {
1099                 set_ia32_frame_ent(irn, lea_ent);
1100                 set_ia32_use_frame(irn);
1101         }
1102
1103         /* get the AM attributes from the LEA */
1104         add_ia32_am_offs_int(irn, get_ia32_am_offs_int(lea));
1105         set_ia32_am_scale(irn, get_ia32_am_scale(lea));
1106         set_ia32_am_flavour(irn, get_ia32_am_flavour(lea));
1107
1108         set_ia32_am_sc(irn, get_ia32_am_sc(lea));
1109         if (is_ia32_am_sc_sign(lea))
1110                 set_ia32_am_sc_sign(irn);
1111
1112         set_ia32_op_type(irn, is_ia32_Ld(irn) ? ia32_AddrModeS : ia32_AddrModeD);
1113
1114         /* set base and index */
1115         set_irn_n(irn, 0, get_irn_n(lea, 0));
1116         set_irn_n(irn, 1, get_irn_n(lea, 1));
1117
1118         try_remove_from_sched(lea);
1119
1120         /* clear remat flag */
1121         set_ia32_flags(irn, get_ia32_flags(irn) & ~arch_irn_flags_rematerializable);
1122
1123         if (is_ia32_Ld(irn))
1124                 DBG_OPT_LOAD_LEA(lea, irn);
1125         else
1126                 DBG_OPT_STORE_LEA(lea, irn);
1127
1128 }
1129
1130 /**
1131  * Sets new_right index of irn to right and new_left index to left.
1132  * Also exchange left and right
1133  */
1134 static void exchange_left_right(ir_node *irn, ir_node **left, ir_node **right, int new_left, int new_right) {
1135         ir_node *temp;
1136
1137         set_irn_n(irn, new_right, *right);
1138         set_irn_n(irn, new_left, *left);
1139
1140         temp   = *left;
1141         *left  = *right;
1142         *right = temp;
1143
1144         /* this is only needed for Compares, but currently ALL nodes
1145          * have this attribute :-) */
1146         set_ia32_pncode(irn, get_inversed_pnc(get_ia32_pncode(irn)));
1147 }
1148
1149 /**
1150  * Performs address calculation optimization (create LEAs if possible)
1151  */
1152 static void optimize_lea(ia32_code_gen_t *cg, ir_node *irn) {
1153         if (! is_ia32_irn(irn))
1154                 return;
1155
1156         /* Following cases can occur:                                  */
1157         /* - Sub (l, imm) -> LEA [base - offset]                       */
1158         /* - Sub (l, r == LEA with ia32_am_O)   -> LEA [base - offset] */
1159         /* - Add (l, imm) -> LEA [base + offset]                       */
1160         /* - Add (l, r == LEA with ia32_am_O)  -> LEA [base + offset]  */
1161         /* - Add (l == LEA with ia32_am_O, r)  -> LEA [base + offset]  */
1162         /* - Add (l, r) -> LEA [base + index * scale]                  */
1163         /*              with scale > 1 iff l/r == shl (1,2,3)          */
1164         if (is_ia32_Sub(irn) || is_ia32_Add(irn)) {
1165                 ir_node *res;
1166
1167                 if(!is_addr_candidate(irn))
1168                         return;
1169
1170                 DBG((dbg, LEVEL_1, "\tfound address calculation candidate %+F ... ", irn));
1171                 res = fold_addr(cg, irn);
1172
1173                 if (res != irn)
1174                         DB((dbg, LEVEL_1, "transformed into %+F\n", res));
1175                 else
1176                         DB((dbg, LEVEL_1, "not transformed\n"));
1177         } else if (is_ia32_Ld(irn) || is_ia32_St(irn) || is_ia32_Store8Bit(irn)) {
1178                 /* - Load  -> LEA into Load  } TODO: If the LEA is used by more than one Load/Store */
1179                 /* - Store -> LEA into Store }       it might be better to keep the LEA             */
1180                 ir_node *left = get_irn_n(irn, 0);
1181
1182                 if (is_ia32_Lea(left)) {
1183                         const ir_edge_t *edge, *ne;
1184                         ir_node *src;
1185
1186                         /* merge all Loads/Stores connected to this LEA with the LEA */
1187                         foreach_out_edge_safe(left, edge, ne) {
1188                                 src = get_edge_src_irn(edge);
1189
1190                                 if (src && (get_edge_src_pos(edge) == 0) && (is_ia32_Ld(src) || is_ia32_St(src) || is_ia32_Store8Bit(src))) {
1191                                         DBG((dbg, LEVEL_1, "\nmerging %+F into %+F\n", left, irn));
1192                                         if (! is_ia32_got_lea(src))
1193                                                 merge_loadstore_lea(src, left);
1194                                         set_ia32_got_lea(src);
1195                                 }
1196                         }
1197                 }
1198         }
1199 }
1200
1201 static void optimize_conv_store(ia32_code_gen_t *cg, ir_node *node)
1202 {
1203         ir_node *pred;
1204
1205         if(! (is_ia32_Store(node) || is_ia32_Store8Bit(node)))
1206                 return;
1207
1208         pred = get_irn_n(node, 2);
1209         if(!(is_ia32_Conv_I2I(pred) || is_ia32_Conv_I2I8Bit(pred)))
1210                 return;
1211
1212         if(get_ia32_ls_mode(pred) != get_ia32_ls_mode(node))
1213                 return;
1214
1215         /* unnecessary conv, the store already does the conversion */
1216         set_irn_n(node, 2, get_irn_n(pred, 2));
1217         if(get_irn_n_edges(pred) == 0) {
1218                 be_kill_node(pred);
1219         }
1220 }
1221
1222 static void optimize_load_conv(ia32_code_gen_t *cg, ir_node *node)
1223 {
1224         ir_node *pred, *predpred;
1225
1226         if (!is_ia32_Conv_I2I(node) || is_ia32_Conv_I2I8Bit(node))
1227                 return;
1228
1229         pred = get_irn_n(node, 2);
1230         if(!is_Proj(pred))
1231                 return;
1232
1233         predpred = get_Proj_pred(pred);
1234         if(!is_ia32_Load(predpred))
1235                 return;
1236         if(get_ia32_ls_mode(predpred) != get_ia32_ls_mode(node))
1237                 return;
1238
1239         /* unnecessary conv, the load already did the conversion */
1240         exchange(node, pred);
1241 }
1242
1243 static void optimize_node(ir_node *node, void *env)
1244 {
1245         ia32_code_gen_t *cg = env;
1246
1247         optimize_load_conv(cg, node);
1248         optimize_conv_store(cg, node);
1249         optimize_lea(cg, node);
1250 }
1251
1252 /**
1253  * Checks for address mode patterns and performs the
1254  * necessary transformations.
1255  * This function is called by a walker.
1256  */
1257 static void optimize_am(ir_node *irn, void *env) {
1258         ia32_am_opt_env_t *am_opt_env = env;
1259         ia32_code_gen_t   *cg         = am_opt_env->cg;
1260         ir_graph          *irg        = get_irn_irg(irn);
1261         heights_t         *h          = am_opt_env->h;
1262         ir_node           *block, *left, *right;
1263         ir_node           *store, *load, *mem_proj;
1264         ir_node           *addr_b, *addr_i;
1265         int               need_exchange_on_fail = 0;
1266         ia32_am_type_t    am_support;
1267         ia32_am_cand_t cand;
1268         ia32_am_cand_t orig_cand;
1269         int               dest_possible;
1270         int               source_possible;
1271
1272         if (!is_ia32_irn(irn) || is_ia32_Ld(irn) || is_ia32_St(irn) || is_ia32_Store8Bit(irn))
1273                 return;
1274         if (is_ia32_Lea(irn))
1275                 return;
1276
1277         am_support = get_ia32_am_support(irn);
1278         block = get_nodes_block(irn);
1279
1280         DBG((dbg, LEVEL_1, "checking for AM\n"));
1281
1282         /* fold following patterns:                                                         */
1283         /* - op -> Load into AMop with am_Source                                            */
1284         /*   conditions:                                                                    */
1285         /*     - op is am_Source capable AND                                                */
1286         /*     - the Load is only used by this op AND                                       */
1287         /*     - the Load is in the same block                                              */
1288         /* - Store -> op -> Load  into AMop with am_Dest                                    */
1289         /*   conditions:                                                                    */
1290         /*     - op is am_Dest capable AND                                                  */
1291         /*     - the Store uses the same address as the Load AND                            */
1292         /*     - the Load is only used by this op AND                                       */
1293         /*     - the Load and Store are in the same block AND                               */
1294         /*     - nobody else uses the result of the op                                      */
1295         if (get_ia32_am_support(irn) == ia32_am_None)
1296                 return;
1297
1298         cand = is_am_candidate(cg, h, block, irn);
1299         if (cand == IA32_AM_CAND_NONE)
1300                 return;
1301
1302         orig_cand = cand;
1303         DBG((dbg, LEVEL_1, "\tfound address mode candidate %+F ... ", irn));
1304
1305         left  = get_irn_n(irn, 2);
1306         if (get_irn_arity(irn) == 4) {
1307                 /* it's an "unary" operation */
1308                 right = left;
1309                 assert(cand == IA32_AM_CAND_BOTH);
1310         } else {
1311                 right = get_irn_n(irn, 3);
1312         }
1313
1314         dest_possible = am_support & ia32_am_Dest ? 1 : 0;
1315         source_possible = am_support & ia32_am_Source ? 1 : 0;
1316
1317         if (dest_possible) {
1318                 addr_b = NULL;
1319                 addr_i = NULL;
1320                 store  = NULL;
1321
1322                 /* we should only have 1 user which is a store */
1323                 if (ia32_get_irn_n_edges(irn) == 1) {
1324                         ir_node *succ = get_edge_src_irn(get_irn_out_edge_first(irn));
1325
1326                         if (is_ia32_xStore(succ) || is_ia32_Store(succ)) {
1327                                 store  = succ;
1328                                 addr_b = get_irn_n(store, 0);
1329                                 addr_i = get_irn_n(store, 1);
1330                         }
1331                 }
1332
1333                 if (store == NULL) {
1334                         dest_possible = 0;
1335                 }
1336         }
1337
1338         if (dest_possible) {
1339                 /* normalize nodes, we need the interesting load on the left side */
1340                 if (cand & IA32_AM_CAND_RIGHT) {
1341                         load = get_Proj_pred(right);
1342                         if (load_store_addr_is_equal(load, store, addr_b, addr_i)) {
1343                                 exchange_left_right(irn, &left, &right, 3, 2);
1344                                 need_exchange_on_fail ^= 1;
1345                                 if (cand == IA32_AM_CAND_RIGHT)
1346                                         cand = IA32_AM_CAND_LEFT;
1347                         }
1348                 }
1349         }
1350
1351         if (dest_possible) {
1352                 if(cand & IA32_AM_CAND_LEFT && is_Proj(left)) {
1353                         load = get_Proj_pred(left);
1354
1355 #ifndef AGGRESSIVE_AM
1356                         /* we have to be the only user of the load */
1357                         if (get_irn_n_edges(left) > 1) {
1358                                 dest_possible = 0;
1359                         }
1360 #endif
1361                 } else {
1362                         dest_possible = 0;
1363                 }
1364         }
1365
1366         if (dest_possible) {
1367                 /* the store has to use the loads memory or the same memory
1368                  * as the load */
1369                 ir_node *loadmem = get_irn_n(load, 2);
1370                 ir_node *storemem = get_irn_n(store, 3);
1371                 assert(get_irn_mode(loadmem) == mode_M);
1372                 assert(get_irn_mode(storemem) == mode_M);
1373                 if(storemem != loadmem || !is_Proj(storemem)
1374                                 || get_Proj_pred(storemem) != load) {
1375                         dest_possible = 0;
1376                 }
1377         }
1378
1379         if (dest_possible) {
1380                 /* Compare Load and Store address */
1381                 if (!load_store_addr_is_equal(load, store, addr_b, addr_i))
1382                         dest_possible = 0;
1383         }
1384
1385         if (dest_possible) {
1386                 /* all conditions fullfilled, do the transformation */
1387                 assert(cand & IA32_AM_CAND_LEFT);
1388
1389                 /* set new base, index and attributes */
1390                 set_irn_n(irn, 0, addr_b);
1391                 set_irn_n(irn, 1, addr_i);
1392                 add_ia32_am_offs_int(irn, get_ia32_am_offs_int(load));
1393                 set_ia32_am_scale(irn, get_ia32_am_scale(load));
1394                 set_ia32_am_flavour(irn, get_ia32_am_flavour(load));
1395                 set_ia32_op_type(irn, ia32_AddrModeD);
1396                 set_ia32_frame_ent(irn, get_ia32_frame_ent(load));
1397                 set_ia32_ls_mode(irn, get_ia32_ls_mode(load));
1398
1399                 set_ia32_am_sc(irn, get_ia32_am_sc(load));
1400                 if (is_ia32_am_sc_sign(load))
1401                         set_ia32_am_sc_sign(irn);
1402
1403                 /* connect to Load memory and disconnect Load */
1404                 if (get_irn_arity(irn) == 5) {
1405                         /* binary AMop */
1406                         set_irn_n(irn, 4, get_irn_n(load, 2));
1407                         set_irn_n(irn, 2, ia32_get_admissible_noreg(cg, irn, 2));
1408                 } else {
1409                         /* unary AMop */
1410                         set_irn_n(irn, 3, get_irn_n(load, 2));
1411                         set_irn_n(irn, 2, ia32_get_admissible_noreg(cg, irn, 2));
1412                 }
1413
1414                 set_irn_mode(irn, mode_M);
1415
1416                 /* connect the memory Proj of the Store to the op */
1417                 mem_proj = ia32_get_proj_for_mode(store, mode_M);
1418                 edges_reroute(mem_proj, irn, irg);
1419
1420                 /* clear remat flag */
1421                 set_ia32_flags(irn, get_ia32_flags(irn) & ~arch_irn_flags_rematerializable);
1422
1423                 try_remove_from_sched(load);
1424                 try_remove_from_sched(store);
1425                 DBG_OPT_AM_D(load, store, irn);
1426
1427                 DB((dbg, LEVEL_1, "merged with %+F and %+F into dest AM\n", load, store));
1428                 need_exchange_on_fail = 0;
1429                 source_possible = 0;
1430         }
1431
1432         if (source_possible) {
1433                 /* normalize ops, we need the load on the right */
1434                 if(cand == IA32_AM_CAND_LEFT) {
1435                         if(node_is_ia32_comm(irn)) {
1436                                 exchange_left_right(irn, &left, &right, 3, 2);
1437                                 need_exchange_on_fail ^= 1;
1438                                 cand = IA32_AM_CAND_RIGHT;
1439                         } else {
1440                                 source_possible = 0;
1441                         }
1442                 }
1443         }
1444
1445         if (source_possible) {
1446                 /* all conditions fullfilled, do transform */
1447                 assert(cand & IA32_AM_CAND_RIGHT);
1448                 load = get_Proj_pred(right);
1449
1450                 if(get_irn_n_edges(load) > 1) {
1451                         source_possible = 0;
1452                 }
1453         }
1454
1455         if (source_possible) {
1456                 addr_b = get_irn_n(load, 0);
1457                 addr_i = get_irn_n(load, 1);
1458
1459                 /* set new base, index and attributes */
1460                 set_irn_n(irn, 0, addr_b);
1461                 set_irn_n(irn, 1, addr_i);
1462                 add_ia32_am_offs_int(irn, get_ia32_am_offs_int(load));
1463                 set_ia32_am_scale(irn, get_ia32_am_scale(load));
1464                 set_ia32_am_flavour(irn, get_ia32_am_flavour(load));
1465                 set_ia32_op_type(irn, ia32_AddrModeS);
1466                 set_ia32_frame_ent(irn, get_ia32_frame_ent(load));
1467                 set_ia32_ls_mode(irn, get_ia32_ls_mode(load));
1468
1469                 set_ia32_am_sc(irn, get_ia32_am_sc(load));
1470                 if (is_ia32_am_sc_sign(load))
1471                         set_ia32_am_sc_sign(irn);
1472
1473                 /* clear remat flag */
1474                 set_ia32_flags(irn, get_ia32_flags(irn) & ~arch_irn_flags_rematerializable);
1475
1476                 if (is_ia32_use_frame(load)) {
1477                         if(get_ia32_frame_ent(load) == NULL) {
1478                                 set_ia32_need_stackent(irn);
1479                         }
1480                         set_ia32_use_frame(irn);
1481                 }
1482
1483                 /* connect to Load memory and disconnect Load */
1484                 if (get_irn_arity(irn) == 5) {
1485                         /* binary AMop */
1486                         set_irn_n(irn, 3, ia32_get_admissible_noreg(cg, irn, 3));
1487                         set_irn_n(irn, 4, get_irn_n(load, 2));
1488                 } else {
1489                         assert(get_irn_arity(irn) == 4);
1490                         /* unary AMop */
1491                         set_irn_n(irn, 2, ia32_get_admissible_noreg(cg, irn, 2));
1492                         set_irn_n(irn, 3, get_irn_n(load, 2));
1493                 }
1494
1495                 DBG_OPT_AM_S(load, irn);
1496
1497                 /* If Load has a memory Proj, connect it to the op */
1498                 mem_proj = ia32_get_proj_for_mode(load, mode_M);
1499                 if (mem_proj != NULL) {
1500                         ir_node *res_proj;
1501                         ir_mode *mode = get_irn_mode(irn);
1502
1503                         res_proj = new_rd_Proj(get_irn_dbg_info(irn), irg,
1504                                                get_nodes_block(irn), new_Unknown(mode_T),
1505                                                                    mode, 0);
1506                         set_irn_mode(irn, mode_T);
1507                         edges_reroute(irn, res_proj, irg);
1508                         set_Proj_pred(res_proj, irn);
1509
1510                         set_Proj_pred(mem_proj, irn);
1511                         set_Proj_proj(mem_proj, 1);
1512
1513                         if(sched_is_scheduled(irn)) {
1514                                 sched_add_after(irn, res_proj);
1515                                 sched_add_after(irn, mem_proj);
1516                         }
1517                 }
1518
1519                 if(get_irn_n_edges(load) == 0) {
1520                         try_remove_from_sched(load);
1521                 }
1522                 need_exchange_on_fail = 0;
1523
1524                 DB((dbg, LEVEL_1, "merged with %+F into source AM\n", load));
1525         }
1526
1527         /* was exchanged but optimize failed: exchange back */
1528         if (need_exchange_on_fail) {
1529                 exchange_left_right(irn, &left, &right, 3, 2);
1530         }
1531 }
1532
1533 /**
1534  * Performs conv and address mode optimization.
1535  */
1536 void ia32_optimize_graph(ia32_code_gen_t *cg) {
1537         /* if we are supposed to do AM or LEA optimization: recalculate edges */
1538         if (! (cg->opt & (IA32_OPT_DOAM | IA32_OPT_LEA))) {
1539                 /* no optimizations at all */
1540                 return;
1541         }
1542
1543         /* beware: we cannot optimize LEA and AM in one run because */
1544         /*         LEA optimization adds new nodes to the irg which */
1545         /*         invalidates the phase data                       */
1546
1547         if (cg->opt & IA32_OPT_LEA) {
1548                 irg_walk_blkwise_graph(cg->irg, NULL, optimize_node, cg);
1549         }
1550
1551         if (cg->dump)
1552                 be_dump(cg->irg, "-lea", dump_ir_block_graph_sched);
1553
1554         /* hack for now, so these don't get created during optimize, because then
1555          * they will be unknown to the heights module
1556          */
1557         ia32_new_NoReg_gp(cg);
1558         ia32_new_NoReg_fp(cg);
1559         ia32_new_NoReg_vfp(cg);
1560
1561         if (cg->opt & IA32_OPT_DOAM) {
1562                 /* we need height information for am optimization */
1563                 heights_t *h = heights_new(cg->irg);
1564                 ia32_am_opt_env_t env;
1565
1566                 env.cg = cg;
1567                 env.h  = h;
1568
1569                 irg_walk_blkwise_graph(cg->irg, NULL, optimize_am, &env);
1570
1571                 heights_free(h);
1572         }
1573 }
1574
1575 void ia32_init_optimize(void)
1576 {
1577         FIRM_DBG_REGISTER(dbg, "firm.be.ia32.optimize");
1578 }