- handle strictConv and remainderlessDiv for in opcode map
[libfirm] / ir / opt / combo.c
1 /*
2  * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief   Cliff Click's Combined Analysis/Optimization
23  * @author  Michael Beck
24  * @version $Id$
25  *
26  * This is a slightly enhanced version of Cliff Clicks combo algorithm
27  * - support for commutative nodes is added, Add(a,b) and Add(b,a) ARE congruent
28  * - supports all Firm direct (by a data edge) identities except Mux
29  *   (Mux can be a 2-input or 1-input identity, only 2-input is implemented yet)
30  * - supports Confirm nodes (handle them like Copies but do NOT remove them)
31  * - let Cmp nodes calculate Top like all othe data nodes: this would let
32  *   Mux nodes to calculate Unknown instead of taking the true result
33  * - let Cond(Top) always select FALSE/default: This is tricky. Nodes are only reavaluated
34  *   IFF the predecessor changed its type. Because nodes are initialized with Top
35  *   this never happens, let all Proj(Cond) be unreachable.
36  *   We avoid this condition by the same way we work around Phi: whenever a Block
37  *   node is placed on the list, place its Cond nodes (and because they are Tuple
38  *   all its Proj-nodes either on the cprop list)
39  *   Especially, this changes the meaning of Click's example:
40  *
41  *   int main() {
42  *     int x;
43  *
44  *     if (x == 2)
45  *       printf("x == 2\n");
46  *     if (x == 3)
47  *       printf("x == 3\n");
48  *   }
49  *
50  *   Would print:
51  *   x == 2
52  *   x == 3
53  *
54  *   using Click's version while is silent with our.
55  * - support for global congruences is implemented but not tested yet
56  *
57  * Note further that we use the terminology from Click's work here, which is different
58  * in some cases from Firm terminology.  Especially, Click's type is a
59  * Firm tarval/entity, nevertheless we call it type here for "maximum compatibility".
60  */
61 #include "config.h"
62
63 #include <assert.h>
64
65 #include "iroptimize.h"
66 #include "archop.h"
67 #include "irflag.h"
68 #include "ircons.h"
69 #include "list.h"
70 #include "set.h"
71 #include "pmap.h"
72 #include "obstack.h"
73 #include "irgraph_t.h"
74 #include "irnode_t.h"
75 #include "iropt_t.h"
76 #include "irgwalk.h"
77 #include "irop.h"
78 #include "irouts.h"
79 #include "irgmod.h"
80 #include "iropt_dbg.h"
81 #include "debug.h"
82 #include "array_t.h"
83 #include "error.h"
84 #include "irnodeset.h"
85
86 #include "tv_t.h"
87
88 #include "irprintf.h"
89 #include "irdump.h"
90
91 /* define this to check that all type translations are monotone */
92 #define VERIFY_MONOTONE
93
94 /* define this to check the consistency of partitions */
95 #define CHECK_PARTITIONS
96
97 typedef struct node_t            node_t;
98 typedef struct partition_t       partition_t;
99 typedef struct opcode_key_t      opcode_key_t;
100 typedef struct listmap_entry_t   listmap_entry_t;
101
102 /** The type of the compute function. */
103 typedef void (*compute_func)(node_t *node);
104
105 /**
106  * An opcode map key.
107  */
108 struct opcode_key_t {
109         ir_opcode   code;   /**< The Firm opcode. */
110         ir_mode     *mode;  /**< The mode of all nodes in the partition. */
111         int         arity;  /**< The arity of this opcode (needed for Phi etc. */
112         union {
113                 long      proj;   /**< For Proj nodes, its proj number */
114                 ir_entity *ent;   /**< For Sel Nodes, its entity */
115                 int       intVal; /**< For Conv/Div Nodes: strict/remainderless */
116         } u;
117 };
118
119 /**
120  * An entry in the list_map.
121  */
122 struct listmap_entry_t {
123         void            *id;    /**< The id. */
124         node_t          *list;  /**< The associated list for this id. */
125         listmap_entry_t *next;  /**< Link to the next entry in the map. */
126 };
127
128 /** We must map id's to lists. */
129 typedef struct listmap_t {
130         set             *map;    /**< Map id's to listmap_entry_t's */
131         listmap_entry_t *values; /**< List of all values in the map. */
132 } listmap_t;
133
134 /**
135  * A lattice element. Because we handle constants and symbolic constants different, we
136  * have to use this union.
137  */
138 typedef union {
139         tarval          *tv;
140         symconst_symbol sym;
141 } lattice_elem_t;
142
143 /**
144  * A node.
145  */
146 struct node_t {
147         ir_node         *node;          /**< The IR-node itself. */
148         list_head       node_list;      /**< Double-linked list of leader/follower entries. */
149         list_head       cprop_list;     /**< Double-linked partition.cprop list. */
150         partition_t     *part;          /**< points to the partition this node belongs to */
151         node_t          *next;          /**< Next node on local list (partition.touched, fallen). */
152         node_t          *race_next;     /**< Next node on race list. */
153         lattice_elem_t  type;           /**< The associated lattice element "type". */
154         int             max_user_input; /**< Maximum input number of Def-Use edges. */
155         int             next_edge;      /**< Index of the next Def-Use edge to use. */
156         int             n_followers;    /**< Number of Follower in the outs set. */
157         unsigned        on_touched:1;   /**< Set, if this node is on the partition.touched set. */
158         unsigned        on_cprop:1;     /**< Set, if this node is on the partition.cprop list. */
159         unsigned        on_fallen:1;    /**< Set, if this node is on the fallen list. */
160         unsigned        is_follower:1;  /**< Set, if this node is a follower. */
161         unsigned        flagged:2;      /**< 2 Bits, set if this node was visited by race 1 or 2. */
162 };
163
164 /**
165  * A partition containing congruent nodes.
166  */
167 struct partition_t {
168         list_head         Leader;          /**< The head of partition Leader node list. */
169         list_head         Follower;        /**< The head of partition Follower node list. */
170         list_head         cprop;           /**< The head of partition.cprop list. */
171         list_head         cprop_X;         /**< The head of partition.cprop (Cond nodes and its Projs) list. */
172         partition_t       *wl_next;        /**< Next entry in the work list if any. */
173         partition_t       *touched_next;   /**< Points to the next partition in the touched set. */
174         partition_t       *cprop_next;     /**< Points to the next partition in the cprop list. */
175         partition_t       *split_next;     /**< Points to the next partition in the list that must be split by split_by(). */
176         node_t            *touched;        /**< The partition.touched set of this partition. */
177         unsigned          n_leader;        /**< Number of entries in this partition.Leader. */
178         unsigned          n_touched;       /**< Number of entries in the partition.touched. */
179         int               max_user_inputs; /**< Maximum number of user inputs of all entries. */
180         unsigned          on_worklist:1;   /**< Set, if this partition is in the work list. */
181         unsigned          on_touched:1;    /**< Set, if this partition is on the touched set. */
182         unsigned          on_cprop:1;      /**< Set, if this partition is on the cprop list. */
183         unsigned          type_is_T_or_C:1;/**< Set, if all nodes in this partition have type Top or Constant. */
184 #ifdef DEBUG_libfirm
185         partition_t       *dbg_next;       /**< Link all partitions for debugging */
186         unsigned          nr;              /**< A unique number for (what-)mapping, >0. */
187 #endif
188 };
189
190 typedef struct environment_t {
191         struct obstack  obst;           /**< obstack to allocate data structures. */
192         partition_t     *worklist;      /**< The work list. */
193         partition_t     *cprop;         /**< The constant propagation list. */
194         partition_t     *touched;       /**< the touched set. */
195         partition_t     *initial;       /**< The initial partition. */
196         set             *opcode2id_map; /**< The opcodeMode->id map. */
197         pmap            *type2id_map;   /**< The type->id map. */
198         ir_node         **kept_memory;  /**< Array of memory nodes that must be kept. */
199         int             end_idx;        /**< -1 for local and 0 for global congruences. */
200         int             lambda_input;   /**< Captured argument for lambda_partition(). */
201         unsigned        modified:1;     /**< Set, if the graph was modified. */
202         unsigned        unopt_cf:1;     /**< If set, control flow is not optimized due to Unknown. */
203         /* options driving the optimization */
204         unsigned        commutative:1;  /**< Set, if commutation nodes should be handled specially. */
205         unsigned        opt_unknown:1;  /**< Set, if non-strict programs should be optimized. */
206 #ifdef DEBUG_libfirm
207         partition_t     *dbg_list;      /**< List of all partitions. */
208 #endif
209 } environment_t;
210
211 /** Type of the what function. */
212 typedef void *(*what_func)(const node_t *node, environment_t *env);
213
214 #define get_irn_node(irn)         ((node_t *)get_irn_link(irn))
215 #define set_irn_node(irn, node)   set_irn_link(irn, node)
216
217 /* we do NOT use tarval_unreachable here, instead we use Top for this purpose */
218 #undef tarval_unreachable
219 #define tarval_unreachable tarval_top
220
221
222 /** The debug module handle. */
223 DEBUG_ONLY(static firm_dbg_module_t *dbg;)
224
225 /** The what reason. */
226 DEBUG_ONLY(static const char *what_reason;)
227
228 /** Next partition number. */
229 DEBUG_ONLY(static unsigned part_nr = 0);
230
231 /** The tarval returned by Unknown nodes: set to either tarval_bad OR tarval_top. */
232 static tarval *tarval_UNKNOWN;
233
234 /* forward */
235 static node_t *identity(node_t *node);
236
237 #ifdef CHECK_PARTITIONS
238 /**
239  * Check a partition.
240  */
241 static void check_partition(const partition_t *T) {
242         node_t   *node;
243         unsigned n = 0;
244
245         list_for_each_entry(node_t, node, &T->Leader, node_list) {
246                 assert(node->is_follower == 0);
247                 assert(node->flagged == 0);
248                 assert(node->part == T);
249                 ++n;
250         }
251         assert(n == T->n_leader);
252
253         list_for_each_entry(node_t, node, &T->Follower, node_list) {
254                 assert(node->is_follower == 1);
255                 assert(node->flagged == 0);
256                 assert(node->part == T);
257         }
258 }  /* check_partition */
259
260 /**
261  * check that all leader nodes in the partition have the same opcode.
262  */
263 static void check_opcode(const partition_t *Z) {
264         node_t       *node;
265         opcode_key_t key;
266         int          first = 1;
267
268         list_for_each_entry(node_t, node, &Z->Leader, node_list) {
269                 ir_node *irn = node->node;
270
271                 if (first) {
272                         key.code   = get_irn_opcode(irn);
273                         key.mode   = get_irn_mode(irn);
274                         key.arity  = get_irn_arity(irn);
275                         key.u.proj = 0;
276                         key.u.ent  = NULL;
277
278                         switch (get_irn_opcode(irn)) {
279                         case iro_Proj:
280                                 key.u.proj = get_Proj_proj(irn);
281                                 break;
282                         case iro_Sel:
283                                 key.u.ent = get_Sel_entity(irn);
284                                 break;
285                         case iro_Conv:
286                                 key.u.intVal = get_Conv_strict(irn);
287                                 break;
288                         case iro_Div:
289                                 key.u.intVal = is_Div_remainderless(irn);
290                                 break;
291                         default:
292                                 break;
293                         }
294                         first = 0;
295                 } else {
296                         assert(key.code  == get_irn_opcode(irn));
297                         assert(key.mode  == get_irn_mode(irn));
298                         assert(key.arity == get_irn_arity(irn));
299
300                         switch (get_irn_opcode(irn)) {
301                         case iro_Proj:
302                                 assert(key.u.proj == get_Proj_proj(irn));
303                                 break;
304                         case iro_Sel:
305                                 assert(key.u.ent == get_Sel_entity(irn));
306                                 break;
307                         case iro_Conv:
308                                 assert(key.u.intVal == get_Conv_strict(irn));
309                                 break;
310                         case iro_Div:
311                                 assert(key.u.intVal == is_Div_remainderless(irn));
312                                 break;
313                         default:
314                                 break;
315                         }
316                 }
317         }
318 }  /* check_opcode */
319
320 static void check_all_partitions(environment_t *env) {
321 #ifdef DEBUG_libfirm
322         partition_t *P;
323         node_t      *node;
324
325         for (P = env->dbg_list; P != NULL; P = P->dbg_next) {
326                 check_partition(P);
327                 if (! P->type_is_T_or_C)
328                         check_opcode(P);
329                 list_for_each_entry(node_t, node, &P->Follower, node_list) {
330                         node_t *leader = identity(node);
331
332                         assert(leader != node && leader->part == node->part);
333                 }
334         }
335 #endif
336 }
337
338 /**
339  * Check list.
340  */
341 static void do_check_list(const node_t *list, int ofs, const partition_t *Z) {
342         const node_t *e;
343
344 #define NEXT(e)  *((const node_t **)((char *)(e) + (ofs)))
345         for (e = list; e != NULL; e = NEXT(e)) {
346                 assert(e->part == Z);
347         }
348 #undef NEXT
349 }  /* ido_check_list */
350
351 /**
352  * Check a local list.
353  */
354 static void check_list(const node_t *list, const partition_t *Z) {
355         do_check_list(list, offsetof(node_t, next), Z);
356 }  /* check_list */
357
358 #else
359 #define check_partition(T)
360 #define check_list(list, Z)
361 #define check_all_partitions(env)
362 #endif /* CHECK_PARTITIONS */
363
364 #ifdef DEBUG_libfirm
365 static inline lattice_elem_t get_partition_type(const partition_t *X);
366
367 /**
368  * Dump partition to output.
369  */
370 static void dump_partition(const char *msg, const partition_t *part) {
371         const node_t   *node;
372         int            first = 1;
373         lattice_elem_t type = get_partition_type(part);
374
375         DB((dbg, LEVEL_2, "%s part%u%s (%u, %+F) {\n  ",
376                 msg, part->nr, part->type_is_T_or_C ? "*" : "",
377                 part->n_leader, type));
378         list_for_each_entry(node_t, node, &part->Leader, node_list) {
379                 DB((dbg, LEVEL_2, "%s%+F", first ? "" : ", ", node->node));
380                 first = 0;
381         }
382         if (! list_empty(&part->Follower)) {
383                 DB((dbg, LEVEL_2, "\n---\n  "));
384                 first = 1;
385                 list_for_each_entry(node_t, node, &part->Follower, node_list) {
386                         DB((dbg, LEVEL_2, "%s%+F", first ? "" : ", ", node->node));
387                         first = 0;
388                 }
389         }
390         DB((dbg, LEVEL_2, "\n}\n"));
391 }  /* dump_partition */
392
393 /**
394  * Dumps a list.
395  */
396 static void do_dump_list(const char *msg, const node_t *node, int ofs) {
397         const node_t *p;
398         int          first = 1;
399
400 #define GET_LINK(p, ofs)  *((const node_t **)((char *)(p) + (ofs)))
401
402         DB((dbg, LEVEL_3, "%s = {\n  ", msg));
403         for (p = node; p != NULL; p = GET_LINK(p, ofs)) {
404                 DB((dbg, LEVEL_3, "%s%+F", first ? "" : ", ", p->node));
405                 first = 0;
406         }
407         DB((dbg, LEVEL_3, "\n}\n"));
408
409 #undef GET_LINK
410 }  /* do_dump_list */
411
412 /**
413  * Dumps a race list.
414  */
415 static void dump_race_list(const char *msg, const node_t *list) {
416         do_dump_list(msg, list, offsetof(node_t, race_next));
417 }  /* dump_race_list */
418
419 /**
420  * Dumps a local list.
421  */
422 static void dump_list(const char *msg, const node_t *list) {
423         do_dump_list(msg, list, offsetof(node_t, next));
424 }  /* dump_list */
425
426 /**
427  * Dump all partitions.
428  */
429 static void dump_all_partitions(const environment_t *env) {
430         const partition_t *P;
431
432         DB((dbg, LEVEL_2, "All partitions\n===============\n"));
433         for (P = env->dbg_list; P != NULL; P = P->dbg_next)
434                 dump_partition("", P);
435 }  /* dump_all_partitions */
436
437 /**
438  * Sump a split list.
439  */
440 static void dump_split_list(const partition_t *list) {
441         const partition_t *p;
442
443         DB((dbg, LEVEL_2, "Split by %s produced = {\n", what_reason));
444         for (p = list; p != NULL; p = p->split_next)
445                 DB((dbg, LEVEL_2, "part%u, ", p->nr));
446         DB((dbg, LEVEL_2, "\n}\n"));
447 }  /* dump_split_list */
448
449 /**
450  * Dump partition and type for a node.
451  */
452 static int dump_partition_hook(FILE *F, ir_node *n, ir_node *local) {
453         ir_node *irn = local != NULL ? local : n;
454         node_t *node = get_irn_node(irn);
455
456         ir_fprintf(F, "info2 : \"partition %u type %+F\"\n", node->part->nr, node->type);
457         return 1;
458 }  /* dump_partition_hook */
459
460 #else
461 #define dump_partition(msg, part)
462 #define dump_race_list(msg, list)
463 #define dump_list(msg, list)
464 #define dump_all_partitions(env)
465 #define dump_split_list(list)
466 #endif
467
468 #if defined(VERIFY_MONOTONE) && defined (DEBUG_libfirm)
469 /**
470  * Verify that a type transition is monotone
471  */
472 static void verify_type(const lattice_elem_t old_type, node_t *node) {
473         if (old_type.tv == node->type.tv) {
474                 /* no change */
475                 return;
476         }
477         if (old_type.tv == tarval_top) {
478                 /* from Top down-to is always allowed */
479                 return;
480         }
481         if (node->type.tv == tarval_bottom || node->type.tv == tarval_reachable) {
482                 /* bottom reached */
483                 return;
484         }
485         panic("combo: wrong translation from %+F to %+F on node %+F", old_type, node->type, node->node);
486 }  /* verify_type */
487
488 #else
489 #define verify_type(old_type, node)
490 #endif
491
492 /**
493  * Compare two pointer values of a listmap.
494  */
495 static int listmap_cmp_ptr(const void *elt, const void *key, size_t size) {
496         const listmap_entry_t *e1 = elt;
497         const listmap_entry_t *e2 = key;
498
499         (void) size;
500         return e1->id != e2->id;
501 }  /* listmap_cmp_ptr */
502
503 /**
504  * Initializes a listmap.
505  *
506  * @param map  the listmap
507  */
508 static void listmap_init(listmap_t *map) {
509         map->map    = new_set(listmap_cmp_ptr, 16);
510         map->values = NULL;
511 }  /* listmap_init */
512
513 /**
514  * Terminates a listmap.
515  *
516  * @param map  the listmap
517  */
518 static void listmap_term(listmap_t *map) {
519         del_set(map->map);
520 }  /* listmap_term */
521
522 /**
523  * Return the associated listmap entry for a given id.
524  *
525  * @param map  the listmap
526  * @param id   the id to search for
527  *
528  * @return the associated listmap entry for the given id
529  */
530 static listmap_entry_t *listmap_find(listmap_t *map, void *id) {
531         listmap_entry_t key, *entry;
532
533         key.id   = id;
534         key.list = NULL;
535         key.next = NULL;
536         entry = set_insert(map->map, &key, sizeof(key), HASH_PTR(id));
537
538         if (entry->list == NULL) {
539                 /* a new entry, put into the list */
540                 entry->next = map->values;
541                 map->values = entry;
542         }
543         return entry;
544 }  /* listmap_find */
545
546 /**
547  * Calculate the hash value for an opcode map entry.
548  *
549  * @param entry  an opcode map entry
550  *
551  * @return a hash value for the given opcode map entry
552  */
553 static unsigned opcode_hash(const opcode_key_t *entry) {
554         return (entry->mode - (ir_mode *)0) * 9 + entry->code + entry->u.proj * 3 + HASH_PTR(entry->u.ent) + entry->arity;
555 }  /* opcode_hash */
556
557 /**
558  * Compare two entries in the opcode map.
559  */
560 static int cmp_opcode(const void *elt, const void *key, size_t size) {
561         const opcode_key_t *o1 = elt;
562         const opcode_key_t *o2 = key;
563
564         (void) size;
565         return o1->code != o2->code || o1->mode != o2->mode ||
566                o1->arity != o2->arity ||
567                o1->u.proj != o2->u.proj || o1->u.ent != o2->u.ent ||
568                    o1->u.intVal != o2->u.intVal;
569 }  /* cmp_opcode */
570
571 /**
572  * Compare two Def-Use edges for input position.
573  */
574 static int cmp_def_use_edge(const void *a, const void *b) {
575         const ir_def_use_edge *ea = a;
576         const ir_def_use_edge *eb = b;
577
578         /* no overrun, because range is [-1, MAXINT] */
579         return ea->pos - eb->pos;
580 }  /* cmp_def_use_edge */
581
582 /**
583  * We need the Def-Use edges sorted.
584  */
585 static void sort_irn_outs(node_t *node) {
586         ir_node *irn = node->node;
587         int n_outs = get_irn_n_outs(irn);
588
589         if (n_outs > 1) {
590                 qsort(&irn->out[1], n_outs, sizeof(irn->out[0]), cmp_def_use_edge);
591         }
592         node->max_user_input = irn->out[n_outs].pos;
593 }  /* sort_irn_outs */
594
595 /**
596  * Return the type of a node.
597  *
598  * @param irn  an IR-node
599  *
600  * @return the associated type of this node
601  */
602 static inline lattice_elem_t get_node_type(const ir_node *irn) {
603         return get_irn_node(irn)->type;
604 }  /* get_node_type */
605
606 /**
607  * Return the tarval of a node.
608  *
609  * @param irn  an IR-node
610  *
611  * @return the associated type of this node
612  */
613 static inline tarval *get_node_tarval(const ir_node *irn) {
614         lattice_elem_t type = get_node_type(irn);
615
616         if (is_tarval(type.tv))
617                 return type.tv;
618         return tarval_bottom;
619 }  /* get_node_type */
620
621 /**
622  * Add a partition to the worklist.
623  */
624 static inline void add_to_worklist(partition_t *X, environment_t *env) {
625         assert(X->on_worklist == 0);
626         DB((dbg, LEVEL_2, "Adding part%d to worklist\n", X->nr));
627         X->wl_next     = env->worklist;
628         X->on_worklist = 1;
629         env->worklist  = X;
630 }  /* add_to_worklist */
631
632 /**
633  * Create a new empty partition.
634  *
635  * @param env   the environment
636  *
637  * @return a newly allocated partition
638  */
639 static inline partition_t *new_partition(environment_t *env) {
640         partition_t *part = obstack_alloc(&env->obst, sizeof(*part));
641
642         INIT_LIST_HEAD(&part->Leader);
643         INIT_LIST_HEAD(&part->Follower);
644         INIT_LIST_HEAD(&part->cprop);
645         INIT_LIST_HEAD(&part->cprop_X);
646         part->wl_next         = NULL;
647         part->touched_next    = NULL;
648         part->cprop_next      = NULL;
649         part->split_next      = NULL;
650         part->touched         = NULL;
651         part->n_leader        = 0;
652         part->n_touched       = 0;
653         part->max_user_inputs = 0;
654         part->on_worklist     = 0;
655         part->on_touched      = 0;
656         part->on_cprop        = 0;
657         part->type_is_T_or_C  = 0;
658 #ifdef DEBUG_libfirm
659         part->dbg_next        = env->dbg_list;
660         env->dbg_list         = part;
661         part->nr              = part_nr++;
662 #endif
663
664         return part;
665 }  /* new_partition */
666
667 /**
668  * Get the first node from a partition.
669  */
670 static inline node_t *get_first_node(const partition_t *X) {
671         return list_entry(X->Leader.next, node_t, node_list);
672 }  /* get_first_node */
673
674 /**
675  * Return the type of a partition (assuming partition is non-empty and
676  * all elements have the same type).
677  *
678  * @param X  a partition
679  *
680  * @return the type of the first element of the partition
681  */
682 static inline lattice_elem_t get_partition_type(const partition_t *X) {
683         const node_t *first = get_first_node(X);
684         return first->type;
685 }  /* get_partition_type */
686
687 /**
688  * Creates a partition node for the given IR-node and place it
689  * into the given partition.
690  *
691  * @param irn   an IR-node
692  * @param part  a partition to place the node in
693  * @param env   the environment
694  *
695  * @return the created node
696  */
697 static node_t *create_partition_node(ir_node *irn, partition_t *part, environment_t *env) {
698         /* create a partition node and place it in the partition */
699         node_t *node = obstack_alloc(&env->obst, sizeof(*node));
700
701         INIT_LIST_HEAD(&node->node_list);
702         INIT_LIST_HEAD(&node->cprop_list);
703         node->node           = irn;
704         node->part           = part;
705         node->next           = NULL;
706         node->race_next      = NULL;
707         node->type.tv        = tarval_top;
708         node->max_user_input = 0;
709         node->next_edge      = 0;
710         node->n_followers    = 0;
711         node->on_touched     = 0;
712         node->on_cprop       = 0;
713         node->on_fallen      = 0;
714         node->is_follower    = 0;
715         node->flagged        = 0;
716         set_irn_node(irn, node);
717
718         list_add_tail(&node->node_list, &part->Leader);
719         ++part->n_leader;
720
721         return node;
722 }  /* create_partition_node */
723
724 /**
725  * Pre-Walker, initialize all Nodes' type to U or top and place
726  * all nodes into the TOP partition.
727  */
728 static void create_initial_partitions(ir_node *irn, void *ctx) {
729         environment_t *env  = ctx;
730         partition_t   *part = env->initial;
731         node_t        *node;
732
733         node = create_partition_node(irn, part, env);
734         sort_irn_outs(node);
735         if (node->max_user_input > part->max_user_inputs)
736                 part->max_user_inputs = node->max_user_input;
737
738         if (is_Block(irn)) {
739                 set_Block_phis(irn, NULL);
740         }
741 }  /* create_initial_partitions */
742
743 /**
744  * Post-Walker, collect  all Block-Phi lists, set Cond.
745  */
746 static void init_block_phis(ir_node *irn, void *ctx) {
747         (void) ctx;
748
749         if (is_Phi(irn)) {
750                 add_Block_phi(get_nodes_block(irn), irn);
751         }
752 }  /* init_block_phis */
753
754 /**
755  * Add a node to the entry.partition.touched set and
756  * node->partition to the touched set if not already there.
757  *
758  * @param y    a node
759  * @param env  the environment
760  */
761 static inline void add_to_touched(node_t *y, environment_t *env) {
762         if (y->on_touched == 0) {
763                 partition_t *part = y->part;
764
765                 y->next       = part->touched;
766                 part->touched = y;
767                 y->on_touched = 1;
768                 ++part->n_touched;
769
770                 if (part->on_touched == 0) {
771                         part->touched_next = env->touched;
772                         env->touched       = part;
773                         part->on_touched   = 1;
774                 }
775
776                 check_list(part->touched, part);
777         }
778 }  /* add_to_touched */
779
780 /**
781  * Place a node on the cprop list.
782  *
783  * @param y    the node
784  * @param env  the environment
785  */
786 static void add_to_cprop(node_t *y, environment_t *env) {
787         ir_node *irn;
788
789         /* Add y to y.partition.cprop. */
790         if (y->on_cprop == 0) {
791                 partition_t *Y = y->part;
792                 ir_node *irn   = y->node;
793
794                 /* place Conds and all its Projs on the cprop_X list */
795                 if (is_Cond(skip_Proj(irn)))
796                         list_add_tail(&y->cprop_list, &Y->cprop_X);
797                 else
798                         list_add_tail(&y->cprop_list, &Y->cprop);
799                 y->on_cprop   = 1;
800
801                 DB((dbg, LEVEL_3, "Add %+F to part%u.cprop\n", y->node, Y->nr));
802
803                 /* place its partition on the cprop list */
804                 if (Y->on_cprop == 0) {
805                         Y->cprop_next = env->cprop;
806                         env->cprop    = Y;
807                         Y->on_cprop   = 1;
808                 }
809         }
810         irn = y->node;
811         if (get_irn_mode(irn) == mode_T) {
812                 /* mode_T nodes always produce tarval_bottom, so we must explicitly
813                    add it's Proj's to get constant evaluation to work */
814                 int i;
815
816                 for (i = get_irn_n_outs(irn) - 1; i >= 0; --i) {
817                         node_t *proj = get_irn_node(get_irn_out(irn, i));
818
819                         add_to_cprop(proj, env);
820                 }
821         } else if (is_Block(irn)) {
822                 /* Due to the way we handle Phi's, we must place all Phis of a block on the list
823                  * if someone placed the block. The Block is only placed if the reachability
824                  * changes, and this must be re-evaluated in compute_Phi(). */
825                 ir_node *phi;
826                 for (phi = get_Block_phis(irn); phi != NULL; phi = get_Phi_next(phi)) {
827                         node_t *p = get_irn_node(phi);
828                         add_to_cprop(p, env);
829                 }
830         }
831 }  /* add_to_cprop */
832
833 /**
834  * Update the worklist: If Z is on worklist then add Z' to worklist.
835  * Else add the smaller of Z and Z' to worklist.
836  *
837  * @param Z        the Z partition
838  * @param Z_prime  the Z' partition, a previous part of Z
839  * @param env      the environment
840  */
841 static void update_worklist(partition_t *Z, partition_t *Z_prime, environment_t *env) {
842         if (Z->on_worklist || Z_prime->n_leader < Z->n_leader) {
843                 add_to_worklist(Z_prime, env);
844         } else {
845                 add_to_worklist(Z, env);
846         }
847 }  /* update_worklist */
848
849 /**
850  * Make all inputs to x no longer be F.def_use edges.
851  *
852  * @param x  the node
853  */
854 static void move_edges_to_leader(node_t *x) {
855         ir_node     *irn = x->node;
856         int         i, j, k;
857
858         for (i = get_irn_arity(irn) - 1; i >= 0; --i) {
859                 node_t  *pred = get_irn_node(get_irn_n(irn, i));
860                 ir_node *p;
861                 int     n;
862
863                 p = pred->node;
864                 n = get_irn_n_outs(p);
865                 for (j = 1; j <= pred->n_followers; ++j) {
866                         if (p->out[j].pos == i && p->out[j].use == irn) {
867                                 /* found a follower edge to x, move it to the Leader */
868                                 ir_def_use_edge edge = p->out[j];
869
870                                 /* remove this edge from the Follower set */
871                                 p->out[j] = p->out[pred->n_followers];
872                                 --pred->n_followers;
873
874                                 /* sort it into the leader set */
875                                 for (k = pred->n_followers + 2; k <= n; ++k) {
876                                         if (p->out[k].pos >= edge.pos)
877                                                 break;
878                                         p->out[k - 1] = p->out[k];
879                                 }
880                                 /* place the new edge here */
881                                 p->out[k - 1] = edge;
882
883                                 /* edge found and moved */
884                                 break;
885                         }
886                 }
887         }
888 }  /* move_edges_to_leader */
889
890 /**
891  * Split a partition that has NO followers by a local list.
892  *
893  * @param Z    partition to split
894  * @param g    a (non-empty) node list
895  * @param env  the environment
896  *
897  * @return  a new partition containing the nodes of g
898  */
899 static partition_t *split_no_followers(partition_t *Z, node_t *g, environment_t *env) {
900         partition_t *Z_prime;
901         node_t      *node;
902         unsigned    n = 0;
903         int         max_input;
904
905         dump_partition("Splitting ", Z);
906         dump_list("by list ", g);
907
908         assert(g != NULL);
909
910         /* Remove g from Z. */
911         for (node = g; node != NULL; node = node->next) {
912                 assert(node->part == Z);
913                 list_del(&node->node_list);
914                 ++n;
915         }
916         assert(n < Z->n_leader);
917         Z->n_leader -= n;
918
919         /* Move g to a new partition, Z'. */
920         Z_prime = new_partition(env);
921         max_input = 0;
922         for (node = g; node != NULL; node = node->next) {
923                 list_add_tail(&node->node_list, &Z_prime->Leader);
924                 node->part = Z_prime;
925                 if (node->max_user_input > max_input)
926                         max_input = node->max_user_input;
927         }
928         Z_prime->max_user_inputs = max_input;
929         Z_prime->n_leader        = n;
930
931         check_partition(Z);
932         check_partition(Z_prime);
933
934         /* for now, copy the type info tag, it will be adjusted in split_by(). */
935         Z_prime->type_is_T_or_C = Z->type_is_T_or_C;
936
937         update_worklist(Z, Z_prime, env);
938
939         dump_partition("Now ", Z);
940         dump_partition("Created new ", Z_prime);
941         return Z_prime;
942 }  /* split_no_followers */
943
944 /**
945  * Make the Follower -> Leader transition for a node.
946  *
947  * @param n  the node
948  */
949 static void follower_to_leader(node_t *n) {
950         assert(n->is_follower == 1);
951
952         DB((dbg, LEVEL_2, "%+F make the follower -> leader transition\n", n->node));
953         n->is_follower = 0;
954         move_edges_to_leader(n);
955         list_del(&n->node_list);
956         list_add_tail(&n->node_list, &n->part->Leader);
957         ++n->part->n_leader;
958 }  /* follower_to_leader */
959
960 /**
961  * The environment for one race step.
962  */
963 typedef struct step_env {
964         node_t   *initial;    /**< The initial node list. */
965         node_t   *unwalked;   /**< The unwalked node list. */
966         node_t   *walked;     /**< The walked node list. */
967         int      index;       /**< Next index of Follower use_def edge. */
968         unsigned side;        /**< side number. */
969 } step_env;
970
971 /**
972  * Return non-zero, if a input is a real follower
973  *
974  * @param irn    the node to check
975  * @param input  number of the input
976  */
977 static int is_real_follower(const ir_node *irn, int input) {
978         node_t *pred;
979
980         switch (get_irn_opcode(irn)) {
981         case iro_Confirm:
982                 if (input == 1) {
983                         /* ignore the Confirm bound input */
984                         return 0;
985                 }
986                 break;
987         case iro_Mux:
988                 if (input == 0) {
989                         /* ignore the Mux sel input */
990                         return 0;
991                 }
992                 break;
993         case iro_Phi: {
994                 /* dead inputs are not follower edges */
995                 ir_node *block = get_nodes_block(irn);
996                 node_t  *pred  = get_irn_node(get_Block_cfgpred(block, input));
997
998                 if (pred->type.tv == tarval_unreachable)
999                         return 0;
1000                 break;
1001         }
1002         case iro_Sub:
1003         case iro_Shr:
1004         case iro_Shl:
1005         case iro_Shrs:
1006         case iro_Rotl:
1007                 if (input == 1) {
1008                         /* only a Sub x,0 / Shift x,0 might be a follower */
1009                         return 0;
1010                 }
1011                 break;
1012         case iro_Add:
1013         case iro_Or:
1014         case iro_Eor:
1015                 pred = get_irn_node(get_irn_n(irn, input));
1016                 if (is_tarval(pred->type.tv) && tarval_is_null(pred->type.tv))
1017                         return 0;
1018                 break;
1019         case iro_Mul:
1020                 pred = get_irn_node(get_irn_n(irn, input));
1021                 if (is_tarval(pred->type.tv) && tarval_is_one(pred->type.tv))
1022                         return 0;
1023                 break;
1024         case iro_And:
1025                 pred = get_irn_node(get_irn_n(irn, input));
1026                 if (is_tarval(pred->type.tv) && tarval_is_all_one(pred->type.tv))
1027                         return 0;
1028                 break;
1029         case iro_Min:
1030         case iro_Max:
1031                 /* all inputs are followers */
1032                 return 1;
1033         default:
1034                 assert(!"opcode not implemented yet");
1035                 break;
1036         }
1037         return 1;
1038 }  /* is_real_follower */
1039
1040 /**
1041  * Do one step in the race.
1042  */
1043 static int step(step_env *env) {
1044         node_t *n;
1045
1046         if (env->initial != NULL) {
1047                 /* Move node from initial to unwalked */
1048                 n             = env->initial;
1049                 env->initial  = n->race_next;
1050
1051                 n->race_next  = env->unwalked;
1052                 env->unwalked = n;
1053
1054                 return 0;
1055         }
1056
1057         while (env->unwalked != NULL) {
1058                 /* let n be the first node in unwalked */
1059                 n = env->unwalked;
1060                 while (env->index < n->n_followers) {
1061                         const ir_def_use_edge *edge = &n->node->out[1 + env->index];
1062
1063                         /* let m be n.F.def_use[index] */
1064                         node_t *m = get_irn_node(edge->use);
1065
1066                         assert(m->is_follower);
1067                         /*
1068                          * Some inputs, like the get_Confirm_bound are NOT
1069                          * real followers, sort them out.
1070                          */
1071                         if (! is_real_follower(m->node, edge->pos)) {
1072                                 ++env->index;
1073                                 continue;
1074                         }
1075                         ++env->index;
1076
1077                         /* only followers from our partition */
1078                         if (m->part != n->part)
1079                                 continue;
1080
1081                         if ((m->flagged & env->side) == 0) {
1082                                 m->flagged |= env->side;
1083
1084                                 if (m->flagged != 3) {
1085                                         /* visited the first time */
1086                                         /* add m to unwalked not as first node (we might still need to
1087                                            check for more follower node */
1088                                         m->race_next = n->race_next;
1089                                         n->race_next = m;
1090                                         return 0;
1091                                 }
1092                                 /* else already visited by the other side and on the other list */
1093                         }
1094                 }
1095                 /* move n to walked */
1096                 env->unwalked = n->race_next;
1097                 n->race_next  = env->walked;
1098                 env->walked   = n;
1099                 env->index    = 0;
1100         }
1101         return 1;
1102 }  /* step */
1103
1104 /**
1105  * Clear the flags from a list and check for
1106  * nodes that where touched from both sides.
1107  *
1108  * @param list  the list
1109  */
1110 static int clear_flags(node_t *list) {
1111         int    res = 0;
1112         node_t *n;
1113
1114         for (n = list; n != NULL; n = n->race_next) {
1115                 if (n->flagged == 3) {
1116                         /* we reach a follower from both sides, this will split congruent
1117                          * inputs and make it a leader. */
1118                         follower_to_leader(n);
1119                         res = 1;
1120                 }
1121                 n->flagged = 0;
1122         }
1123         return res;
1124 }  /* clear_flags */
1125
1126 /**
1127  * Split a partition by a local list using the race.
1128  *
1129  * @param pX   pointer to the partition to split, might be changed!
1130  * @param gg   a (non-empty) node list
1131  * @param env  the environment
1132  *
1133  * @return  a new partition containing the nodes of gg
1134  */
1135 static partition_t *split(partition_t **pX, node_t *gg, environment_t *env) {
1136         partition_t *X = *pX;
1137         partition_t *X_prime;
1138         list_head   tmp;
1139         step_env    senv[2];
1140         node_t      *g, *h, *node, *t;
1141         int         max_input, transitions, winner, shf;
1142         unsigned    n;
1143         DEBUG_ONLY(static int run = 0;)
1144
1145         DB((dbg, LEVEL_2, "Run %d ", run++));
1146         if (list_empty(&X->Follower)) {
1147                 /* if the partition has NO follower, we can use the fast
1148                    splitting algorithm. */
1149                 return split_no_followers(X, gg, env);
1150         }
1151         /* else do the race */
1152
1153         dump_partition("Splitting ", X);
1154         dump_list("by list ", gg);
1155
1156         INIT_LIST_HEAD(&tmp);
1157
1158         /* Remove gg from X.Leader and put into g */
1159         g = NULL;
1160         for (node = gg; node != NULL; node = node->next) {
1161                 assert(node->part == X);
1162                 assert(node->is_follower == 0);
1163
1164                 list_del(&node->node_list);
1165                 list_add_tail(&node->node_list, &tmp);
1166                 node->race_next = g;
1167                 g               = node;
1168         }
1169         /* produce h */
1170         h = NULL;
1171         list_for_each_entry(node_t, node, &X->Leader, node_list) {
1172                 node->race_next = h;
1173                 h               = node;
1174         }
1175         /* restore X.Leader */
1176         list_splice(&tmp, &X->Leader);
1177
1178         senv[0].initial   = g;
1179         senv[0].unwalked  = NULL;
1180         senv[0].walked    = NULL;
1181         senv[0].index     = 0;
1182         senv[0].side      = 1;
1183
1184         senv[1].initial   = h;
1185         senv[1].unwalked  = NULL;
1186         senv[1].walked    = NULL;
1187         senv[1].index     = 0;
1188         senv[1].side      = 2;
1189
1190         /*
1191          * Some informations on the race that are not stated clearly in Click's
1192          * thesis.
1193          * 1) A follower stays on the side that reach him first.
1194          * 2) If the other side reches a follower, if will be converted to
1195          *    a leader. /This must be done after the race is over, else the
1196          *    edges we are iterating on are renumbered./
1197          * 3) /New leader might end up on both sides./
1198          * 4) /If one side ends up with new Leaders, we must ensure that
1199          *    they can split out by opcode, hence we have to put _every_
1200          *    partition with new Leader nodes on the cprop list, as
1201          *    opcode splitting is done by split_by() at the end of
1202          *    constant propagation./
1203          */
1204         for (;;) {
1205                 if (step(&senv[0])) {
1206                         winner = 0;
1207                         break;
1208                 }
1209                 if (step(&senv[1])) {
1210                         winner = 1;
1211                         break;
1212                 }
1213         }
1214         assert(senv[winner].initial == NULL);
1215         assert(senv[winner].unwalked == NULL);
1216
1217         /* clear flags from walked/unwalked */
1218         shf = winner;
1219         transitions  = clear_flags(senv[0].unwalked) << shf;
1220         transitions |= clear_flags(senv[0].walked)   << shf;
1221         shf ^= 1;
1222         transitions |= clear_flags(senv[1].unwalked) << shf;
1223         transitions |= clear_flags(senv[1].walked)   << shf;
1224
1225         dump_race_list("winner ", senv[winner].walked);
1226
1227         /* Move walked_{winner} to a new partition, X'. */
1228         X_prime   = new_partition(env);
1229         max_input = 0;
1230         n         = 0;
1231         for (node = senv[winner].walked; node != NULL; node = node->race_next) {
1232                 list_del(&node->node_list);
1233                 node->part = X_prime;
1234                 if (node->is_follower) {
1235                         list_add_tail(&node->node_list, &X_prime->Follower);
1236                 } else {
1237                         list_add_tail(&node->node_list, &X_prime->Leader);
1238                         ++n;
1239                 }
1240                 if (node->max_user_input > max_input)
1241                         max_input = node->max_user_input;
1242         }
1243         X_prime->n_leader        = n;
1244         X_prime->max_user_inputs = max_input;
1245         X->n_leader             -= X_prime->n_leader;
1246
1247         /* for now, copy the type info tag, it will be adjusted in split_by(). */
1248         X_prime->type_is_T_or_C = X->type_is_T_or_C;
1249
1250         /*
1251          * Even if a follower was not checked by both sides, it might have
1252          * loose its congruence, so we need to check this case for all follower.
1253          */
1254         list_for_each_entry_safe(node_t, node, t, &X_prime->Follower, node_list) {
1255                 if (identity(node) == node) {
1256                         follower_to_leader(node);
1257                         transitions |= 1;
1258                 }
1259         }
1260
1261         check_partition(X);
1262         check_partition(X_prime);
1263
1264         /* X' is the smaller part */
1265         add_to_worklist(X_prime, env);
1266
1267         /*
1268          * If there where follower to leader transitions, ensure that the nodes
1269          * can be split out if necessary.
1270          */
1271         if (transitions & 1) {
1272                 /* place winner partition on the cprop list */
1273                 if (X_prime->on_cprop == 0) {
1274                         X_prime->cprop_next = env->cprop;
1275                         env->cprop          = X_prime;
1276                         X_prime->on_cprop   = 1;
1277                 }
1278         }
1279         if (transitions & 2) {
1280                 /* place other partition on the cprop list */
1281                 if (X->on_cprop == 0) {
1282                         X->cprop_next = env->cprop;
1283                         env->cprop    = X;
1284                         X->on_cprop   = 1;
1285                 }
1286         }
1287
1288         dump_partition("Now ", X);
1289         dump_partition("Created new ", X_prime);
1290
1291         /* we have to ensure that the partition containing g is returned */
1292         if (winner != 0) {
1293                 *pX = X_prime;
1294                 return X;
1295         }
1296
1297         return X_prime;
1298 }  /* split */
1299
1300 /**
1301  * Returns non-zero if the i'th input of a Phi node is live.
1302  *
1303  * @param phi  a Phi-node
1304  * @param i    an input number
1305  *
1306  * @return non-zero if the i'th input of the given Phi node is live
1307  */
1308 static int is_live_input(ir_node *phi, int i) {
1309         if (i >= 0) {
1310                 ir_node        *block = get_nodes_block(phi);
1311                 ir_node        *pred  = get_Block_cfgpred(block, i);
1312                 lattice_elem_t type   = get_node_type(pred);
1313
1314                 return type.tv != tarval_unreachable;
1315         }
1316         /* else it's the control input, always live */
1317         return 1;
1318 }  /* is_live_input */
1319
1320 /**
1321  * Return non-zero if a type is a constant.
1322  */
1323 static int is_constant_type(lattice_elem_t type) {
1324         if (type.tv != tarval_bottom && type.tv != tarval_top)
1325                 return 1;
1326         return 0;
1327 }  /* is_constant_type */
1328
1329 /**
1330  * Check whether a type is neither Top or a constant.
1331  * Note: U is handled like Top here, R is a constant.
1332  *
1333  * @param type  the type to check
1334  */
1335 static int type_is_neither_top_nor_const(const lattice_elem_t type) {
1336         if (is_tarval(type.tv)) {
1337                 if (type.tv == tarval_top)
1338                         return 0;
1339                 if (tarval_is_constant(type.tv))
1340                         return 0;
1341         } else {
1342                 /* is a symconst */
1343                 return 0;
1344         }
1345         return 1;
1346 }  /* type_is_neither_top_nor_const */
1347
1348 /**
1349  * Collect nodes to the touched list.
1350  *
1351  * @param list  the list which contains the nodes that must be evaluated
1352  * @param idx   the index of the def_use edge to evaluate
1353  * @param env   the environment
1354  */
1355 static void collect_touched(list_head *list, int idx, environment_t *env) {
1356         node_t  *x, *y;
1357         int     end_idx = env->end_idx;
1358
1359         list_for_each_entry(node_t, x, list, node_list) {
1360                 int num_edges;
1361
1362                 if (idx == -1) {
1363                         /* leader edges start AFTER follower edges */
1364                         x->next_edge = x->n_followers + 1;
1365                 }
1366                 num_edges = get_irn_n_outs(x->node);
1367
1368                 /* for all edges in x.L.def_use_{idx} */
1369                 while (x->next_edge <= num_edges) {
1370                         const ir_def_use_edge *edge = &x->node->out[x->next_edge];
1371                         ir_node               *succ;
1372
1373                         /* check if we have necessary edges */
1374                         if (edge->pos > idx)
1375                                 break;
1376
1377                         ++x->next_edge;
1378
1379                         succ = edge->use;
1380
1381                         /* only non-commutative nodes */
1382                         if (env->commutative &&
1383                             (idx == 0 || idx == 1) && is_op_commutative(get_irn_op(succ)))
1384                                 continue;
1385
1386                         /* ignore the "control input" for non-pinned nodes
1387                         if we are running in GCSE mode */
1388                         if (idx < end_idx && get_irn_pinned(succ) != op_pin_state_pinned)
1389                                 continue;
1390
1391                         y = get_irn_node(succ);
1392                         assert(get_irn_n(succ, idx) == x->node);
1393
1394                         /* ignore block edges touching followers */
1395                         if (idx == -1 && y->is_follower)
1396                                 continue;
1397
1398                         if (is_constant_type(y->type)) {
1399                                 ir_opcode code = get_irn_opcode(succ);
1400                                 if (code == iro_Sub || code == iro_Cmp)
1401                                         add_to_cprop(y, env);
1402                         }
1403
1404                         /* Partitions of constants should not be split simply because their Nodes have unequal
1405                            functions or incongruent inputs. */
1406                         if (type_is_neither_top_nor_const(y->type) &&
1407                                 (! is_Phi(y->node) || is_live_input(y->node, idx))) {
1408                                         add_to_touched(y, env);
1409                         }
1410                 }
1411         }
1412 }  /* collect_touched */
1413
1414 /**
1415  * Collect commutative nodes to the touched list.
1416  *
1417  * @param X     the partition of the list
1418  * @param list  the list which contains the nodes that must be evaluated
1419  * @param env   the environment
1420  */
1421 static void collect_commutative_touched(partition_t *X, list_head *list, environment_t *env) {
1422         int     first      = 1;
1423         int     both_input = 0;
1424         node_t  *x, *y;
1425
1426         list_for_each_entry(node_t, x, list, node_list) {
1427                 int num_edges;
1428
1429                 num_edges = get_irn_n_outs(x->node);
1430
1431                 x->next_edge = x->n_followers + 1;
1432
1433                 /* for all edges in x.L.def_use_{idx} */
1434                 while (x->next_edge <= num_edges) {
1435                         const ir_def_use_edge *edge = &x->node->out[x->next_edge];
1436                         ir_node               *succ;
1437
1438                         /* check if we have necessary edges */
1439                         if (edge->pos > 1)
1440                                 break;
1441
1442                         ++x->next_edge;
1443                         if (edge->pos < 0)
1444                                 continue;
1445
1446                         succ = edge->use;
1447
1448                         /* only commutative nodes */
1449                         if (!is_op_commutative(get_irn_op(succ)))
1450                                 continue;
1451
1452                         y = get_irn_node(succ);
1453                         if (is_constant_type(y->type)) {
1454                                 ir_opcode code = get_irn_opcode(succ);
1455                                 if (code == iro_Eor)
1456                                         add_to_cprop(y, env);
1457                         }
1458
1459                         /* Partitions of constants should not be split simply because their Nodes have unequal
1460                            functions or incongruent inputs. */
1461                         if (type_is_neither_top_nor_const(y->type)) {
1462                                 int    other_idx = edge->pos ^ 1;
1463                                 node_t *other    = get_irn_node(get_irn_n(succ, other_idx));
1464                                 int    equal     = X == other->part;
1465
1466                                 /*
1467                                  * Note: op(a, a) is NOT congruent to op(a, b).
1468                                  * So, either all touch nodes must have both inputs congruent,
1469                                  * or not. We decide this by the first occurred node.
1470                                  */
1471                                 if (first) {
1472                                         first      = 0;
1473                                         both_input = equal;
1474                                 }
1475                                 if (both_input == equal)
1476                                         add_to_touched(y, env);
1477                         }
1478                 }
1479         }
1480 }  /* collect_commutative_touched */
1481
1482 /**
1483  * Split the partitions if caused by the first entry on the worklist.
1484  *
1485  * @param env  the environment
1486  */
1487 static void cause_splits(environment_t *env) {
1488         partition_t *X, *Z, *N;
1489         int         idx;
1490
1491         /* remove the first partition from the worklist */
1492         X = env->worklist;
1493         env->worklist  = X->wl_next;
1494         X->on_worklist = 0;
1495
1496         dump_partition("Cause_split: ", X);
1497
1498         if (env->commutative) {
1499                 /* handle commutative nodes first */
1500
1501                 /* empty the touched set: already done, just clear the list */
1502                 env->touched = NULL;
1503
1504                 collect_commutative_touched(X, &X->Leader, env);
1505                 collect_commutative_touched(X, &X->Follower, env);
1506
1507                 for (Z = env->touched; Z != NULL; Z = N) {
1508                         node_t   *e;
1509                         node_t   *touched  = Z->touched;
1510                         unsigned n_touched = Z->n_touched;
1511
1512                         assert(Z->touched != NULL);
1513
1514                         /* beware, split might change Z */
1515                         N = Z->touched_next;
1516
1517                         /* remove it from the touched set */
1518                         Z->on_touched = 0;
1519
1520                         /* Empty local Z.touched. */
1521                         for (e = touched; e != NULL; e = e->next) {
1522                                 assert(e->is_follower == 0);
1523                                 e->on_touched = 0;
1524                         }
1525                         Z->touched   = NULL;
1526                         Z->n_touched = 0;
1527
1528                         if (0 < n_touched && n_touched < Z->n_leader) {
1529                                 DB((dbg, LEVEL_2, "Split part%d by touched\n", Z->nr));
1530                                 split(&Z, touched, env);
1531                         } else
1532                                 assert(n_touched <= Z->n_leader);
1533                 }
1534         }
1535
1536         /* combine temporary leader and follower list */
1537         for (idx = -1; idx <= X->max_user_inputs; ++idx) {
1538                 /* empty the touched set: already done, just clear the list */
1539                 env->touched = NULL;
1540
1541                 collect_touched(&X->Leader, idx, env);
1542                 collect_touched(&X->Follower, idx, env);
1543
1544                 for (Z = env->touched; Z != NULL; Z = N) {
1545                         node_t   *e;
1546                         node_t   *touched  = Z->touched;
1547                         unsigned n_touched = Z->n_touched;
1548
1549                         assert(Z->touched != NULL);
1550
1551                         /* beware, split might change Z */
1552                         N = Z->touched_next;
1553
1554                         /* remove it from the touched set */
1555                         Z->on_touched = 0;
1556
1557                         /* Empty local Z.touched. */
1558                         for (e = touched; e != NULL; e = e->next) {
1559                                 assert(e->is_follower == 0);
1560                                 e->on_touched = 0;
1561                         }
1562                         Z->touched   = NULL;
1563                         Z->n_touched = 0;
1564
1565                         if (0 < n_touched && n_touched < Z->n_leader) {
1566                                 DB((dbg, LEVEL_2, "Split part%d by touched\n", Z->nr));
1567                                 split(&Z, touched, env);
1568                         } else
1569                                 assert(n_touched <= Z->n_leader);
1570                 }
1571         }
1572 }  /* cause_splits */
1573
1574 /**
1575  * Implements split_by_what(): Split a partition by characteristics given
1576  * by the what function.
1577  *
1578  * @param X     the partition to split
1579  * @param What  a function returning an Id for every node of the partition X
1580  * @param P     a list to store the result partitions
1581  * @param env   the environment
1582  *
1583  * @return *P
1584  */
1585 static partition_t *split_by_what(partition_t *X, what_func What,
1586                                   partition_t **P, environment_t *env) {
1587         node_t          *x, *S;
1588         listmap_t       map;
1589         listmap_entry_t *iter;
1590         partition_t     *R;
1591
1592         /* Let map be an empty mapping from the range of What to (local) list of Nodes. */
1593         listmap_init(&map);
1594         list_for_each_entry(node_t, x, &X->Leader, node_list) {
1595                 void            *id = What(x, env);
1596                 listmap_entry_t *entry;
1597
1598                 if (id == NULL) {
1599                         /* input not allowed, ignore */
1600                         continue;
1601                 }
1602                 /* Add x to map[What(x)]. */
1603                 entry = listmap_find(&map, id);
1604                 x->next     = entry->list;
1605                 entry->list = x;
1606         }
1607         /* Let P be a set of Partitions. */
1608
1609         /* for all sets S except one in the range of map do */
1610         for (iter = map.values; iter != NULL; iter = iter->next) {
1611                 if (iter->next == NULL) {
1612                         /* this is the last entry, ignore */
1613                         break;
1614                 }
1615                 S = iter->list;
1616
1617                 /* Add SPLIT( X, S ) to P. */
1618                 DB((dbg, LEVEL_2, "Split part%d by WHAT = %s\n", X->nr, what_reason));
1619                 R = split(&X, S, env);
1620                 R->split_next = *P;
1621                 *P            = R;
1622         }
1623         /* Add X to P. */
1624         X->split_next = *P;
1625         *P            = X;
1626
1627         listmap_term(&map);
1628         return *P;
1629 }  /* split_by_what */
1630
1631 /** lambda n.(n.type) */
1632 static void *lambda_type(const node_t *node, environment_t *env) {
1633         (void)env;
1634         return node->type.tv;
1635 }  /* lambda_type */
1636
1637 /** lambda n.(n.opcode) */
1638 static void *lambda_opcode(const node_t *node, environment_t *env) {
1639         opcode_key_t key, *entry;
1640         ir_node      *irn = node->node;
1641
1642         key.code   = get_irn_opcode(irn);
1643         key.mode   = get_irn_mode(irn);
1644         key.arity  = get_irn_arity(irn);
1645         key.u.proj = 0;
1646         key.u.ent  = NULL;
1647
1648         switch (get_irn_opcode(irn)) {
1649         case iro_Proj:
1650                 key.u.proj = get_Proj_proj(irn);
1651                 break;
1652         case iro_Sel:
1653                 key.u.ent = get_Sel_entity(irn);
1654                 break;
1655         case iro_Conv:
1656                 key.u.intVal = get_Conv_strict(irn);
1657                 break;
1658         case iro_Div:
1659                 key.u.intVal = is_Div_remainderless(irn);
1660                 break;
1661         default:
1662                 break;
1663         }
1664
1665         entry = set_insert(env->opcode2id_map, &key, sizeof(key), opcode_hash(&key));
1666         return entry;
1667 }  /* lambda_opcode */
1668
1669 /** lambda n.(n[i].partition) */
1670 static void *lambda_partition(const node_t *node, environment_t *env) {
1671         ir_node *skipped = skip_Proj(node->node);
1672         ir_node *pred;
1673         node_t  *p;
1674         int     i = env->lambda_input;
1675
1676         if (i >= get_irn_arity(node->node)) {
1677                 /*
1678                  * We are outside the allowed range: This can happen even
1679                  * if we have split by opcode first: doing so might move Followers
1680                  * to Leaders and those will have a different opcode!
1681                  * Note that in this case the partition is on the cprop list and will be
1682                  * split again.
1683                  */
1684                 return NULL;
1685         }
1686
1687         /* ignore the "control input" for non-pinned nodes
1688            if we are running in GCSE mode */
1689         if (i < env->end_idx && get_irn_pinned(skipped) != op_pin_state_pinned)
1690                 return NULL;
1691
1692         pred = i == -1 ? get_irn_n(skipped, i) : get_irn_n(node->node, i);
1693         p    = get_irn_node(pred);
1694
1695         return p->part;
1696 }  /* lambda_partition */
1697
1698 /** lambda n.(n[i].partition) for commutative nodes */
1699 static void *lambda_commutative_partition(const node_t *node, environment_t *env) {
1700         ir_node     *irn     = node->node;
1701         ir_node     *skipped = skip_Proj(irn);
1702         ir_node     *pred, *left, *right;
1703         node_t      *p;
1704         partition_t *pl, *pr;
1705         int         i = env->lambda_input;
1706
1707         if (i >= get_irn_arity(node->node)) {
1708                 /*
1709                  * We are outside the allowed range: This can happen even
1710                  * if we have split by opcode first: doing so might move Followers
1711                  * to Leaders and those will have a different opcode!
1712                  * Note that in this case the partition is on the cprop list and will be
1713                  * split again.
1714                  */
1715                 return NULL;
1716         }
1717
1718         /* ignore the "control input" for non-pinned nodes
1719            if we are running in GCSE mode */
1720         if (i < env->end_idx && get_irn_pinned(skipped) != op_pin_state_pinned)
1721                 return NULL;
1722
1723         if (i == -1) {
1724                 pred = get_irn_n(skipped, i);
1725                 p    = get_irn_node(pred);
1726                 return p->part;
1727         }
1728
1729         if (is_op_commutative(get_irn_op(irn))) {
1730                 /* normalize partition order by returning the "smaller" on input 0,
1731                    the "bigger" on input 1. */
1732                 left  = get_binop_left(irn);
1733                 pl    = get_irn_node(left)->part;
1734                 right = get_binop_right(irn);
1735                 pr    = get_irn_node(right)->part;
1736
1737                 if (i == 0)
1738                         return pl < pr ? pl : pr;
1739                 else
1740                 return pl > pr ? pl : pr;
1741         } else {
1742                 /* a not split out Follower */
1743                 pred = get_irn_n(irn, i);
1744                 p    = get_irn_node(pred);
1745
1746                 return p->part;
1747         }
1748 }  /* lambda_commutative_partition */
1749
1750 /**
1751  * Returns true if a type is a constant (and NOT Top
1752  * or Bottom).
1753  */
1754 static int is_con(const lattice_elem_t type) {
1755         /* be conservative */
1756         if (is_tarval(type.tv))
1757                 return tarval_is_constant(type.tv);
1758         return is_entity(type.sym.entity_p);
1759 }  /* is_con */
1760
1761 /**
1762  * Implements split_by().
1763  *
1764  * @param X    the partition to split
1765  * @param env  the environment
1766  */
1767 static void split_by(partition_t *X, environment_t *env) {
1768         partition_t *I, *P = NULL;
1769         int         input;
1770
1771         dump_partition("split_by", X);
1772
1773         if (X->n_leader == 1) {
1774                 /* we have only one leader, no need to split, just check it's type */
1775                 node_t *x = get_first_node(X);
1776                 X->type_is_T_or_C = x->type.tv == tarval_top || is_con(x->type);
1777                 return;
1778         }
1779
1780         DEBUG_ONLY(what_reason = "lambda n.(n.type)";)
1781         P = split_by_what(X, lambda_type, &P, env);
1782         dump_split_list(P);
1783
1784         /* adjust the type tags, we have split partitions by type */
1785         for (I = P; I != NULL; I = I->split_next) {
1786                 node_t *x = get_first_node(I);
1787                 I->type_is_T_or_C = x->type.tv == tarval_top || is_con(x->type);
1788         }
1789
1790         do {
1791                 partition_t *Y = P;
1792
1793                 P = P->split_next;
1794                 if (Y->n_leader > 1) {
1795                         /* we do not want split the TOP or constant partitions */
1796                         if (! Y->type_is_T_or_C) {
1797                                 partition_t *Q = NULL;
1798
1799                                 DEBUG_ONLY(what_reason = "lambda n.(n.opcode)";)
1800                                 Q = split_by_what(Y, lambda_opcode, &Q, env);
1801                                 dump_split_list(Q);
1802
1803                                 do {
1804                                         partition_t *Z = Q;
1805
1806                                         Q = Q->split_next;
1807                                         if (Z->n_leader > 1) {
1808                                                 const node_t *first = get_first_node(Z);
1809                                                 int          arity  = get_irn_arity(first->node);
1810                                                 partition_t  *R, *S;
1811                                                 what_func    what = lambda_partition;
1812                                                 DEBUG_ONLY(char buf[64];)
1813
1814                                                 if (env->commutative && is_op_commutative(get_irn_op(first->node)))
1815                                                         what = lambda_commutative_partition;
1816
1817                                                 /*
1818                                                  * BEWARE: during splitting by input 2 for instance we might
1819                                                  * create new partitions which are different by input 1, so collect
1820                                                  * them and split further.
1821                                                  */
1822                                                 Z->split_next = NULL;
1823                                                 R             = Z;
1824                                                 S             = NULL;
1825                                                 for (input = arity - 1; input >= -1; --input) {
1826                                                         do {
1827                                                                 partition_t *Z_prime = R;
1828
1829                                                                 R = R->split_next;
1830                                                                 if (Z_prime->n_leader > 1) {
1831                                                                         env->lambda_input = input;
1832                                                                         DEBUG_ONLY(snprintf(buf, sizeof(buf), "lambda n.(n[%d].partition)", input);)
1833                                                                         DEBUG_ONLY(what_reason = buf;)
1834                                                                         S = split_by_what(Z_prime, what, &S, env);
1835                                                                         dump_split_list(S);
1836                                                                 } else {
1837                                                                         Z_prime->split_next = S;
1838                                                                         S                   = Z_prime;
1839                                                                 }
1840                                                         } while (R != NULL);
1841                                                         R = S;
1842                                                         S = NULL;
1843                                                 }
1844                                         }
1845                                 } while (Q != NULL);
1846                         }
1847                 }
1848         } while (P != NULL);
1849 }  /* split_by */
1850
1851 /**
1852  * (Re-)compute the type for a given node.
1853  *
1854  * @param node  the node
1855  */
1856 static void default_compute(node_t *node) {
1857         int     i;
1858         ir_node *irn = node->node;
1859
1860         /* if any of the data inputs have type top, the result is type top */
1861         for (i = get_irn_arity(irn) - 1; i >= 0; --i) {
1862                 ir_node *pred = get_irn_n(irn, i);
1863                 node_t  *p    = get_irn_node(pred);
1864
1865                 if (p->type.tv == tarval_top) {
1866                         node->type.tv = tarval_top;
1867                         return;
1868                 }
1869         }
1870
1871         if (get_irn_mode(node->node) == mode_X)
1872                 node->type.tv = tarval_reachable;
1873         else
1874                 node->type.tv = computed_value(irn);
1875 }  /* default_compute */
1876
1877 /**
1878  * (Re-)compute the type for a Block node.
1879  *
1880  * @param node  the node
1881  */
1882 static void compute_Block(node_t *node) {
1883         int     i;
1884         ir_node *block = node->node;
1885
1886         if (block == get_irg_start_block(current_ir_graph)) {
1887                 /* start block is always reachable */
1888                 node->type.tv = tarval_reachable;
1889                 return;
1890         }
1891
1892         for (i = get_Block_n_cfgpreds(block) - 1; i >= 0; --i) {
1893                 node_t *pred = get_irn_node(get_Block_cfgpred(block, i));
1894
1895                 if (pred->type.tv == tarval_reachable) {
1896                         /* A block is reachable, if at least of predecessor is reachable. */
1897                         node->type.tv = tarval_reachable;
1898                         return;
1899                 }
1900         }
1901         node->type.tv = tarval_top;
1902 }  /* compute_Block */
1903
1904 /**
1905  * (Re-)compute the type for a Bad node.
1906  *
1907  * @param node  the node
1908  */
1909 static void compute_Bad(node_t *node) {
1910         /* Bad nodes ALWAYS compute Top */
1911         node->type.tv = tarval_top;
1912 }  /* compute_Bad */
1913
1914 /**
1915  * (Re-)compute the type for an Unknown node.
1916  *
1917  * @param node  the node
1918  */
1919 static void compute_Unknown(node_t *node) {
1920         /* While Unknown nodes should compute Top this is dangerous:
1921          * a Top input to a Cond would lead to BOTH control flows unreachable.
1922          * While this is correct in the given semantics, it would destroy the Firm
1923          * graph.
1924          *
1925          * It would be safe to compute Top IF it can be assured, that only Cmp
1926          * nodes are inputs to Conds. We check that first.
1927          * This is the way Frontends typically build Firm, but some optimizations
1928          * (cond_eval for instance) might replace them by Phib's...
1929          */
1930         node->type.tv = tarval_UNKNOWN;
1931 }  /* compute_Unknown */
1932
1933 /**
1934  * (Re-)compute the type for a Jmp node.
1935  *
1936  * @param node  the node
1937  */
1938 static void compute_Jmp(node_t *node) {
1939         node_t *block = get_irn_node(get_nodes_block(node->node));
1940
1941         node->type = block->type;
1942 }  /* compute_Jmp */
1943
1944 /**
1945  * (Re-)compute the type for the Return node.
1946  *
1947  * @param node  the node
1948  */
1949 static void compute_Return(node_t *node) {
1950         /* The Return node is NOT dead if it is in a reachable block.
1951          * This is already checked in compute(). so we can return
1952          * Reachable here. */
1953         node->type.tv = tarval_reachable;
1954 }  /* compute_Return */
1955
1956 /**
1957  * (Re-)compute the type for the End node.
1958  *
1959  * @param node  the node
1960  */
1961 static void compute_End(node_t *node) {
1962         /* the End node is NOT dead of course */
1963         node->type.tv = tarval_reachable;
1964 }  /* compute_End */
1965
1966 /**
1967  * (Re-)compute the type for a Call.
1968  *
1969  * @param node  the node
1970  */
1971 static void compute_Call(node_t *node) {
1972         /*
1973          * A Call computes always bottom, even if it has Unknown
1974          * predecessors.
1975          */
1976         node->type.tv = tarval_bottom;
1977 }  /* compute_Call */
1978
1979 /**
1980  * (Re-)compute the type for a SymConst node.
1981  *
1982  * @param node  the node
1983  */
1984 static void compute_SymConst(node_t *node) {
1985         ir_node *irn = node->node;
1986         node_t  *block = get_irn_node(get_nodes_block(irn));
1987
1988         if (block->type.tv == tarval_unreachable) {
1989                 node->type.tv = tarval_top;
1990                 return;
1991         }
1992         switch (get_SymConst_kind(irn)) {
1993         case symconst_addr_ent:
1994         /* case symconst_addr_name: cannot handle this yet */
1995                 node->type.sym = get_SymConst_symbol(irn);
1996                 break;
1997         default:
1998                 node->type.tv = computed_value(irn);
1999         }
2000 }  /* compute_SymConst */
2001
2002 /**
2003  * (Re-)compute the type for a Phi node.
2004  *
2005  * @param node  the node
2006  */
2007 static void compute_Phi(node_t *node) {
2008         int            i;
2009         ir_node        *phi = node->node;
2010         lattice_elem_t type;
2011
2012         /* if a Phi is in a unreachable block, its type is TOP */
2013         node_t *block = get_irn_node(get_nodes_block(phi));
2014
2015         if (block->type.tv == tarval_unreachable) {
2016                 node->type.tv = tarval_top;
2017                 return;
2018         }
2019
2020         /* Phi implements the Meet operation */
2021         type.tv = tarval_top;
2022         for (i = get_Phi_n_preds(phi) - 1; i >= 0; --i) {
2023                 node_t *pred   = get_irn_node(get_Phi_pred(phi, i));
2024                 node_t *pred_X = get_irn_node(get_Block_cfgpred(block->node, i));
2025
2026                 if (pred_X->type.tv == tarval_unreachable || pred->type.tv == tarval_top) {
2027                         /* ignore TOP inputs: We must check here for unreachable blocks,
2028                            because Firm constants live in the Start Block are NEVER Top.
2029                            Else, a Phi (1,2) will produce Bottom, even if the 2 for instance
2030                            comes from a unreachable input. */
2031                         continue;
2032                 }
2033                 if (pred->type.tv == tarval_bottom) {
2034                         node->type.tv = tarval_bottom;
2035                         return;
2036                 } else if (type.tv == tarval_top) {
2037                         /* first constant found */
2038                         type = pred->type;
2039                 } else if (type.tv != pred->type.tv) {
2040                         /* different constants or tarval_bottom */
2041                         node->type.tv = tarval_bottom;
2042                         return;
2043                 }
2044                 /* else nothing, constants are the same */
2045         }
2046         node->type = type;
2047 }  /* compute_Phi */
2048
2049 /**
2050  * (Re-)compute the type for an Add. Special case: one nodes is a Zero Const.
2051  *
2052  * @param node  the node
2053  */
2054 static void compute_Add(node_t *node) {
2055         ir_node        *sub = node->node;
2056         node_t         *l   = get_irn_node(get_Add_left(sub));
2057         node_t         *r   = get_irn_node(get_Add_right(sub));
2058         lattice_elem_t a    = l->type;
2059         lattice_elem_t b    = r->type;
2060         ir_mode        *mode;
2061
2062         if (a.tv == tarval_top || b.tv == tarval_top) {
2063                 node->type.tv = tarval_top;
2064         } else if (a.tv == tarval_bottom || b.tv == tarval_bottom) {
2065                 node->type.tv = tarval_bottom;
2066         } else {
2067                 /* x + 0 = 0 + x = x, but beware of floating point +0 + -0, so we
2068                    must call tarval_add() first to handle this case! */
2069                 if (is_tarval(a.tv)) {
2070                         if (is_tarval(b.tv)) {
2071                                 node->type.tv = tarval_add(a.tv, b.tv);
2072                                 return;
2073                         }
2074                         mode = get_tarval_mode(a.tv);
2075                         if (a.tv == get_mode_null(mode)) {
2076                                 node->type = b;
2077                                 return;
2078                         }
2079                 } else if (is_tarval(b.tv)) {
2080                         mode = get_tarval_mode(b.tv);
2081                         if (b.tv == get_mode_null(mode)) {
2082                                 node->type = a;
2083                                 return;
2084                         }
2085                 }
2086                 node->type.tv = tarval_bottom;
2087         }
2088 }  /* compute_Add */
2089
2090 /**
2091  * (Re-)compute the type for a Sub. Special case: both nodes are congruent.
2092  *
2093  * @param node  the node
2094  */
2095 static void compute_Sub(node_t *node) {
2096         ir_node        *sub = node->node;
2097         node_t         *l   = get_irn_node(get_Sub_left(sub));
2098         node_t         *r   = get_irn_node(get_Sub_right(sub));
2099         lattice_elem_t a    = l->type;
2100         lattice_elem_t b    = r->type;
2101         tarval         *tv;
2102
2103         if (a.tv == tarval_top || b.tv == tarval_top) {
2104                 node->type.tv = tarval_top;
2105         } else if (is_con(a) && is_con(b)) {
2106                 if (is_tarval(a.tv) && is_tarval(b.tv)) {
2107                         node->type.tv = tarval_sub(a.tv, b.tv, get_irn_mode(sub));
2108                 } else if (is_tarval(a.tv) && tarval_is_null(a.tv)) {
2109                         node->type = b;
2110                 } else if (is_tarval(b.tv) && tarval_is_null(b.tv)) {
2111                         node->type = a;
2112                 } else {
2113                         node->type.tv = tarval_bottom;
2114                 }
2115         } else if (r->part == l->part &&
2116                    (!mode_is_float(get_irn_mode(l->node)))) {
2117                 /*
2118                  * BEWARE: a - a is NOT always 0 for floating Point values, as
2119                  * NaN op NaN = NaN, so we must check this here.
2120                  */
2121                 ir_mode *mode = get_irn_mode(sub);
2122                 tv = get_mode_null(mode);
2123
2124                 /* if the node was ONCE evaluated by all constants, but now
2125                    this breaks AND we get from the argument partitions a different
2126                    result, switch to bottom.
2127                    This happens because initially all nodes are in the same partition ... */
2128                 if (node->type.tv != tv)
2129                         tv = tarval_bottom;
2130                 node->type.tv = tv;
2131         } else {
2132                 node->type.tv = tarval_bottom;
2133         }
2134 }  /* compute_Sub */
2135
2136 /**
2137  * (Re-)compute the type for an Eor. Special case: both nodes are congruent.
2138  *
2139  * @param node  the node
2140  */
2141 static void compute_Eor(node_t *node) {
2142         ir_node        *eor = node->node;
2143         node_t         *l   = get_irn_node(get_Eor_left(eor));
2144         node_t         *r   = get_irn_node(get_Eor_right(eor));
2145         lattice_elem_t a    = l->type;
2146         lattice_elem_t b    = r->type;
2147         tarval         *tv;
2148
2149         if (a.tv == tarval_top || b.tv == tarval_top) {
2150                 node->type.tv = tarval_top;
2151         } else if (is_con(a) && is_con(b)) {
2152                 if (is_tarval(a.tv) && is_tarval(b.tv)) {
2153                         node->type.tv = tarval_eor(a.tv, b.tv);
2154                 } else if (is_tarval(a.tv) && tarval_is_null(a.tv)) {
2155                         node->type = b;
2156                 } else if (is_tarval(b.tv) && tarval_is_null(b.tv)) {
2157                         node->type = a;
2158                 } else {
2159                         node->type.tv = tarval_bottom;
2160                 }
2161         } else if (r->part == l->part) {
2162                 ir_mode *mode = get_irn_mode(eor);
2163                 tv = get_mode_null(mode);
2164
2165                 /* if the node was ONCE evaluated by all constants, but now
2166                    this breaks AND we get from the argument partitions a different
2167                    result, switch to bottom.
2168                    This happens because initially all nodes are in the same partition ... */
2169                 if (node->type.tv != tv)
2170                         tv = tarval_bottom;
2171                 node->type.tv = tv;
2172         } else {
2173                 node->type.tv = tarval_bottom;
2174         }
2175 }  /* compute_Eor */
2176
2177 /**
2178  * (Re-)compute the type for Cmp.
2179  *
2180  * @param node  the node
2181  */
2182 static void compute_Cmp(node_t *node) {
2183         ir_node        *cmp  = node->node;
2184         node_t         *l    = get_irn_node(get_Cmp_left(cmp));
2185         node_t         *r    = get_irn_node(get_Cmp_right(cmp));
2186         lattice_elem_t a     = l->type;
2187         lattice_elem_t b     = r->type;
2188
2189         if (a.tv == tarval_top || b.tv == tarval_top) {
2190                 node->type.tv = tarval_top;
2191         } else if (r->part == l->part) {
2192                 /* both nodes congruent, we can probably do something */
2193                 node->type.tv = tarval_b_true;
2194         } else if (is_con(a) && is_con(b)) {
2195                 /* both nodes are constants, we can probably do something */
2196                 node->type.tv = tarval_b_true;
2197         } else {
2198                 node->type.tv = tarval_bottom;
2199         }
2200 }  /* compute_Cmp */
2201
2202 /**
2203  * (Re-)compute the type for a Proj(Cmp).
2204  *
2205  * @param node  the node
2206  * @param cond  the predecessor Cmp node
2207  */
2208 static void compute_Proj_Cmp(node_t *node, ir_node *cmp) {
2209         ir_node        *proj = node->node;
2210         node_t         *l    = get_irn_node(get_Cmp_left(cmp));
2211         node_t         *r    = get_irn_node(get_Cmp_right(cmp));
2212         lattice_elem_t a     = l->type;
2213         lattice_elem_t b     = r->type;
2214         pn_Cmp         pnc   = get_Proj_proj(proj);
2215         tarval         *tv;
2216
2217         if (a.tv == tarval_top || b.tv == tarval_top) {
2218                 node->type.tv = tarval_undefined;
2219         } else if (is_con(a) && is_con(b)) {
2220                 default_compute(node);
2221         } else if (r->part == l->part &&
2222                    (!mode_is_float(get_irn_mode(l->node)) || pnc == pn_Cmp_Lt || pnc == pn_Cmp_Gt)) {
2223                 /*
2224                  * BEWARE: a == a is NOT always True for floating Point values, as
2225                  * NaN != NaN is defined, so we must check this here.
2226                  */
2227                 tv = pnc & pn_Cmp_Eq ? tarval_b_true: tarval_b_false;
2228
2229                 /* if the node was ONCE evaluated by all constants, but now
2230                    this breaks AND we get from the argument partitions a different
2231                    result, switch to bottom.
2232                    This happens because initially all nodes are in the same partition ... */
2233                 if (node->type.tv != tv)
2234                         tv = tarval_bottom;
2235                 node->type.tv = tv;
2236         } else {
2237                 node->type.tv = tarval_bottom;
2238         }
2239 }  /* compute_Proj_Cmp */
2240
2241 /**
2242  * (Re-)compute the type for a Proj(Cond).
2243  *
2244  * @param node  the node
2245  * @param cond  the predecessor Cond node
2246  */
2247 static void compute_Proj_Cond(node_t *node, ir_node *cond) {
2248         ir_node *proj     = node->node;
2249         long    pnc       = get_Proj_proj(proj);
2250         ir_node *sel      = get_Cond_selector(cond);
2251         node_t  *selector = get_irn_node(sel);
2252
2253         /*
2254          * Note: it is crucial for the monotony that the Proj(Cond)
2255          * are evaluates after all predecessors of the Cond selector are
2256          * processed.
2257          * Example
2258          *
2259          * if (x != 0)
2260          *
2261          * Due to the fact that 0 is a const, the Cmp gets immediately
2262          * on the cprop list. It will be evaluated before x is evaluated,
2263          * might leaving x as Top. When later x is evaluated, the Cmp
2264          * might change its value.
2265          * BUT if the Cond is evaluated before this happens, Proj(Cond, FALSE)
2266          * gets R, and later changed to F if Cmp is evaluated to True!
2267          *
2268          * We prevent this by putting Conds in an extra cprop_X queue, which
2269          * gets evaluated after the cprop queue is empty.
2270          *
2271          * Note that this even happens with Click's original algorithm, if
2272          * Cmp(x, 0) is evaluated to True first and later changed to False
2273          * if x was Top first and later changed to a Const ...
2274          * It is unclear how Click solved that problem ...
2275          *
2276          * However, in rare cases even this does not help, if a Top reaches
2277          * a compare  through a Phi, than Proj(Cond) is evaluated changing
2278          * the type of the Phi to something other.
2279          * So, we take the last resort and bind the type to R once
2280          * it is calculated.
2281          *
2282          * (This might be even the way Click works around the whole problem).
2283          *
2284          * Finally, we may miss some optimization possibilities due to this:
2285          *
2286          * x = phi(Top, y)
2287          * if (x == 0)
2288          *
2289          * If Top reaches the if first, than we decide for != here.
2290          * If y later is evaluated to 0, we cannot revert this decision
2291          * and must live with both outputs enabled. If this happens,
2292          * we get an unresolved if (true) in the code ...
2293          *
2294          * In Click's version where this decision is done at the Cmp,
2295          * the Cmp is NOT optimized away than (if y evaluated to 1
2296          * for instance) and we get a if (1 == 0) here ...
2297          *
2298          * Both solutions are suboptimal.
2299          * At least, we could easily detect this problem and run
2300          * cf_opt() (or even combo) again :-(
2301          */
2302         if (node->type.tv == tarval_reachable)
2303                 return;
2304
2305         if (get_irn_mode(sel) == mode_b) {
2306                 /* an IF */
2307                 if (pnc == pn_Cond_true) {
2308                         if (selector->type.tv == tarval_b_false) {
2309                                 node->type.tv = tarval_unreachable;
2310                         } else if (selector->type.tv == tarval_b_true) {
2311                                 node->type.tv = tarval_reachable;
2312                         } else if (selector->type.tv == tarval_bottom) {
2313                                 node->type.tv = tarval_reachable;
2314                         } else {
2315                                 assert(selector->type.tv == tarval_top);
2316                                 if (tarval_UNKNOWN == tarval_top) {
2317                                         /* any condition based on Top is "!=" */
2318                                         node->type.tv = tarval_unreachable;
2319                                 } else {
2320                                         node->type.tv = tarval_unreachable;
2321                                 }
2322                         }
2323                 } else {
2324                         assert(pnc == pn_Cond_false);
2325
2326                         if (selector->type.tv == tarval_b_false) {
2327                                 node->type.tv = tarval_reachable;
2328                         } else if (selector->type.tv == tarval_b_true) {
2329                                 node->type.tv = tarval_unreachable;
2330                         } else if (selector->type.tv == tarval_bottom) {
2331                                 node->type.tv = tarval_reachable;
2332                         } else {
2333                                 assert(selector->type.tv == tarval_top);
2334                                 if (tarval_UNKNOWN == tarval_top) {
2335                                         /* any condition based on Top is "!=" */
2336                                         node->type.tv = tarval_reachable;
2337                                 } else {
2338                                         node->type.tv = tarval_unreachable;
2339                                 }
2340                         }
2341                 }
2342         } else {
2343                 /* an SWITCH */
2344                 if (selector->type.tv == tarval_bottom) {
2345                         node->type.tv = tarval_reachable;
2346                 } else if (selector->type.tv == tarval_top) {
2347                         if (tarval_UNKNOWN == tarval_top &&
2348                             pnc == get_Cond_defaultProj(cond)) {
2349                                 /* a switch based of Top is always "default" */
2350                                 node->type.tv = tarval_reachable;
2351                         } else {
2352                                 node->type.tv = tarval_unreachable;
2353                         }
2354                 } else {
2355                         long value = get_tarval_long(selector->type.tv);
2356                         if (pnc == get_Cond_defaultProj(cond)) {
2357                                 /* default switch, have to check ALL other cases */
2358                                 int i;
2359
2360                                 for (i = get_irn_n_outs(cond) - 1; i >= 0; --i) {
2361                                         ir_node *succ = get_irn_out(cond, i);
2362
2363                                         if (succ == proj)
2364                                                 continue;
2365                                         if (value == get_Proj_proj(succ)) {
2366                                                 /* we found a match, will NOT take the default case */
2367                                                 node->type.tv = tarval_unreachable;
2368                                                 return;
2369                                         }
2370                                 }
2371                                 /* all cases checked, no match, will take default case */
2372                                 node->type.tv = tarval_reachable;
2373                         } else {
2374                                 /* normal case */
2375                                 node->type.tv = value == pnc ? tarval_reachable : tarval_unreachable;
2376                         }
2377                 }
2378         }
2379 }  /* compute_Proj_Cond */
2380
2381 /**
2382  * (Re-)compute the type for a Proj-Node.
2383  *
2384  * @param node  the node
2385  */
2386 static void compute_Proj(node_t *node) {
2387         ir_node *proj = node->node;
2388         ir_mode *mode = get_irn_mode(proj);
2389         node_t  *block = get_irn_node(get_nodes_block(skip_Proj(proj)));
2390         ir_node *pred  = get_Proj_pred(proj);
2391
2392         if (block->type.tv == tarval_unreachable) {
2393                 /* a Proj in a unreachable Block stay Top */
2394                 node->type.tv = tarval_top;
2395                 return;
2396         }
2397         if (get_irn_node(pred)->type.tv == tarval_top && !is_Cond(pred)) {
2398                 /* if the predecessor is Top, its Proj follow */
2399                 node->type.tv = tarval_top;
2400                 return;
2401         }
2402
2403         if (mode == mode_M) {
2404                 /* mode M is always bottom */
2405                 node->type.tv = tarval_bottom;
2406                 return;
2407         }
2408         if (mode != mode_X) {
2409                 if (is_Cmp(pred))
2410                         compute_Proj_Cmp(node, pred);
2411                 else
2412                         default_compute(node);
2413                 return;
2414         }
2415         /* handle mode_X nodes */
2416
2417         switch (get_irn_opcode(pred)) {
2418         case iro_Start:
2419                 /* the Proj_X from the Start is always reachable.
2420                    However this is already handled at the top. */
2421                 node->type.tv = tarval_reachable;
2422                 break;
2423         case iro_Cond:
2424                 compute_Proj_Cond(node, pred);
2425                 break;
2426         default:
2427                 default_compute(node);
2428         }
2429 }  /* compute_Proj */
2430
2431 /**
2432  * (Re-)compute the type for a Confirm.
2433  *
2434  * @param node  the node
2435  */
2436 static void compute_Confirm(node_t *node) {
2437         ir_node *confirm = node->node;
2438         node_t  *pred = get_irn_node(get_Confirm_value(confirm));
2439
2440         if (get_Confirm_cmp(confirm) == pn_Cmp_Eq) {
2441                 node_t *bound = get_irn_node(get_Confirm_bound(confirm));
2442
2443                 if (is_con(bound->type)) {
2444                         /* is equal to a constant */
2445                         node->type = bound->type;
2446                         return;
2447                 }
2448         }
2449         /* a Confirm is a copy OR a Const */
2450         node->type = pred->type;
2451 }  /* compute_Confirm */
2452
2453 /**
2454  * (Re-)compute the type for a Max.
2455  *
2456  * @param node  the node
2457  */
2458 static void compute_Max(node_t *node) {
2459         ir_node        *op = node->node;
2460         node_t         *l  = get_irn_node(get_binop_left(op));
2461         node_t         *r  = get_irn_node(get_binop_right(op));
2462         lattice_elem_t a   = l->type;
2463         lattice_elem_t b   = r->type;
2464
2465         if (a.tv == tarval_top || b.tv == tarval_top) {
2466                 node->type.tv = tarval_top;
2467         } else if (is_con(a) && is_con(b)) {
2468                 /* both nodes are constants, we can probably do something */
2469                 if (a.tv == b.tv) {
2470                         /* this case handles SymConsts as well */
2471                         node->type = a;
2472                 } else {
2473                         ir_mode *mode   = get_irn_mode(op);
2474                         tarval  *tv_min = get_mode_min(mode);
2475
2476                         if (a.tv == tv_min)
2477                                 node->type = b;
2478                         else if (b.tv == tv_min)
2479                                 node->type = a;
2480                         else if (is_tarval(a.tv) && is_tarval(b.tv)) {
2481                                 if (tarval_cmp(a.tv, b.tv) & pn_Cmp_Gt)
2482                                         node->type.tv = a.tv;
2483                                 else
2484                                         node->type.tv = b.tv;
2485                         } else {
2486                                 node->type.tv = tarval_bad;
2487                         }
2488                 }
2489         } else if (r->part == l->part) {
2490                 /* both nodes congruent, we can probably do something */
2491                 node->type = a;
2492         } else {
2493                 node->type.tv = tarval_bottom;
2494         }
2495 }  /* compute_Max */
2496
2497 /**
2498  * (Re-)compute the type for a Min.
2499  *
2500  * @param node  the node
2501  */
2502 static void compute_Min(node_t *node) {
2503         ir_node        *op = node->node;
2504         node_t         *l  = get_irn_node(get_binop_left(op));
2505         node_t         *r  = get_irn_node(get_binop_right(op));
2506         lattice_elem_t a   = l->type;
2507         lattice_elem_t b   = r->type;
2508
2509         if (a.tv == tarval_top || b.tv == tarval_top) {
2510                 node->type.tv = tarval_top;
2511         } else if (is_con(a) && is_con(b)) {
2512                 /* both nodes are constants, we can probably do something */
2513                 if (a.tv == b.tv) {
2514                         /* this case handles SymConsts as well */
2515                         node->type = a;
2516                 } else {
2517                         ir_mode *mode   = get_irn_mode(op);
2518                         tarval  *tv_max = get_mode_max(mode);
2519
2520                         if (a.tv == tv_max)
2521                                 node->type = b;
2522                         else if (b.tv == tv_max)
2523                                 node->type = a;
2524                         else if (is_tarval(a.tv) && is_tarval(b.tv)) {
2525                                 if (tarval_cmp(a.tv, b.tv) & pn_Cmp_Gt)
2526                                         node->type.tv = a.tv;
2527                                 else
2528                                         node->type.tv = b.tv;
2529                         } else {
2530                                 node->type.tv = tarval_bad;
2531                         }
2532                 }
2533         } else if (r->part == l->part) {
2534                 /* both nodes congruent, we can probably do something */
2535                 node->type = a;
2536         } else {
2537                 node->type.tv = tarval_bottom;
2538         }
2539 }  /* compute_Min */
2540
2541 /**
2542  * (Re-)compute the type for a given node.
2543  *
2544  * @param node  the node
2545  */
2546 static void compute(node_t *node) {
2547         ir_node *irn = node->node;
2548         compute_func func;
2549
2550 #ifndef VERIFY_MONOTONE
2551         /*
2552          * Once a node reaches bottom, the type cannot fall further
2553          * in the lattice and we can stop computation.
2554          * Do not take this exit if the monotony verifier is
2555          * enabled to catch errors.
2556          */
2557         if (node->type.tv == tarval_bottom)
2558                 return;
2559 #endif
2560
2561         if (is_no_Block(irn)) {
2562                 /* for pinned nodes, check its control input */
2563                 if (get_irn_pinned(skip_Proj(irn)) == op_pin_state_pinned) {
2564                         node_t *block = get_irn_node(get_nodes_block(irn));
2565
2566                         if (block->type.tv == tarval_unreachable) {
2567                                 node->type.tv = tarval_top;
2568                                 return;
2569                         }
2570                 }
2571         }
2572
2573         func = (compute_func)node->node->op->ops.generic;
2574         if (func != NULL)
2575                 func(node);
2576 }  /* compute */
2577
2578 /*
2579  * Identity functions: Note that one might thing that identity() is just a
2580  * synonym for equivalent_node(). While this is true, we cannot use it for the algorithm
2581  * here, because it expects that the identity node is one of the inputs, which is NOT
2582  * always true for equivalent_node() which can handle (and does sometimes) DAGs.
2583  * So, we have our own implementation, which copies some parts of equivalent_node()
2584  */
2585
2586 /**
2587  * Calculates the Identity for Phi nodes
2588  */
2589 static node_t *identity_Phi(node_t *node) {
2590         ir_node *phi    = node->node;
2591         ir_node *block  = get_nodes_block(phi);
2592         node_t  *n_part = NULL;
2593         int     i;
2594
2595         for (i = get_Phi_n_preds(phi) - 1; i >= 0; --i) {
2596                 node_t *pred_X = get_irn_node(get_Block_cfgpred(block, i));
2597
2598                 if (pred_X->type.tv == tarval_reachable) {
2599                         node_t *pred = get_irn_node(get_Phi_pred(phi, i));
2600
2601                         if (n_part == NULL)
2602                                 n_part = pred;
2603                         else if (n_part->part != pred->part) {
2604                                 /* incongruent inputs, not a follower */
2605                                 return node;
2606                         }
2607                 }
2608         }
2609         /* if n_part is NULL here, all inputs path are dead, the Phi computes
2610          * tarval_top, is in the TOP partition and should NOT being split! */
2611         assert(n_part != NULL);
2612         return n_part;
2613 }  /* identity_Phi */
2614
2615 /**
2616  * Calculates the Identity for commutative 0 neutral nodes.
2617  */
2618 static node_t *identity_comm_zero_binop(node_t *node) {
2619         ir_node *op   = node->node;
2620         node_t  *a    = get_irn_node(get_binop_left(op));
2621         node_t  *b    = get_irn_node(get_binop_right(op));
2622         ir_mode *mode = get_irn_mode(op);
2623         tarval  *zero;
2624
2625         /* for FP these optimizations are only allowed if fp_strict_algebraic is disabled */
2626         if (mode_is_float(mode) && (get_irg_fp_model(current_ir_graph) & fp_strict_algebraic))
2627                 return node;
2628
2629         /* node: no input should be tarval_top, else the binop would be also
2630          * Top and not being split. */
2631         zero = get_mode_null(mode);
2632         if (a->type.tv == zero)
2633                 return b;
2634         if (b->type.tv == zero)
2635                 return a;
2636         return node;
2637 }  /* identity_comm_zero_binop */
2638
2639 /**
2640  * Calculates the Identity for Shift nodes.
2641  */
2642 static node_t *identity_shift(node_t *node) {
2643         ir_node *op   = node->node;
2644         node_t  *b    = get_irn_node(get_binop_right(op));
2645         ir_mode *mode = get_irn_mode(b->node);
2646         tarval  *zero;
2647
2648         /* node: no input should be tarval_top, else the binop would be also
2649          * Top and not being split. */
2650         zero = get_mode_null(mode);
2651         if (b->type.tv == zero)
2652                 return get_irn_node(get_binop_left(op));
2653         return node;
2654 }  /* identity_shift */
2655
2656 /**
2657  * Calculates the Identity for Mul nodes.
2658  */
2659 static node_t *identity_Mul(node_t *node) {
2660         ir_node *op   = node->node;
2661         node_t  *a    = get_irn_node(get_Mul_left(op));
2662         node_t  *b    = get_irn_node(get_Mul_right(op));
2663         ir_mode *mode = get_irn_mode(op);
2664         tarval  *one;
2665
2666         /* for FP these optimizations are only allowed if fp_strict_algebraic is disabled */
2667         if (mode_is_float(mode) && (get_irg_fp_model(current_ir_graph) & fp_strict_algebraic))
2668                 return node;
2669
2670         /* node: no input should be tarval_top, else the binop would be also
2671          * Top and not being split. */
2672         one = get_mode_one(mode);
2673         if (a->type.tv == one)
2674                 return b;
2675         if (b->type.tv == one)
2676                 return a;
2677         return node;
2678 }  /* identity_Mul */
2679
2680 /**
2681  * Calculates the Identity for Sub nodes.
2682  */
2683 static node_t *identity_Sub(node_t *node) {
2684         ir_node *sub  = node->node;
2685         node_t  *b    = get_irn_node(get_Sub_right(sub));
2686         ir_mode *mode = get_irn_mode(sub);
2687
2688         /* for FP these optimizations are only allowed if fp_strict_algebraic is disabled */
2689         if (mode_is_float(mode) && (get_irg_fp_model(current_ir_graph) & fp_strict_algebraic))
2690                 return node;
2691
2692         /* node: no input should be tarval_top, else the binop would be also
2693          * Top and not being split. */
2694         if (b->type.tv == get_mode_null(mode))
2695                 return get_irn_node(get_Sub_left(sub));
2696         return node;
2697 }  /* identity_Sub */
2698
2699 /**
2700  * Calculates the Identity for And nodes.
2701  */
2702 static node_t *identity_And(node_t *node) {
2703         ir_node *and = node->node;
2704         node_t  *a   = get_irn_node(get_And_left(and));
2705         node_t  *b   = get_irn_node(get_And_right(and));
2706         tarval  *neutral = get_mode_all_one(get_irn_mode(and));
2707
2708         /* node: no input should be tarval_top, else the And would be also
2709          * Top and not being split. */
2710         if (a->type.tv == neutral)
2711                 return b;
2712         if (b->type.tv == neutral)
2713                 return a;
2714         return node;
2715 }  /* identity_And */
2716
2717 /**
2718  * Calculates the Identity for Confirm nodes.
2719  */
2720 static node_t *identity_Confirm(node_t *node) {
2721         ir_node *confirm = node->node;
2722
2723         /* a Confirm is always a Copy */
2724         return get_irn_node(get_Confirm_value(confirm));
2725 }  /* identity_Confirm */
2726
2727 /**
2728  * Calculates the Identity for Mux nodes.
2729  */
2730 static node_t *identity_Mux(node_t *node) {
2731         ir_node *mux = node->node;
2732         node_t  *t   = get_irn_node(get_Mux_true(mux));
2733         node_t  *f   = get_irn_node(get_Mux_false(mux));
2734         /*node_t  *sel; */
2735
2736         if (t->part == f->part)
2737                 return t;
2738
2739         /* for now, the 1-input identity is not supported */
2740 #if 0
2741         sel = get_irn_node(get_Mux_sel(mux));
2742
2743         /* Mux sel input is mode_b, so it is always a tarval */
2744         if (sel->type.tv == tarval_b_true)
2745                 return t;
2746         if (sel->type.tv == tarval_b_false)
2747                 return f;
2748 #endif
2749         return node;
2750 }  /* identity_Mux */
2751
2752 /**
2753  * Calculates the Identity for Min nodes.
2754  */
2755 static node_t *identity_Min(node_t *node) {
2756         ir_node *op   = node->node;
2757         node_t  *a    = get_irn_node(get_binop_left(op));
2758         node_t  *b    = get_irn_node(get_binop_right(op));
2759         ir_mode *mode = get_irn_mode(op);
2760         tarval  *tv_max;
2761
2762         if (a->part == b->part) {
2763                 /* leader of multiple predecessors */
2764                 return a;
2765         }
2766
2767         /* works even with NaN */
2768         tv_max = get_mode_max(mode);
2769         if (a->type.tv == tv_max)
2770                 return b;
2771         if (b->type.tv == tv_max)
2772                 return a;
2773         return node;
2774 }  /* identity_Min */
2775
2776 /**
2777  * Calculates the Identity for Max nodes.
2778  */
2779 static node_t *identity_Max(node_t *node) {
2780         ir_node *op   = node->node;
2781         node_t  *a    = get_irn_node(get_binop_left(op));
2782         node_t  *b    = get_irn_node(get_binop_right(op));
2783         ir_mode *mode = get_irn_mode(op);
2784         tarval  *tv_min;
2785
2786         if (a->part == b->part) {
2787                 /* leader of multiple predecessors */
2788                 return a;
2789         }
2790
2791         /* works even with NaN */
2792         tv_min = get_mode_min(mode);
2793         if (a->type.tv == tv_min)
2794                 return b;
2795         if (b->type.tv == tv_min)
2796                 return a;
2797         return node;
2798 }  /* identity_Max */
2799
2800 /**
2801  * Calculates the Identity for nodes.
2802  */
2803 static node_t *identity(node_t *node) {
2804         ir_node *irn = node->node;
2805
2806         switch (get_irn_opcode(irn)) {
2807         case iro_Phi:
2808                 return identity_Phi(node);
2809         case iro_Mul:
2810                 return identity_Mul(node);
2811         case iro_Add:
2812         case iro_Or:
2813         case iro_Eor:
2814                 return identity_comm_zero_binop(node);
2815         case iro_Shr:
2816         case iro_Shl:
2817         case iro_Shrs:
2818         case iro_Rotl:
2819                 return identity_shift(node);
2820         case iro_And:
2821                 return identity_And(node);
2822         case iro_Sub:
2823                 return identity_Sub(node);
2824         case iro_Confirm:
2825                 return identity_Confirm(node);
2826         case iro_Mux:
2827                 return identity_Mux(node);
2828         case iro_Min:
2829                 return identity_Min(node);
2830         case iro_Max:
2831                 return identity_Max(node);
2832         default:
2833                 return node;
2834         }
2835 }  /* identity */
2836
2837 /**
2838  * Node follower is a (new) follower of leader, segregate Leader
2839  * out edges.
2840  */
2841 static void segregate_def_use_chain_1(const ir_node *follower, node_t *leader) {
2842         ir_node *l   = leader->node;
2843         int     j, i, n = get_irn_n_outs(l);
2844
2845         DB((dbg, LEVEL_2, "%+F is a follower of %+F\n", follower, leader->node));
2846         /* The leader edges must remain sorted, but follower edges can
2847            be unsorted. */
2848         for (i = leader->n_followers + 1; i <= n; ++i) {
2849                 if (l->out[i].use == follower) {
2850                         ir_def_use_edge t = l->out[i];
2851
2852                         for (j = i - 1; j >= leader->n_followers + 1; --j)
2853                                 l->out[j + 1] = l->out[j];
2854                         ++leader->n_followers;
2855                         l->out[leader->n_followers] = t;
2856                         break;
2857                 }
2858         }
2859 }  /* segregate_def_use_chain_1 */
2860
2861 /**
2862  * Node follower is a (new) follower segregate its Leader
2863  * out edges.
2864  *
2865  * @param follower  the follower IR node
2866  */
2867 static void segregate_def_use_chain(const ir_node *follower) {
2868         int i;
2869
2870         for (i = get_irn_arity(follower) - 1; i >= 0; --i) {
2871                 node_t *pred = get_irn_node(get_irn_n(follower, i));
2872
2873                 segregate_def_use_chain_1(follower, pred);
2874         }
2875 }  /* segregate_def_use_chain */
2876
2877 /**
2878  * Propagate constant evaluation.
2879  *
2880  * @param env  the environment
2881  */
2882 static void propagate(environment_t *env) {
2883         partition_t    *X, *Y;
2884         node_t         *x;
2885         lattice_elem_t old_type;
2886         node_t         *fallen;
2887         unsigned       n_fallen, old_type_was_T_or_C;
2888         int            i;
2889
2890         while (env->cprop != NULL) {
2891                 void *oldopcode = NULL;
2892
2893                 /* remove the first partition X from cprop */
2894                 X           = env->cprop;
2895                 X->on_cprop = 0;
2896                 env->cprop  = X->cprop_next;
2897
2898                 old_type_was_T_or_C = X->type_is_T_or_C;
2899
2900                 DB((dbg, LEVEL_2, "Propagate type on part%d\n", X->nr));
2901                 fallen   = NULL;
2902                 n_fallen = 0;
2903                 for (;;) {
2904                         int cprop_empty   = list_empty(&X->cprop);
2905                         int cprop_X_empty = list_empty(&X->cprop_X);
2906
2907                         if (cprop_empty && cprop_X_empty) {
2908                                 /* both cprop lists are empty */
2909                                 break;
2910                         }
2911
2912                         /* remove the first Node x from X.cprop */
2913                         if (cprop_empty) {
2914                                 /* Get a node from the cprop_X list only if
2915                                  * all data nodes are processed.
2916                                  * This ensures, that all inputs of the Cond
2917                                  * predecessor are processed if its type is still Top.
2918                                  */
2919                                 x = list_entry(X->cprop_X.next, node_t, cprop_list);
2920                         } else {
2921                                 x = list_entry(X->cprop.next, node_t, cprop_list);
2922                         }
2923
2924                         //assert(x->part == X);
2925                         list_del(&x->cprop_list);
2926                         x->on_cprop = 0;
2927
2928                         if (x->is_follower && identity(x) == x) {
2929                                 /* check the opcode first */
2930                                 if (oldopcode == NULL) {
2931                                         oldopcode = lambda_opcode(get_first_node(X), env);
2932                                 }
2933                                 if (oldopcode != lambda_opcode(x, env)) {
2934                                         if (x->on_fallen == 0) {
2935                                                 /* different opcode -> x falls out of this partition */
2936                                                 x->next      = fallen;
2937                                                 x->on_fallen = 1;
2938                                                 fallen       = x;
2939                                                 ++n_fallen;
2940                                                 DB((dbg, LEVEL_2, "Add node %+F to fallen\n", x->node));
2941                                         }
2942                                 }
2943
2944                                 /* x will make the follower -> leader transition */
2945                                 follower_to_leader(x);
2946                         }
2947
2948                         /* compute a new type for x */
2949                         old_type = x->type;
2950                         DB((dbg, LEVEL_3, "computing type of %+F\n", x->node));
2951                         compute(x);
2952                         if (x->type.tv != old_type.tv) {
2953                                 DB((dbg, LEVEL_2, "node %+F has changed type from %+F to %+F\n", x->node, old_type, x->type));
2954                                 verify_type(old_type, x);
2955
2956                                 if (x->on_fallen == 0) {
2957                                         /* Add x to fallen. Nodes might fall from T -> const -> _|_, so check that they are
2958                                            not already on the list. */
2959                                         x->next      = fallen;
2960                                         x->on_fallen = 1;
2961                                         fallen       = x;
2962                                         ++n_fallen;
2963                                         DB((dbg, LEVEL_2, "Add node %+F to fallen\n", x->node));
2964                                 }
2965                                 for (i = get_irn_n_outs(x->node) - 1; i >= 0; --i) {
2966                                         ir_node *succ = get_irn_out(x->node, i);
2967                                         node_t  *y    = get_irn_node(succ);
2968
2969                                         /* Add y to y.partition.cprop. */
2970                                         add_to_cprop(y, env);
2971                                 }
2972                         }
2973                 }
2974
2975                 if (n_fallen > 0 && n_fallen != X->n_leader) {
2976                         DB((dbg, LEVEL_2, "Splitting part%d by fallen\n", X->nr));
2977                         Y = split(&X, fallen, env);
2978                         /*
2979                          * We have split out fallen node. The type of the result
2980                          * partition is NOT set yet.
2981                          */
2982                         Y->type_is_T_or_C = 0;
2983                 } else {
2984                         Y = X;
2985                 }
2986                 /* remove the flags from the fallen list */
2987                 for (x = fallen; x != NULL; x = x->next)
2988                         x->on_fallen = 0;
2989
2990                 if (old_type_was_T_or_C) {
2991                         node_t *y, *tmp;
2992
2993                         /* check if some nodes will make the leader -> follower transition */
2994                         list_for_each_entry_safe(node_t, y, tmp, &Y->Leader, node_list) {
2995                                 if (y->type.tv != tarval_top && ! is_con(y->type)) {
2996                                         node_t *eq_node = identity(y);
2997
2998                                         if (eq_node != y && eq_node->part == y->part) {
2999                                                 DB((dbg, LEVEL_2, "Node %+F is a follower of %+F\n", y->node, eq_node->node));
3000                                                 /* move to Follower */
3001                                                 y->is_follower = 1;
3002                                                 list_del(&y->node_list);
3003                                                 list_add_tail(&y->node_list, &Y->Follower);
3004                                                 --Y->n_leader;
3005
3006                                                 segregate_def_use_chain(y->node);
3007                                         }
3008                                 }
3009                         }
3010                 }
3011                 split_by(Y, env);
3012         }
3013 }  /* propagate */
3014
3015 /**
3016  * Get the leader for a given node from its congruence class.
3017  *
3018  * @param irn  the node
3019  */
3020 static ir_node *get_leader(node_t *node) {
3021         partition_t *part = node->part;
3022
3023         if (part->n_leader > 1 || node->is_follower) {
3024                 if (node->is_follower) {
3025                         DB((dbg, LEVEL_2, "Replacing follower %+F\n", node->node));
3026                 }
3027                 else
3028                         DB((dbg, LEVEL_2, "Found congruence class for %+F\n", node->node));
3029
3030                 return get_first_node(part)->node;
3031         }
3032         return node->node;
3033 }  /* get_leader */
3034
3035 /**
3036  * Returns non-zero if a mode_T node has only one reachable output.
3037  */
3038 static int only_one_reachable_proj(ir_node *n) {
3039         int i, k = 0;
3040
3041         for (i = get_irn_n_outs(n) - 1; i >= 0; --i) {
3042                 ir_node *proj = get_irn_out(n, i);
3043                 node_t  *node;
3044
3045                 /* skip non-control flow Proj's */
3046                 if (get_irn_mode(proj) != mode_X)
3047                         continue;
3048
3049                 node = get_irn_node(proj);
3050                 if (node->type.tv == tarval_reachable) {
3051                         if (++k > 1)
3052                                 return 0;
3053                 }
3054         }
3055         return 1;
3056 }  /* only_one_reachable_proj */
3057
3058 /**
3059  * Return non-zero if the control flow predecessor node pred
3060  * is the only reachable control flow exit of its block.
3061  *
3062  * @param pred  the control flow exit
3063  */
3064 static int can_exchange(ir_node *pred) {
3065         if (is_Start(pred))
3066                 return 0;
3067         else if (is_Jmp(pred))
3068                 return 1;
3069         else if (get_irn_mode(pred) == mode_T) {
3070                 /* if the predecessor block has more than one
3071                    reachable outputs we cannot remove the block */
3072                 return only_one_reachable_proj(pred);
3073         }
3074         return 0;
3075 }  /* can_exchange */
3076
3077 /**
3078  * Block Post-Walker, apply the analysis results on control flow by
3079  * shortening Phi's and Block inputs.
3080  */
3081 static void apply_cf(ir_node *block, void *ctx) {
3082         environment_t *env = ctx;
3083         node_t        *node = get_irn_node(block);
3084         int           i, j, k, n;
3085         ir_node       **ins, **in_X;
3086         ir_node       *phi, *next;
3087
3088         n = get_Block_n_cfgpreds(block);
3089
3090         if (node->type.tv == tarval_unreachable) {
3091                 env->modified = 1;
3092
3093                 for (i = n - 1; i >= 0; --i) {
3094                         ir_node *pred = get_Block_cfgpred(block, i);
3095
3096                         if (! is_Bad(pred)) {
3097                                 node_t *pred_bl = get_irn_node(get_nodes_block(skip_Proj(pred)));
3098
3099                                 if (pred_bl->flagged == 0) {
3100                                         pred_bl->flagged = 3;
3101
3102                                         if (pred_bl->type.tv == tarval_reachable) {
3103                                                 /*
3104                                                  * We will remove an edge from block to its pred.
3105                                                  * This might leave the pred block as an endless loop
3106                                                  */
3107                                                 if (! is_backedge(block, i))
3108                                                         keep_alive(pred_bl->node);
3109                                         }
3110                                 }
3111                         }
3112                 }
3113
3114                 /* the EndBlock is always reachable even if the analysis
3115                    finds out the opposite :-) */
3116                 if (block != get_irg_end_block(current_ir_graph)) {
3117                         /* mark dead blocks */
3118                         set_Block_dead(block);
3119                         DB((dbg, LEVEL_1, "Removing dead %+F\n", block));
3120                 } else {
3121                         /* the endblock is unreachable */
3122                         set_irn_in(block, 0, NULL);
3123                 }
3124                 return;
3125         }
3126
3127         if (n == 1) {
3128                 /* only one predecessor combine */
3129                 ir_node *pred = skip_Proj(get_Block_cfgpred(block, 0));
3130
3131                 if (can_exchange(pred)) {
3132                         ir_node *new_block = get_nodes_block(pred);
3133                         DB((dbg, LEVEL_1, "Fuse %+F with %+F\n", block, new_block));
3134                         DBG_OPT_COMBO(block, new_block, FS_OPT_COMBO_CF);
3135                         exchange(block, new_block);
3136                         node->node = new_block;
3137                         env->modified = 1;
3138                 }
3139                 return;
3140         }
3141
3142         NEW_ARR_A(ir_node *, in_X, n);
3143         k = 0;
3144         for (i = 0; i < n; ++i) {
3145                 ir_node *pred = get_Block_cfgpred(block, i);
3146                 node_t  *node = get_irn_node(pred);
3147
3148                 if (node->type.tv == tarval_reachable) {
3149                         in_X[k++] = pred;
3150                 } else {
3151                         DB((dbg, LEVEL_1, "Removing dead input %d from %+F (%+F)\n", i, block, pred));
3152                         if (! is_Bad(pred)) {
3153                                 node_t *pred_bl = get_irn_node(get_nodes_block(skip_Proj(pred)));
3154
3155                                 if (pred_bl->flagged == 0) {
3156                                         pred_bl->flagged = 3;
3157
3158                                         if (pred_bl->type.tv == tarval_reachable) {
3159                                                 /*
3160                                                  * We will remove an edge from block to its pred.
3161                                                  * This might leave the pred block as an endless loop
3162                                                  */
3163                                                 if (! is_backedge(block, i))
3164                                                         keep_alive(pred_bl->node);
3165                                         }
3166                                 }
3167                         }
3168                 }
3169         }
3170         if (k >= n)
3171                 return;
3172
3173         /* fix Phi's */
3174         NEW_ARR_A(ir_node *, ins, n);
3175         for (phi = get_Block_phis(block); phi != NULL; phi = next) {
3176                 node_t *node = get_irn_node(phi);
3177
3178                 next = get_Phi_next(phi);
3179                 if (is_tarval(node->type.tv) && tarval_is_constant(node->type.tv)) {
3180                         /* this Phi is replaced by a constant */
3181                         tarval  *tv = node->type.tv;
3182                         ir_node *c  = new_Const(get_tarval_mode(tv), tv);
3183
3184                         set_irn_node(c, node);
3185                         node->node = c;
3186                         DB((dbg, LEVEL_1, "%+F is replaced by %+F\n", phi, c));
3187                         DBG_OPT_COMBO(phi, c, FS_OPT_COMBO_CONST);
3188                         exchange(phi, c);
3189                         env->modified = 1;
3190                 } else {
3191                         j = 0;
3192                         for (i = 0; i < n; ++i) {
3193                                 node_t *pred = get_irn_node(get_Block_cfgpred(block, i));
3194
3195                                 if (pred->type.tv == tarval_reachable) {
3196                                         ins[j++] = get_Phi_pred(phi, i);
3197                                 }
3198                         }
3199                         if (j == 1) {
3200                                 /* this Phi is replaced by a single predecessor */
3201                                 ir_node *s = ins[0];
3202                                 node_t *phi_node = get_irn_node(phi);
3203
3204                                 node->node = s;
3205                                 DB((dbg, LEVEL_1, "%+F is replaced by %+F because of cf change\n", phi, s));
3206                                 DBG_OPT_COMBO(phi, s, FS_OPT_COMBO_FOLLOWER);
3207                                 exchange(phi, s);
3208                                 phi_node->node = s;
3209                                 env->modified = 1;
3210                         } else {
3211                                 set_irn_in(phi, j, ins);
3212                                 env->modified = 1;
3213                         }
3214                 }
3215         }
3216
3217         /* fix block */
3218         if (k == 1) {
3219                 /* this Block has only one live predecessor */
3220                 ir_node *pred = skip_Proj(in_X[0]);
3221
3222                 if (can_exchange(pred)) {
3223                         ir_node *new_block = get_nodes_block(pred);
3224                         DBG_OPT_COMBO(block, new_block, FS_OPT_COMBO_CF);
3225                         exchange(block, new_block);
3226                         node->node = new_block;
3227                         env->modified = 1;
3228                         return;
3229                 }
3230         }
3231         set_irn_in(block, k, in_X);
3232         env->modified = 1;
3233 }  /* apply_cf */
3234
3235 /**
3236  * Exchange a node by its leader.
3237  * Beware: in rare cases the mode might be wrong here, for instance
3238  * AddP(x, NULL) is a follower of x, but with different mode.
3239  * Fix it here.
3240  */
3241 static void exchange_leader(ir_node *irn, ir_node *leader) {
3242         ir_mode *mode = get_irn_mode(irn);
3243         if (mode != get_irn_mode(leader)) {
3244                 /* The conv is a no-op, so we are free to place it
3245                  * either in the block of the leader OR in irn's block.
3246                  * Probably placing it into leaders block might reduce
3247                  * the number of Conv due to CSE. */
3248                 ir_node  *block = get_nodes_block(leader);
3249                 dbg_info *dbg   = get_irn_dbg_info(irn);
3250
3251                 leader = new_rd_Conv(dbg, current_ir_graph, block, leader, mode);
3252         }
3253         exchange(irn, leader);
3254 }  /* exchange_leader */
3255
3256 /**
3257  * Check, if all users of a mode_M node are dead. Use
3258  * the Def-Use edges for this purpose, as they still
3259  * reflect the situation.
3260  */
3261 static int all_users_are_dead(const ir_node *irn) {
3262         int i, n = get_irn_n_outs(irn);
3263
3264         for (i = 1; i <= n; ++i) {
3265                 const ir_node *succ  = irn->out[i].use;
3266                 const node_t  *block = get_irn_node(get_nodes_block(succ));
3267                 const node_t  *node;
3268
3269                 if (block->type.tv == tarval_unreachable) {
3270                         /* block is unreachable */
3271                         continue;
3272                 }
3273                 node = get_irn_node(succ);
3274                 if (node->type.tv != tarval_top) {
3275                         /* found a reachable user */
3276                         return 0;
3277                 }
3278         }
3279         /* all users are unreachable */
3280         return 1;
3281 }  /* all_user_are_dead */
3282
3283 /**
3284  * Walker: Find reachable mode_M nodes that have only
3285  * unreachable users. These nodes must be kept later.
3286  */
3287 static void find_kept_memory(ir_node *irn, void *ctx) {
3288         environment_t *env = ctx;
3289         node_t        *node, *block;
3290
3291         if (get_irn_mode(irn) != mode_M)
3292                 return;
3293
3294         block = get_irn_node(get_nodes_block(irn));
3295         if (block->type.tv == tarval_unreachable)
3296                 return;
3297
3298         node = get_irn_node(irn);
3299         if (node->type.tv == tarval_top)
3300                 return;
3301
3302         /* ok, we found a live memory node. */
3303         if (all_users_are_dead(irn)) {
3304                 DB((dbg, LEVEL_1, "%+F must be kept\n", irn));
3305                 ARR_APP1(ir_node *, env->kept_memory, irn);
3306         }
3307 }  /* find_kept_memory */
3308
3309 /**
3310  * Post-Walker, apply the analysis results;
3311  */
3312 static void apply_result(ir_node *irn, void *ctx) {
3313         environment_t *env = ctx;
3314         node_t        *node = get_irn_node(irn);
3315
3316         if (is_Block(irn) || is_End(irn) || is_Bad(irn)) {
3317                 /* blocks already handled, do not touch the End node */
3318         } else {
3319                 node_t *block = get_irn_node(get_nodes_block(irn));
3320
3321                 if (block->type.tv == tarval_unreachable) {
3322                         ir_node *bad = get_irg_bad(current_ir_graph);
3323
3324                         /* here, bad might already have a node, but this can be safely ignored
3325                            as long as bad has at least ONE valid node */
3326                         set_irn_node(bad, node);
3327                         node->node = bad;
3328                         DB((dbg, LEVEL_1, "%+F is unreachable\n", irn));
3329                         exchange(irn, bad);
3330                         env->modified = 1;
3331                 } else if (node->type.tv == tarval_top) {
3332                         ir_mode *mode = get_irn_mode(irn);
3333
3334                         if (mode == mode_M) {
3335                                 /* never kill a mode_M node */
3336                                 if (is_Proj(irn)) {
3337                                         ir_node *pred  = get_Proj_pred(irn);
3338                                         node_t  *pnode = get_irn_node(pred);
3339
3340                                         if (pnode->type.tv == tarval_top) {
3341                                                 /* skip the predecessor */
3342                                                 ir_node *mem = get_memop_mem(pred);
3343                                                 node->node = mem;
3344                                                 DB((dbg, LEVEL_1, "%+F computes Top, replaced by %+F\n", irn, mem));
3345                                                 exchange(irn, mem);
3346                                                 env->modified = 1;
3347                                         }
3348                                 }
3349                                 /* leave other nodes, especially PhiM */
3350                         } else if (mode == mode_T) {
3351                                 /* Do not kill mode_T nodes, kill their Projs */
3352                         } else if (! is_Unknown(irn)) {
3353                                 /* don't kick away Unknown's, they might be still needed */
3354                                 ir_node *unk = new_r_Unknown(current_ir_graph, mode);
3355
3356                                 /* control flow should already be handled at apply_cf() */
3357                                 assert(mode != mode_X);
3358
3359                                 /* see comment above */
3360                                 set_irn_node(unk, node);
3361                                 node->node = unk;
3362                                 DB((dbg, LEVEL_1, "%+F computes Top\n", irn));
3363                                 exchange(irn, unk);
3364                                 env->modified = 1;
3365                         }
3366                 }
3367                 else if (get_irn_mode(irn) == mode_X) {
3368                         if (is_Proj(irn)) {
3369                                 /* leave or Jmp */
3370                                 ir_node *cond = get_Proj_pred(irn);
3371
3372                                 if (is_Cond(cond)) {
3373                                         if (only_one_reachable_proj(cond)) {
3374                                                 ir_node *jmp = new_r_Jmp(current_ir_graph, block->node);
3375                                                 set_irn_node(jmp, node);
3376                                                 node->node = jmp;
3377                                                 DB((dbg, LEVEL_1, "%+F is replaced by %+F\n", irn, jmp));
3378                                                 DBG_OPT_COMBO(irn, jmp, FS_OPT_COMBO_CF);
3379                                                 exchange(irn, jmp);
3380                                                 env->modified = 1;
3381                                         } else {
3382                                                 node_t *sel = get_irn_node(get_Cond_selector(cond));
3383                                                 tarval *tv  = sel->type.tv;
3384
3385                                                 if (is_tarval(tv) && tarval_is_constant(tv)) {
3386                                                         /* The selector is a constant, but more
3387                                                          * than one output is active: An unoptimized
3388                                                          * case found. */
3389                                                         env->unopt_cf = 1;
3390                                                 }
3391                                         }
3392                                 }
3393                         }
3394                 } else {
3395                         /* normal data node */
3396                         if (is_tarval(node->type.tv) && tarval_is_constant(node->type.tv)) {
3397                                 tarval *tv = node->type.tv;
3398
3399                                 /*
3400                                  * Beware: never replace mode_T nodes by constants. Currently we must mark
3401                                  * mode_T nodes with constants, but do NOT replace them.
3402                                  */
3403                                 if (! is_Const(irn) && get_irn_mode(irn) != mode_T) {
3404                                         /* can be replaced by a constant */
3405                                         ir_node *c = new_Const(get_tarval_mode(tv), tv);
3406                                         set_irn_node(c, node);
3407                                         node->node = c;
3408                                         DB((dbg, LEVEL_1, "%+F is replaced by %+F\n", irn, c));
3409                                         DBG_OPT_COMBO(irn, c, FS_OPT_COMBO_CONST);
3410                                         exchange_leader(irn, c);
3411                                         env->modified = 1;
3412                                 }
3413                         } else if (is_entity(node->type.sym.entity_p)) {
3414                                 if (! is_SymConst(irn)) {
3415                                         /* can be replaced by a SymConst */
3416                                         ir_node *symc = new_r_SymConst(current_ir_graph, block->node, get_irn_mode(irn), node->type.sym, symconst_addr_ent);
3417                                         set_irn_node(symc, node);
3418                                         node->node = symc;
3419
3420                                         DB((dbg, LEVEL_1, "%+F is replaced by %+F\n", irn, symc));
3421                                         DBG_OPT_COMBO(irn, symc, FS_OPT_COMBO_CONST);
3422                                         exchange_leader(irn, symc);
3423                                         env->modified = 1;
3424                                 }
3425                         } else if (is_Confirm(irn)) {
3426                                 /* Confirms are always follower, but do not kill them here */
3427                         } else {
3428                                 ir_node *leader = get_leader(node);
3429
3430                                 if (leader != irn) {
3431                                         int non_strict_phi = 0;
3432
3433                                         /*
3434                                          * Beware: Do not remove Phi(Unknown, ..., x, ..., Unknown)
3435                                          * as this might create non-strict programs.
3436                                          */
3437                                         if (node->is_follower && is_Phi(irn) && !is_Unknown(leader)) {
3438                                                 int i;
3439
3440                                                 for (i = get_Phi_n_preds(irn) - 1; i >= 0; --i) {
3441                                                         ir_node *pred = get_Phi_pred(irn, i);
3442
3443                                                         if (is_Unknown(pred)) {
3444                                                                 non_strict_phi = 1;
3445                                                                 break;
3446                                                         }
3447                                                 }
3448                                         }
3449                                         if (! non_strict_phi) {
3450                                                 DB((dbg, LEVEL_1, "%+F from part%d is replaced by %+F\n", irn, node->part->nr, leader));
3451                                                 if (node->is_follower)
3452                                                         DBG_OPT_COMBO(irn, leader, FS_OPT_COMBO_FOLLOWER);
3453                                                 else
3454                                                         DBG_OPT_COMBO(irn, leader, FS_OPT_COMBO_CONGRUENT);
3455                                                 exchange_leader(irn, leader);
3456                                                 env->modified = 1;
3457                                         }
3458                                 }
3459                         }
3460                 }
3461         }
3462 }  /* apply_result */
3463
3464 /**
3465  * Fix the keep-alives by deleting unreachable ones.
3466  */
3467 static void apply_end(ir_node *end, environment_t *env) {
3468         int i, j,  n = get_End_n_keepalives(end);
3469         ir_node **in;
3470
3471         if (n > 0)
3472                 NEW_ARR_A(ir_node *, in, n);
3473
3474         /* fix the keep alive */
3475         for (i = j = 0; i < n; i++) {
3476                 ir_node *ka   = get_End_keepalive(end, i);
3477                 node_t  *node = get_irn_node(ka);
3478
3479                 if (! is_Block(ka))
3480                         node = get_irn_node(get_nodes_block(ka));
3481
3482                 if (node->type.tv != tarval_unreachable && !is_Bad(ka))
3483                         in[j++] = ka;
3484         }
3485         if (j != n) {
3486                 set_End_keepalives(end, j, in);
3487                 env->modified = 1;
3488         }
3489 }  /* apply_end */
3490
3491 #define SET(code) op_##code->ops.generic = (op_func)compute_##code
3492
3493 /**
3494  * sets the generic functions to compute.
3495  */
3496 static void set_compute_functions(void) {
3497         int i;
3498
3499         /* set the default compute function */
3500         for (i = get_irp_n_opcodes() - 1; i >= 0; --i) {
3501                 ir_op *op = get_irp_opcode(i);
3502                 op->ops.generic = (op_func)default_compute;
3503         }
3504
3505         /* set specific functions */
3506         SET(Block);
3507         SET(Unknown);
3508         SET(Bad);
3509         SET(Jmp);
3510         SET(Phi);
3511         SET(Add);
3512         SET(Sub);
3513         SET(Eor);
3514         SET(SymConst);
3515         SET(Cmp);
3516         SET(Proj);
3517         SET(Confirm);
3518         SET(Return);
3519         SET(End);
3520         SET(Call);
3521
3522         if (op_Max != NULL)
3523                 SET(Max);
3524         if (op_Min != NULL)
3525                 SET(Min);
3526 }  /* set_compute_functions */
3527
3528 /**
3529  * Add memory keeps.
3530  */
3531 static void add_memory_keeps(ir_node **kept_memory, int len) {
3532         ir_node      *end = get_irg_end(current_ir_graph);
3533         int          i;
3534         ir_nodeset_t set;
3535
3536         ir_nodeset_init(&set);
3537
3538         /* check, if those nodes are already kept */
3539         for (i = get_End_n_keepalives(end) - 1; i >= 0; --i)
3540                 ir_nodeset_insert(&set, get_End_keepalive(end, i));
3541
3542         for (i = len - 1; i >= 0; --i) {
3543                 ir_node *ka = kept_memory[i];
3544
3545                 if (! ir_nodeset_contains(&set, ka)) {
3546                         add_End_keepalive(end, ka);
3547                 }
3548         }
3549         ir_nodeset_destroy(&set);
3550 }  /* add_memory_keeps */
3551
3552 void combo(ir_graph *irg) {
3553         environment_t env;
3554         ir_node       *initial_bl;
3555         node_t        *start;
3556         ir_graph      *rem = current_ir_graph;
3557         int           len;
3558
3559         current_ir_graph = irg;
3560
3561         /* register a debug mask */
3562         FIRM_DBG_REGISTER(dbg, "firm.opt.combo");
3563
3564         DB((dbg, LEVEL_1, "Doing COMBO for %+F\n", irg));
3565
3566         obstack_init(&env.obst);
3567         env.worklist       = NULL;
3568         env.cprop          = NULL;
3569         env.touched        = NULL;
3570         env.initial        = NULL;
3571 #ifdef DEBUG_libfirm
3572         env.dbg_list       = NULL;
3573 #endif
3574         env.opcode2id_map  = new_set(cmp_opcode, iro_Last * 4);
3575         env.type2id_map    = pmap_create();
3576         env.kept_memory    = NEW_ARR_F(ir_node *, 0);
3577         env.end_idx        = get_opt_global_cse() ? 0 : -1;
3578         env.lambda_input   = 0;
3579         env.modified       = 0;
3580         env.unopt_cf       = 0;
3581         /* options driving the optimization */
3582         env.commutative    = 1;
3583         env.opt_unknown    = 1;
3584
3585         assure_irg_outs(irg);
3586         assure_cf_loop(irg);
3587
3588         /* we have our own value_of function */
3589         set_value_of_func(get_node_tarval);
3590
3591         set_compute_functions();
3592         DEBUG_ONLY(part_nr = 0);
3593
3594         ir_reserve_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_PHI_LIST);
3595
3596         if (env.opt_unknown)
3597                 tarval_UNKNOWN = tarval_top;
3598         else
3599                 tarval_UNKNOWN = tarval_bad;
3600
3601         /* create the initial partition and place it on the work list */
3602         env.initial = new_partition(&env);
3603         add_to_worklist(env.initial, &env);
3604         irg_walk_graph(irg, create_initial_partitions, init_block_phis, &env);
3605
3606         /* set the hook: from now, every node has a partition and a type */
3607         DEBUG_ONLY(set_dump_node_vcgattr_hook(dump_partition_hook));
3608
3609         /* all nodes on the initial partition have type Top */
3610         env.initial->type_is_T_or_C = 1;
3611
3612         /* Place the START Node's partition on cprop.
3613            Place the START Node on its local worklist. */
3614         initial_bl = get_irg_start_block(irg);
3615         start      = get_irn_node(initial_bl);
3616         add_to_cprop(start, &env);
3617
3618         do {
3619                 propagate(&env);
3620                 if (env.worklist != NULL)
3621                         cause_splits(&env);
3622         } while (env.cprop != NULL || env.worklist != NULL);
3623
3624         dump_all_partitions(&env);
3625         check_all_partitions(&env);
3626
3627 #if 0
3628         dump_ir_block_graph(irg, "-partition");
3629 #endif
3630
3631         /* apply the result */
3632
3633         /* check, which nodes must be kept */
3634         irg_walk_graph(irg, NULL, find_kept_memory, &env);
3635
3636         /* kill unreachable control flow */
3637         irg_block_walk_graph(irg, NULL, apply_cf, &env);
3638         /* Kill keep-alives of dead blocks: this speeds up apply_result()
3639          * and fixes assertion because dead cf to dead blocks is NOT removed by
3640          * apply_cf(). */
3641         apply_end(get_irg_end(irg), &env);
3642         irg_walk_graph(irg, NULL, apply_result, &env);
3643
3644         len = ARR_LEN(env.kept_memory);
3645         if (len > 0)
3646                 add_memory_keeps(env.kept_memory, len);
3647
3648         if (env.unopt_cf) {
3649                 DB((dbg, LEVEL_1, "Unoptimized Control Flow left"));
3650         }
3651
3652         if (env.modified) {
3653                 /* control flow might changed */
3654                 set_irg_outs_inconsistent(irg);
3655                 set_irg_extblk_inconsistent(irg);
3656                 set_irg_doms_inconsistent(irg);
3657                 set_irg_loopinfo_inconsistent(irg);
3658         }
3659
3660         ir_free_resources(irg, IR_RESOURCE_IRN_LINK | IR_RESOURCE_PHI_LIST);
3661
3662         /* remove the partition hook */
3663         DEBUG_ONLY(set_dump_node_vcgattr_hook(NULL));
3664
3665         DEL_ARR_F(env.kept_memory);
3666         pmap_destroy(env.type2id_map);
3667         del_set(env.opcode2id_map);
3668         obstack_free(&env.obst, NULL);
3669
3670         /* restore value_of() default behavior */
3671         set_value_of_func(NULL);
3672         current_ir_graph = rem;
3673 }  /* combo */