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