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