ca637d7ee47ab7934c00fa52d8a4f8a5f4faacb3
[libfirm] / ir / ir / iropt.c
1 /*
2  * Project:     libFIRM
3  * File name:   ir/ir/iropt.c
4  * Purpose:     iropt --- optimizations intertwined with IR construction.
5  * Author:      Christian Schaefer
6  * Modified by: Goetz Lindenmaier, Michael Beck
7  * Created:
8  * CVS-ID:      $Id$
9  * Copyright:   (c) 1998-2005 Universität Karlsruhe
10  * Licence:     This file protected by GPL -  GNU GENERAL PUBLIC LICENSE.
11  */
12
13 #ifdef HAVE_CONFIG_H
14 # include "config.h"
15 #endif
16
17 #ifdef HAVE_ALLOCA_H
18 #include <alloca.h>
19 #endif
20 #ifdef HAVE_MALLOC_H
21 #include <malloc.h>
22 #endif
23 #ifdef HAVE_STRING_H
24 #include <string.h>
25 #endif
26
27 # include "irnode_t.h"
28 # include "irgraph_t.h"
29 # include "iredges_t.h"
30 # include "irmode_t.h"
31 # include "iropt_t.h"
32 # include "ircons_t.h"
33 # include "irgmod.h"
34 # include "irvrfy.h"
35 # include "tv_t.h"
36 # include "dbginfo_t.h"
37 # include "iropt_dbg.h"
38 # include "irflag_t.h"
39 # include "irhooks.h"
40 # include "irarch.h"
41 # include "hashptr.h"
42 # include "archop.h"
43 # include "opt_polymorphy.h"
44 # include "opt_confirms.h"
45
46 /* Make types visible to allow most efficient access */
47 # include "entity_t.h"
48
49 /**
50  * return the value of a Constant
51  */
52 static tarval *computed_value_Const(ir_node *n)
53 {
54   return get_Const_tarval(n);
55 }
56
57 /**
58  * return the value of a 'sizeof' SymConst
59  */
60 static tarval *computed_value_SymConst(ir_node *n)
61 {
62   if ((get_SymConst_kind(n) == symconst_size) &&
63       (get_type_state(get_SymConst_type(n))) == layout_fixed)
64     return new_tarval_from_long(get_type_size_bytes(get_SymConst_type(n)), get_irn_mode(n));
65   return tarval_bad;
66 }
67
68 /**
69  * return the value of an Add
70  */
71 static tarval *computed_value_Add(ir_node *n)
72 {
73   ir_node *a = get_Add_left(n);
74   ir_node *b = get_Add_right(n);
75
76   tarval *ta = value_of(a);
77   tarval *tb = value_of(b);
78
79   if ((ta != tarval_bad) && (tb != tarval_bad) && (get_irn_mode(a) == get_irn_mode(b)))
80     return tarval_add(ta, tb);
81
82   return tarval_bad;
83 }
84
85 /**
86  * return the value of a Sub
87  * Special case: a - a
88  */
89 static tarval *computed_value_Sub(ir_node *n)
90 {
91   ir_node *a = get_Sub_left(n);
92   ir_node *b = get_Sub_right(n);
93   tarval *ta;
94   tarval *tb;
95
96   /* a - a */
97   if (a == b && !is_Bad(a))
98     return get_mode_null(get_irn_mode(n));
99
100   ta = value_of(a);
101   tb = value_of(b);
102
103   if ((ta != tarval_bad) && (tb != tarval_bad) && (get_irn_mode(a) == get_irn_mode(b)))
104     return tarval_sub(ta, tb);
105
106   return tarval_bad;
107 }
108
109 /**
110  * return the value of an unary Minus
111  */
112 static tarval *computed_value_Minus(ir_node *n)
113 {
114   ir_node *a = get_Minus_op(n);
115   tarval *ta = value_of(a);
116
117   if ((ta != tarval_bad) && mode_is_signed(get_irn_mode(a)))
118     return tarval_neg(ta);
119
120   return tarval_bad;
121 }
122
123 /**
124  * return the value of a Mul
125  */
126 static tarval *computed_value_Mul(ir_node *n)
127 {
128   ir_node *a = get_Mul_left(n);
129   ir_node *b = get_Mul_right(n);
130
131   tarval *ta = value_of(a);
132   tarval *tb = value_of(b);
133
134   if ((ta != tarval_bad) && (tb != tarval_bad) && (get_irn_mode(a) == get_irn_mode(b))) {
135     return tarval_mul(ta, tb);
136   } else {
137     /* a*0 = 0 or 0*b = 0:
138        calls computed_value recursive and returns the 0 with proper
139        mode. */
140     if ((ta != tarval_bad) && (ta == get_mode_null(get_tarval_mode(ta))))
141       return ta;
142     if ((tb != tarval_bad) && (tb == get_mode_null(get_tarval_mode(tb))))
143       return tb;
144   }
145   return tarval_bad;
146 }
147
148 /**
149  * return the value of a floating point Quot
150  */
151 static tarval *computed_value_Quot(ir_node *n)
152 {
153   ir_node *a = get_Quot_left(n);
154   ir_node *b = get_Quot_right(n);
155
156   tarval *ta = value_of(a);
157   tarval *tb = value_of(b);
158
159   /* This was missing in original implementation. Why? */
160   if ((ta != tarval_bad) && (tb != tarval_bad) && (get_irn_mode(a) == get_irn_mode(b))) {
161     if (tb != get_mode_null(get_tarval_mode(tb)))   /* div by zero: return tarval_bad */
162       return tarval_quo(ta, tb);
163   }
164   return tarval_bad;
165 }
166
167 /**
168  * calculate the value of an integer Div of two nodes
169  * Special case: 0 / b
170  */
171 static tarval *do_computed_value_Div(ir_node *a, ir_node *b)
172 {
173   tarval *ta = value_of(a);
174   tarval *tb = value_of(b);
175
176   /* Compute c1 / c2 or 0 / a, a != 0 */
177   if (ta != tarval_bad) {
178     if ((tb != tarval_bad) && (tb != get_mode_null(get_irn_mode(b))))   /* div by zero: return tarval_bad */
179       return tarval_div(ta, tb);
180     else if (ta == get_mode_null(get_tarval_mode(ta)))  /* 0 / b == 0 */
181       return ta;
182   }
183   return tarval_bad;
184 }
185
186 /**
187  * return the value of an integer Div
188  */
189 static tarval *computed_value_Div(ir_node *n)
190 {
191   return do_computed_value_Div(get_Div_left(n), get_Div_right(n));
192 }
193
194 /**
195  * calculate the value of an integer Mod of two nodes
196  * Special case: a % 1
197  */
198 static tarval *do_computed_value_Mod(ir_node *a, ir_node *b)
199 {
200   tarval *ta = value_of(a);
201   tarval *tb = value_of(b);
202
203   /* Compute c1 % c2 or a % 1 */
204   if (tb != tarval_bad) {
205     if ((ta != tarval_bad) && (tb != get_mode_null(get_tarval_mode(tb))))   /* div by zero: return tarval_bad */
206       return tarval_mod(ta, tb);
207     else if (tb == get_mode_one(get_tarval_mode(tb)))    /* x mod 1 == 0 */
208       return get_mode_null(get_irn_mode(a));
209   }
210
211   return tarval_bad;
212 }
213
214 /**
215  * return the value of an integer Mod
216  */
217 static tarval *computed_value_Mod(ir_node *n)
218 {
219   return do_computed_value_Mod(get_Mod_left(n), get_Mod_right(n));
220 }
221
222 /**
223  * return the value of an Abs
224  */
225 static tarval *computed_value_Abs(ir_node *n)
226 {
227   ir_node *a = get_Abs_op(n);
228   tarval *ta = value_of(a);
229
230   if (ta != tarval_bad)
231     return tarval_abs(ta);
232
233   return tarval_bad;
234 }
235
236 /**
237  * return the value of an And
238  * Special case: a & 0, 0 & b
239  */
240 static tarval *computed_value_And(ir_node *n)
241 {
242   ir_node *a = get_And_left(n);
243   ir_node *b = get_And_right(n);
244
245   tarval *ta = value_of(a);
246   tarval *tb = value_of(b);
247
248   if ((ta != tarval_bad) && (tb != tarval_bad)) {
249     return tarval_and (ta, tb);
250   } else {
251     tarval *v;
252
253     if (   (classify_tarval ((v = ta)) == TV_CLASSIFY_NULL)
254         || (classify_tarval ((v = tb)) == TV_CLASSIFY_NULL)) {
255       return v;
256     }
257   }
258   return tarval_bad;
259 }
260
261 /**
262  * return the value of an Or
263  * Special case: a | 1...1, 1...1 | b
264  */
265 static tarval *computed_value_Or(ir_node *n)
266 {
267   ir_node *a = get_Or_left(n);
268   ir_node *b = get_Or_right(n);
269
270   tarval *ta = value_of(a);
271   tarval *tb = value_of(b);
272
273   if ((ta != tarval_bad) && (tb != tarval_bad)) {
274     return tarval_or (ta, tb);
275   } else {
276     tarval *v;
277     if (   (classify_tarval ((v = ta)) == TV_CLASSIFY_ALL_ONE)
278         || (classify_tarval ((v = tb)) == TV_CLASSIFY_ALL_ONE)) {
279       return v;
280     }
281   }
282   return tarval_bad;
283 }
284
285 /**
286  * return the value of an Eor
287  */
288 static tarval *computed_value_Eor(ir_node *n)
289 {
290   ir_node *a = get_Eor_left(n);
291   ir_node *b = get_Eor_right(n);
292
293   tarval *ta, *tb;
294
295   if (a == b)
296     return get_mode_null(get_irn_mode(n));
297
298   ta = value_of(a);
299   tb = value_of(b);
300
301   if ((ta != tarval_bad) && (tb != tarval_bad)) {
302     return tarval_eor (ta, tb);
303   }
304   return tarval_bad;
305 }
306
307 /**
308  * return the value of a Not
309  */
310 static tarval *computed_value_Not(ir_node *n)
311 {
312   ir_node *a = get_Not_op(n);
313   tarval *ta = value_of(a);
314
315   if (ta != tarval_bad)
316     return tarval_not(ta);
317
318   return tarval_bad;
319 }
320
321 /**
322  * return the value of a Shl
323  */
324 static tarval *computed_value_Shl(ir_node *n)
325 {
326   ir_node *a = get_Shl_left(n);
327   ir_node *b = get_Shl_right(n);
328
329   tarval *ta = value_of(a);
330   tarval *tb = value_of(b);
331
332   if ((ta != tarval_bad) && (tb != tarval_bad)) {
333     return tarval_shl (ta, tb);
334   }
335   return tarval_bad;
336 }
337
338 /**
339  * return the value of a Shr
340  */
341 static tarval *computed_value_Shr(ir_node *n)
342 {
343   ir_node *a = get_Shr_left(n);
344   ir_node *b = get_Shr_right(n);
345
346   tarval *ta = value_of(a);
347   tarval *tb = value_of(b);
348
349   if ((ta != tarval_bad) && (tb != tarval_bad)) {
350     return tarval_shr (ta, tb);
351   }
352   return tarval_bad;
353 }
354
355 /**
356  * return the value of a Shrs
357  */
358 static tarval *computed_value_Shrs(ir_node *n)
359 {
360   ir_node *a = get_Shrs_left(n);
361   ir_node *b = get_Shrs_right(n);
362
363   tarval *ta = value_of(a);
364   tarval *tb = value_of(b);
365
366   if ((ta != tarval_bad) && (tb != tarval_bad)) {
367     return tarval_shrs (ta, tb);
368   }
369   return tarval_bad;
370 }
371
372 /**
373  * return the value of a Rot
374  */
375 static tarval *computed_value_Rot(ir_node *n)
376 {
377   ir_node *a = get_Rot_left(n);
378   ir_node *b = get_Rot_right(n);
379
380   tarval *ta = value_of(a);
381   tarval *tb = value_of(b);
382
383   if ((ta != tarval_bad) && (tb != tarval_bad)) {
384     return tarval_rot (ta, tb);
385   }
386   return tarval_bad;
387 }
388
389 /**
390  * return the value of a Conv
391  */
392 static tarval *computed_value_Conv(ir_node *n)
393 {
394   ir_node *a = get_Conv_op(n);
395   tarval *ta = value_of(a);
396
397   if (ta != tarval_bad)
398     return tarval_convert_to(ta, get_irn_mode(n));
399
400   return tarval_bad;
401 }
402
403 /**
404  * return the value of a Proj(Cmp)
405  *
406  * This performs a first step of unreachable code elimination.
407  * Proj can not be computed, but folding a Cmp above the Proj here is
408  * not as wasteful as folding a Cmp into a Tuple of 16 Consts of which
409  * only 1 is used.
410  * There are several case where we can evaluate a Cmp node, see later.
411  */
412 static tarval *computed_value_Proj_Cmp(ir_node *n)
413 {
414   ir_node *a   = get_Proj_pred(n);
415   ir_node *aa  = get_Cmp_left(a);
416   ir_node *ab  = get_Cmp_right(a);
417   long proj_nr = get_Proj_proj(n);
418
419   /*
420    * BEWARE: a == a is NOT always True for floating Point values, as
421    * NaN != NaN is defined, so we must check this here.
422    */
423   if (aa == ab && (
424       !mode_is_float(get_irn_mode(aa)) || proj_nr == pn_Cmp_Lt ||  proj_nr == pn_Cmp_Gt)
425       ) { /* 1.: */
426
427     /* This is a trick with the bits used for encoding the Cmp
428        Proj numbers, the following statement is not the same:
429     return new_tarval_from_long (proj_nr == pn_Cmp_Eq, mode_b) */
430     return new_tarval_from_long (proj_nr & pn_Cmp_Eq, mode_b);
431   }
432   else {
433     tarval *taa = value_of(aa);
434     tarval *tab = value_of(ab);
435     ir_mode *mode = get_irn_mode(aa);
436
437     /*
438      * The predecessors of Cmp are target values.  We can evaluate
439      * the Cmp.
440      */
441     if ((taa != tarval_bad) && (tab != tarval_bad)) {
442       /* strange checks... */
443       pn_Cmp flags = tarval_cmp(taa, tab);
444       if (flags != pn_Cmp_False) {
445         return new_tarval_from_long (proj_nr & flags, mode_b);
446       }
447     }
448     /* for integer values, we can check against MIN/MAX */
449     else if (mode_is_int(mode)) {
450       /* MIN <=/> x.  This results in true/false. */
451       if (taa == get_mode_min(mode)) {
452         /* a compare with the MIN value */
453         if (proj_nr == pn_Cmp_Le)
454           return get_tarval_b_true();
455         else if (proj_nr == pn_Cmp_Gt)
456           return get_tarval_b_false();
457       }
458       /* x >=/< MIN.  This results in true/false. */
459       else
460       if (tab == get_mode_min(mode)) {
461         /* a compare with the MIN value */
462         if (proj_nr == pn_Cmp_Ge)
463           return get_tarval_b_true();
464         else if (proj_nr == pn_Cmp_Lt)
465           return get_tarval_b_false();
466       }
467       /* MAX >=/< x.  This results in true/false. */
468       else if (taa == get_mode_max(mode)) {
469         if (proj_nr == pn_Cmp_Ge)
470           return get_tarval_b_true();
471         else if (proj_nr == pn_Cmp_Lt)
472           return get_tarval_b_false();
473       }
474       /* x <=/> MAX.  This results in true/false. */
475       else if (tab == get_mode_max(mode)) {
476         if (proj_nr == pn_Cmp_Le)
477           return get_tarval_b_true();
478         else if (proj_nr == pn_Cmp_Gt)
479           return get_tarval_b_false();
480       }
481     }
482     /*
483      * The predecessors are Allocs or (void*)(0) constants.  Allocs never
484      * return NULL, they raise an exception.   Therefore we can predict
485      * the Cmp result.
486      */
487     else {
488       ir_node *aaa = skip_Id(skip_Proj(aa));
489       ir_node *aba = skip_Id(skip_Proj(ab));
490
491       if (   (   (/* aa is ProjP and aaa is Alloc */
492                      (get_irn_op(aa) == op_Proj)
493                   && (mode_is_reference(get_irn_mode(aa)))
494                   && (get_irn_op(aaa) == op_Alloc))
495               && (   (/* ab is NULL */
496                          (get_irn_op(ab) == op_Const)
497                       && (mode_is_reference(get_irn_mode(ab)))
498                       && (get_Const_tarval(ab) == get_mode_null(get_irn_mode(ab))))
499                   || (/* ab is other Alloc */
500                          (get_irn_op(ab) == op_Proj)
501                       && (mode_is_reference(get_irn_mode(ab)))
502                       && (get_irn_op(aba) == op_Alloc)
503                       && (aaa != aba))))
504           || (/* aa is NULL and aba is Alloc */
505                  (get_irn_op(aa) == op_Const)
506               && (mode_is_reference(get_irn_mode(aa)))
507               && (get_Const_tarval(aa) == get_mode_null(get_irn_mode(aa)))
508               && (get_irn_op(ab) == op_Proj)
509               && (mode_is_reference(get_irn_mode(ab)))
510               && (get_irn_op(aba) == op_Alloc)))
511         /* 3.: */
512         return new_tarval_from_long(proj_nr & pn_Cmp_Ne, mode_b);
513     }
514   }
515
516   return computed_value_Cmp_Confirm(a, aa, ab, proj_nr);
517 }
518
519 /**
520  * return the value of a Proj, handle Proj(Cmp), Proj(Div), Proj(Mod), Proj(DivMod)
521  */
522 static tarval *computed_value_Proj(ir_node *n)
523 {
524   ir_node *a = get_Proj_pred(n);
525   long proj_nr;
526
527   switch (get_irn_opcode(a)) {
528   case iro_Cmp:
529     return computed_value_Proj_Cmp(n);
530
531   case iro_DivMod:
532     /* compute either the Div or the Mod part */
533     proj_nr = get_Proj_proj(n);
534     if (proj_nr == pn_DivMod_res_div)
535       return do_computed_value_Div(get_DivMod_left(a), get_DivMod_right(a));
536     else if (proj_nr == pn_DivMod_res_mod)
537       return do_computed_value_Mod(get_DivMod_left(a), get_DivMod_right(a));
538     break;
539
540   case iro_Div:
541     if (get_Proj_proj(n) == pn_Div_res)
542       return computed_value(a);
543     break;
544
545   case iro_Mod:
546     if (get_Proj_proj(n) == pn_Mod_res)
547       return computed_value(a);
548     break;
549
550   default:
551     return tarval_bad;
552   }
553   return tarval_bad;
554 }
555
556 /**
557  * calculate the value of a Mux: can be evaluated, if the
558  * sel and the right input are known
559  */
560 static tarval *computed_value_Mux(ir_node *n)
561 {
562   ir_node *sel = get_Mux_sel(n);
563   tarval *ts = value_of(sel);
564
565   if (ts == get_tarval_b_true()) {
566     ir_node *v = get_Mux_true(n);
567     return value_of(v);
568   }
569   else if (ts == get_tarval_b_false()) {
570     ir_node *v = get_Mux_false(n);
571     return value_of(v);
572   }
573   return tarval_bad;
574 }
575
576 /**
577  * calculate the value of a Confirm: can be evaluated,
578  * if it has the form Confirm(x, '=', Const).
579  */
580 static tarval *computed_value_Confirm(ir_node *n)
581 {
582   return get_Confirm_cmp(n) == pn_Cmp_Eq ?
583     value_of(get_Confirm_bound(n)) : tarval_bad;
584 }
585
586 /**
587  * If the parameter n can be computed, return its value, else tarval_bad.
588  * Performs constant folding.
589  *
590  * @param n  The node this should be evaluated
591  */
592 tarval *computed_value(ir_node *n)
593 {
594   if (n->op->computed_value)
595     return n->op->computed_value(n);
596   return tarval_bad;
597 }
598
599 /**
600  * set the default computed_value evaluator
601  */
602 static ir_op *firm_set_default_computed_value(ir_op *op)
603 {
604 #define CASE(a)                               \
605   case iro_##a:                               \
606     op->computed_value  = computed_value_##a; \
607     break
608
609   switch (op->code) {
610   CASE(Const);
611   CASE(SymConst);
612   CASE(Add);
613   CASE(Sub);
614   CASE(Minus);
615   CASE(Mul);
616   CASE(Quot);
617   CASE(Div);
618   CASE(Mod);
619   CASE(Abs);
620   CASE(And);
621   CASE(Or);
622   CASE(Eor);
623   CASE(Not);
624   CASE(Shl);
625   CASE(Shr);
626   CASE(Shrs);
627   CASE(Rot);
628   CASE(Conv);
629   CASE(Proj);
630   CASE(Mux);
631   CASE(Confirm);
632   default:
633     op->computed_value  = NULL;
634   }
635
636   return op;
637 #undef CASE
638 }
639
640 #if 0
641 /* returns 1 if the a and b are pointers to different locations. */
642 static bool
643 different_identity (ir_node *a, ir_node *b)
644 {
645   assert (mode_is_reference(get_irn_mode (a))
646           && mode_is_reference(get_irn_mode (b)));
647
648   if (get_irn_op (a) == op_Proj && get_irn_op(b) == op_Proj) {
649     ir_node *a1 = get_Proj_pred (a);
650     ir_node *b1 = get_Proj_pred (b);
651     if (a1 != b1 && get_irn_op (a1) == op_Alloc
652                 && get_irn_op (b1) == op_Alloc)
653       return 1;
654   }
655   return 0;
656 }
657 #endif
658
659 /**
660  * Returns a equivalent block for another block.
661  * If the block has only one predecessor, this is
662  * the equivalent one. If the only predecessor of a block is
663  * the block itself, this is a dead block.
664  *
665  * If both predecessors of a block are the branches of a binary
666  * Cond, the equivalent block is Cond's block.
667  *
668  * If all predecessors of a block are bad or lies in a dead
669  * block, the current block is dead as well.
670  *
671  * Note, that blocks are NEVER turned into Bad's, instead
672  * the dead_block flag is set. So, never test for is_Bad(block),
673  * always use is_dead_Block(block).
674  */
675 static ir_node *equivalent_node_Block(ir_node *n)
676 {
677   ir_node *oldn = n;
678   int n_preds   = get_Block_n_cfgpreds(n);
679
680   /* The Block constructor does not call optimize, but mature_immBlock
681      calls the optimization. */
682   assert(get_Block_matured(n));
683
684   /* Straightening: a single entry Block following a single exit Block
685      can be merged, if it is not the Start block. */
686   /* !!! Beware, all Phi-nodes of n must have been optimized away.
687      This should be true, as the block is matured before optimize is called.
688      But what about Phi-cycles with the Phi0/Id that could not be resolved?
689      Remaining Phi nodes are just Ids. */
690    if ((n_preds == 1) && (get_irn_op(get_Block_cfgpred(n, 0)) == op_Jmp)) {
691      ir_node *predblock = get_nodes_block(get_Block_cfgpred(n, 0));
692      if (predblock == oldn) {
693        /* Jmp jumps into the block it is in -- deal self cycle. */
694        n = set_Block_dead(n);
695        DBG_OPT_DEAD(oldn, n);
696      } else if (get_opt_control_flow_straightening()) {
697        n = predblock;
698        DBG_OPT_STG(oldn, n);
699      }
700    }
701    else if ((n_preds == 1) &&
702             (get_irn_op(skip_Proj(get_Block_cfgpred(n, 0))) == op_Cond)) {
703      ir_node *predblock = get_nodes_block(get_Block_cfgpred(n, 0));
704      if (predblock == oldn) {
705        /* Jmp jumps into the block it is in -- deal self cycle. */
706        n = set_Block_dead(n);
707        DBG_OPT_DEAD(oldn, n);
708      }
709    }
710    else if ((n_preds == 2) &&
711             (get_opt_control_flow_weak_simplification())) {
712     /* Test whether Cond jumps twice to this block
713        @@@ we could do this also with two loops finding two preds from several ones. */
714     ir_node *a = get_Block_cfgpred(n, 0);
715     ir_node *b = get_Block_cfgpred(n, 1);
716
717     if ((get_irn_op(a) == op_Proj) &&
718         (get_irn_op(b) == op_Proj) &&
719         (get_Proj_pred(a) == get_Proj_pred(b)) &&
720         (get_irn_op(get_Proj_pred(a)) == op_Cond) &&
721         (get_irn_mode(get_Cond_selector(get_Proj_pred(a))) == mode_b)) {
722       /* Also a single entry Block following a single exit Block.  Phis have
723          twice the same operand and will be optimized away. */
724       n = get_nodes_block(a);
725       DBG_OPT_IFSIM(oldn, a, b, n);
726     }
727   } else if (get_opt_unreachable_code() &&
728              (n != current_ir_graph->start_block) &&
729              (n != current_ir_graph->end_block)     ) {
730     int i, n_cfg = get_Block_n_cfgpreds(n);
731
732     /* If all inputs are dead, this block is dead too, except if it is
733        the start or end block.  This is a step of unreachable code
734        elimination */
735     for (i = 0; i < n_cfg; i++) {
736       ir_node *pred = get_Block_cfgpred(n, i);
737       ir_node *pred_blk;
738
739       if (is_Bad(pred)) continue;
740       pred_blk = get_nodes_block(pred);
741
742       if (is_Block_dead(pred_blk)) continue;
743
744       if (pred_blk != n) {
745         /* really found a living input */
746         break;
747       }
748     }
749     if (i == n_cfg)
750       n = set_Block_dead(n);
751   }
752
753   return n;
754 }
755
756 /**
757  * Returns a equivalent node for a Jmp, a Bad :-)
758  * Of course this only happens if the Block of the Jmp is Bad.
759  */
760 static ir_node *equivalent_node_Jmp(ir_node *n)
761 {
762   /* GL: Why not same for op_Raise?? */
763   /* unreachable code elimination */
764   if (is_Block_dead(get_nodes_block(n)))
765     n = new_Bad();
766
767   return n;
768 }
769
770 static ir_node *equivalent_node_Cond(ir_node *n)
771 {
772   /* We do not evaluate Cond here as we replace it by a new node, a Jmp.
773      See cases for iro_Cond and iro_Proj in transform_node(). */
774   return n;
775 }
776
777 /**
778  * optimize operations that are commutative and have neutral 0,
779  * so a op 0 = 0 op a = a.
780  */
781 static ir_node *equivalent_node_neutral_zero(ir_node *n)
782 {
783   ir_node *oldn = n;
784
785   ir_node *a = get_binop_left(n);
786   ir_node *b = get_binop_right(n);
787
788   tarval *tv;
789   ir_node *on;
790
791   /* After running compute_node there is only one constant predecessor.
792      Find this predecessors value and remember the other node: */
793   if ((tv = value_of(a)) != tarval_bad) {
794     on = b;
795   } else if ((tv = value_of(b)) != tarval_bad) {
796     on = a;
797   } else
798     return n;
799
800   /* If this predecessors constant value is zero, the operation is
801      unnecessary. Remove it: */
802   if (classify_tarval (tv) == TV_CLASSIFY_NULL) {
803     n = on;
804
805     DBG_OPT_ALGSIM1(oldn, a, b, n);
806   }
807
808   return n;
809 }
810
811 #define equivalent_node_Add  equivalent_node_neutral_zero
812 #define equivalent_node_Eor  equivalent_node_neutral_zero
813
814 /**
815  * optimize operations that are not commutative but have neutral 0 on left,
816  * so a op 0 = a.
817  */
818 static ir_node *equivalent_node_left_zero(ir_node *n)
819 {
820   ir_node *oldn = n;
821
822   ir_node *a = get_binop_left(n);
823   ir_node *b = get_binop_right(n);
824
825   if (classify_tarval(value_of(b)) == TV_CLASSIFY_NULL) {
826     n = a;
827
828     DBG_OPT_ALGSIM1(oldn, a, b, n);
829   }
830
831   return n;
832 }
833
834 #define equivalent_node_Shl   equivalent_node_left_zero
835 #define equivalent_node_Shr   equivalent_node_left_zero
836 #define equivalent_node_Shrs  equivalent_node_left_zero
837 #define equivalent_node_Rot   equivalent_node_left_zero
838
839 /**
840  * Optimize a - 0 and (a + x) - x (for modes with wrap-around).
841  *
842  * The second one looks strange, but this construct
843  * is used heavily in the LCC sources :-).
844  */
845 static ir_node *equivalent_node_Sub(ir_node *n)
846 {
847   ir_node *oldn = n;
848
849   ir_node *a = get_Sub_left(n);
850   ir_node *b = get_Sub_right(n);
851
852   if (classify_tarval(value_of(b)) == TV_CLASSIFY_NULL) {
853     n = a;
854
855     DBG_OPT_ALGSIM1(oldn, a, b, n);
856   }
857   else if (get_irn_op(a) == op_Add) {
858     ir_mode *mode = get_irn_mode(n);
859
860     if (mode_wrap_around(mode)) {
861       ir_node *left  = get_Add_left(a);
862       ir_node *right = get_Add_right(a);
863
864       if (left == b) {
865         n = right;
866
867         DBG_OPT_ALGSIM1(oldn, a, b, n);
868       }
869       else if (right == b) {
870         n = left;
871
872         DBG_OPT_ALGSIM1(oldn, a, b, n);
873       }
874     }
875   }
876
877   return n;
878 }
879
880
881 /**
882  * Optimize an "idempotent unary op", ie op(op(n)) = n.
883  *
884  * @fixme -(-a) == a, but might overflow two times.
885  * We handle it anyway here but the better way would be a
886  * flag. This would be needed for Pascal for instance.
887  */
888 static ir_node *equivalent_node_idempotent_unop(ir_node *n)
889 {
890   ir_node *oldn = n;
891   ir_node *pred = get_unop_op(n);
892
893   /* optimize symmetric unop */
894   if (get_irn_op(pred) == get_irn_op(n)) {
895     n = get_unop_op(pred);
896     DBG_OPT_ALGSIM2(oldn, pred, n);
897   }
898   return n;
899 }
900
901 /* Not(Not(x)) == x */
902 #define equivalent_node_Not    equivalent_node_idempotent_unop
903
904 /* --x == x */  /* ??? Is this possible or can --x raise an
905                        out of bounds exception if min =! max? */
906 #define equivalent_node_Minus  equivalent_node_idempotent_unop
907
908 /**
909  * Optimize a * 1 = 1 * a = a.
910  */
911 static ir_node *equivalent_node_Mul(ir_node *n)
912 {
913   ir_node *oldn = n;
914
915   ir_node *a = get_Mul_left(n);
916   ir_node *b = get_Mul_right(n);
917
918   /* Mul is commutative and has again an other neutral element. */
919   if (classify_tarval(value_of(a)) == TV_CLASSIFY_ONE) {
920     n = b;
921     DBG_OPT_ALGSIM1(oldn, a, b, n);
922   } else if (classify_tarval(value_of(b)) == TV_CLASSIFY_ONE) {
923     n = a;
924     DBG_OPT_ALGSIM1(oldn, a, b, n);
925   }
926   return n;
927 }
928
929 /**
930  * Optimize a / 1 = a.
931  */
932 static ir_node *equivalent_node_Div(ir_node *n)
933 {
934   ir_node *a = get_Div_left(n);
935   ir_node *b = get_Div_right(n);
936
937   /* Div is not commutative. */
938   if (classify_tarval(value_of(b)) == TV_CLASSIFY_ONE) { /* div(x, 1) == x */
939     /* Turn Div into a tuple (mem, bad, a) */
940     ir_node *mem = get_Div_mem(n);
941     turn_into_tuple(n, 3);
942     set_Tuple_pred(n, pn_Div_M,        mem);
943     set_Tuple_pred(n, pn_Div_X_except, new_Bad());        /* no exception */
944     set_Tuple_pred(n, pn_Div_res,      a);
945   }
946   return n;
947 }
948
949 /**
950  * Optimize a / 1 = a.
951  */
952 static ir_node *equivalent_node_DivMod(ir_node *n)
953 {
954   ir_node *a = get_DivMod_left(n);
955   ir_node *b = get_DivMod_right(n);
956
957   /* Div is not commutative. */
958   if (classify_tarval(value_of(b)) == TV_CLASSIFY_ONE) { /* div(x, 1) == x */
959     /* Turn DivMod into a tuple (mem, bad, a, 0) */
960     ir_node *mem = get_Div_mem(n);
961     ir_mode *mode = get_irn_mode(b);
962
963     turn_into_tuple(n, 4);
964     set_Tuple_pred(n, pn_DivMod_M,        mem);
965     set_Tuple_pred(n, pn_DivMod_X_except, new_Bad());        /* no exception */
966     set_Tuple_pred(n, pn_DivMod_res_div,  a);
967     set_Tuple_pred(n, pn_DivMod_res_mod,  new_Const(mode, get_mode_null(mode)));
968   }
969   return n;
970 }
971
972 /**
973  * Use algebraic simplification a | a = a | 0 = 0 | a = a.
974  */
975 static ir_node *equivalent_node_Or(ir_node *n)
976 {
977   ir_node *oldn = n;
978
979   ir_node *a = get_Or_left(n);
980   ir_node *b = get_Or_right(n);
981
982   if (a == b) {
983     n = a;    /* Or has it's own neutral element */
984   } else if (classify_tarval(value_of(a)) == TV_CLASSIFY_NULL) {
985     n = b;
986     DBG_OPT_ALGSIM1(oldn, a, b, n);
987   } else if (classify_tarval(value_of(b)) == TV_CLASSIFY_NULL) {
988     n = a;
989     DBG_OPT_ALGSIM1(oldn, a, b, n);
990   }
991
992   return n;
993 }
994
995 /**
996  * Optimize a & 0b1...1 = 0b1...1 & a =  a & a = a.
997  */
998 static ir_node *equivalent_node_And(ir_node *n)
999 {
1000   ir_node *oldn = n;
1001
1002   ir_node *a = get_And_left(n);
1003   ir_node *b = get_And_right(n);
1004
1005   if (a == b) {
1006     n = a;    /* And has it's own neutral element */
1007   } else if (classify_tarval(value_of(a)) == TV_CLASSIFY_ALL_ONE) {
1008     n = b;
1009     DBG_OPT_ALGSIM1(oldn, a, b, n);
1010   } else if (classify_tarval(value_of(b)) == TV_CLASSIFY_ALL_ONE) {
1011     n = a;
1012     DBG_OPT_ALGSIM1(oldn, a, b, n);
1013   }
1014   return n;
1015 }
1016
1017 /**
1018  * Try to remove useless Conv's:
1019  */
1020 static ir_node *equivalent_node_Conv(ir_node *n)
1021 {
1022   ir_node *oldn = n;
1023   ir_node *a = get_Conv_op(n);
1024   ir_node *b;
1025
1026   ir_mode *n_mode = get_irn_mode(n);
1027   ir_mode *a_mode = get_irn_mode(a);
1028
1029   if (n_mode == a_mode) { /* No Conv necessary */
1030     n = a;
1031     DBG_OPT_ALGSIM3(oldn, a, n);
1032   } else if (get_irn_op(a) == op_Conv) { /* Conv(Conv(b)) */
1033     ir_mode *b_mode;
1034
1035     b = get_Conv_op(a);
1036     n_mode = get_irn_mode(n);
1037     b_mode = get_irn_mode(b);
1038
1039     if (n_mode == b_mode) {
1040       if (n_mode == mode_b) {
1041         n = b; /* Convb(Conv*(xxxb(...))) == xxxb(...) */
1042         DBG_OPT_ALGSIM1(oldn, a, b, n);
1043       }
1044       else if (mode_is_int(n_mode) || mode_is_character(n_mode)) {
1045         if (smaller_mode(b_mode, a_mode)){
1046           n = b;        /* ConvS(ConvL(xxxS(...))) == xxxS(...) */
1047           DBG_OPT_ALGSIM1(oldn, a, b, n);
1048         }
1049       }
1050     }
1051   }
1052   return n;
1053 }
1054
1055 /**
1056  * A Cast may be removed if the type of the previous node
1057  * is already the type of the Cast.
1058  */
1059 static ir_node *equivalent_node_Cast(ir_node *n) {
1060   ir_node *pred = get_Cast_op(n);
1061   if (get_irn_type(pred) == get_Cast_type(n))
1062     n = pred;
1063   return n;
1064 }
1065
1066 /* Several optimizations:
1067    - no Phi in start block.
1068    - remove Id operators that are inputs to Phi
1069    - fold Phi-nodes, iff they have only one predecessor except
1070            themselves.
1071 */
1072 static ir_node *equivalent_node_Phi(ir_node *n)
1073 {
1074   int i, n_preds;
1075
1076   ir_node *oldn = n;
1077   ir_node *block = NULL;     /* to shutup gcc */
1078   ir_node *first_val = NULL; /* to shutup gcc */
1079   ir_node *scnd_val = NULL;  /* to shutup gcc */
1080
1081   if (!get_opt_normalize()) return n;
1082
1083   n_preds = get_Phi_n_preds(n);
1084
1085   block = get_nodes_block(n);
1086   /* @@@ fliegt 'raus, sollte aber doch immer wahr sein!!!
1087      assert(get_irn_arity(block) == n_preds && "phi in wrong block!"); */
1088   if ((is_Block_dead(block)) ||                  /* Control dead */
1089       (block == current_ir_graph->start_block))  /* There should be no Phi nodes */
1090     return new_Bad();                            /* in the Start Block. */
1091
1092   if (n_preds == 0) return n;           /* Phi of dead Region without predecessors. */
1093
1094 #if 0
1095   /* first we test for a special case: */
1096   /* Confirm is a special node fixing additional information for a
1097      value that is known at a certain point.  This is useful for
1098      dataflow analysis. */
1099   if (n_preds == 2) {
1100     ir_node *a = get_Phi_pred(n, 0);
1101     ir_node *b = get_Phi_pred(n, 1);
1102     if (   (get_irn_op(a) == op_Confirm)
1103         && (get_irn_op(b) == op_Confirm)
1104         && (get_irn_n(a, 0) == get_irn_n(b, 0))
1105         && (get_irn_n(a, 1) == get_irn_n(b, 1))
1106         && (a->data.num == (~b->data.num & irpn_True) )) {
1107       return get_irn_n(a, 0);
1108     }
1109   }
1110 #endif
1111
1112   /* If the Block has a Bad pred, we also have one. */
1113   for (i = 0;  i < n_preds;  ++i)
1114     if (is_Bad (get_Block_cfgpred(block, i)))
1115       set_Phi_pred(n, i, new_Bad());
1116
1117   /* Find first non-self-referencing input */
1118   for (i = 0;  i < n_preds;  ++i) {
1119     first_val = get_Phi_pred(n, i);
1120     if (   (first_val != n)                            /* not self pointer */
1121 #if 1
1122         && (get_irn_op(first_val) != op_Bad)
1123 #endif
1124            ) {        /* value not dead */
1125       break;          /* then found first value. */
1126     }
1127   }
1128
1129   /* A totally Bad or self-referencing Phi (we didn't break the above loop) */
1130   if (i >= n_preds) { return new_Bad(); }
1131
1132   scnd_val = NULL;
1133
1134   /* follow_Id () for rest of inputs, determine if any of these
1135      are non-self-referencing */
1136   while (++i < n_preds) {
1137     scnd_val = get_Phi_pred(n, i);
1138     if (   (scnd_val != n)
1139         && (scnd_val != first_val)
1140 #if 1
1141         && (get_irn_op(scnd_val) != op_Bad)
1142 #endif
1143            ) {
1144       break;
1145     }
1146   }
1147
1148   /* Fold, if no multiple distinct non-self-referencing inputs */
1149   if (i >= n_preds) {
1150     n = first_val;
1151     DBG_OPT_PHI(oldn, first_val, n);
1152   } else {
1153     /* skip the remaining Ids (done in get_Phi_pred). */
1154     /* superfluous, since we walk all to propagate Block's Bads.
1155        while (++i < n_preds) get_Phi_pred(n, i);     */
1156   }
1157   return n;
1158 }
1159
1160 /**
1161  * optimize Proj(Tuple) and gigo for ProjX in Bad block
1162  */
1163 static ir_node *equivalent_node_Proj(ir_node *n)
1164 {
1165   ir_node *oldn = n;
1166
1167   ir_node *a = get_Proj_pred(n);
1168
1169   if ( get_irn_op(a) == op_Tuple) {
1170     /* Remove the Tuple/Proj combination. */
1171     if ( get_Proj_proj(n) <= get_Tuple_n_preds(a) ) {
1172       n = get_Tuple_pred(a, get_Proj_proj(n));
1173       DBG_OPT_TUPLE(oldn, a, n);
1174     } else {
1175       assert(0); /* This should not happen! */
1176       n = new_Bad();
1177     }
1178   } else if (get_irn_mode(n) == mode_X &&
1179              is_Block_dead(get_nodes_block(n))) {
1180     /* Remove dead control flow -- early gigo. */
1181     n = new_Bad();
1182   }
1183   return n;
1184 }
1185
1186 /**
1187  * Remove Id's.
1188  */
1189 static ir_node *equivalent_node_Id(ir_node *n)
1190 {
1191   ir_node *oldn = n;
1192
1193   do {
1194     n = get_Id_pred(n);
1195   } while (get_irn_op(n) == op_Id);
1196
1197   DBG_OPT_ID(oldn, n);
1198   return n;
1199 }
1200
1201 /**
1202  * optimize a Mux
1203  */
1204 static ir_node *equivalent_node_Mux(ir_node *n)
1205 {
1206   ir_node *oldn = n, *sel = get_Mux_sel(n);
1207   tarval *ts = value_of(sel);
1208
1209   /* Mux(true, f, t) == t */
1210   if (ts == get_tarval_b_true()) {
1211     n = get_Mux_true(n);
1212     DBG_OPT_ALGSIM0(oldn, n);
1213   }
1214   /* Mux(false, f, t) == f */
1215   else if (ts == get_tarval_b_false()) {
1216     n = get_Mux_false(n);
1217     DBG_OPT_ALGSIM0(oldn, n);
1218   }
1219   /* Mux(v, x, x) == x */
1220   else if (get_Mux_false(n) == get_Mux_true(n)) {
1221     n = get_Mux_true(n);
1222     DBG_OPT_ALGSIM0(oldn, n);
1223   }
1224   else if (get_irn_op(sel) == op_Proj && !mode_honor_signed_zeros(get_irn_mode(n))) {
1225     ir_node *cmp = get_Proj_pred(sel);
1226     long proj_nr = get_Proj_proj(sel);
1227     ir_node *b   = get_Mux_false(n);
1228     ir_node *a   = get_Mux_true(n);
1229
1230     /*
1231      * Note: normalization puts the constant on the right site,
1232      * so we check only one case.
1233      *
1234      * Note further that these optimization work even for floating point
1235      * with NaN's because -NaN == NaN.
1236      * However, if +0 and -0 is handled differently, we cannot use the first one.
1237      */
1238     if (get_irn_op(cmp) == op_Cmp && get_Cmp_left(cmp) == a) {
1239       if (classify_Const(get_Cmp_right(cmp)) == CNST_NULL) {
1240         /* Mux(a CMP 0, X, a) */
1241         if (get_irn_op(b) == op_Minus && get_Minus_op(b) == a) {
1242           /* Mux(a CMP 0, -a, a) */
1243           if (proj_nr == pn_Cmp_Eq) {
1244             /* Mux(a == 0, -a, a)  ==>  -a */
1245             n = b;
1246             DBG_OPT_ALGSIM0(oldn, n);
1247           }
1248           else if (proj_nr == pn_Cmp_Lg || proj_nr == pn_Cmp_Ne) {
1249             /* Mux(a != 0, -a, a)  ==> a */
1250             n = a;
1251             DBG_OPT_ALGSIM0(oldn, n);
1252           }
1253         }
1254         else if (classify_Const(b) == CNST_NULL) {
1255           /* Mux(a CMP 0, 0, a) */
1256           if (proj_nr == pn_Cmp_Lg || proj_nr == pn_Cmp_Ne) {
1257             /* Mux(a != 0, 0, a) ==> a */
1258             n = a;
1259             DBG_OPT_ALGSIM0(oldn, n);
1260           }
1261           else if (proj_nr == pn_Cmp_Eq) {
1262             /* Mux(a == 0, 0, a) ==> 0 */
1263             n = b;
1264             DBG_OPT_ALGSIM0(oldn, n);
1265           }
1266         }
1267       }
1268     }
1269   }
1270
1271   return n;
1272 }
1273
1274 /**
1275  * Optimize -a CMP -b into b CMP a.
1276  * This works only for for modes where unary Minus
1277  * cannot Overflow.
1278  * Note that two-complement integers can Overflow
1279  * so it will NOT work.
1280  */
1281 static ir_node *equivalent_node_Cmp(ir_node *n)
1282 {
1283   ir_node *left  = get_Cmp_left(n);
1284   ir_node *right = get_Cmp_right(n);
1285
1286   if (get_irn_op(left) == op_Minus && get_irn_op(right) == op_Minus &&
1287       !mode_overflow_on_unary_Minus(get_irn_mode(left))) {
1288     left  = get_Minus_op(left);
1289     right = get_Minus_op(right);
1290     set_Cmp_left(n, right);
1291     set_Cmp_right(n, left);
1292   }
1293   return n;
1294 }
1295
1296 /**
1297  * Remove Confirm nodes if setting is on.
1298  */
1299 static ir_node *equivalent_node_Confirm(ir_node *n)
1300 {
1301   if (get_Confirm_cmp(n) == pn_Cmp_Eq) {
1302     ir_node *bound = get_Confirm_bound(n);
1303     ir_op *op      = get_irn_op(bound);
1304
1305     /*
1306      * Optimize a rare case:
1307      * Confirm(x, '=', Const) ==> Const
1308      */
1309     if (op == op_Const || op == op_SymConst)
1310       return bound;
1311   }
1312   return get_opt_remove_Confirm() ? get_Confirm_value(n) : n;
1313 }
1314
1315 /**
1316  * equivalent_node() returns a node equivalent to input n. It skips all nodes that
1317  * perform no actual computation, as, e.g., the Id nodes.  It does not create
1318  * new nodes.  It is therefore safe to free n if the node returned is not n.
1319  * If a node returns a Tuple we can not just skip it.  If the size of the
1320  * in array fits, we transform n into a tuple (e.g., Div).
1321  */
1322 ir_node *
1323 equivalent_node(ir_node *n)
1324 {
1325   if (n->op->equivalent_node)
1326     return n->op->equivalent_node(n);
1327   return n;
1328 }
1329
1330 /**
1331  * set the default equivalent node operation
1332  */
1333 static ir_op *firm_set_default_equivalent_node(ir_op *op)
1334 {
1335 #define CASE(a)                                 \
1336   case iro_##a:                                 \
1337     op->equivalent_node  = equivalent_node_##a; \
1338     break
1339
1340   switch (op->code) {
1341   CASE(Block);
1342   CASE(Jmp);
1343   CASE(Cond);
1344   CASE(Or);
1345   CASE(Add);
1346   CASE(Eor);
1347   CASE(Sub);
1348   CASE(Shl);
1349   CASE(Shr);
1350   CASE(Shrs);
1351   CASE(Rot);
1352   CASE(Not);
1353   CASE(Minus);
1354   CASE(Mul);
1355   CASE(Div);
1356   CASE(DivMod);
1357   CASE(And);
1358   CASE(Conv);
1359   CASE(Cast);
1360   CASE(Phi);
1361   CASE(Proj);
1362   CASE(Id);
1363   CASE(Mux);
1364   CASE(Cmp);
1365   CASE(Confirm);
1366   default:
1367     op->equivalent_node  = NULL;
1368   }
1369
1370   return op;
1371 #undef CASE
1372 }
1373
1374 /**
1375  * Do node specific optimizations of nodes predecessors.
1376  */
1377 static void
1378 optimize_preds(ir_node *n) {
1379   ir_node *a = NULL, *b = NULL;
1380
1381   /* get the operands we will work on for simple cases. */
1382   if (is_binop(n)) {
1383     a = get_binop_left(n);
1384     b = get_binop_right(n);
1385   } else if (is_unop(n)) {
1386     a = get_unop_op(n);
1387   }
1388
1389   switch (get_irn_opcode(n)) {
1390
1391   case iro_Cmp:
1392     /* We don't want Cast as input to Cmp. */
1393     if (get_irn_op(a) == op_Cast) {
1394       a = get_Cast_op(a);
1395       set_Cmp_left(n, a);
1396     }
1397     if (get_irn_op(b) == op_Cast) {
1398       b = get_Cast_op(b);
1399       set_Cmp_right(n, b);
1400     }
1401     break;
1402
1403   default: break;
1404   } /* end switch */
1405 }
1406
1407 /**
1408  * Transform AddP(P, ConvIs(Iu)), AddP(P, ConvIu(Is)) and
1409  * SubP(P, ConvIs(Iu)), SubP(P, ConvIu(Is)).
1410  * If possible, remove the Conv's.
1411  */
1412 static ir_node *transform_node_AddSub(ir_node *n)
1413 {
1414   ir_mode *mode = get_irn_mode(n);
1415
1416   if (mode_is_reference(mode)) {
1417     ir_node *left  = get_binop_left(n);
1418     ir_node *right = get_binop_right(n);
1419     int ref_bits   = get_mode_size_bits(mode);
1420
1421     if (get_irn_op(left) == op_Conv) {
1422       ir_mode *mode = get_irn_mode(left);
1423       int bits      = get_mode_size_bits(mode);
1424
1425       if (ref_bits == bits &&
1426           mode_is_int(mode) &&
1427           get_mode_arithmetic(mode) == irma_twos_complement) {
1428         ir_node *pre      = get_Conv_op(left);
1429         ir_mode *pre_mode = get_irn_mode(pre);
1430
1431         if (mode_is_int(pre_mode) &&
1432             get_mode_size_bits(pre_mode) == bits &&
1433             get_mode_arithmetic(pre_mode) == irma_twos_complement) {
1434           /* ok, this conv just changes to sign, moreover the calculation
1435            * is done with same number of bits as our address mode, so
1436            * we can ignore the conv as address calculation can be viewed
1437            * as either signed or unsigned
1438            */
1439           set_binop_left(n, pre);
1440         }
1441       }
1442     }
1443
1444     if (get_irn_op(right) == op_Conv) {
1445       ir_mode *mode = get_irn_mode(right);
1446       int bits      = get_mode_size_bits(mode);
1447
1448       if (ref_bits == bits &&
1449           mode_is_int(mode) &&
1450           get_mode_arithmetic(mode) == irma_twos_complement) {
1451         ir_node *pre      = get_Conv_op(right);
1452         ir_mode *pre_mode = get_irn_mode(pre);
1453
1454         if (mode_is_int(pre_mode) &&
1455             get_mode_size_bits(pre_mode) == bits &&
1456             get_mode_arithmetic(pre_mode) == irma_twos_complement) {
1457           /* ok, this conv just changes to sign, moreover the calculation
1458            * is done with same number of bits as our address mode, so
1459            * we can ignore the conv as address calculation can be viewed
1460            * as either signed or unsigned
1461            */
1462           set_binop_right(n, pre);
1463         }
1464       }
1465     }
1466   }
1467   return n;
1468 }
1469
1470 /**
1471  * Do the AddSub optimization, then Transform Add(a,a) into Mul(a, 2)
1472  * if the mode is integer or float.
1473  * Transform Add(a,-b) into Sub(a,b).
1474  * Reassociation might fold this further.
1475  */
1476 static ir_node *transform_node_Add(ir_node *n)
1477 {
1478   ir_mode *mode;
1479   ir_node *oldn = n;
1480
1481   n = transform_node_AddSub(n);
1482
1483   mode = get_irn_mode(n);
1484   if (mode_is_num(mode)) {
1485     ir_node *a = get_Add_left(n);
1486
1487     if (a == get_Add_right(n)) {
1488       ir_node *block = get_nodes_block(n);
1489
1490       n = new_rd_Mul(
1491             get_irn_dbg_info(n),
1492             current_ir_graph,
1493             block,
1494             a,
1495             new_r_Const_long(current_ir_graph, block, mode, 2),
1496             mode);
1497       DBG_OPT_ALGSIM0(oldn, n);
1498     }
1499     else {
1500       ir_node *b = get_Add_right(n);
1501
1502       if (get_irn_op(a) == op_Minus) {
1503         n = new_rd_Sub(
1504             get_irn_dbg_info(n),
1505             current_ir_graph,
1506             get_nodes_block(n),
1507             b,
1508             get_Minus_op(a),
1509             mode);
1510         DBG_OPT_ALGSIM0(oldn, n);
1511       }
1512       else if (get_irn_op(b) == op_Minus) {
1513         n = new_rd_Sub(
1514             get_irn_dbg_info(n),
1515             current_ir_graph,
1516             get_nodes_block(n),
1517             a,
1518             get_Minus_op(b),
1519             mode);
1520         DBG_OPT_ALGSIM0(oldn, n);
1521       }
1522     }
1523   }
1524   return n;
1525 }
1526
1527 /**
1528  * Do the AddSub optimization, then Transform Sub(0,a) into Minus(a).
1529  */
1530 static ir_node *transform_node_Sub(ir_node *n)
1531 {
1532   ir_mode *mode;
1533   ir_node *oldn = n;
1534
1535   n = transform_node_AddSub(n);
1536
1537   mode = get_irn_mode(n);
1538   if (mode_is_num(mode) && (classify_Const(get_Sub_left(n)) == CNST_NULL)) {
1539     n = new_rd_Minus(
1540           get_irn_dbg_info(n),
1541           current_ir_graph,
1542           get_nodes_block(n),
1543           get_Sub_right(n),
1544           mode);
1545     DBG_OPT_ALGSIM0(oldn, n);
1546   }
1547
1548   return n;
1549 }
1550
1551 /**
1552   Transform Mul(a,-1) into -a.
1553  * Do architecture dependent optimizations on Mul nodes
1554  */
1555 static ir_node *transform_node_Mul(ir_node *n) {
1556   ir_node *oldn = n;
1557   ir_mode *mode = get_irn_mode(n);
1558
1559   if (mode_is_signed(mode)) {
1560     ir_node *r = NULL;
1561     ir_node *a = get_Mul_left(n);
1562     ir_node *b = get_Mul_right(n);
1563
1564     if (value_of(a) == get_mode_minus_one(mode))
1565       r = b;
1566     else if (value_of(b) == get_mode_minus_one(mode))
1567       r = a;
1568     if (r) {
1569       n = new_rd_Minus(get_irn_dbg_info(n), current_ir_graph, get_nodes_block(n), r, mode);
1570       DBG_OPT_ALGSIM1(oldn, a, b, n);
1571       return n;
1572     }
1573   }
1574   return arch_dep_replace_mul_with_shifts(n);
1575 }
1576
1577 /**
1578  * transform a Div Node
1579  */
1580 static ir_node *transform_node_Div(ir_node *n)
1581 {
1582   tarval *tv = value_of(n);
1583   ir_node *value = n;
1584
1585   /* BEWARE: it is NOT possible to optimize a/a to 1, as this may cause a exception */
1586
1587   if (tv != tarval_bad) {
1588     value = new_Const(get_tarval_mode(tv), tv);
1589
1590     DBG_OPT_CSTEVAL(n, value);
1591   }
1592   else /* Try architecture dependent optimization */
1593     value = arch_dep_replace_div_by_const(n);
1594
1595   if (value != n) {
1596     /* Turn Div into a tuple (mem, bad, value) */
1597     ir_node *mem = get_Div_mem(n);
1598
1599     turn_into_tuple(n, 3);
1600     set_Tuple_pred(n, pn_Div_M, mem);
1601     set_Tuple_pred(n, pn_Div_X_except, new_Bad());
1602     set_Tuple_pred(n, pn_Div_res, value);
1603   }
1604   return n;
1605 }
1606
1607 /**
1608  * transform a Mod node
1609  */
1610 static ir_node *transform_node_Mod(ir_node *n)
1611 {
1612   tarval *tv = value_of(n);
1613   ir_node *value = n;
1614
1615   /* BEWARE: it is NOT possible to optimize a%a to 0, as this may cause a exception */
1616
1617   if (tv != tarval_bad) {
1618     value = new_Const(get_tarval_mode(tv), tv);
1619
1620     DBG_OPT_CSTEVAL(n, value);
1621   }
1622   else /* Try architecture dependent optimization */
1623     value = arch_dep_replace_mod_by_const(n);
1624
1625   if (value != n) {
1626     /* Turn Mod into a tuple (mem, bad, value) */
1627     ir_node *mem = get_Mod_mem(n);
1628
1629     turn_into_tuple(n, 3);
1630     set_Tuple_pred(n, pn_Mod_M, mem);
1631     set_Tuple_pred(n, pn_Mod_X_except, new_Bad());
1632     set_Tuple_pred(n, pn_Mod_res, value);
1633   }
1634   return n;
1635 }
1636
1637 /**
1638  * transform a DivMod node
1639  */
1640 static ir_node *transform_node_DivMod(ir_node *n)
1641 {
1642   int evaluated = 0;
1643
1644   ir_node *a = get_DivMod_left(n);
1645   ir_node *b = get_DivMod_right(n);
1646   ir_mode *mode = get_irn_mode(a);
1647   tarval *ta = value_of(a);
1648   tarval *tb = value_of(b);
1649
1650   if (!(mode_is_int(mode) && mode_is_int(get_irn_mode(b))))
1651     return n;
1652
1653   /* BEWARE: it is NOT possible to optimize a/a to 1, as this may cause a exception */
1654
1655   if (tb != tarval_bad) {
1656     if (tb == get_mode_one(get_tarval_mode(tb))) {
1657       b = new_Const (mode, get_mode_null(mode));
1658       evaluated = 1;
1659
1660       DBG_OPT_CSTEVAL(n, b);
1661     }
1662     else if (ta != tarval_bad) {
1663       tarval *resa, *resb;
1664       resa = tarval_div (ta, tb);
1665       if (resa == tarval_bad) return n; /* Causes exception!!! Model by replacing through
1666                                         Jmp for X result!? */
1667       resb = tarval_mod (ta, tb);
1668       if (resb == tarval_bad) return n; /* Causes exception! */
1669       a = new_Const (mode, resa);
1670       b = new_Const (mode, resb);
1671       evaluated = 1;
1672
1673       DBG_OPT_CSTEVAL(n, a);
1674       DBG_OPT_CSTEVAL(n, b);
1675     }
1676     else { /* Try architecture dependent optimization */
1677       arch_dep_replace_divmod_by_const(&a, &b, n);
1678       evaluated = a != NULL;
1679     }
1680   } else if (ta == get_mode_null(mode)) {
1681     /* 0 / non-Const = 0 */
1682     b = a;
1683     evaluated = 1;
1684   }
1685
1686   if (evaluated) { /* replace by tuple */
1687     ir_node *mem = get_DivMod_mem(n);
1688     turn_into_tuple(n, 4);
1689     set_Tuple_pred(n, pn_DivMod_M,        mem);
1690     set_Tuple_pred(n, pn_DivMod_X_except, new_Bad());  /* no exception */
1691     set_Tuple_pred(n, pn_DivMod_res_div,  a);
1692     set_Tuple_pred(n, pn_DivMod_res_mod,  b);
1693     assert(get_nodes_block(n));
1694   }
1695
1696   return n;
1697 }
1698
1699 /**
1700  * Optimize Abs(x) into  x if x is Confirmed >= 0
1701  * Optimize Abs(x) into -x if x is Confirmed <= 0
1702  */
1703 static ir_node *transform_node_Abs(ir_node *n)
1704 {
1705   ir_node        *oldn = n;
1706   ir_node        *a = get_Abs_op(n);
1707   value_classify sign = classify_value_sign(a);
1708
1709   if (sign == VALUE_NEGATIVE) {
1710     ir_mode *mode = get_irn_mode(n);
1711
1712     /*
1713      * We can replace the Abs by -x here.
1714      * We even could add a new Confirm here.
1715      *
1716      * Note that -x would create a new node, so we could
1717      * not run it in the equivalent_node() context.
1718      */
1719     n = new_rd_Minus(get_irn_dbg_info(n), current_ir_graph,
1720                      get_nodes_block(n), a, mode);
1721
1722     DBG_OPT_CONFIRM(oldn, n);
1723   }
1724   else if (sign == VALUE_POSITIVE) {
1725     /* n is positive, Abs is not needed */
1726     n = a;
1727
1728     DBG_OPT_CONFIRM(oldn, n);
1729   }
1730
1731   return n;
1732 }
1733
1734 /**
1735  * transform a Cond node
1736  */
1737 static ir_node *transform_node_Cond(ir_node *n)
1738 {
1739   /* Replace the Cond by a Jmp if it branches on a constant
1740      condition. */
1741   ir_node *jmp;
1742   ir_node *a = get_Cond_selector(n);
1743   tarval *ta = value_of(a);
1744
1745   if ((ta != tarval_bad) &&
1746       (get_irn_mode(a) == mode_b) &&
1747       (get_opt_unreachable_code())) {
1748     /* It's a boolean Cond, branching on a boolean constant.
1749                Replace it by a tuple (Bad, Jmp) or (Jmp, Bad) */
1750     jmp = new_r_Jmp(current_ir_graph, get_nodes_block(n));
1751     turn_into_tuple(n, 2);
1752     if (ta == tarval_b_true) {
1753       set_Tuple_pred(n, pn_Cond_false, new_Bad());
1754       set_Tuple_pred(n, pn_Cond_true, jmp);
1755     } else {
1756       set_Tuple_pred(n, pn_Cond_false, jmp);
1757       set_Tuple_pred(n, pn_Cond_true, new_Bad());
1758     }
1759     /* We might generate an endless loop, so keep it alive. */
1760     add_End_keepalive(get_irg_end(current_ir_graph), get_nodes_block(n));
1761   } else if ((ta != tarval_bad) &&
1762              (get_irn_mode(a) == mode_Iu) &&
1763              (get_Cond_kind(n) == dense) &&
1764              (get_opt_unreachable_code())) {
1765     /* I don't want to allow Tuples smaller than the biggest Proj.
1766        Also this tuple might get really big...
1767        I generate the Jmp here, and remember it in link.  Link is used
1768        when optimizing Proj. */
1769     set_irn_link(n, new_r_Jmp(current_ir_graph, get_nodes_block(n)));
1770     /* We might generate an endless loop, so keep it alive. */
1771     add_End_keepalive(get_irg_end(current_ir_graph), get_nodes_block(n));
1772   } else if ((get_irn_op(a) == op_Eor)
1773              && (get_irn_mode(a) == mode_b)
1774              && (classify_tarval(value_of(get_Eor_right(a))) == TV_CLASSIFY_ONE)) {
1775     /* The Eor is a negate.  Generate a new Cond without the negate,
1776        simulate the negate by exchanging the results. */
1777     set_irn_link(n, new_r_Cond(current_ir_graph, get_nodes_block(n),
1778                                get_Eor_left(a)));
1779   } else if ((get_irn_op(a) == op_Not)
1780              && (get_irn_mode(a) == mode_b)) {
1781     /* A Not before the Cond.  Generate a new Cond without the Not,
1782        simulate the Not by exchanging the results. */
1783     set_irn_link(n, new_r_Cond(current_ir_graph, get_nodes_block(n),
1784                                get_Not_op(a)));
1785   }
1786   return n;
1787 }
1788
1789 /**
1790  * Transform an Eor.
1791  */
1792 static ir_node *transform_node_Eor(ir_node *n)
1793 {
1794   ir_node *oldn = n;
1795   ir_node *a = get_Eor_left(n);
1796   ir_node *b = get_Eor_right(n);
1797   ir_mode *mode = get_irn_mode(n);
1798
1799   if (a == b) {
1800     /* a ^ a = 0 */
1801     n = new_rd_Const(get_irn_dbg_info(n), current_ir_graph, get_nodes_block(n),
1802                      mode, get_mode_null(mode));
1803     DBG_OPT_ALGSIM0(oldn, n);
1804   }
1805   else if ((mode == mode_b)
1806       && (get_irn_op(a) == op_Proj)
1807       && (get_irn_mode(a) == mode_b)
1808       && (classify_tarval (value_of(b)) == TV_CLASSIFY_ONE)
1809       && (get_irn_op(get_Proj_pred(a)) == op_Cmp)) {
1810     /* The Eor negates a Cmp. The Cmp has the negated result anyways! */
1811     n = new_r_Proj(current_ir_graph, get_nodes_block(n), get_Proj_pred(a),
1812                    mode_b, get_negated_pnc(get_Proj_proj(a)));
1813
1814     DBG_OPT_ALGSIM0(oldn, n);
1815   }
1816   else if ((mode == mode_b)
1817         && (classify_tarval (value_of(b)) == TV_CLASSIFY_ONE)) {
1818     /* The Eor is a Not. Replace it by a Not. */
1819     /*   ????!!!Extend to bitfield 1111111. */
1820     n = new_r_Not(current_ir_graph, get_nodes_block(n), a, mode_b);
1821
1822     DBG_OPT_ALGSIM0(oldn, n);
1823   }
1824
1825   return n;
1826 }
1827
1828 /**
1829  * Transform a boolean Not.
1830  */
1831 static ir_node *transform_node_Not(ir_node *n)
1832 {
1833   ir_node *oldn = n;
1834   ir_node *a = get_Not_op(n);
1835
1836   if (   (get_irn_mode(n) == mode_b)
1837       && (get_irn_op(a) == op_Proj)
1838       && (get_irn_mode(a) == mode_b)
1839       && (get_irn_op(get_Proj_pred(a)) == op_Cmp)) {
1840     /* We negate a Cmp. The Cmp has the negated result anyways! */
1841     n = new_r_Proj(current_ir_graph, get_nodes_block(n), get_Proj_pred(a),
1842                    mode_b, get_negated_pnc(get_Proj_proj(a)));
1843     DBG_OPT_ALGSIM0(oldn, n);
1844   }
1845
1846   return n;
1847 }
1848
1849 /**
1850  * Transform a Cast_type(Const) into a new Const_type
1851  */
1852 static ir_node *transform_node_Cast(ir_node *n) {
1853   ir_node *oldn = n;
1854   ir_node *pred = get_Cast_op(n);
1855   type *tp = get_irn_type(n);
1856
1857   if (get_irn_op(pred) == op_Const && get_Const_type(pred) != tp) {
1858     n = new_rd_Const_type(NULL, current_ir_graph, get_nodes_block(pred), get_irn_mode(pred),
1859               get_Const_tarval(pred), tp);
1860     DBG_OPT_CSTEVAL(oldn, n);
1861   } else if ((get_irn_op(pred) == op_SymConst) && (get_SymConst_value_type(pred) != tp)) {
1862     n = new_rd_SymConst_type(NULL, current_ir_graph, get_nodes_block(pred), get_SymConst_symbol(pred),
1863                  get_SymConst_kind(pred), tp);
1864     DBG_OPT_CSTEVAL(oldn, n);
1865   }
1866
1867   return n;
1868 }
1869
1870 /**
1871  * Transform a Proj(Div) with a non-zero value.
1872  * Removes the exceptions and routes the memory to the NoMem node.
1873  */
1874 static ir_node *transform_node_Proj_Div(ir_node *proj)
1875 {
1876   ir_node *n = get_Proj_pred(proj);
1877   ir_node *b = get_Div_right(n);
1878   long proj_nr;
1879
1880   if (value_not_zero(b)) {
1881     /* div(x, y) && y != 0 */
1882     proj_nr = get_Proj_proj(proj);
1883
1884     /* this node may float */
1885     set_irn_pinned(n, op_pin_state_floats);
1886
1887     if (proj_nr == pn_Div_X_except) {
1888       /* we found an exception handler, remove it */
1889       return new_Bad();
1890     } else {
1891       /* the memory Proj can be removed */
1892       ir_node *res = get_Div_mem(n);
1893       set_Div_mem(n, get_irg_no_mem(current_ir_graph));
1894       if (proj_nr == pn_Div_M)
1895         return res;
1896     }
1897   }
1898   return proj;
1899 }
1900
1901 /**
1902  * Transform a Proj(Mod) with a non-zero value.
1903  * Removes the exceptions and routes the memory to the NoMem node.
1904  */
1905 static ir_node *transform_node_Proj_Mod(ir_node *proj)
1906 {
1907   ir_node *n = get_Proj_pred(proj);
1908   ir_node *b = get_Mod_right(n);
1909   long proj_nr;
1910
1911   if (value_not_zero(b)) {
1912     /* mod(x, y) && y != 0 */
1913     proj_nr = get_Proj_proj(proj);
1914
1915     /* this node may float */
1916     set_irn_pinned(n, op_pin_state_floats);
1917
1918     if (proj_nr == pn_Mod_X_except) {
1919       /* we found an exception handler, remove it */
1920       return new_Bad();
1921     } else {
1922       /* the memory Proj can be removed */
1923       ir_node *res = get_Mod_mem(n);
1924       set_Mod_mem(n, get_irg_no_mem(current_ir_graph));
1925       if (proj_nr == pn_Mod_M)
1926         return res;
1927     }
1928   }
1929   return proj;
1930 }
1931
1932 /**
1933  * Transform a Proj(DivMod) with a non-zero value.
1934  * Removes the exceptions and routes the memory to the NoMem node.
1935  */
1936 static ir_node *transform_node_Proj_DivMod(ir_node *proj)
1937 {
1938   ir_node *n = get_Proj_pred(proj);
1939   ir_node *b = get_DivMod_right(n);
1940   long proj_nr;
1941
1942   if (value_not_zero(b)) {
1943     /* DivMod(x, y) && y != 0 */
1944     proj_nr = get_Proj_proj(proj);
1945
1946     /* this node may float */
1947     set_irn_pinned(n, op_pin_state_floats);
1948
1949     if (proj_nr == pn_DivMod_X_except) {
1950       /* we found an exception handler, remove it */
1951       return new_Bad();
1952     }
1953     else {
1954       /* the memory Proj can be removed */
1955       ir_node *res = get_DivMod_mem(n);
1956       set_DivMod_mem(n, get_irg_no_mem(current_ir_graph));
1957       if (proj_nr == pn_DivMod_M)
1958         return res;
1959     }
1960   }
1961   return proj;
1962 }
1963
1964 /**
1965  * Optimizes jump tables (CondIs or CondIu) by removing all impossible cases.
1966  */
1967 static ir_node *transform_node_Proj_Cond(ir_node *proj)
1968 {
1969   if (get_opt_unreachable_code()) {
1970     ir_node *n = get_Proj_pred(proj);
1971     ir_node *b = get_Cond_selector(n);
1972     tarval *tb = value_of(b);
1973
1974     if (tb != tarval_bad && mode_is_int(get_tarval_mode(tb))) {
1975       /* we have a constant switch */
1976       long num = get_Proj_proj(proj);
1977
1978       if (num != get_Cond_defaultProj(n)) { /* we cannot optimize default Proj's yet */
1979         if (get_tarval_long(tb) == num) {
1980           /* Do NOT create a jump here, or we will have 2 control flow ops
1981            * in a block. This case is optimized away in optimize_cf(). */
1982           return proj;
1983         }
1984         else {
1985           /* this case will NEVER be taken, kill it */
1986           return new_Bad();
1987         }
1988       }
1989     }
1990   }
1991   return proj;
1992 }
1993
1994 /**
1995  * Normalizes and optimizes Cmp nodes.
1996  */
1997 static ir_node *transform_node_Proj_Cmp(ir_node *proj)
1998 {
1999   if (get_opt_reassociation()) {
2000     ir_node *n     = get_Proj_pred(proj);
2001     ir_node *left  = get_Cmp_left(n);
2002     ir_node *right = get_Cmp_right(n);
2003     ir_node *c     = NULL;
2004     tarval *tv     = NULL;
2005     int changed    = 0;
2006     ir_mode *mode  = NULL;
2007     long proj_nr   = get_Proj_proj(proj);
2008
2009     /*
2010      * First step: normalize the compare op
2011      * by placing the constant on the right site
2012      * or moving the lower address node to the left.
2013      * We ignore the case that both are constants
2014      * this case should be optimized away.
2015      */
2016     if (get_irn_op(right) == op_Const)
2017       c = right;
2018     else if (get_irn_op(left) == op_Const) {
2019       c     = left;
2020       left  = right;
2021       right = c;
2022
2023       proj_nr = get_inversed_pnc(proj_nr);
2024       changed |= 1;
2025     }
2026     else if (left > right) {
2027       ir_node *t = left;
2028
2029       left  = right;
2030       right = t;
2031
2032       proj_nr = get_inversed_pnc(proj_nr);
2033       changed |= 1;
2034     }
2035
2036     /*
2037      * Second step: Try to reduce the magnitude
2038      * of a constant. This may help to generate better code
2039      * later and may help to normalize more compares.
2040      * Of course this is only possible for integer values.
2041      */
2042     if (c) {
2043       mode = get_irn_mode(c);
2044       tv = get_Const_tarval(c);
2045
2046       if (tv != tarval_bad) {
2047         /* the following optimization is possible on modes without Overflow
2048          * on Unary Minus or on == and !=:
2049          * -a CMP c  ==>  a swap(CMP) -c
2050          *
2051          * Beware: for two-complement Overflow may occur, so only == and != can
2052          * be optimized, see this:
2053          * -MININT < 0 =/=> MININT > 0 !!!
2054          */
2055         if (get_opt_constant_folding() && get_irn_op(left) == op_Minus &&
2056             (!mode_overflow_on_unary_Minus(mode) ||
2057              (mode_is_int(mode) && (proj_nr == pn_Cmp_Eq || proj_nr == pn_Cmp_Lg)))) {
2058           left = get_Minus_op(left);
2059           tv = tarval_sub(get_mode_null(mode), tv);
2060
2061           proj_nr = get_inversed_pnc(proj_nr);
2062           changed |= 2;
2063         }
2064
2065         /* for integer modes, we have more */
2066         if (mode_is_int(mode)) {
2067           /* Ne includes Unordered which is not possible on integers.
2068            * However, frontends often use this wrong, so fix it here */
2069           if (proj_nr == pn_Cmp_Ne) {
2070             proj_nr = pn_Cmp_Lg;
2071             set_Proj_proj(proj, proj_nr);
2072           }
2073
2074           /* c > 0 : a < c  ==>  a <= (c-1)    a >= c  ==>  a > (c-1) */
2075           if ((proj_nr == pn_Cmp_Lt || proj_nr == pn_Cmp_Ge) &&
2076               tarval_cmp(tv, get_mode_null(mode)) == pn_Cmp_Gt) {
2077             tv = tarval_sub(tv, get_mode_one(mode));
2078
2079             proj_nr ^= pn_Cmp_Eq;
2080             changed |= 2;
2081           }
2082           /* c < 0 : a > c  ==>  a >= (c+1)    a <= c  ==>  a < (c+1) */
2083           else if ((proj_nr == pn_Cmp_Gt || proj_nr == pn_Cmp_Le) &&
2084               tarval_cmp(tv, get_mode_null(mode)) == pn_Cmp_Lt) {
2085             tv = tarval_add(tv, get_mode_one(mode));
2086
2087             proj_nr ^= pn_Cmp_Eq;
2088             changed |= 2;
2089           }
2090
2091           /* the following reassociations work only for == and != */
2092           if (proj_nr == pn_Cmp_Eq || proj_nr == pn_Cmp_Lg) {
2093
2094             /* a-b == 0  ==>  a == b,  a-b != 0  ==>  a != b */
2095             if (classify_tarval(tv) == TV_CLASSIFY_NULL && get_irn_op(left) == op_Sub) {
2096               right = get_Sub_right(left);
2097               left  = get_Sub_left(left);
2098
2099               tv = value_of(right);
2100               changed = 1;
2101             }
2102
2103             if (tv != tarval_bad) {
2104               ir_op *op = get_irn_op(left);
2105
2106               /* a-c1 == c2  ==>  a == c2+c1,  a-c1 != c2  ==>  a != c2+c1 */
2107               if (op == op_Sub) {
2108                 ir_node *c1 = get_Sub_right(left);
2109                 tarval *tv2 = value_of(c1);
2110
2111                 if (tv2 != tarval_bad) {
2112                   tv2 = tarval_add(tv, value_of(c1));
2113
2114                   if (tv2 != tarval_bad) {
2115                     left    = get_Sub_left(left);
2116                     tv      = tv2;
2117                     changed |= 2;
2118                   }
2119                 }
2120               }
2121               /* a+c1 == c2  ==>  a == c2-c1,  a+c1 != c2  ==>  a != c2-c1 */
2122               else if (op == op_Add) {
2123                 ir_node *a_l = get_Add_left(left);
2124                 ir_node *a_r = get_Add_right(left);
2125                 ir_node *a;
2126                 tarval *tv2;
2127
2128                 if (get_irn_op(a_l) == op_Const) {
2129                   a = a_r;
2130                   tv2 = value_of(a_l);
2131                 }
2132                 else {
2133                   a = a_l;
2134                   tv2 = value_of(a_r);
2135                 }
2136
2137                 if (tv2 != tarval_bad) {
2138                   tv2 = tarval_sub(tv, tv2);
2139
2140                   if (tv2 != tarval_bad) {
2141                     left    = a;
2142                     tv      = tv2;
2143                     changed |= 2;
2144                   }
2145                 }
2146               }
2147               /* -a == c ==> a == -c, -a != c ==> a != -c */
2148               else if (op == op_Minus) {
2149                 tarval *tv2 = tarval_sub(get_mode_null(mode), tv);
2150
2151                 if (tv2 != tarval_bad) {
2152                   left    = get_Minus_op(left);
2153                   tv      = tv2;
2154                   changed |= 2;
2155                 }
2156               }
2157             }
2158           } /* == or != */
2159           /* the following reassociations work only for <= */
2160           else if (proj_nr == pn_Cmp_Le || proj_nr == pn_Cmp_Lt) {
2161             if (tv != tarval_bad) {
2162               ir_op *op = get_irn_op(left);
2163
2164               /* c >= 0 : Abs(a) <= c  ==>  (unsigned)(a + c) <= 2*c */
2165               if (op == op_Abs) {
2166               }
2167             }
2168           }
2169         } /* mode_is_int */
2170       }
2171     }
2172
2173     if (changed) {
2174       ir_node *block = get_nodes_block(n);
2175
2176       if (changed & 2)      /* need a new Const */
2177         right = new_Const(mode, tv);
2178
2179       /* create a new compare */
2180       n = new_rd_Cmp(get_irn_dbg_info(n), current_ir_graph, block,
2181             left, right);
2182
2183       set_Proj_pred(proj, n);
2184       set_Proj_proj(proj, proj_nr);
2185     }
2186   }
2187   return proj;
2188 }
2189
2190 /**
2191  * Does all optimizations on nodes that must be done on it's Proj's
2192  * because of creating new nodes.
2193  */
2194 static ir_node *transform_node_Proj(ir_node *proj)
2195 {
2196   ir_node *n = get_Proj_pred(proj);
2197
2198   switch (get_irn_opcode(n)) {
2199   case iro_Div:
2200     return transform_node_Proj_Div(proj);
2201
2202   case iro_Mod:
2203     return transform_node_Proj_Mod(proj);
2204
2205   case iro_DivMod:
2206     return transform_node_Proj_DivMod(proj);
2207
2208   case iro_Cond:
2209     return transform_node_Proj_Cond(proj);
2210
2211   case iro_Cmp:
2212     return transform_node_Proj_Cmp(proj);
2213
2214   case iro_Tuple:
2215     /* should not happen, but if it does will be optimized away */
2216     return equivalent_node_Proj(proj);
2217
2218   default:
2219     /* do nothing */
2220     return proj;
2221   }
2222 }
2223
2224 /**
2225  * returns the operands of a commutative bin-op, if one operand is
2226  * a const, it is returned as the second one.
2227  */
2228 static void get_comm_Binop_Ops(ir_node *binop, ir_node **a, ir_node **c)
2229 {
2230   ir_node *op_a = get_binop_left(binop);
2231   ir_node *op_b = get_binop_right(binop);
2232
2233   assert(is_op_commutative(get_irn_op(binop)));
2234
2235   if (get_irn_op(op_a) == op_Const) {
2236     *a = op_b;
2237     *c = op_a;
2238   }
2239   else {
2240     *a = op_a;
2241     *c = op_b;
2242   }
2243 }
2244
2245 /**
2246  * Optimize a Or(And(Or(And(v,c4),c3),c2),c1) pattern if possible.
2247  * Such pattern may arise in bitfield stores.
2248  *
2249  * value  c4                  value      c4 & c2
2250  *    AND     c3                    AND           c1 | c3
2251  *        OR     c2      ===>               OR
2252  *           AND    c1
2253  *               OR
2254  */
2255 static ir_node *transform_node_Or_bf_store(ir_node *or)
2256 {
2257   ir_node *and, *c1;
2258   ir_node *or_l, *c2;
2259   ir_node *and_l, *c3;
2260   ir_node *value, *c4;
2261   ir_node *new_and, *new_const, *block;
2262   ir_mode *mode = get_irn_mode(or);
2263
2264   tarval *tv1, *tv2, *tv3, *tv4, *tv, *n_tv4, *n_tv2;
2265
2266   get_comm_Binop_Ops(or, &and, &c1);
2267   if ((get_irn_op(c1) != op_Const) || (get_irn_op(and) != op_And))
2268     return or;
2269
2270   get_comm_Binop_Ops(and, &or_l, &c2);
2271   if ((get_irn_op(c2) != op_Const) || (get_irn_op(or_l) != op_Or))
2272     return or;
2273
2274   get_comm_Binop_Ops(or_l, &and_l, &c3);
2275   if ((get_irn_op(c3) != op_Const) || (get_irn_op(and_l) != op_And))
2276     return or;
2277
2278   get_comm_Binop_Ops(and_l, &value, &c4);
2279   if (get_irn_op(c4) != op_Const)
2280     return or;
2281
2282   /* ok, found the pattern, check for conditions */
2283   assert(mode == get_irn_mode(and));
2284   assert(mode == get_irn_mode(or_l));
2285   assert(mode == get_irn_mode(and_l));
2286
2287   tv1 = get_Const_tarval(c1);
2288   tv2 = get_Const_tarval(c2);
2289   tv3 = get_Const_tarval(c3);
2290   tv4 = get_Const_tarval(c4);
2291
2292   tv = tarval_or(tv4, tv2);
2293   if (classify_tarval(tv) != TV_CLASSIFY_ALL_ONE) {
2294     /* have at least one 0 at the same bit position */
2295     return or;
2296   }
2297
2298   n_tv4 = tarval_not(tv4);
2299   if (tv3 != tarval_and(tv3, n_tv4)) {
2300     /* bit in the or_mask is outside the and_mask */
2301     return or;
2302   }
2303
2304   n_tv2 = tarval_not(tv2);
2305   if (tv1 != tarval_and(tv1, n_tv2)) {
2306     /* bit in the or_mask is outside the and_mask */
2307     return or;
2308   }
2309
2310   /* ok, all conditions met */
2311   block = get_nodes_block(or);
2312
2313   new_and = new_r_And(current_ir_graph, block,
2314       value, new_r_Const(current_ir_graph, block, mode, tarval_and(tv4, tv2)), mode);
2315
2316   new_const = new_r_Const(current_ir_graph, block, mode, tarval_or(tv3, tv1));
2317
2318   set_Or_left(or, new_and);
2319   set_Or_right(or, new_const);
2320
2321   /* check for more */
2322   return transform_node_Or_bf_store(or);
2323 }
2324
2325 /**
2326  * Optimize an Or(shl(x, c), shr(x, bits - c)) into a Rot
2327  */
2328 static ir_node *transform_node_Or_Rot(ir_node *or)
2329 {
2330   ir_mode *mode = get_irn_mode(or);
2331   ir_node *shl, *shr, *block;
2332   ir_node *irn, *x, *c1, *c2, *v, *sub, *n;
2333   tarval *tv1, *tv2;
2334
2335   if (! mode_is_int(mode))
2336     return or;
2337
2338   shl = get_binop_left(or);
2339   shr = get_binop_right(or);
2340
2341   if (get_irn_op(shl) == op_Shr) {
2342     if (get_irn_op(shr) != op_Shl)
2343       return or;
2344
2345     irn = shl;
2346     shl = shr;
2347     shr = irn;
2348   }
2349   else if (get_irn_op(shl) != op_Shl)
2350     return or;
2351   else if (get_irn_op(shr) != op_Shr)
2352     return or;
2353
2354   x = get_Shl_left(shl);
2355   if (x != get_Shr_left(shr))
2356     return or;
2357
2358   c1 = get_Shl_right(shl);
2359   c2 = get_Shr_right(shr);
2360   if (get_irn_op(c1) == op_Const && get_irn_op(c2) == op_Const) {
2361     tv1 = get_Const_tarval(c1);
2362     if (! tarval_is_long(tv1))
2363       return or;
2364
2365     tv2 = get_Const_tarval(c2);
2366     if (! tarval_is_long(tv2))
2367       return or;
2368
2369     if (get_tarval_long(tv1) + get_tarval_long(tv2)
2370         != get_mode_size_bits(mode))
2371       return or;
2372
2373     /* yet, condition met */
2374     block = get_nodes_block(or);
2375
2376     n = new_r_Rot(current_ir_graph, block, x, c1, mode);
2377
2378     DBG_OPT_ALGSIM1(or, shl, shr, n);
2379     return n;
2380   }
2381   else if (get_irn_op(c1) == op_Sub) {
2382     v   = c2;
2383     sub = c1;
2384
2385     if (get_Sub_right(sub) != v)
2386       return or;
2387
2388     c1 = get_Sub_left(sub);
2389     if (get_irn_op(c1) != op_Const)
2390       return or;
2391
2392     tv1 = get_Const_tarval(c1);
2393     if (! tarval_is_long(tv1))
2394       return or;
2395
2396     if (get_tarval_long(tv1) != get_mode_size_bits(mode))
2397       return or;
2398
2399     /* yet, condition met */
2400     block = get_nodes_block(or);
2401
2402     /* a Rot right is not supported, so use a rot left */
2403     n =  new_r_Rot(current_ir_graph, block, x, sub, mode);
2404
2405     DBG_OPT_ALGSIM0(or, n);
2406     return n;
2407   }
2408   else if (get_irn_op(c2) == op_Sub) {
2409     v   = c1;
2410     sub = c2;
2411
2412     c1 = get_Sub_left(sub);
2413     if (get_irn_op(c1) != op_Const)
2414       return or;
2415
2416     tv1 = get_Const_tarval(c1);
2417     if (! tarval_is_long(tv1))
2418       return or;
2419
2420     if (get_tarval_long(tv1) != get_mode_size_bits(mode))
2421       return or;
2422
2423     /* yet, condition met */
2424     block = get_nodes_block(or);
2425
2426     /* a Rot Left */
2427     n = new_r_Rot(current_ir_graph, block, x, v, mode);
2428
2429     DBG_OPT_ALGSIM0(or, n);
2430     return n;
2431   }
2432
2433   return or;
2434 }
2435
2436 /**
2437  * Optimize an Or
2438  */
2439 static ir_node *transform_node_Or(ir_node *or)
2440 {
2441   or = transform_node_Or_bf_store(or);
2442   or = transform_node_Or_Rot(or);
2443
2444   return or;
2445 }
2446
2447 /* forward */
2448 static ir_node *transform_node(ir_node *n);
2449
2450 /**
2451  * Optimize (a >> c1) >> c2), works for Shr, Shrs, Shl
2452  */
2453 static ir_node *transform_node_shift(ir_node *n)
2454 {
2455   ir_node *left, *right;
2456   tarval *tv1, *tv2, *res;
2457   ir_mode *mode;
2458   int modulo_shf, flag;
2459
2460   left = get_binop_left(n);
2461
2462   /* different operations */
2463   if (get_irn_op(left) != get_irn_op(n))
2464     return n;
2465
2466   right = get_binop_right(n);
2467   tv1 = value_of(right);
2468   if (tv1 == tarval_bad)
2469     return n;
2470
2471   tv2 = value_of(get_binop_right(left));
2472   if (tv2 == tarval_bad)
2473     return n;
2474
2475   res = tarval_add(tv1, tv2);
2476
2477   /* beware: a simple replacement works only, if res < modulo shift */
2478   mode = get_irn_mode(n);
2479
2480   flag = 0;
2481
2482   modulo_shf = get_mode_modulo_shift(mode);
2483   if (modulo_shf > 0) {
2484     tarval *modulo = new_tarval_from_long(modulo_shf, get_tarval_mode(res));
2485
2486     if (tarval_cmp(res, modulo) & pn_Cmp_Lt)
2487       flag = 1;
2488   }
2489   else
2490     flag = 1;
2491
2492   if (flag) {
2493     /* ok, we can replace it */
2494     ir_node *in[2], *irn, *block = get_nodes_block(n);
2495
2496     in[0] = get_binop_left(left);
2497     in[1] = new_r_Const(current_ir_graph, block, get_tarval_mode(res), res);
2498
2499     irn = new_ir_node(NULL, current_ir_graph, block, get_irn_op(n), mode, 2, in);
2500
2501     DBG_OPT_ALGSIM0(n, irn);
2502
2503     return transform_node(irn);
2504   }
2505   return n;
2506 }
2507
2508 #define transform_node_Shr  transform_node_shift
2509 #define transform_node_Shrs transform_node_shift
2510 #define transform_node_Shl  transform_node_shift
2511
2512 /**
2513  * Remove dead blocks in keep alive list.  We do not generate a new End node.
2514  */
2515 static ir_node *transform_node_End(ir_node *n) {
2516   int i, n_keepalives = get_End_n_keepalives(n);
2517
2518   for (i = 0; i < n_keepalives; ++i) {
2519     ir_node *ka = get_End_keepalive(n, i);
2520     if (is_Block(ka) && is_Block_dead(ka))
2521       set_End_keepalive(n, i, new_Bad());
2522   }
2523   return n;
2524 }
2525
2526 /**
2527  * Optimize a Mux into some simpler cases.
2528  */
2529 static ir_node *transform_node_Mux(ir_node *n)
2530 {
2531   ir_node *oldn = n, *sel = get_Mux_sel(n);
2532   ir_mode *mode = get_irn_mode(n);
2533
2534   if (get_irn_op(sel) == op_Proj && !mode_honor_signed_zeros(mode)) {
2535     ir_node *cmp = get_Proj_pred(sel);
2536     long proj_nr = get_Proj_proj(sel);
2537     ir_node *f   =  get_Mux_false(n);
2538     ir_node *t   = get_Mux_true(n);
2539
2540     if (get_irn_op(cmp) == op_Cmp && classify_Const(get_Cmp_right(cmp)) == CNST_NULL) {
2541       ir_node *block = get_nodes_block(n);
2542
2543       /*
2544        * Note: normalization puts the constant on the right site,
2545        * so we check only one case.
2546        *
2547        * Note further that these optimization work even for floating point
2548        * with NaN's because -NaN == NaN.
2549        * However, if +0 and -0 is handled differently, we cannot use the first one.
2550        */
2551       if (get_irn_op(f) == op_Minus &&
2552           get_Minus_op(f)   == t &&
2553           get_Cmp_left(cmp) == t) {
2554
2555         if (proj_nr == pn_Cmp_Ge || proj_nr == pn_Cmp_Gt) {
2556           /* Mux(a >=/> 0, -a, a)  ==>  Abs(a) */
2557           n = new_rd_Abs(get_irn_dbg_info(n),
2558                 current_ir_graph,
2559                 block,
2560                 t, mode);
2561           DBG_OPT_ALGSIM1(oldn, cmp, sel, n);
2562           return n;
2563         }
2564         else if (proj_nr == pn_Cmp_Le || proj_nr == pn_Cmp_Lt) {
2565           /* Mux(a <=/< 0, -a, a)  ==>  Minus(Abs(a)) */
2566           n = new_rd_Abs(get_irn_dbg_info(n),
2567                 current_ir_graph,
2568                 block,
2569                 t, mode);
2570           n = new_rd_Minus(get_irn_dbg_info(n),
2571                 current_ir_graph,
2572                 block,
2573                 n, mode);
2574
2575           DBG_OPT_ALGSIM1(oldn, cmp, sel, n);
2576           return n;
2577         }
2578       }
2579       else if (get_irn_op(t) == op_Minus &&
2580           get_Minus_op(t)   == f &&
2581           get_Cmp_left(cmp) == f) {
2582
2583         if (proj_nr == pn_Cmp_Le || proj_nr == pn_Cmp_Lt) {
2584           /* Mux(a <=/< 0, a, -a)  ==>  Abs(a) */
2585           n = new_rd_Abs(get_irn_dbg_info(n),
2586                 current_ir_graph,
2587                 block,
2588                 f, mode);
2589           DBG_OPT_ALGSIM1(oldn, cmp, sel, n);
2590           return n;
2591         }
2592         else if (proj_nr == pn_Cmp_Ge || proj_nr == pn_Cmp_Gt) {
2593           /* Mux(a >=/> 0, a, -a)  ==>  Minus(Abs(a)) */
2594           n = new_rd_Abs(get_irn_dbg_info(n),
2595                 current_ir_graph,
2596                 block,
2597                 f, mode);
2598           n = new_rd_Minus(get_irn_dbg_info(n),
2599                 current_ir_graph,
2600                 block,
2601                 n, mode);
2602
2603           DBG_OPT_ALGSIM1(oldn, cmp, sel, n);
2604           return n;
2605         }
2606       }
2607
2608       if (mode_is_int(mode) && mode_is_signed(mode) &&
2609           get_mode_arithmetic(mode) == irma_twos_complement) {
2610         ir_node *x = get_Cmp_left(cmp);
2611
2612         /* the following optimization works only with signed integer two-complement mode */
2613
2614         if (mode == get_irn_mode(x)) {
2615           /*
2616            * FIXME: this restriction is two rigid, as it would still
2617            * work if mode(x) = Hs and mode == Is, but at least it removes
2618            * all wrong cases.
2619            */
2620           if ((proj_nr == pn_Cmp_Lt || proj_nr == pn_Cmp_Le) &&
2621               classify_Const(t) == CNST_ALL_ONE &&
2622               classify_Const(f) == CNST_NULL) {
2623             /*
2624              * Mux(x:T </<= 0, 0, -1) -> Shrs(x, sizeof_bits(T) - 1)
2625              * Conditions:
2626              * T must be signed.
2627              */
2628             n = new_rd_Shrs(get_irn_dbg_info(n),
2629                   current_ir_graph, block, x,
2630                   new_r_Const_long(current_ir_graph, block, mode_Iu,
2631                     get_mode_size_bits(mode) - 1),
2632                   mode);
2633             DBG_OPT_ALGSIM1(oldn, cmp, sel, n);
2634             return n;
2635           }
2636           else if ((proj_nr == pn_Cmp_Gt || proj_nr == pn_Cmp_Ge) &&
2637                    classify_Const(t) == CNST_ONE &&
2638                    classify_Const(f) == CNST_NULL) {
2639             /*
2640              * Mux(x:T >/>= 0, 0, 1) -> Shr(-x, sizeof_bits(T) - 1)
2641              * Conditions:
2642              * T must be signed.
2643              */
2644             n = new_rd_Shr(get_irn_dbg_info(n),
2645                   current_ir_graph, block,
2646                   new_r_Minus(current_ir_graph, block, x, mode),
2647                   new_r_Const_long(current_ir_graph, block, mode_Iu,
2648                     get_mode_size_bits(mode) - 1),
2649                   mode);
2650             DBG_OPT_ALGSIM1(oldn, cmp, sel, n);
2651             return n;
2652           }
2653         }
2654       }
2655     }
2656   }
2657   return arch_transform_node_Mux(n);
2658 }
2659
2660 /**
2661  * Tries several [inplace] [optimizing] transformations and returns an
2662  * equivalent node.  The difference to equivalent_node() is that these
2663  * transformations _do_ generate new nodes, and thus the old node must
2664  * not be freed even if the equivalent node isn't the old one.
2665  */
2666 static ir_node *transform_node(ir_node *n)
2667 {
2668   if (n->op->transform_node)
2669     n = n->op->transform_node(n);
2670   return n;
2671 }
2672
2673 /**
2674  * set the default transform node operation
2675  */
2676 static ir_op *firm_set_default_transform_node(ir_op *op)
2677 {
2678 #define CASE(a)                                 \
2679   case iro_##a:                                 \
2680     op->transform_node  = transform_node_##a;   \
2681     break
2682
2683   switch (op->code) {
2684   CASE(Add);
2685   CASE(Sub);
2686   CASE(Mul);
2687   CASE(Div);
2688   CASE(Mod);
2689   CASE(DivMod);
2690   CASE(Abs);
2691   CASE(Cond);
2692   CASE(Eor);
2693   CASE(Not);
2694   CASE(Cast);
2695   CASE(Proj);
2696   CASE(Sel);
2697   CASE(Or);
2698   CASE(Shr);
2699   CASE(Shrs);
2700   CASE(Shl);
2701   CASE(End);
2702   CASE(Mux);
2703   default:
2704     op->transform_node = NULL;
2705   }
2706
2707   return op;
2708 #undef CASE
2709 }
2710
2711
2712 /* **************** Common Subexpression Elimination **************** */
2713
2714 /** The size of the hash table used, should estimate the number of nodes
2715     in a graph. */
2716 #define N_IR_NODES 512
2717
2718 /** Compares the attributes of two Const nodes. */
2719 static int node_cmp_attr_Const(ir_node *a, ir_node *b)
2720 {
2721   return (get_Const_tarval(a) != get_Const_tarval(b))
2722       || (get_Const_type(a) != get_Const_type(b));
2723 }
2724
2725 /** Compares the attributes of two Proj nodes. */
2726 static int node_cmp_attr_Proj(ir_node *a, ir_node *b)
2727 {
2728   return get_irn_proj_attr (a) != get_irn_proj_attr (b);
2729 }
2730
2731 /** Compares the attributes of two Filter nodes. */
2732 static int node_cmp_attr_Filter(ir_node *a, ir_node *b)
2733 {
2734   return get_Filter_proj(a) != get_Filter_proj(b);
2735 }
2736
2737 /** Compares the attributes of two Alloc nodes. */
2738 static int node_cmp_attr_Alloc(ir_node *a, ir_node *b)
2739 {
2740   return (get_irn_alloc_attr(a).where != get_irn_alloc_attr(b).where)
2741       || (get_irn_alloc_attr(a).type != get_irn_alloc_attr(b).type);
2742 }
2743
2744 /** Compares the attributes of two Free nodes. */
2745 static int node_cmp_attr_Free(ir_node *a, ir_node *b)
2746 {
2747   return (get_irn_free_attr(a).where != get_irn_free_attr(b).where)
2748       || (get_irn_free_attr(a).type != get_irn_free_attr(b).type);
2749 }
2750
2751 /** Compares the attributes of two SymConst nodes. */
2752 static int node_cmp_attr_SymConst(ir_node *a, ir_node *b)
2753 {
2754   return (get_irn_symconst_attr(a).num != get_irn_symconst_attr(b).num)
2755       || (get_irn_symconst_attr(a).sym.type_p != get_irn_symconst_attr(b).sym.type_p)
2756       || (get_irn_symconst_attr(a).tp != get_irn_symconst_attr(b).tp);
2757 }
2758
2759 /** Compares the attributes of two Call nodes. */
2760 static int node_cmp_attr_Call(ir_node *a, ir_node *b)
2761 {
2762   return (get_irn_call_attr(a) != get_irn_call_attr(b));
2763 }
2764
2765 /** Compares the attributes of two Sel nodes. */
2766 static int node_cmp_attr_Sel(ir_node *a, ir_node *b)
2767 {
2768   return (get_irn_sel_attr(a).ent->kind  != get_irn_sel_attr(b).ent->kind)
2769       || (get_irn_sel_attr(a).ent->name    != get_irn_sel_attr(b).ent->name)
2770       || (get_irn_sel_attr(a).ent->owner   != get_irn_sel_attr(b).ent->owner)
2771       || (get_irn_sel_attr(a).ent->ld_name != get_irn_sel_attr(b).ent->ld_name)
2772       || (get_irn_sel_attr(a).ent->type    != get_irn_sel_attr(b).ent->type);
2773 }
2774
2775 /** Compares the attributes of two Phi nodes. */
2776 static int node_cmp_attr_Phi(ir_node *a, ir_node *b)
2777 {
2778   return get_irn_phi_attr (a) != get_irn_phi_attr (b);
2779 }
2780
2781 /** Compares the attributes of two Cast nodes. */
2782 static int node_cmp_attr_Cast(ir_node *a, ir_node *b)
2783 {
2784   return get_Cast_type(a) != get_Cast_type(b);
2785 }
2786
2787 /** Compares the attributes of two Load nodes. */
2788 static int node_cmp_attr_Load(ir_node *a, ir_node *b)
2789 {
2790   if (get_Load_volatility(a) == volatility_is_volatile ||
2791       get_Load_volatility(b) == volatility_is_volatile)
2792     /* NEVER do CSE on volatile Loads */
2793     return 1;
2794
2795   return get_Load_mode(a) != get_Load_mode(b);
2796 }
2797
2798 /** Compares the attributes of two Store nodes. */
2799 static int node_cmp_attr_Store(ir_node *a, ir_node *b)
2800 {
2801   /* NEVER do CSE on volatile Stores */
2802   return (get_Store_volatility(a) == volatility_is_volatile ||
2803           get_Store_volatility(b) == volatility_is_volatile);
2804 }
2805
2806 /** Compares the attributes of two Confirm nodes. */
2807 static int node_cmp_attr_Confirm(ir_node *a, ir_node *b)
2808 {
2809   return (get_Confirm_cmp(a) != get_Confirm_cmp(b));
2810 }
2811
2812 /**
2813  * set the default node attribute compare operation
2814  */
2815 static ir_op *firm_set_default_node_cmp_attr(ir_op *op)
2816 {
2817 #define CASE(a)                             \
2818   case iro_##a:                             \
2819     op->node_cmp_attr  = node_cmp_attr_##a; \
2820     break
2821
2822   switch (op->code) {
2823   CASE(Const);
2824   CASE(Proj);
2825   CASE(Filter);
2826   CASE(Alloc);
2827   CASE(Free);
2828   CASE(SymConst);
2829   CASE(Call);
2830   CASE(Sel);
2831   CASE(Phi);
2832   CASE(Cast);
2833   CASE(Load);
2834   CASE(Store);
2835   CASE(Confirm);
2836   default:
2837     op->node_cmp_attr  = NULL;
2838   }
2839
2840   return op;
2841 #undef CASE
2842 }
2843
2844 /**
2845  * Compare function for two nodes in the hash table. Gets two
2846  * nodes as parameters.  Returns 0 if the nodes are a cse.
2847  */
2848 static int
2849 vt_cmp (const void *elt, const void *key)
2850 {
2851   ir_node *a, *b;
2852   int i, irn_arity_a;
2853
2854   a = (void *)elt;
2855   b = (void *)key;
2856
2857   if (a == b) return 0;
2858
2859   if ((get_irn_op(a) != get_irn_op(b)) ||
2860       (get_irn_mode(a) != get_irn_mode(b))) return 1;
2861
2862   /* compare if a's in and b's in are of equal length */
2863   irn_arity_a = get_irn_intra_arity (a);
2864   if (irn_arity_a != get_irn_intra_arity(b))
2865     return 1;
2866
2867   /* for block-local cse and op_pin_state_pinned nodes: */
2868   if (!get_opt_global_cse() || (get_irn_pinned(a) == op_pin_state_pinned)) {
2869     if (get_irn_intra_n(a, -1) != get_irn_intra_n(b, -1))
2870       return 1;
2871   }
2872
2873   /* compare a->in[0..ins] with b->in[0..ins] */
2874   for (i = 0; i < irn_arity_a; i++)
2875     if (get_irn_intra_n(a, i) != get_irn_intra_n(b, i))
2876       return 1;
2877
2878   /*
2879    * here, we already now that the nodes are identical except their
2880    * attributes
2881    */
2882   if (a->op->node_cmp_attr)
2883     return a->op->node_cmp_attr(a, b);
2884
2885   return 0;
2886 }
2887
2888 /*
2889  * Calculate a hash value of a node.
2890  */
2891 unsigned
2892 ir_node_hash (ir_node *node)
2893 {
2894   unsigned h;
2895   int i, irn_arity;
2896
2897   if (node->op == op_Const) {
2898     /* special value for const, as they only differ in their tarval. */
2899     h = HASH_PTR(node->attr.con.tv);
2900     h = 9*h + HASH_PTR(get_irn_mode(node));
2901   } else if (node->op == op_SymConst) {
2902     /* special value for const, as they only differ in their symbol. */
2903     h = HASH_PTR(node->attr.i.sym.type_p);
2904     h = 9*h + HASH_PTR(get_irn_mode(node));
2905   } else {
2906
2907     /* hash table value = 9*(9*(9*(9*(9*arity+in[0])+in[1])+ ...)+mode)+code */
2908     h = irn_arity = get_irn_intra_arity(node);
2909
2910     /* consider all in nodes... except the block if not a control flow. */
2911     for (i =  is_cfop(node) ? -1 : 0;  i < irn_arity;  i++) {
2912       h = 9*h + HASH_PTR(get_irn_intra_n(node, i));
2913     }
2914
2915     /* ...mode,... */
2916     h = 9*h + HASH_PTR(get_irn_mode(node));
2917     /* ...and code */
2918     h = 9*h + HASH_PTR(get_irn_op(node));
2919   }
2920
2921   return h;
2922 }
2923
2924 pset *
2925 new_identities(void) {
2926   return new_pset(vt_cmp, N_IR_NODES);
2927 }
2928
2929 void
2930 del_identities(pset *value_table) {
2931   del_pset(value_table);
2932 }
2933
2934 /**
2935  * Return the canonical node computing the same value as n.
2936  * Looks up the node in a hash table.
2937  *
2938  * For Const nodes this is performed in the constructor, too.  Const
2939  * nodes are extremely time critical because of their frequent use in
2940  * constant string arrays.
2941  */
2942 static INLINE ir_node *
2943 identify (pset *value_table, ir_node *n)
2944 {
2945   ir_node *o = NULL;
2946
2947   if (!value_table) return n;
2948
2949   if (get_opt_reassociation()) {
2950     if (is_op_commutative(get_irn_op(n))) {
2951       ir_node *l = get_binop_left(n);
2952       ir_node *r = get_binop_right(n);
2953
2954       /* for commutative operators perform  a OP b == b OP a */
2955       if (l > r) {
2956         set_binop_left(n, r);
2957         set_binop_right(n, l);
2958       }
2959     }
2960   }
2961
2962   o = pset_find (value_table, n, ir_node_hash (n));
2963   if (!o) return n;
2964
2965   DBG_OPT_CSE(n, o);
2966
2967   return o;
2968 }
2969
2970 /**
2971  * During construction we set the op_pin_state_pinned flag in the graph right when the
2972  * optimization is performed.  The flag turning on procedure global cse could
2973  * be changed between two allocations.  This way we are safe.
2974  */
2975 static INLINE ir_node *
2976 identify_cons (pset *value_table, ir_node *n) {
2977   ir_node *old = n;
2978
2979   n = identify(value_table, n);
2980   if (get_irn_n(old, -1) != get_irn_n(n, -1))
2981     set_irg_pinned(current_ir_graph, op_pin_state_floats);
2982   return n;
2983 }
2984
2985 /**
2986  * Return the canonical node computing the same value as n.
2987  * Looks up the node in a hash table, enters it in the table
2988  * if it isn't there yet.
2989  */
2990 static ir_node *
2991 identify_remember (pset *value_table, ir_node *n)
2992 {
2993   ir_node *o = NULL;
2994
2995   if (!value_table) return n;
2996
2997   if (get_opt_reassociation()) {
2998     if (is_op_commutative(get_irn_op(n))) {
2999       ir_node *l = get_binop_left(n);
3000       ir_node *r = get_binop_right(n);
3001
3002       /* for commutative operators perform  a OP b == b OP a */
3003       if (l > r) {
3004         set_binop_left(n, r);
3005         set_binop_right(n, l);
3006       }
3007     }
3008   }
3009
3010   /* lookup or insert in hash table with given hash key. */
3011   o = pset_insert (value_table, n, ir_node_hash (n));
3012
3013   if (o != n) {
3014     DBG_OPT_CSE(n, o);
3015   }
3016
3017   return o;
3018 }
3019
3020 void
3021 add_identities (pset *value_table, ir_node *node) {
3022   if (get_opt_cse() && (get_irn_opcode(node) != iro_Block))
3023     identify_remember (value_table, node);
3024 }
3025
3026 /**
3027  * garbage in, garbage out. If a node has a dead input, i.e., the
3028  * Bad node is input to the node, return the Bad node.
3029  */
3030 static INLINE ir_node *
3031 gigo (ir_node *node)
3032 {
3033   int i, irn_arity;
3034   ir_op* op = get_irn_op(node);
3035
3036   /* remove garbage blocks by looking at control flow that leaves the block
3037      and replacing the control flow by Bad. */
3038   if (get_irn_mode(node) == mode_X) {
3039     ir_node *block = get_nodes_block(node);
3040     if (!get_Block_matured(block)) return node;  /* Don't optimize nodes in immature blocks. */
3041     if (op == op_End) return node;     /* Don't optimize End, may have Bads. */
3042
3043     if (get_irn_op(block) == op_Block && get_Block_matured(block)) {
3044       irn_arity = get_irn_arity(block);
3045       for (i = 0; i < irn_arity; i++) {
3046         if (!is_Bad(get_irn_n(block, i))) break;
3047       }
3048       if (i == irn_arity) return new_Bad();
3049     }
3050   }
3051
3052   /* Blocks, Phis and Tuples may have dead inputs, e.g., if one of the
3053      blocks predecessors is dead. */
3054   if ( op != op_Block && op != op_Phi && op != op_Tuple) {
3055     irn_arity = get_irn_arity(node);
3056
3057     if (is_Block_dead(get_nodes_block(node)))
3058       return new_Bad();
3059
3060     for (i = 0; i < irn_arity; i++) {
3061       if (is_Bad(get_irn_n(node, i))) {
3062         return new_Bad();
3063       }
3064     }
3065   }
3066 #if 0
3067   /* With this code we violate the agreement that local_optimize
3068      only leaves Bads in Block, Phi and Tuple nodes. */
3069   /* If Block has only Bads as predecessors it's garbage. */
3070   /* If Phi has only Bads as predecessors it's garbage. */
3071   if ((op == op_Block && get_Block_matured(node)) || op == op_Phi)  {
3072     irn_arity = get_irn_arity(node);
3073     for (i = 0; i < irn_arity; i++) {
3074       if (!is_Bad(get_irn_n(node, i))) break;
3075     }
3076     if (i == irn_arity) node = new_Bad();
3077   }
3078 #endif
3079   return node;
3080 }
3081
3082
3083 /**
3084  * These optimizations deallocate nodes from the obstack.
3085  * It can only be called if it is guaranteed that no other nodes
3086  * reference this one, i.e., right after construction of a node.
3087  */
3088 ir_node *
3089 optimize_node(ir_node *n)
3090 {
3091   tarval *tv;
3092   ir_node *oldn = n;
3093   opcode iro = get_irn_opcode(n);
3094
3095   /* Always optimize Phi nodes: part of the construction. */
3096   if ((!get_opt_optimize()) && (iro != iro_Phi)) return n;
3097
3098   /* constant expression evaluation / constant folding */
3099   if (get_opt_constant_folding()) {
3100     /* neither constants nor Tuple values can be evaluated */
3101     if (iro != iro_Const && (get_irn_mode(n) != mode_T)) {
3102       /* try to evaluate */
3103       tv = computed_value(n);
3104       if (tv != tarval_bad) {
3105         ir_node *nw;
3106         type *old_tp = get_irn_type(n);
3107         int i, arity = get_irn_arity(n);
3108         int node_size;
3109
3110         /*
3111          * Try to recover the type of the new expression.
3112          */
3113         for (i = 0; i < arity && !old_tp; ++i)
3114           old_tp = get_irn_type(get_irn_n(n, i));
3115
3116         /*
3117          * we MUST copy the node here temporary, because it's still needed
3118          * for DBG_OPT_CSTEVAL
3119          */
3120         node_size = offsetof(ir_node, attr) +  n->op->attr_size;
3121         oldn = alloca(node_size);
3122
3123         memcpy(oldn, n, node_size);
3124         CLONE_ARR_A(ir_node *, oldn->in, n->in);
3125
3126         /* ARG, copy the in array, we need it for statistics */
3127         memcpy(oldn->in, n->in, ARR_LEN(n->in) * sizeof(n->in[0]));
3128
3129         /* note the inplace edges module */
3130         edges_node_deleted(n, current_ir_graph);
3131
3132         /* evaluation was successful -- replace the node. */
3133         obstack_free(current_ir_graph->obst, n);
3134         nw = new_Const(get_tarval_mode (tv), tv);
3135
3136         if (old_tp && get_type_mode(old_tp) == get_tarval_mode (tv))
3137           set_Const_type(nw, old_tp);
3138         DBG_OPT_CSTEVAL(oldn, nw);
3139         return nw;
3140       }
3141     }
3142   }
3143
3144   /* remove unnecessary nodes */
3145   if (get_opt_constant_folding() ||
3146     (iro == iro_Phi)  ||   /* always optimize these nodes. */
3147     (iro == iro_Id)   ||
3148     (iro == iro_Proj) ||
3149     (iro == iro_Block)  )  /* Flags tested local. */
3150     n = equivalent_node (n);
3151
3152   optimize_preds(n);                  /* do node specific optimizations of nodes predecessors. */
3153
3154   /* Common Subexpression Elimination.
3155    *
3156    * Checks whether n is already available.
3157    * The block input is used to distinguish different subexpressions. Right
3158    * now all nodes are op_pin_state_pinned to blocks, i.e., the CSE only finds common
3159    * subexpressions within a block.
3160    */
3161   if (get_opt_cse())
3162     n = identify_cons (current_ir_graph->value_table, n);
3163
3164   if (n != oldn) {
3165     edges_node_deleted(oldn, current_ir_graph);
3166
3167     /* We found an existing, better node, so we can deallocate the old node. */
3168     obstack_free (current_ir_graph->obst, oldn);
3169
3170     return n;
3171   }
3172
3173   /* Some more constant expression evaluation that does not allow to
3174      free the node. */
3175   iro = get_irn_opcode(n);
3176   if (get_opt_constant_folding() ||
3177     (iro == iro_Cond) ||
3178     (iro == iro_Proj) ||
3179     (iro == iro_Sel))     /* Flags tested local. */
3180     n = transform_node (n);
3181
3182   /* Remove nodes with dead (Bad) input.
3183      Run always for transformation induced Bads. */
3184   n = gigo (n);
3185
3186   /* Now we have a legal, useful node. Enter it in hash table for cse */
3187   if (get_opt_cse() && (get_irn_opcode(n) != iro_Block)) {
3188     n = identify_remember (current_ir_graph->value_table, n);
3189   }
3190
3191   return n;
3192 }
3193
3194
3195 /**
3196  * These optimizations never deallocate nodes (in place).  This can cause dead
3197  * nodes lying on the obstack.  Remove these by a dead node elimination,
3198  * i.e., a copying garbage collection.
3199  */
3200 ir_node *
3201 optimize_in_place_2 (ir_node *n)
3202 {
3203   tarval *tv;
3204   ir_node *oldn = n;
3205   opcode iro = get_irn_opcode(n);
3206
3207   if (!get_opt_optimize() && (get_irn_op(n) != op_Phi)) return n;
3208
3209   /* constant expression evaluation / constant folding */
3210   if (get_opt_constant_folding()) {
3211     /* neither constants nor Tuple values can be evaluated */
3212     if (iro != iro_Const && get_irn_mode(n) != mode_T) {
3213       /* try to evaluate */
3214       tv = computed_value(n);
3215       if (tv != tarval_bad) {
3216         /* evaluation was successful -- replace the node. */
3217         type *old_tp = get_irn_type(n);
3218         int i, arity = get_irn_arity(n);
3219
3220         /*
3221          * Try to recover the type of the new expression.
3222          */
3223         for (i = 0; i < arity && !old_tp; ++i)
3224           old_tp = get_irn_type(get_irn_n(n, i));
3225
3226         n = new_Const(get_tarval_mode(tv), tv);
3227
3228         if (old_tp && get_type_mode(old_tp) == get_tarval_mode(tv))
3229           set_Const_type(n, old_tp);
3230
3231         DBG_OPT_CSTEVAL(oldn, n);
3232         return n;
3233       }
3234     }
3235   }
3236
3237   /* remove unnecessary nodes */
3238   if (get_opt_constant_folding() ||
3239       (iro == iro_Phi)  ||   /* always optimize these nodes. */
3240       (iro == iro_Id)   ||   /* ... */
3241       (iro == iro_Proj) ||   /* ... */
3242       (iro == iro_Block)  )  /* Flags tested local. */
3243     n = equivalent_node(n);
3244
3245   optimize_preds(n);                  /* do node specific optimizations of nodes predecessors. */
3246
3247   /** common subexpression elimination **/
3248   /* Checks whether n is already available. */
3249   /* The block input is used to distinguish different subexpressions.  Right
3250      now all nodes are op_pin_state_pinned to blocks, i.e., the cse only finds common
3251      subexpressions within a block. */
3252   if (get_opt_cse()) {
3253     n = identify(current_ir_graph->value_table, n);
3254   }
3255
3256   /* Some more constant expression evaluation. */
3257   iro = get_irn_opcode(n);
3258   if (get_opt_constant_folding() ||
3259       (iro == iro_Cond) ||
3260       (iro == iro_Proj) ||
3261       (iro == iro_Sel))     /* Flags tested local. */
3262     n = transform_node(n);
3263
3264   /* Remove nodes with dead (Bad) input.
3265      Run always for transformation induced Bads.  */
3266   n = gigo(n);
3267
3268   /* Now we can verify the node, as it has no dead inputs any more. */
3269   irn_vrfy(n);
3270
3271   /* Now we have a legal, useful node. Enter it in hash table for cse.
3272      Blocks should be unique anyways.  (Except the successor of start:
3273      is cse with the start block!) */
3274   if (get_opt_cse() && (get_irn_opcode(n) != iro_Block))
3275     n = identify_remember(current_ir_graph->value_table, n);
3276
3277   return n;
3278 }
3279
3280 /**
3281  * Wrapper for external use, set proper status bits after optimization.
3282  */
3283 ir_node *
3284 optimize_in_place (ir_node *n)
3285 {
3286   /* Handle graph state */
3287   assert(get_irg_phase_state(current_ir_graph) != phase_building);
3288
3289   if (get_opt_global_cse())
3290     set_irg_pinned(current_ir_graph, op_pin_state_floats);
3291   if (get_irg_outs_state(current_ir_graph) == outs_consistent)
3292     set_irg_outs_inconsistent(current_ir_graph);
3293
3294   /* Maybe we could also test whether optimizing the node can
3295      change the control graph. */
3296   if (get_irg_dom_state(current_ir_graph) == dom_consistent)
3297     set_irg_dom_inconsistent(current_ir_graph);
3298   return optimize_in_place_2 (n);
3299 }
3300
3301 /**
3302  * set the default ir op operations
3303  */
3304 ir_op *firm_set_default_operations(ir_op *op)
3305 {
3306   op = firm_set_default_computed_value(op);
3307   op = firm_set_default_equivalent_node(op);
3308   op = firm_set_default_transform_node(op);
3309   op = firm_set_default_node_cmp_attr(op);
3310   op = firm_set_default_get_type(op);
3311
3312   return op;
3313 }