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