Some things not stated (or not clear) in Clicks Diss:
[libfirm] / ir / opt / combo.c
1 /*
2  * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief   Cliff Click's Combined Analysis/Optimization
23  * @author  Michael Beck
24  * @version $Id$
25  *
26  * Note further that we use the terminology from Click's work here, which is different
27  * in some cases from Firm terminology.  Especially, Click's type is a
28  * Firm tarval/entity, nevertheless we call it type here for "maximum compatibility".
29  */
30 #ifdef HAVE_CONFIG_H
31 # include "config.h"
32 #endif
33
34 #include <assert.h>
35
36 #include "iroptimize.h"
37 #include "archop.h"
38 #include "irflag.h"
39 #include "ircons.h"
40 #include "list.h"
41 #include "set.h"
42 #include "pmap.h"
43 #include "obstack.h"
44 #include "irgraph_t.h"
45 #include "irnode_t.h"
46 #include "iropt_t.h"
47 #include "irgwalk.h"
48 #include "irop.h"
49 #include "irouts.h"
50 #include "irgmod.h"
51 #include "debug.h"
52 #include "error.h"
53
54 #include "tv_t.h"
55
56 #include "irprintf.h"
57 #include "irdump.h"
58
59 /* define this to check that all type translations are monotone */
60 #define VERIFY_MONOTONE
61
62 #undef NO_FOLLOWER
63
64 typedef struct node_t            node_t;
65 typedef struct partition_t       partition_t;
66 typedef struct opcode_key_t      opcode_key_t;
67 typedef struct listmap_entry_t   listmap_entry_t;
68
69 /** The type of the compute function. */
70 typedef void (*compute_func)(node_t *node);
71
72 /**
73  * An opcode map key.
74  */
75 struct opcode_key_t {
76         ir_opcode   code;   /**< The Firm opcode. */
77         ir_mode     *mode;  /**< The mode of all nodes in the partition. */
78         union {
79                 long      proj;   /**< For Proj nodes, its proj number */
80                 ir_entity *ent;   /**< For Sel Nodes, its entity */
81         } u;
82 };
83
84 /**
85  * An entry in the list_map.
86  */
87 struct listmap_entry_t {
88         void            *id;    /**< The id. */
89         node_t          *list;  /**< The associated list for this id. */
90         listmap_entry_t *next;  /**< Link to the next entry in the map. */
91 };
92
93 /** We must map id's to lists. */
94 typedef struct listmap_t {
95         set             *map;    /**< Map id's to listmap_entry_t's */
96         listmap_entry_t *values; /**< List of all values in the map. */
97 } listmap_t;
98
99 /**
100  * A lattice element. Because we handle constants and symbolic constants different, we
101  * have to use this union.
102  */
103 typedef union {
104         tarval          *tv;
105         symconst_symbol sym;
106 } lattice_elem_t;
107
108 /**
109  * A node.
110  */
111 struct node_t {
112         ir_node         *node;          /**< The IR-node itself. */
113         list_head       node_list;      /**< Double-linked list of leader/follower entries. */
114         list_head       cprop_list;     /**< Double-linked partition.cprop list. */
115         partition_t     *part;          /**< points to the partition this node belongs to */
116         node_t          *next;          /**< Next node on local list (partition.touched, fallen). */
117         node_t          *race_next;     /**< Next node on race list. */
118         lattice_elem_t  type;           /**< The associated lattice element "type". */
119         int             max_user_input; /**< Maximum input number of Def-Use edges. */
120         int             next_edge;      /**< Index of the next Def-Use edge to use. */
121         int             n_followers;    /**< Number of Follower in the outs set. */
122         unsigned        on_touched:1;   /**< Set, if this node is on the partition.touched set. */
123         unsigned        on_cprop:1;     /**< Set, if this node is on the partition.cprop list. */
124         unsigned        on_fallen:1;    /**< Set, if this node is on the fallen list. */
125         unsigned        is_follower:1;  /**< Set, if this node is a follower. */
126         unsigned        is_flagged:1;   /**< Set, if this node is flagged by step(). */
127         unsigned        by_all_const:1; /**< Set, if this node was once evaluated by all constants. */
128 };
129
130 /**
131  * A partition containing congruent nodes.
132  */
133 struct partition_t {
134         list_head         Leader;          /**< The head of partition Leader node list. */
135         list_head         Follower;        /**< The head of partition Follower node list. */
136         list_head         cprop;           /**< The head of partition.cprop list. */
137         partition_t       *wl_next;        /**< Next entry in the work list if any. */
138         partition_t       *touched_next;   /**< Points to the next partition in the touched set. */
139         partition_t       *cprop_next;     /**< Points to the next partition in the cprop list. */
140         partition_t       *split_next;     /**< Points to the next partition in the list that must be split by split_by(). */
141         node_t            *touched;        /**< The partition.touched set of this partition. */
142         unsigned          n_leader;        /**< Number of entries in this partition.Leader. */
143         unsigned          n_touched;       /**< Number of entries in the partition.touched. */
144         int               max_user_inputs; /**< Maximum number of user inputs of all entries. */
145         unsigned          on_worklist:1;   /**< Set, if this partition is in the work list. */
146         unsigned          on_touched:1;    /**< Set, if this partition is on the touched set. */
147         unsigned          on_cprop:1;      /**< Set, if this partition is on the cprop list. */
148         unsigned          type_is_T_or_C:1;/**< Set, if all nodes in this partition have type Top or Constant. */
149 #ifdef DEBUG_libfirm
150         partition_t       *dbg_next;       /**< Link all partitions for debugging */
151         unsigned          nr;              /**< A unique number for (what-)mapping, >0. */
152 #endif
153 };
154
155 typedef struct environment_t {
156         struct obstack  obst;           /**< obstack to allocate data structures. */
157         partition_t     *worklist;      /**< The work list. */
158         partition_t     *cprop;         /**< The constant propagation list. */
159         partition_t     *touched;       /**< the touched set. */
160         partition_t     *initial;       /**< The initial partition. */
161         set             *opcode2id_map; /**< The opcodeMode->id map. */
162         pmap            *type2id_map;   /**< The type->id map. */
163         int             end_idx;        /**< -1 for local and 0 for global congruences. */
164         int             lambda_input;   /**< Captured argument for lambda_partition(). */
165         int             modified;       /**< Set, if the graph was modified. */
166 #ifdef DEBUG_libfirm
167         partition_t     *dbg_list;      /**< List of all partitions. */
168 #endif
169 } environment_t;
170
171 /** Type of the what function. */
172 typedef void *(*what_func)(const node_t *node, environment_t *env);
173
174 #define get_irn_node(follower)         ((node_t *)get_irn_link(follower))
175 #define set_irn_node(follower, node)   set_irn_link(follower, node)
176
177 /* we do NOT use tarval_unreachable here, instead we use Top for this purpose */
178 #undef tarval_unreachable
179 #define tarval_unreachable tarval_top
180
181
182 /** The debug module handle. */
183 DEBUG_ONLY(static firm_dbg_module_t *dbg;)
184
185 /** Next partition number. */
186 DEBUG_ONLY(static unsigned part_nr = 0);
187
188 #ifdef DEBUG_libfirm
189 static INLINE lattice_elem_t get_partition_type(const partition_t *X);
190
191 /**
192  * Dump partition to output.
193  */
194 static void dump_partition(const char *msg, const partition_t *part) {
195         const node_t   *node;
196         int            first = 1;
197         lattice_elem_t type = get_partition_type(part);
198
199         DB((dbg, LEVEL_2, "%s part%u%s (%u, %+F) {\n  ",
200                 msg, part->nr, part->type_is_T_or_C ? "*" : "",
201                 part->n_leader, type));
202         list_for_each_entry(node_t, node, &part->Leader, node_list) {
203                 DB((dbg, LEVEL_2, "%s%+F", first ? "" : ", ", node->node));
204                 first = 0;
205         }
206         if (! list_empty(&part->Follower)) {
207                 DB((dbg, LEVEL_2, "\n---\n  "));
208                 first = 1;
209                 list_for_each_entry(node_t, node, &part->Follower, node_list) {
210                         DB((dbg, LEVEL_2, "%s%+F", first ? "" : ", ", node->node));
211                         first = 0;
212                 }
213         }
214         DB((dbg, LEVEL_2, "\n}\n"));
215 }  /* dump_partition */
216
217 /**
218  * Dumps a list.
219  */
220 static void do_dump_list(const char *msg, const node_t *node, int ofs) {
221         const node_t *p;
222         int          first = 1;
223
224 #define GET_LINK(p, ofs)  *((const node_t **)((char *)(p) + (ofs)))
225
226         DB((dbg, LEVEL_3, "%s = {\n  ", msg));
227         for (p = node; p != NULL; p = GET_LINK(p, ofs)) {
228                 DB((dbg, LEVEL_3, "%s%+F", first ? "" : ", ", p->node));
229                 first = 0;
230         }
231         DB((dbg, LEVEL_3, "\n}\n"));
232
233 #undef GET_LINK
234 }
235
236 /**
237  * Dumps a race list.
238  */
239 static void dump_race_list(const char *msg, const node_t *list) {
240         do_dump_list(msg, list, offsetof(node_t, race_next));
241 }
242
243 /**
244  * Dumps a local list.
245  */
246 static void dump_list(const char *msg, const node_t *list) {
247         do_dump_list(msg, list, offsetof(node_t, next));
248 }
249
250 /**
251  * Dump all partitions.
252  */
253 static void dump_all_partitions(const environment_t *env) {
254         const partition_t *P;
255
256         DB((dbg, LEVEL_2, "All partitions\n===============\n"));
257         for (P = env->dbg_list; P != NULL; P = P->dbg_next)
258                 dump_partition("", P);
259 }
260
261 #else
262 #define dump_partition(msg, part)
263 #define dump_race_list(msg, list)
264 #define dump_list(msg, list)
265 #define dump_all_partitions(env)
266 #endif
267
268 #if defined(VERIFY_MONOTONE) && defined (DEBUG_libfirm)
269 /**
270  * Verify that a type transition is monotone
271  */
272 static void verify_type(const lattice_elem_t old_type, const lattice_elem_t new_type) {
273         if (old_type.tv == new_type.tv) {
274                 /* no change */
275                 return;
276         }
277         if (old_type.tv == tarval_top) {
278                 /* from Top down-to is always allowed */
279                 return;
280         }
281         if (old_type.tv == tarval_reachable) {
282                 panic("verify_type(): wrong translation from %+F to %+F", old_type, new_type);
283         }
284         if (new_type.tv == tarval_bottom || new_type.tv == tarval_reachable) {
285                 /* bottom reached */
286                 return;
287         }
288         panic("verify_type(): wrong translation from %+F to %+F", old_type, new_type);
289 }
290 #else
291 #define verify_type(old_type, new_type)
292 #endif
293
294 /**
295  * Compare two pointer values of a listmap.
296  */
297 static int listmap_cmp_ptr(const void *elt, const void *key, size_t size) {
298         const listmap_entry_t *e1 = elt;
299         const listmap_entry_t *e2 = key;
300
301         (void) size;
302         return e1->id != e2->id;
303 }  /* listmap_cmp_ptr */
304
305 /**
306  * Initializes a listmap.
307  *
308  * @param map  the listmap
309  */
310 static void listmap_init(listmap_t *map) {
311         map->map    = new_set(listmap_cmp_ptr, 16);
312         map->values = NULL;
313 }  /* listmap_init */
314
315 /**
316  * Terminates a listmap.
317  *
318  * @param map  the listmap
319  */
320 static void listmap_term(listmap_t *map) {
321         del_set(map->map);
322 }  /* listmap_term */
323
324 /**
325  * Return the associated listmap entry for a given id.
326  *
327  * @param map  the listmap
328  * @param id   the id to search for
329  *
330  * @return the asociated listmap entry for the given id
331  */
332 static listmap_entry_t *listmap_find(listmap_t *map, void *id) {
333         listmap_entry_t key, *entry;
334
335         key.id   = id;
336         key.list = NULL;
337         key.next = NULL;
338         entry = set_insert(map->map, &key, sizeof(key), HASH_PTR(id));
339
340         if (entry->list == NULL) {
341                 /* a new entry, put into the list */
342                 entry->next = map->values;
343                 map->values = entry;
344         }
345         return entry;
346 }  /* listmap_find */
347
348 /**
349  * Calculate the hash value for an opcode map entry.
350  *
351  * @param entry  an opcode map entry
352  *
353  * @return a hash value for the given opcode map entry
354  */
355 static unsigned opcode_hash(const opcode_key_t *entry) {
356         return (entry->mode - (ir_mode *)0) * 9 + entry->code + entry->u.proj * 3 + HASH_PTR(entry->u.ent);
357 }  /* opcode_hash */
358
359 /**
360  * Compare two entries in the opcode map.
361  */
362 static int cmp_opcode(const void *elt, const void *key, size_t size) {
363         const opcode_key_t *o1 = elt;
364         const opcode_key_t *o2 = key;
365
366         (void) size;
367         return o1->code != o2->code || o1->mode != o2->mode ||
368                o1->u.proj != o2->u.proj || o1->u.ent != o2->u.ent;
369 }  /* cmp_opcode */
370
371 /**
372  * Compare two Def-Use edges for input position.
373  */
374 static int cmp_def_use_edge(const void *a, const void *b) {
375         const ir_def_use_edge *ea = a;
376         const ir_def_use_edge *eb = b;
377
378         /* no overrun, because range is [-1, MAXINT] */
379         return ea->pos - eb->pos;
380 }  /* cmp_def_use_edge */
381
382 /**
383  * We need the Def-Use edges sorted.
384  */
385 static void sort_irn_outs(node_t *node) {
386         ir_node *irn = node->node;
387         int n_outs = get_irn_n_outs(irn);
388
389         if (n_outs > 1) {
390                 qsort(&irn->out[1], n_outs, sizeof(irn->out[0]), cmp_def_use_edge);
391         }
392         node->max_user_input = irn->out[n_outs].pos;
393 }  /* sort_irn_outs */
394
395 /**
396  * Return the type of a node.
397  *
398  * @param irn  an IR-node
399  *
400  * @return the associated type of this node
401  */
402 static INLINE lattice_elem_t get_node_type(const ir_node *irn) {
403         return get_irn_node(irn)->type;
404 }  /* get_node_type */
405
406 /**
407  * Return the tarval of a node.
408  *
409  * @param irn  an IR-node
410  *
411  * @return the associated type of this node
412  */
413 static INLINE tarval *get_node_tarval(const ir_node *irn) {
414         lattice_elem_t type = get_node_type(irn);
415
416         if (is_tarval(type.tv))
417                 return type.tv;
418         return tarval_bottom;
419 }  /* get_node_type */
420
421 /**
422  * Add a partition to the worklist.
423  */
424 static INLINE void add_to_worklist(partition_t *X, environment_t *env) {
425         assert(X->on_worklist == 0);
426         X->wl_next     = env->worklist;
427         X->on_worklist = 1;
428         env->worklist  = X;
429 }  /* add_to_worklist */
430
431 /**
432  * Create a new empty partition.
433  *
434  * @param env   the environment
435  *
436  * @return a newly allocated partition
437  */
438 static INLINE partition_t *new_partition(environment_t *env) {
439         partition_t *part = obstack_alloc(&env->obst, sizeof(*part));
440
441         INIT_LIST_HEAD(&part->Leader);
442         INIT_LIST_HEAD(&part->Follower);
443         INIT_LIST_HEAD(&part->cprop);
444         part->wl_next         = NULL;
445         part->touched_next    = NULL;
446         part->cprop_next      = NULL;
447         part->split_next      = NULL;
448         part->touched         = NULL;
449         part->n_leader        = 0;
450         part->n_touched       = 0;
451         part->max_user_inputs = 0;
452         part->on_worklist     = 0;
453         part->on_touched      = 0;
454         part->on_cprop        = 0;
455         part->type_is_T_or_C  = 0;
456 #ifdef DEBUG_libfirm
457         part->dbg_next        = env->dbg_list;
458         env->dbg_list         = part;
459         part->nr              = part_nr++;
460 #endif
461
462         return part;
463 }  /* new_partition */
464
465 /**
466  * Get the first node from a partition.
467  */
468 static INLINE node_t *get_first_node(const partition_t *X) {
469         return list_entry(X->Leader.next, node_t, node_list);
470 }
471
472 /**
473  * Return the type of a partition (assuming partition is non-empty and
474  * all elements have the same type).
475  *
476  * @param X  a partition
477  *
478  * @return the type of the first element of the partition
479  */
480 static INLINE lattice_elem_t get_partition_type(const partition_t *X) {
481         const node_t *first = get_first_node(X);
482         return first->type;
483 }  /* get_partition_type */
484
485 /**
486  * Creates a partition node for the given IR-node and place it
487  * into the given partition.
488  *
489  * @param irn   an IR-node
490  * @param part  a partition to place the node in
491  * @param env   the environment
492  *
493  * @return the created node
494  */
495 static node_t *create_partition_node(ir_node *irn, partition_t *part, environment_t *env) {
496         /* create a partition node and place it in the partition */
497         node_t *node = obstack_alloc(&env->obst, sizeof(*node));
498
499         INIT_LIST_HEAD(&node->node_list);
500         INIT_LIST_HEAD(&node->cprop_list);
501         node->node           = irn;
502         node->part           = part;
503         node->next           = NULL;
504         node->race_next      = NULL;
505         node->type.tv        = tarval_top;
506         node->max_user_input = 0;
507         node->next_edge      = 0;
508         node->n_followers    = 0;
509         node->on_touched     = 0;
510         node->on_cprop       = 0;
511         node->on_fallen      = 0;
512         node->is_follower    = 0;
513         node->is_flagged     = 0;
514         node->by_all_const   = 0;
515         set_irn_node(irn, node);
516
517         list_add_tail(&node->node_list, &part->Leader);
518         ++part->n_leader;
519
520         return node;
521 }  /* create_partition_node */
522
523 /**
524  * Pre-Walker, init all Block-Phi lists.
525  */
526 static void init_block_phis(ir_node *irn, void *env) {
527         (void) env;
528
529         if (is_Block(irn)) {
530                 set_Block_phis(irn, NULL);
531         }
532 }
533
534 /**
535  * Post-Walker, initialize all Nodes' type to U or top and place
536  * all nodes into the TOP partition.
537  */
538 static void create_initial_partitions(ir_node *irn, void *ctx) {
539         environment_t *env  = ctx;
540         partition_t   *part = env->initial;
541         node_t        *node;
542
543         node = create_partition_node(irn, part, env);
544         sort_irn_outs(node);
545         if (node->max_user_input > part->max_user_inputs)
546                 part->max_user_inputs = node->max_user_input;
547
548         if (is_Phi(irn)) {
549                 add_Block_phi(get_nodes_block(irn), irn);
550         }
551 }  /* create_initial_partitions */
552
553 /**
554  * Add a node to the entry.partition.touched set and
555  * node->partition to the touched set if not already there.
556  *
557  * @param y    a node
558  * @param env  the environment
559  */
560 static INLINE void add_to_touched(node_t *y, environment_t *env) {
561         if (y->on_touched == 0) {
562                 partition_t *part = y->part;
563
564                 y->next       = part->touched;
565                 part->touched = y;
566                 y->on_touched = 1;
567                 ++part->n_touched;
568
569                 if (part->on_touched == 0) {
570                         part->touched_next = env->touched;
571                         env->touched       = part;
572                         part->on_touched   = 1;
573                 }
574         }
575 }  /* add_to_touched */
576
577 /**
578  * Place a node on the cprop list.
579  *
580  * @param y    the node
581  * @param env  the environment
582  */
583 static void add_to_cprop(node_t *y, environment_t *env) {
584         /* Add y to y.partition.cprop. */
585         if (y->on_cprop == 0) {
586                 partition_t *Y = y->part;
587
588                 list_add_tail(&y->cprop_list, &Y->cprop);
589                 y->on_cprop   = 1;
590
591                 DB((dbg, LEVEL_3, "Add %+F to part%u.cprop\n", y->node, Y->nr));
592
593                 /* place its partition on the cprop list */
594                 if (Y->on_cprop == 0) {
595                         Y->cprop_next = env->cprop;
596                         env->cprop    = Y;
597                         Y->on_cprop   = 1;
598                 }
599         }
600         if (get_irn_mode(y->node) == mode_T) {
601                 /* mode_T nodes always produce tarval_bottom, so we must explicitly
602                    add it's Proj's to get constant evaluation to work */
603                 int i;
604
605                 for (i = get_irn_n_outs(y->node) - 1; i >= 0; --i) {
606                         node_t *proj = get_irn_node(get_irn_out(y->node, i));
607
608                         add_to_cprop(proj, env);
609                 }
610         } else if (is_Block(y->node)) {
611                 /* Due to the way we handle Phi's, we must place all Phis of a block on the list
612                  * if someone placed the block. The Block is only placed if the reachability
613                  * changes, and this must be re-evaluated in compute_Phi(). */
614                 ir_node *phi;
615                 for (phi = get_Block_phis(y->node); phi != NULL; phi = get_Phi_next(phi)) {
616                         node_t *p = get_irn_node(phi);
617                         add_to_cprop(p, env);
618                 }
619         }
620 }  /* add_to_cprop */
621
622 /**
623  * Update the worklist: If Z is on worklist then add Z' to worklist.
624  * Else add the smaller of Z and Z' to worklist.
625  *
626  * @param Z        the Z partition
627  * @param Z_prime  the Z' partition, a previous part of Z
628  * @param env      the environment
629  */
630 static void update_worklist(partition_t *Z, partition_t *Z_prime, environment_t *env) {
631         if (Z->on_worklist || Z_prime->n_leader < Z->n_leader) {
632                 add_to_worklist(Z_prime, env);
633         } else {
634                 add_to_worklist(Z, env);
635         }
636 }  /* update_worklist */
637
638 /**
639  * Split a partition that has NO followers by a local list.
640  *
641  * @param Z    partition to split
642  * @param g    a (non-empty) node list
643  * @param env  the environment
644  *
645  * @return  a new partition containing the nodes of g
646  */
647 static partition_t *split_no_followers(partition_t *Z, node_t *g, environment_t *env) {
648         partition_t *Z_prime;
649         node_t      *node;
650         unsigned    n = 0;
651         int         max_input;
652
653         dump_partition("Splitting ", Z);
654         dump_list("by list ", g);
655
656         assert(g != NULL);
657
658         /* Remove g from Z. */
659         for (node = g; node != NULL; node = node->next) {
660                 assert(node->part == Z);
661                 list_del(&node->node_list);
662                 ++n;
663         }
664         assert(n < Z->n_leader);
665         Z->n_leader -= n;
666
667         /* Move g to a new partition, Z\92. */
668         Z_prime = new_partition(env);
669         max_input = 0;
670         for (node = g; node != NULL; node = node->next) {
671                 list_add(&node->node_list, &Z_prime->Leader);
672                 node->part = Z_prime;
673                 if (node->max_user_input > max_input)
674                         max_input = node->max_user_input;
675         }
676         Z_prime->max_user_inputs = max_input;
677         Z_prime->n_leader        = n;
678
679         /* for now, copy the type info tag, it will be adjusted in split_by(). */
680         Z_prime->type_is_T_or_C = Z->type_is_T_or_C;
681
682         update_worklist(Z, Z_prime, env);
683
684         dump_partition("Now ", Z);
685         dump_partition("Created new ", Z_prime);
686         return Z_prime;
687 }  /* split_no_followers */
688
689 #ifdef NO_FOLLOWER
690
691 #define split(Z, g, env) split_no_followers(*(Z), g, env)
692
693 #else
694
695 /**
696  * The environment for one race step.
697  */
698 typedef struct step_env {
699         node_t *initial;       /**< The initial node list. */
700         node_t *unwalked;      /**< The unwalked node list. */
701         node_t *walked;        /**< The walked node list. */
702         int    index;          /**< Next index of Follower use_def edge. */
703         int    n_leader;       /**< number of Leader in initial. */
704 } step_env;
705
706 /**
707  * Do one step in the race.
708  */
709 static int step(step_env *env) {
710         node_t *n;
711
712         if (env->initial != NULL) {
713                 /* Move node from initial to unwalked */
714                 n             = env->initial;
715                 env->initial  = n->race_next;
716
717                 n->race_next  = env->unwalked;
718                 env->unwalked = n;
719
720                 return 0;
721         }
722
723         while (env->unwalked != NULL) {
724                 /* let n be the first node in unwalked */
725                 n = env->unwalked;
726                 while (env->index < n->n_followers) {
727                         /* let m be n.F.def_use[index] */
728                         node_t *m = get_irn_node(n->node->out[1 + env->index].use);
729
730                         assert(m->is_follower);
731                         ++env->index;
732
733                         /* only followers from our partition */
734                         if (m->part != n->part)
735                                 continue;
736
737                         if (! m->is_flagged) {
738                                 m->is_flagged = 1;
739
740                                 /* add m to unwalked not as first node (we might still need to
741                                    check for more follower node */
742                                 m->race_next = n->race_next;
743                                 n->race_next = m;
744                                 return 0;
745                         }
746                 }
747                 /* move n to walked */
748                 env->unwalked = n->race_next;
749                 n->race_next  = env->walked;
750                 env->walked   = n;
751                 env->index    = 0;
752         }
753         return 1;
754 }  /* step */
755
756 /**
757  * Clear the flags from a list.
758  *
759  * @param list  the list
760  */
761 static void clear_flags(node_t *list) {
762         node_t *n;
763
764         for (n = list; n != NULL; n = n->race_next)
765                 n->is_flagged = 0;
766 }  /* clear_flags */
767
768 /**
769  * Split a partition by a local list using the race.
770  *
771  * @param pX   pointer to the partition to split, might be changed!
772  * @param gg   a (non-empty) node list
773  * @param env  the environment
774  *
775  * @return  a new partition containing the nodes of gg
776  */
777 static partition_t *split(partition_t **pX, node_t *gg, environment_t *env) {
778         partition_t *X = *pX;
779         partition_t *X_prime;
780         list_head   tmp;
781         step_env    env1, env2, *winner;
782         node_t      *g, *h, *node;
783         int         max_input, n, m;
784
785         if (list_empty(&X->Follower)) {
786                 /* if the partition has NO follower, we can use the fast
787                    splitting algorithm. */
788                 return split_no_followers(X, gg, env);
789         }
790         /* else do the race */
791
792         /* Note: there might be n-Input followers in this partition. When we split it
793            there inputs might end up in different partitions and these nodes must
794            do the Follower->Leader transition. Put them on the cprop list to let
795            this happen. */
796         list_for_each_entry(node_t, node, &X->Follower, node_list) {
797                 assert(node->is_follower);
798                 add_to_cprop(node, env);
799         }
800
801         dump_partition("Splitting ", X);
802         dump_list("by list ", gg);
803
804         INIT_LIST_HEAD(&tmp);
805
806         /* Remove gg from X.Leader and put into g */
807         g = NULL;
808         n = 0;
809         for (node = gg; node != NULL; node = node->next) {
810                 assert(node->part == X);
811                 assert(node->is_follower == 0);
812
813                 list_del(&node->node_list);
814                 list_add_tail(&node->node_list, &tmp);
815                 node->race_next = g;
816                 g               = node;
817                 ++n;
818         }
819         /* produce h */
820         h = NULL;
821         m = 0;
822         list_for_each_entry(node_t, node, &X->Leader, node_list) {
823                 node->race_next = h;
824                 h               = node;
825                 ++m;
826         }
827         /* restore X.Leader */
828         list_splice(&tmp, &X->Leader);
829
830         env1.initial       = g;
831         env1.unwalked      = NULL;
832         env1.walked        = NULL;
833         env1.index         = 0;
834         env1.n_leader      = n;
835
836         env2.initial       = h;
837         env2.unwalked      = NULL;
838         env2.walked        = NULL;
839         env2.index         = 0;
840         env2.n_leader      = m;
841
842         for (;;) {
843                 if (step(&env1)) {
844                         winner = &env1;
845                         break;
846                 }
847                 if (step(&env2)) {
848                         winner = &env2;
849                         break;
850                 }
851         }
852         assert(winner->initial == NULL);
853         assert(winner->unwalked == NULL);
854
855         /* clear flags from walked/unwalked */
856         clear_flags(env1.unwalked);
857         clear_flags(env1.walked);
858         clear_flags(env2.unwalked);
859         clear_flags(env2.walked);
860
861         dump_race_list("winner ", winner->walked);
862
863         /* Move walked_{winner} to a new partition, X'. */
864         X_prime = new_partition(env);
865         max_input = 0;
866         for (node = winner->walked; node != NULL; node = node->race_next) {
867                 list_del(&node->node_list);
868                 if (node->is_follower) {
869                         list_add(&node->node_list, &X_prime->Follower);
870                 } else {
871                         list_add(&node->node_list, &X_prime->Leader);
872                         ++X_prime->n_leader;
873                 }
874                 node->part = X_prime;
875                 if (node->max_user_input > max_input)
876                         max_input = node->max_user_input;
877         }
878         X_prime->max_user_inputs = max_input;
879         X->n_leader             -= winner->n_leader;
880
881         /* for now, copy the type info tag, it will be adjusted in split_by(). */
882         X_prime->type_is_T_or_C = X->type_is_T_or_C;
883
884         /* X' is the smaller part */
885         add_to_worklist(X_prime, env);
886
887         dump_partition("Now ", X);
888         dump_partition("Created new ", X_prime);
889
890         /* we have to ensure that the partition containing g is returned */
891         if (winner == &env2) {
892                 *pX = X_prime;
893                 return X;
894         }
895
896         return X_prime;
897 }  /* split */
898 #endif /* NO_FOLLOWER */
899
900 /**
901  * Returns non-zero if the i'th input of a Phi node is live.
902  *
903  * @param phi  a Phi-node
904  * @param i    an input number
905  *
906  * @return non-zero if the i'th input of the given Phi node is live
907  */
908 static int is_live_input(ir_node *phi, int i) {
909         if (i >= 0) {
910                 ir_node        *block = get_nodes_block(phi);
911                 ir_node        *pred  = get_Block_cfgpred(block, i);
912                 lattice_elem_t type   = get_node_type(pred);
913
914                 return type.tv != tarval_unreachable;
915         }
916         /* else it's the control input, always live */
917         return 1;
918 }  /* is_live_input */
919
920 /**
921  * Return non-zero if a type is a constant.
922  */
923 static int is_constant_type(lattice_elem_t type) {
924         if (type.tv != tarval_bottom && type.tv != tarval_top)
925                 return 1;
926         return 0;
927 }  /* is_constant_type */
928
929 /**
930  * Check whether a type is neither Top or a constant.
931  * Note: U is handled like Top here, R is a constant.
932  *
933  * @param type  the type to check
934  */
935 static int type_is_neither_top_nor_const(const lattice_elem_t type) {
936         if (is_tarval(type.tv)) {
937                 if (type.tv == tarval_top)
938                         return 0;
939                 if (tarval_is_constant(type.tv))
940                         return 0;
941         } else {
942                 /* is a symconst */
943                 return 0;
944         }
945         return 1;
946 }
947
948 /**
949  * Collect nodes to the touched list.
950  *
951  * @param list  the list which contains the nodes that must be evaluated
952  * @param idx   the index of the def_use edge to evaluate
953  * @param env   the environment
954  */
955 static void collect_touched(list_head *list, int idx, environment_t *env) {
956         node_t  *x, *y;
957         int     end_idx = env->end_idx;
958
959         list_for_each_entry(node_t, x, list, node_list) {
960                 int num_edges;
961
962                 if (idx == -1) {
963                         /* leader edges start AFTER follower edges */
964                         x->next_edge = 1 + x->n_followers;
965                 }
966                 num_edges = get_irn_n_outs(x->node);
967
968                 /* for all edges in x.L.def_use_{idx} */
969                 while (x->next_edge <= num_edges) {
970                         ir_def_use_edge *edge = &x->node->out[x->next_edge];
971                         ir_node         *succ;
972
973                         /* check if we have necessary edges */
974                         if (edge->pos > idx)
975                                 break;
976
977                         ++x->next_edge;
978
979                         succ = edge->use;
980
981                         /* ignore the "control input" for non-pinned nodes
982                         if we are running in GCSE mode */
983                         if (idx < end_idx && get_irn_pinned(succ) != op_pin_state_pinned)
984                                 continue;
985
986                         y = get_irn_node(succ);
987                         if (is_constant_type(y->type)) {
988                                 ir_opcode code = get_irn_opcode(succ);
989                                 if (code == iro_Sub || code == iro_Cmp)
990                                         add_to_cprop(y, env);
991                         }
992
993                         /* Partitions of constants should not be split simply because their Nodes have unequal
994                            functions or incongruent inputs. */
995                         if (type_is_neither_top_nor_const(y->type) &&
996                                 (! is_Phi(y->node) || is_live_input(y->node, idx))) {
997                                         add_to_touched(y, env);
998                         }
999                 }
1000         }
1001 }  /* collect_touched */
1002
1003 /**
1004  * Split the partitions if caused by the first entry on the worklist.
1005  *
1006  * @param env  the environment
1007  */
1008 static void cause_splits(environment_t *env) {
1009         partition_t *X, *Z, *N;
1010         int         idx;
1011
1012         /* remove the first partition from the worklist */
1013         X = env->worklist;
1014         env->worklist  = X->wl_next;
1015         X->on_worklist = 0;
1016
1017         dump_partition("Cause_split: ", X);
1018
1019         /* combine temporary leader and follower list */
1020         for (idx = -1; idx <= X->max_user_inputs; ++idx) {
1021                 /* empty the touched set: already done, just clear the list */
1022                 env->touched = NULL;
1023
1024                 collect_touched(&X->Leader, idx, env);
1025                 collect_touched(&X->Follower, idx, env);
1026
1027                 for (Z = env->touched; Z != NULL; Z = N) {
1028                         node_t **pe, *e;
1029                         node_t *touched;
1030                         unsigned n_touched = Z->n_touched;
1031
1032                         assert(Z->touched != NULL);
1033
1034                         /* beware, split might change Z */
1035                         N = Z->touched_next;
1036
1037                         /* remove it from the touched set */
1038                         Z->on_touched = 0;
1039
1040                         /* Empty local Z.touched AND filter out followers. */
1041                         for (pe = &Z->touched; (*pe) != NULL; pe = &e->next) {
1042                                 e = *pe;
1043                                 e->on_touched = 0;
1044                                 if (e->is_follower) {
1045                                         DB((dbg, LEVEL_2, "Removed follower %+F from touched\n", e->node));
1046                                         --n_touched;
1047                                         *(pe) = e->next;
1048                                 }
1049                         }
1050                         touched      = Z->touched;
1051                         Z->touched   = NULL;
1052                         Z->n_touched = 0;
1053
1054                         if (n_touched > 0 && Z->n_leader != n_touched) {
1055                                 DB((dbg, LEVEL_2, "Split part%d by touched\n", Z->nr));
1056                                 split(&Z, touched, env);
1057                         }
1058                 }
1059         }
1060 }  /* cause_splits */
1061
1062 /**
1063  * Implements split_by_what(): Split a partition by characteristics given
1064  * by the what function.
1065  *
1066  * @param X     the partition to split
1067  * @param What  a function returning an Id for every node of the partition X
1068  * @param P     a list to store the result partitions
1069  * @param env   the environment
1070  *
1071  * @return *P
1072  */
1073 static partition_t *split_by_what(partition_t *X, what_func What,
1074                                   partition_t **P, environment_t *env) {
1075         node_t          *x, *S;
1076         listmap_t       map;
1077         listmap_entry_t *iter;
1078         partition_t     *R;
1079
1080         /* Let map be an empty mapping from the range of What to (local) list of Nodes. */
1081         listmap_init(&map);
1082         list_for_each_entry(node_t, x, &X->Leader, node_list) {
1083                 void            *id = What(x, env);
1084                 listmap_entry_t *entry;
1085
1086                 if (id == NULL) {
1087                         /* input not allowed, ignore */
1088                         continue;
1089                 }
1090                 /* Add x to map[What(x)]. */
1091                 entry = listmap_find(&map, id);
1092                 x->next     = entry->list;
1093                 entry->list = x;
1094         }
1095         /* Let P be a set of Partitions. */
1096
1097         /* for all sets S except one in the range of map do */
1098         for (iter = map.values; iter != NULL; iter = iter->next) {
1099                 if (iter->next == NULL) {
1100                         /* this is the last entry, ignore */
1101                         break;
1102                 }
1103                 S = iter->list;
1104
1105                 /* Add SPLIT( X, S ) to P. */
1106                 DB((dbg, LEVEL_2, "Split part%d by what\n", X->nr));
1107                 R = split(&X, S, env);
1108                 R->split_next = *P;
1109                 *P            = R;
1110         }
1111         /* Add X to P. */
1112         X->split_next = *P;
1113         *P            = X;
1114
1115         listmap_term(&map);
1116         return *P;
1117 }  /* split_by_what */
1118
1119 /** lambda n.(n.type) */
1120 static void *lambda_type(const node_t *node, environment_t *env) {
1121         (void)env;
1122         return node->type.tv;
1123 }  /* lambda_type */
1124
1125 /** lambda n.(n.opcode) */
1126 static void *lambda_opcode(const node_t *node, environment_t *env) {
1127         opcode_key_t key, *entry;
1128         ir_node      *irn = node->node;
1129
1130         key.code   = get_irn_opcode(irn);
1131         key.mode   = get_irn_mode(irn);
1132         key.u.proj = 0;
1133         key.u.ent  = NULL;
1134
1135         switch (get_irn_opcode(irn)) {
1136         case iro_Proj:
1137                 key.u.proj = get_Proj_proj(irn);
1138                 break;
1139         case iro_Sel:
1140                 key.u.ent = get_Sel_entity(irn);
1141                 break;
1142         default:
1143                 break;
1144         }
1145
1146         entry = set_insert(env->opcode2id_map, &key, sizeof(key), opcode_hash(&key));
1147         return entry;
1148 }  /* lambda_opcode */
1149
1150 /** lambda n.(n[i].partition) */
1151 static void *lambda_partition(const node_t *node, environment_t *env) {
1152         ir_node *skipped = skip_Proj(node->node);
1153         ir_node *pred;
1154         node_t  *p;
1155         int     i = env->lambda_input;
1156
1157         if (i >= get_irn_arity(node->node)) {
1158                 /* we are outside the allowed range */
1159                 return NULL;
1160         }
1161
1162         /* ignore the "control input" for non-pinned nodes
1163            if we are running in GCSE mode */
1164         if (i < env->end_idx && get_irn_pinned(skipped) != op_pin_state_pinned)
1165                 return NULL;
1166
1167         pred = i == -1 ? get_irn_n(skipped, i) : get_irn_n(node->node, i);
1168         p    = get_irn_node(pred);
1169
1170         return p->part;
1171 }  /* lambda_partition */
1172
1173 /**
1174  * Returns true if a type is a constant.
1175  */
1176 static int is_con(const lattice_elem_t type) {
1177         /* be conservative */
1178         if (is_tarval(type.tv))
1179                 return tarval_is_constant(type.tv);
1180         return is_entity(type.sym.entity_p);
1181 }  /* is_con */
1182
1183 /**
1184  * Implements split_by().
1185  *
1186  * @param X    the partition to split
1187  * @param env  the environment
1188  */
1189 static void split_by(partition_t *X, environment_t *env) {
1190         partition_t *I, *P = NULL;
1191         int         input;
1192
1193         dump_partition("split_by", X);
1194
1195         if (X->n_leader == 1) {
1196                 /* we have only one leader, no need to split, just check it's type */
1197                 node_t *x = get_first_node(X);
1198                 X->type_is_T_or_C = x->type.tv == tarval_top || is_con(x->type);
1199                 return;
1200         }
1201
1202         DB((dbg, LEVEL_2, "WHAT = lambda n.(n.type) on part%d\n", X->nr));
1203         P = split_by_what(X, lambda_type, &P, env);
1204
1205         /* adjust the type tags, we have split partitions by type */
1206         for (I = P; I != NULL; I = I->split_next) {
1207                 node_t *x = get_first_node(I);
1208                 I->type_is_T_or_C = x->type.tv == tarval_top || is_con(x->type);
1209         }
1210
1211         do {
1212                 partition_t *Y = P;
1213
1214                 P = P->split_next;
1215                 if (Y->n_leader > 1) {
1216                         /* we do not want split the TOP or constant partitions */
1217                         if (! Y->type_is_T_or_C) {
1218                                 partition_t *Q = NULL;
1219
1220                                 DB((dbg, LEVEL_2, "WHAT = lambda n.(n.opcode) on part%d\n", Y->nr));
1221                                 Q = split_by_what(Y, lambda_opcode, &Q, env);
1222
1223                                 do {
1224                                         partition_t *Z = Q;
1225
1226                                         Q = Q->split_next;
1227                                         if (Z->n_leader > 1) {
1228                                                 const node_t *first = get_first_node(Z);
1229                                                 int          arity  = get_irn_arity(first->node);
1230                                                 partition_t  *R, *S;
1231
1232                                                 /*
1233                                                  * BEWARE: during splitting by input 2 for instance we might
1234                                                  * create new partitions which are different by input 1, so collect
1235                                                  * them and split further.
1236                                                  */
1237                                                 Z->split_next = NULL;
1238                                                 R             = Z;
1239                                                 S             = NULL;
1240                                                 for (input = arity - 1; input >= -1; --input) {
1241                                                         do {
1242                                                                 partition_t *Z_prime = R;
1243
1244                                                                 R = R->split_next;
1245                                                                 if (Z_prime->n_leader > 1) {
1246                                                                         env->lambda_input = input;
1247                                                                         DB((dbg, LEVEL_2, "WHAT = lambda n.(n[%d].partition) on part%d\n", input, Z_prime->nr));
1248                                                                         S = split_by_what(Z_prime, lambda_partition, &S, env);
1249                                                                 } else {
1250                                                                         Z_prime->split_next = S;
1251                                                                         S                   = Z_prime;
1252                                                                 }
1253                                                         } while (R != NULL);
1254                                                         R = S;
1255                                                         S = NULL;
1256                                                 }
1257                                         }
1258                                 } while (Q != NULL);
1259                         }
1260                 }
1261         } while (P != NULL);
1262 }  /* split_by */
1263
1264 /**
1265  * (Re-)compute the type for a given node.
1266  *
1267  * @param node  the node
1268  */
1269 static void default_compute(node_t *node) {
1270         int     i;
1271         ir_node *irn = node->node;
1272         node_t  *block = get_irn_node(get_nodes_block(irn));
1273
1274         if (block->type.tv == tarval_unreachable) {
1275                 node->type.tv = tarval_top;
1276                 return;
1277         }
1278
1279         /* if any of the data inputs have type top, the result is type top */
1280         for (i = get_irn_arity(irn) - 1; i >= 0; --i) {
1281                 ir_node *pred = get_irn_n(irn, i);
1282                 node_t  *p    = get_irn_node(pred);
1283
1284                 if (p->type.tv == tarval_top) {
1285                         node->type.tv = tarval_top;
1286                         return;
1287                 }
1288         }
1289
1290         if (get_irn_mode(node->node) == mode_X)
1291                 node->type.tv = tarval_reachable;
1292         else
1293                 node->type.tv = computed_value(irn);
1294 }  /* default_compute */
1295
1296 /**
1297  * (Re-)compute the type for a Block node.
1298  *
1299  * @param node  the node
1300  */
1301 static void compute_Block(node_t *node) {
1302         int     i;
1303         ir_node *block = node->node;
1304
1305         if (block == get_irg_start_block(current_ir_graph)) {
1306                 /* start block is always reachable */
1307                 node->type.tv = tarval_reachable;
1308                 return;
1309         }
1310
1311         for (i = get_Block_n_cfgpreds(block) - 1; i >= 0; --i) {
1312                 node_t *pred = get_irn_node(get_Block_cfgpred(block, i));
1313
1314                 if (pred->type.tv == tarval_reachable) {
1315                         /* A block is reachable, if at least of predecessor is reachable. */
1316                         node->type.tv = tarval_reachable;
1317                         return;
1318                 }
1319         }
1320         node->type.tv = tarval_top;
1321 }  /* compute_Block */
1322
1323 /**
1324  * (Re-)compute the type for a Bad node.
1325  *
1326  * @param node  the node
1327  */
1328 static void compute_Bad(node_t *node) {
1329         /* Bad nodes ALWAYS compute Top */
1330         node->type.tv = tarval_top;
1331 }  /* compute_Bad */
1332
1333 /**
1334  * (Re-)compute the type for an Unknown node.
1335  *
1336  * @param node  the node
1337  */
1338 static void compute_Unknown(node_t *node) {
1339         /* While Unknown nodes should compute Top this is dangerous:
1340          * a Top input to a Cond would lead to BOTH control flows unreachable.
1341          * While this is correct in the given semantics, it would destroy the Firm
1342          * graph.
1343          *
1344          * It would be safe to compute Top IF it can be assured, that only Cmp
1345          * nodes are inputs to Conds. We check that first.
1346          * This is the way Frontends typically build Firm, but some optimizations
1347          * (cond_eval for instance) might replace them by Phib's...
1348          *
1349          * For now, we compute bottom here.
1350          */
1351         node->type.tv = tarval_bottom;
1352 }  /* compute_Unknown */
1353
1354 /**
1355  * (Re-)compute the type for a Jmp node.
1356  *
1357  * @param node  the node
1358  */
1359 static void compute_Jmp(node_t *node) {
1360         node_t *block = get_irn_node(get_nodes_block(node->node));
1361
1362         node->type = block->type;
1363 }  /* compute_Jmp */
1364
1365 /**
1366  * (Re-)compute the type for the End node.
1367  *
1368  * @param node  the node
1369  */
1370 static void compute_End(node_t *node) {
1371         /* the End node is NOT dead of course */
1372         node->type.tv = tarval_reachable;
1373 }
1374
1375 /**
1376  * (Re-)compute the type for a SymConst node.
1377  *
1378  * @param node  the node
1379  */
1380 static void compute_SymConst(node_t *node) {
1381         ir_node *irn = node->node;
1382         node_t  *block = get_irn_node(get_nodes_block(irn));
1383
1384         if (block->type.tv == tarval_unreachable) {
1385                 node->type.tv = tarval_top;
1386                 return;
1387         }
1388         switch (get_SymConst_kind(irn)) {
1389         case symconst_addr_ent:
1390         /* case symconst_addr_name: cannot handle this yet */
1391                 node->type.sym = get_SymConst_symbol(irn);
1392                 break;
1393         default:
1394                 node->type.tv = computed_value(irn);
1395         }
1396 }  /* compute_SymConst */
1397
1398 /**
1399  * (Re-)compute the type for a Phi node.
1400  *
1401  * @param node  the node
1402  */
1403 static void compute_Phi(node_t *node) {
1404         int            i;
1405         ir_node        *phi = node->node;
1406         lattice_elem_t type;
1407
1408         /* if a Phi is in a unreachable block, its type is TOP */
1409         node_t *block = get_irn_node(get_nodes_block(phi));
1410
1411         if (block->type.tv == tarval_unreachable) {
1412                 node->type.tv = tarval_top;
1413                 return;
1414         }
1415
1416         /* Phi implements the Meet operation */
1417         type.tv = tarval_top;
1418         for (i = get_Phi_n_preds(phi) - 1; i >= 0; --i) {
1419                 node_t *pred   = get_irn_node(get_Phi_pred(phi, i));
1420                 node_t *pred_X = get_irn_node(get_Block_cfgpred(block->node, i));
1421
1422                 if (pred_X->type.tv == tarval_unreachable || pred->type.tv == tarval_top) {
1423                         /* ignore TOP inputs: We must check here for unreachable blocks,
1424                            because Firm constants live in the Start Block are NEVER Top.
1425                            Else, a Phi (1,2) will produce Bottom, even if the 2 for instance
1426                            comes from a unreachable input. */
1427                         continue;
1428                 }
1429                 if (pred->type.tv == tarval_bottom) {
1430                         node->type.tv = tarval_bottom;
1431                         return;
1432                 } else if (type.tv == tarval_top) {
1433                         /* first constant found */
1434                         type = pred->type;
1435                 } else if (type.tv != pred->type.tv) {
1436                         /* different constants or tarval_bottom */
1437                         node->type.tv = tarval_bottom;
1438                         return;
1439                 }
1440                 /* else nothing, constants are the same */
1441         }
1442         node->type = type;
1443 }  /* compute_Phi */
1444
1445 /**
1446  * (Re-)compute the type for an Add. Special case: one nodes is a Zero Const.
1447  *
1448  * @param node  the node
1449  */
1450 static void compute_Add(node_t *node) {
1451         ir_node        *sub = node->node;
1452         node_t         *l   = get_irn_node(get_Add_left(sub));
1453         node_t         *r   = get_irn_node(get_Add_right(sub));
1454         lattice_elem_t a    = l->type;
1455         lattice_elem_t b    = r->type;
1456         ir_mode        *mode;
1457
1458         if (a.tv == tarval_top || b.tv == tarval_top) {
1459                 node->type.tv = tarval_top;
1460         } else if (a.tv == tarval_bottom || b.tv == tarval_bottom) {
1461                 node->type.tv = tarval_bottom;
1462         } else {
1463                 /* x + 0 = 0 + x = x, but beware of floating point +0 + -0, so we
1464                    must call tarval_add() first to handle this case! */
1465                 if (is_tarval(a.tv)) {
1466                         if (is_tarval(b.tv)) {
1467                                 node->type.tv = tarval_add(a.tv, b.tv);
1468                                 return;
1469                         }
1470                         mode = get_tarval_mode(a.tv);
1471                         if (a.tv == get_mode_null(mode)) {
1472                                 node->type = b;
1473                                 return;
1474                         }
1475                 } else if (is_tarval(b.tv)) {
1476                         mode = get_tarval_mode(b.tv);
1477                         if (b.tv == get_mode_null(mode)) {
1478                                 node->type = a;
1479                                 return;
1480                         }
1481                 }
1482                 node->type.tv = tarval_bottom;
1483         }
1484 }  /* compute_Add */
1485
1486 /**
1487  * (Re-)compute the type for a Sub. Special case: both nodes are congruent.
1488  *
1489  * @param node  the node
1490  */
1491 static void compute_Sub(node_t *node) {
1492         ir_node        *sub = node->node;
1493         node_t         *l   = get_irn_node(get_Sub_left(sub));
1494         node_t         *r   = get_irn_node(get_Sub_right(sub));
1495         lattice_elem_t a    = l->type;
1496         lattice_elem_t b    = r->type;
1497         tarval         *tv;
1498
1499         if (a.tv == tarval_top || b.tv == tarval_top) {
1500                 node->type.tv = tarval_top;
1501         } else if (is_con(a) && is_con(b)) {
1502                 if (is_tarval(a.tv) && is_tarval(b.tv)) {
1503                         node->type.tv = tarval_sub(a.tv, b.tv, get_irn_mode(sub));
1504                 } else if (is_tarval(a.tv) && tarval_is_null(a.tv)) {
1505                         node->type = b;
1506                 } else if (is_tarval(b.tv) && tarval_is_null(b.tv)) {
1507                         node->type = a;
1508                 } else {
1509                         node->type.tv = tarval_bottom;
1510                 }
1511                 node->by_all_const = 1;
1512         } else if (r->part == l->part &&
1513                    (!mode_is_float(get_irn_mode(l->node)))) {
1514                 /*
1515                  * BEWARE: a - a is NOT always 0 for floating Point values, as
1516                  * NaN op NaN = NaN, so we must check this here.
1517                  */
1518                 ir_mode *mode = get_irn_mode(sub);
1519                 tv = get_mode_null(mode);
1520
1521                 /* if the node was ONCE evaluated by all constants, but now
1522                    this breakes AND we cat by partition a different result, switch to bottom.
1523                    This happens because initially all nodes are in the same partition ... */
1524                 if (node->by_all_const && node->type.tv != tv)
1525                         tv = tarval_bottom;
1526                 node->type.tv = tv;
1527         } else {
1528                 node->type.tv = tarval_bottom;
1529         }
1530 }  /* compute_Sub */
1531
1532 /**
1533  * (Re-)compute the type for Cmp.
1534  *
1535  * @param node  the node
1536  */
1537 static void compute_Cmp(node_t *node) {
1538         ir_node        *cmp  = node->node;
1539         node_t         *l    = get_irn_node(get_Cmp_left(cmp));
1540         node_t         *r    = get_irn_node(get_Cmp_right(cmp));
1541         lattice_elem_t a     = l->type;
1542         lattice_elem_t b     = r->type;
1543
1544         if (a.tv == tarval_top || b.tv == tarval_top) {
1545                 node->type.tv = tarval_top;
1546         } else if (is_con(a) && is_con(b)) {
1547                 /* both nodes are constants, we can probably do something */
1548                 node->type.tv = tarval_b_true;
1549         } else if (r->part == l->part) {
1550                 /* both nodes congruent, we can probably do something */
1551                 node->type.tv = tarval_b_true;
1552         } else {
1553                 node->type.tv = tarval_bottom;
1554         }
1555 }  /* compute_Proj_Cmp */
1556
1557 /**
1558  * (Re-)compute the type for a Proj(Cmp).
1559  *
1560  * @param node  the node
1561  * @param cond  the predecessor Cmp node
1562  */
1563 static void compute_Proj_Cmp(node_t *node, ir_node *cmp) {
1564         ir_node        *proj = node->node;
1565         node_t         *l    = get_irn_node(get_Cmp_left(cmp));
1566         node_t         *r    = get_irn_node(get_Cmp_right(cmp));
1567         lattice_elem_t a     = l->type;
1568         lattice_elem_t b     = r->type;
1569         pn_Cmp         pnc   = get_Proj_proj(proj);
1570         tarval         *tv;
1571
1572         if (a.tv == tarval_top || b.tv == tarval_top) {
1573                 node->type.tv = tarval_top;
1574         } else if (is_con(a) && is_con(b)) {
1575                 default_compute(node);
1576                 node->by_all_const = 1;
1577         } else if (r->part == l->part &&
1578                    (!mode_is_float(get_irn_mode(l->node)) || pnc == pn_Cmp_Lt || pnc == pn_Cmp_Gt)) {
1579                 /*
1580                  * BEWARE: a == a is NOT always True for floating Point values, as
1581                  * NaN != NaN is defined, so we must check this here.
1582                  */
1583                 tv = new_tarval_from_long(pnc & pn_Cmp_Eq, mode_b);
1584
1585                 /* if the node was ONCE evaluated by all constants, but now
1586                    this breakes AND we cat by partition a different result, switch to bottom.
1587                    This happens because initially all nodes are in the same partition ... */
1588                 if (node->by_all_const && node->type.tv != tv)
1589                         tv = tarval_bottom;
1590                 node->type.tv = tv;
1591         } else {
1592                 node->type.tv = tarval_bottom;
1593         }
1594 }  /* compute_Proj_Cmp */
1595
1596 /**
1597  * (Re-)compute the type for a Proj(Cond).
1598  *
1599  * @param node  the node
1600  * @param cond  the predecessor Cond node
1601  */
1602 static void compute_Proj_Cond(node_t *node, ir_node *cond) {
1603         ir_node *proj     = node->node;
1604         long    pnc       = get_Proj_proj(proj);
1605         ir_node *sel      = get_Cond_selector(cond);
1606         node_t  *selector = get_irn_node(sel);
1607
1608         if (get_irn_mode(sel) == mode_b) {
1609                 /* an IF */
1610                 if (pnc == pn_Cond_true) {
1611                         if (selector->type.tv == tarval_b_false) {
1612                                 node->type.tv = tarval_unreachable;
1613                         } else if (selector->type.tv == tarval_b_true) {
1614                                 node->type.tv = tarval_reachable;
1615                         } else if (selector->type.tv == tarval_bottom) {
1616                                 node->type.tv = tarval_reachable;
1617                         } else {
1618                                 assert(selector->type.tv == tarval_top);
1619                                 node->type.tv = tarval_unreachable;
1620                         }
1621                 } else {
1622                         assert(pnc == pn_Cond_false);
1623
1624                         if (selector->type.tv == tarval_b_false) {
1625                                 node->type.tv = tarval_reachable;
1626                         } else if (selector->type.tv == tarval_b_true) {
1627                                 node->type.tv = tarval_unreachable;
1628                         } else if (selector->type.tv == tarval_bottom) {
1629                                 node->type.tv = tarval_reachable;
1630                         } else {
1631                                 assert(selector->type.tv == tarval_top);
1632                                 node->type.tv = tarval_unreachable;
1633                         }
1634                 }
1635         } else {
1636                 /* an SWITCH */
1637                 if (selector->type.tv == tarval_bottom) {
1638                         node->type.tv = tarval_reachable;
1639                 } else if (selector->type.tv == tarval_top) {
1640                         node->type.tv = tarval_unreachable;
1641                 } else {
1642                         long value = get_tarval_long(selector->type.tv);
1643                         if (pnc == get_Cond_defaultProj(cond)) {
1644                                 /* default switch, have to check ALL other cases */
1645                                 int i;
1646
1647                                 for (i = get_irn_n_outs(cond) - 1; i >= 0; --i) {
1648                                         ir_node *succ = get_irn_out(cond, i);
1649
1650                                         if (succ == proj)
1651                                                 continue;
1652                                         if (value == get_Proj_proj(succ)) {
1653                                                 /* we found a match, will NOT take the default case */
1654                                                 node->type.tv = tarval_unreachable;
1655                                                 return;
1656                                         }
1657                                 }
1658                                 /* all cases checked, no match, will take default case */
1659                                 node->type.tv = tarval_reachable;
1660                         } else {
1661                                 /* normal case */
1662                                 node->type.tv = value == pnc ? tarval_reachable : tarval_unreachable;
1663                         }
1664                 }
1665         }
1666 }  /* compute_Proj_Cond */
1667
1668 /**
1669  * (Re-)compute the type for a Proj-Node.
1670  *
1671  * @param node  the node
1672  */
1673 static void compute_Proj(node_t *node) {
1674         ir_node *proj = node->node;
1675         ir_mode *mode = get_irn_mode(proj);
1676         node_t  *block = get_irn_node(get_nodes_block(skip_Proj(proj)));
1677         ir_node *pred  = get_Proj_pred(proj);
1678
1679         if (block->type.tv == tarval_unreachable) {
1680                 /* a Proj in a unreachable Block stay Top */
1681                 node->type.tv = tarval_top;
1682                 return;
1683         }
1684         if (get_irn_node(pred)->type.tv == tarval_top) {
1685                 /* if the predecessor is Top, its Proj follow */
1686                 node->type.tv = tarval_top;
1687                 return;
1688         }
1689
1690         if (mode == mode_M) {
1691                 /* mode M is always bottom */
1692                 node->type.tv = tarval_bottom;
1693                 return;
1694         }
1695         if (mode != mode_X) {
1696                 if (is_Cmp(pred))
1697                         compute_Proj_Cmp(node, pred);
1698                 else
1699                         default_compute(node);
1700                 return;
1701         }
1702         /* handle mode_X nodes */
1703
1704         switch (get_irn_opcode(pred)) {
1705         case iro_Start:
1706                 /* the Proj_X from the Start is always reachable.
1707                    However this is already handled at the top. */
1708                 node->type.tv = tarval_reachable;
1709                 break;
1710         case iro_Cond:
1711                 compute_Proj_Cond(node, pred);
1712                 break;
1713         default:
1714                 default_compute(node);
1715         }
1716 }  /* compute_Proj */
1717
1718 /**
1719  * (Re-)compute the type for a Confirm.
1720  *
1721  * @param node  the node
1722  */
1723 static void compute_Confirm(node_t *node) {
1724         ir_node *confirm = node->node;
1725         node_t  *pred = get_irn_node(get_Confirm_value(confirm));
1726
1727         if (get_Confirm_cmp(confirm) == pn_Cmp_Eq) {
1728                 node_t *bound = get_irn_node(get_Confirm_bound(confirm));
1729
1730                 if (is_con(bound->type)) {
1731                         /* is equal to a constant */
1732                         node->type = bound->type;
1733                         return;
1734                 }
1735         }
1736         /* a Confirm is a copy OR a Const */
1737         node->type = pred->type;
1738 }  /* compute_Confirm */
1739
1740 /**
1741  * (Re-)compute the type for a Max.
1742  *
1743  * @param node  the node
1744  */
1745 static void compute_Max(node_t *node) {
1746         ir_node        *op   = node->node;
1747         node_t         *l    = get_irn_node(get_binop_left(op));
1748         node_t         *r    = get_irn_node(get_binop_right(op));
1749         lattice_elem_t a     = l->type;
1750         lattice_elem_t b     = r->type;
1751
1752         if (a.tv == tarval_top || b.tv == tarval_top) {
1753                 node->type.tv = tarval_top;
1754         } else if (is_con(a) && is_con(b)) {
1755                 /* both nodes are constants, we can probably do something */
1756                 if (a.tv == b.tv) {
1757                         /* this case handles symconsts as well */
1758                         node->type = a;
1759                 } else {
1760                         ir_mode *mode   = get_irn_mode(op);
1761                         tarval  *tv_min = get_mode_min(mode);
1762
1763                         if (a.tv == tv_min)
1764                                 node->type = b;
1765                         else if (b.tv == tv_min)
1766                                 node->type = a;
1767                         else if (is_tarval(a.tv) && is_tarval(b.tv)) {
1768                                 if (tarval_cmp(a.tv, b.tv) & pn_Cmp_Gt)
1769                                         node->type.tv = a.tv;
1770                                 else
1771                                         node->type.tv = b.tv;
1772                         } else {
1773                                 node->type.tv = tarval_bad;
1774                         }
1775                 }
1776         } else if (r->part == l->part) {
1777                 /* both nodes congruent, we can probably do something */
1778                 node->type = a;
1779         } else {
1780                 node->type.tv = tarval_bottom;
1781         }
1782 }  /* compute_Max */
1783
1784 /**
1785  * (Re-)compute the type for a Min.
1786  *
1787  * @param node  the node
1788  */
1789 static void compute_Min(node_t *node) {
1790         ir_node        *op   = node->node;
1791         node_t         *l    = get_irn_node(get_binop_left(op));
1792         node_t         *r    = get_irn_node(get_binop_right(op));
1793         lattice_elem_t a     = l->type;
1794         lattice_elem_t b     = r->type;
1795
1796         if (a.tv == tarval_top || b.tv == tarval_top) {
1797                 node->type.tv = tarval_top;
1798         } else if (is_con(a) && is_con(b)) {
1799                 /* both nodes are constants, we can probably do something */
1800                 if (a.tv == b.tv) {
1801                         /* this case handles symconsts as well */
1802                         node->type = a;
1803                 } else {
1804                         ir_mode *mode   = get_irn_mode(op);
1805                         tarval  *tv_max = get_mode_max(mode);
1806
1807                         if (a.tv == tv_max)
1808                                 node->type = b;
1809                         else if (b.tv == tv_max)
1810                                 node->type = a;
1811                         else if (is_tarval(a.tv) && is_tarval(b.tv)) {
1812                                 if (tarval_cmp(a.tv, b.tv) & pn_Cmp_Gt)
1813                                         node->type.tv = a.tv;
1814                                 else
1815                                         node->type.tv = b.tv;
1816                         } else {
1817                                 node->type.tv = tarval_bad;
1818                         }
1819                 }
1820         } else if (r->part == l->part) {
1821                 /* both nodes congruent, we can probably do something */
1822                 node->type = a;
1823         } else {
1824                 node->type.tv = tarval_bottom;
1825         }
1826 }  /* compute_Min */
1827
1828 /**
1829  * (Re-)compute the type for a given node.
1830  *
1831  * @param node  the node
1832  */
1833 static void compute(node_t *node) {
1834         compute_func func;
1835
1836         if (is_no_Block(node->node)) {
1837                 node_t *block = get_irn_node(get_nodes_block(node->node));
1838
1839                 if (block->type.tv == tarval_unreachable) {
1840                         node->type.tv = tarval_top;
1841                         return;
1842                 }
1843         }
1844
1845         func = (compute_func)node->node->op->ops.generic;
1846         if (func != NULL)
1847                 func(node);
1848 }  /* compute */
1849
1850 /*
1851  * Identity functions: Note that one might thing that identity() is just a
1852  * synonym for equivalent_node(). While this is true, we cannot use it for the algorithm
1853  * here, because it expects that the identity node is one of the inputs, which is NOT
1854  * always true for equivalent_node() which can handle (and does sometimes) DAGs.
1855  * So, we have our own implementation, which copies some parts of equivalent_node()
1856  */
1857
1858 /**
1859  * Calculates the Identity for Phi nodes
1860  */
1861 static node_t *identity_Phi(node_t *node) {
1862         ir_node *phi    = node->node;
1863         ir_node *block  = get_nodes_block(phi);
1864         node_t  *n_part = NULL;
1865         int     i;
1866
1867         for (i = get_Phi_n_preds(phi) - 1; i >= 0; --i) {
1868                 node_t *pred_X = get_irn_node(get_Block_cfgpred(block, i));
1869
1870                 if (pred_X->type.tv == tarval_reachable) {
1871                         node_t *pred = get_irn_node(get_Phi_pred(phi, i));
1872
1873                         if (n_part == NULL)
1874                                 n_part = pred;
1875                         else if (n_part->part != pred->part) {
1876                                 /* incongruent inputs, not a follower */
1877                                 return node;
1878                         }
1879                 }
1880         }
1881         /* if n_part is NULL here, all inputs path are dead, the Phi computes
1882          * tarval_top, is in the TOP partition and should NOT being split! */
1883         assert(n_part != NULL);
1884         return n_part;
1885 }  /* identity_Phi */
1886
1887 /**
1888  * Calculates the Identity for commutative 0 neutral nodes.
1889  */
1890 static node_t *identity_comm_zero_binop(node_t *node) {
1891         ir_node *op   = node->node;
1892         node_t  *a    = get_irn_node(get_binop_left(op));
1893         node_t  *b    = get_irn_node(get_binop_right(op));
1894         ir_mode *mode = get_irn_mode(op);
1895         tarval  *zero;
1896
1897         /* for FP these optimizations are only allowed if fp_strict_algebraic is disabled */
1898         if (mode_is_float(mode) && (get_irg_fp_model(current_ir_graph) & fp_strict_algebraic))
1899                 return node;
1900
1901         /* node: no input should be tarval_top, else the binop would be also
1902          * Top and not being split. */
1903         zero = get_mode_null(mode);
1904         if (a->type.tv == zero)
1905                 return b;
1906         if (b->type.tv == zero)
1907                 return a;
1908         return node;
1909 }  /* identity_comm_zero_binop */
1910
1911 #define identity_Add  identity_comm_zero_binop
1912 #define identity_Or   identity_comm_zero_binop
1913
1914 /**
1915  * Calculates the Identity for Mul nodes.
1916  */
1917 static node_t *identity_Mul(node_t *node) {
1918         ir_node *op   = node->node;
1919         node_t  *a    = get_irn_node(get_Mul_left(op));
1920         node_t  *b    = get_irn_node(get_Mul_right(op));
1921         ir_mode *mode = get_irn_mode(op);
1922         tarval  *one;
1923
1924         /* for FP these optimizations are only allowed if fp_strict_algebraic is disabled */
1925         if (mode_is_float(mode) && (get_irg_fp_model(current_ir_graph) & fp_strict_algebraic))
1926                 return node;
1927
1928         /* node: no input should be tarval_top, else the binop would be also
1929          * Top and not being split. */
1930         one = get_mode_one(mode);
1931         if (a->type.tv == one)
1932                 return b;
1933         if (b->type.tv == one)
1934                 return a;
1935         return node;
1936 }  /* identity_Mul */
1937
1938 /**
1939  * Calculates the Identity for Sub nodes.
1940  */
1941 static node_t *identity_Sub(node_t *node) {
1942         ir_node *sub  = node->node;
1943         node_t  *b    = get_irn_node(get_Sub_right(sub));
1944         ir_mode *mode = get_irn_mode(sub);
1945
1946         /* for FP these optimizations are only allowed if fp_strict_algebraic is disabled */
1947         if (mode_is_float(mode) && (get_irg_fp_model(current_ir_graph) & fp_strict_algebraic))
1948                 return node;
1949
1950         /* node: no input should be tarval_top, else the binop would be also
1951          * Top and not being split. */
1952         if (b->type.tv == get_mode_null(mode))
1953                 return get_irn_node(get_Sub_left(sub));
1954         return node;
1955 }  /* identity_Mul */
1956
1957 /**
1958  * Calculates the Identity for And nodes.
1959  */
1960 static node_t *identity_And(node_t *node) {
1961         ir_node *and = node->node;
1962         node_t  *a   = get_irn_node(get_And_left(and));
1963         node_t  *b   = get_irn_node(get_And_right(and));
1964         tarval  *neutral = get_mode_all_one(get_irn_mode(and));
1965
1966         /* node: no input should be tarval_top, else the And would be also
1967          * Top and not being split. */
1968         if (a->type.tv == neutral)
1969                 return b;
1970         if (b->type.tv == neutral)
1971                 return a;
1972         return node;
1973 }  /* identity_And */
1974
1975 /**
1976  * Calculates the Identity for Confirm nodes.
1977  */
1978 static node_t *identity_Confirm(node_t *node) {
1979         ir_node *confirm = node->node;
1980
1981         /* a Confirm is always a Copy */
1982         return get_irn_node(get_Confirm_value(confirm));
1983 }  /* identity_Confirm */
1984
1985 /**
1986  * Calculates the Identity for Mux nodes.
1987  */
1988 static node_t *identity_Mux(node_t *node) {
1989         ir_node *mux = node->node;
1990         node_t  *sel = get_irn_node(get_Mux_sel(mux));
1991         node_t  *t   = get_irn_node(get_Mux_true(mux));
1992         node_t  *f   = get_irn_node(get_Mux_false(mux));
1993
1994         if (t->part == f->part)
1995                 return t;
1996
1997         /* Mux sel input is mode_b, so it is always a tarval */
1998         if (sel->type.tv == tarval_b_true)
1999                 return t;
2000         if (sel->type.tv == tarval_b_false)
2001                 return f;
2002         return node;
2003 }  /* identity_Mux */
2004
2005 /**
2006  * Calculates the Identity for Min nodes.
2007  */
2008 static node_t *identity_Min(node_t *node) {
2009         ir_node *op   = node->node;
2010         node_t  *a    = get_irn_node(get_binop_left(op));
2011         node_t  *b    = get_irn_node(get_binop_right(op));
2012         ir_mode *mode = get_irn_mode(op);
2013         tarval  *tv_max;
2014
2015         if (a->part == b->part) {
2016                 /* leader of multiple predecessors */
2017                 return a;
2018         }
2019
2020         /* works even with NaN */
2021         tv_max = get_mode_max(mode);
2022         if (a->type.tv == tv_max)
2023                 return b;
2024         if (b->type.tv == tv_max)
2025                 return a;
2026         return node;
2027 }  /* identity_Min */
2028
2029 /**
2030  * Calculates the Identity for Max nodes.
2031  */
2032 static node_t *identity_Max(node_t *node) {
2033         ir_node *op   = node->node;
2034         node_t  *a    = get_irn_node(get_binop_left(op));
2035         node_t  *b    = get_irn_node(get_binop_right(op));
2036         ir_mode *mode = get_irn_mode(op);
2037         tarval  *tv_min;
2038
2039         if (a->part == b->part) {
2040                 /* leader of multiple predecessors */
2041                 return a;
2042         }
2043
2044         /* works even with NaN */
2045         tv_min = get_mode_min(mode);
2046         if (a->type.tv == tv_min)
2047                 return b;
2048         if (b->type.tv == tv_min)
2049                 return a;
2050         return node;
2051 }  /* identity_Max */
2052
2053 /**
2054  * Calculates the Identity for nodes.
2055  */
2056 static node_t *identity(node_t *node) {
2057         ir_node *irn = node->node;
2058
2059         switch (get_irn_opcode(irn)) {
2060         case iro_Phi:
2061                 return identity_Phi(node);
2062         case iro_Add:
2063                 return identity_Add(node);
2064         case iro_Mul:
2065                 return identity_Mul(node);
2066         case iro_Or:
2067                 return identity_Or(node);
2068         case iro_And:
2069                 return identity_And(node);
2070         case iro_Sub:
2071                 return identity_Sub(node);
2072         case iro_Confirm:
2073                 return identity_Confirm(node);
2074         case iro_Mux:
2075                 return identity_Mux(node);
2076         case iro_Min:
2077                 return identity_Min(node);
2078         case iro_Max:
2079                 return identity_Max(node);
2080         default:
2081                 return node;
2082         }
2083 }  /* identity */
2084
2085 /**
2086  * Node follower is a (new) follower of leader, segregate Leader
2087  * out edges.
2088  */
2089 static void segregate_def_use_chain_1(const ir_node *follower, node_t *leader) {
2090         ir_node *l   = leader->node;
2091         int     j, i, n = get_irn_n_outs(l);
2092
2093         DB((dbg, LEVEL_2, "%+F is a follower of %+F\n", follower, leader->node));
2094         /* The leader edges must remain sorted, but follower edges can
2095            be unsorted. */
2096         for (i = leader->n_followers + 1; i <= n; ++i) {
2097                 if (l->out[i].use == follower) {
2098                         ir_def_use_edge t = l->out[i];
2099
2100                         for (j = i - 1; j >= leader->n_followers + 1; --j)
2101                                 l->out[j + 1] = l->out[j];
2102                         ++leader->n_followers;
2103                         l->out[leader->n_followers] = t;
2104                         break;
2105                 }
2106         }
2107 }  /* segregate_def_use_chain_1 */
2108
2109 /**
2110  * Node follower is a (new) follower of leader, segregate Leader
2111  * out edges. If follower is a n-congruent Input identity, all follower
2112  * inputs congruent to follower are also leader.
2113  */
2114 static void segregate_def_use_chain(const ir_node *follower, node_t *leader) {
2115         ir_op *op = get_irn_op(follower);
2116
2117         if (op == op_Phi) {
2118                 /* n-Congruent Input Identity for Phi's */
2119                 int i;
2120                 ir_node *block = get_nodes_block(follower);
2121
2122                 DB((dbg, LEVEL_2, "n-Congruent follower %+F\n", follower));
2123                 for (i = get_irn_arity(follower) - 1; i >= 0; --i) {
2124                         node_t *pred_X = get_irn_node(get_Block_cfgpred(block, i));
2125
2126                         /* beware: we are NOT followers of dead inputs */
2127                         if (pred_X->type.tv == tarval_reachable) {
2128                                 node_t *pred = get_irn_node(get_irn_n(follower, i));
2129
2130                                 if (pred->part == leader->part)
2131                                         segregate_def_use_chain_1(follower, pred);
2132                         }
2133                 }
2134         } else if (op == op_Mux || op == op_Max || op == op_Min) {
2135                 /* n-Congruent Input Identity */
2136                 int i;
2137
2138                 DB((dbg, LEVEL_2, "n-Congruent follower %+F\n", follower));
2139                 for (i = get_irn_arity(follower) - 1; i >= 0; --i) {
2140                         node_t *pred = get_irn_node(get_irn_n(follower, i));
2141
2142                         if (pred->part == leader->part)
2143                                 segregate_def_use_chain_1(follower, pred);
2144                 }
2145         } else {
2146                 /* 1-Congruent Input Identity */
2147                 segregate_def_use_chain_1(follower, leader);
2148         }
2149 }  /* segregate_def_use_chain */
2150
2151 /**
2152  * Make all inputs to x from inside X no longer be F.def_use edges.
2153  */
2154 static void move_edges_to_leader(node_t *x) {
2155         ir_node     *irn = x->node;
2156         int         i, j, k;
2157
2158         for (i = get_irn_arity(irn) - 1; i >= 0; --i) {
2159                 node_t  *pred = get_irn_node(get_irn_n(irn, i));
2160                 ir_node *p;
2161                 int     n;
2162
2163                 p = pred->node;
2164                 n = get_irn_n_outs(p);
2165                 for (j = 1; j <= pred->n_followers; ++j) {
2166                         if (p->out[j].pos == i && p->out[j].use == irn) {
2167                                 /* found a follower edge to x, move it to the Leader */
2168                                 ir_def_use_edge edge = p->out[j];
2169
2170                                 /* remove this edge from the Follower set */
2171                                 p->out[j] = p->out[pred->n_followers];
2172                                 --pred->n_followers;
2173
2174                                 /* sort it into the leader set */
2175                                 for (k = pred->n_followers + 2; k <= n; ++k) {
2176                                         if (p->out[k].pos >= edge.pos)
2177                                                 break;
2178                                         p->out[k - 1] = p->out[k];
2179                                 }
2180                                 /* place the new edge here */
2181                                 p->out[k - 1] = edge;
2182
2183                                 /* edge found and moved */
2184                                 break;
2185                         }
2186                 }
2187         }
2188 }
2189
2190 /**
2191  * Propagate constant evaluation.
2192  *
2193  * @param env  the environment
2194  */
2195 static void propagate(environment_t *env) {
2196         partition_t    *X, *Y;
2197         node_t         *x;
2198         lattice_elem_t old_type;
2199         node_t         *fallen;
2200         unsigned       n_fallen, old_type_was_T_or_C;
2201         int            i;
2202
2203         while (env->cprop != NULL) {
2204                 void *oldopcode = NULL;
2205
2206                 /* remove the first partition X from cprop */
2207                 X           = env->cprop;
2208                 X->on_cprop = 0;
2209                 env->cprop  = X->cprop_next;
2210
2211                 old_type_was_T_or_C = X->type_is_T_or_C;
2212
2213                 DB((dbg, LEVEL_2, "Propagate type on part%d\n", X->nr));
2214                 fallen   = NULL;
2215                 n_fallen = 0;
2216                 while (! list_empty(&X->cprop)) {
2217                         /* remove the first Node x from X.cprop */
2218                         x = list_entry(X->cprop.next, node_t, cprop_list);
2219                         list_del(&x->cprop_list);
2220                         x->on_cprop = 0;
2221
2222                         if (x->is_follower && identity(x) == x) {
2223                                 /* x will make the follower -> leader transition */
2224                                 DB((dbg, LEVEL_2, "%+F make the follower -> leader transition\n", x->node));
2225
2226                                 if (oldopcode == NULL) {
2227                                         oldopcode = lambda_opcode(get_first_node(X), env);
2228                                 }
2229                                 if (oldopcode != lambda_opcode(x, env)) {
2230                                         if (x->on_fallen == 0) {
2231                                                 /* different opcode -> x falls out of this partition */
2232                                                 x->next      = fallen;
2233                                                 x->on_fallen = 1;
2234                                                 fallen       = x;
2235                                                 ++n_fallen;
2236                                                 DB((dbg, LEVEL_2, "Add node %+F to fallen\n", x->node));
2237                                         }
2238                                 }
2239
2240                                 /* move x from X.Follower to X.Leader */
2241                                 list_del(&x->node_list);
2242                                 list_add_tail(&x->node_list, &X->Leader);
2243                                 x->is_follower = 0;
2244                                 X->n_leader++;
2245
2246                                 /* Make all inputs to x from inside X no longer be F.def_use edges */
2247                                 move_edges_to_leader(x);
2248                         }
2249
2250                         /* compute a new type for x */
2251                         old_type = x->type;
2252                         DB((dbg, LEVEL_3, "computing type of %+F\n", x->node));
2253                         compute(x);
2254                         if (x->type.tv != old_type.tv) {
2255                                 verify_type(old_type, x->type);
2256                                 DB((dbg, LEVEL_2, "node %+F has changed type from %+F to %+F\n", x->node, old_type, x->type));
2257
2258                                 if (x->on_fallen == 0) {
2259                                         /* Add x to fallen. Nodes might fall from T -> const -> _|_, so check that they are
2260                                            not already on the list. */
2261                                         x->next      = fallen;
2262                                         x->on_fallen = 1;
2263                                         fallen       = x;
2264                                         ++n_fallen;
2265                                         DB((dbg, LEVEL_2, "Add node %+F to fallen\n", x->node));
2266                                 }
2267                                 for (i = get_irn_n_outs(x->node) - 1; i >= 0; --i) {
2268                                         ir_node *succ = get_irn_out(x->node, i);
2269                                         node_t  *y    = get_irn_node(succ);
2270
2271                                         /* Add y to y.partition.cprop. */
2272                                         add_to_cprop(y, env);
2273                                 }
2274                         }
2275                 }
2276
2277                 if (n_fallen > 0 && n_fallen != X->n_leader) {
2278                         DB((dbg, LEVEL_2, "Splitting part%d by fallen\n", X->nr));
2279                         Y = split(&X, fallen, env);
2280                 } else {
2281                         Y = X;
2282                 }
2283                 /* remove the flags from the fallen list */
2284                 for (x = fallen; x != NULL; x = x->next)
2285                         x->on_fallen = 0;
2286
2287 #ifndef NO_FOLLOWER
2288                 if (old_type_was_T_or_C) {
2289                         node_t *y, *tmp;
2290
2291                         if (Y->on_worklist == 0)
2292                                 add_to_worklist(Y, env);
2293
2294                         /* check if some nodes will make the leader -> follower transition */
2295                         list_for_each_entry_safe(node_t, y, tmp, &Y->Leader, node_list) {
2296                                 if (y->type.tv != tarval_top && ! is_con(y->type)) {
2297                                         node_t *eq_node = identity(y);
2298
2299                                         if (eq_node != y && eq_node->part == y->part) {
2300                                                 DB((dbg, LEVEL_2, "Node %+F is a follower of %+F\n", y->node, eq_node->node));
2301                                                 /* move to Follower */
2302                                                 y->is_follower = 1;
2303                                                 list_del(&y->node_list);
2304                                                 list_add_tail(&y->node_list, &Y->Follower);
2305                                                 --Y->n_leader;
2306
2307                                                 segregate_def_use_chain(y->node, eq_node);
2308                                         }
2309                                 }
2310                         }
2311                 }
2312 #endif
2313                 split_by(Y, env);
2314         }
2315 }  /* propagate */
2316
2317 /**
2318  * Get the leader for a given node from its congruence class.
2319  *
2320  * @param irn  the node
2321  */
2322 static ir_node *get_leader(node_t *node) {
2323         partition_t *part = node->part;
2324
2325         if (part->n_leader > 1 || node->is_follower) {
2326                 DB((dbg, LEVEL_2, "Found congruence class for %+F\n", node->node));
2327
2328                 return get_first_node(part)->node;
2329         }
2330         return node->node;
2331 }  /* get_leader */
2332
2333 /**
2334  * Return non-zero if the control flow predecessor node pred
2335  * is the only reachable control flow exit of its block.
2336  *
2337  * @param pred  the control flow exit
2338  */
2339 static int can_exchange(ir_node *pred) {
2340         if (is_Start(pred))
2341                 return 0;
2342         else if (is_Jmp(pred))
2343                 return 1;
2344         else if (get_irn_mode(pred) == mode_T) {
2345                 int i, k;
2346
2347                 /* if the predecessor block has more than one
2348                 reachable outputs we cannot remove the block */
2349                 k = 0;
2350                 for (i = get_irn_n_outs(pred) - 1; i >= 0; --i) {
2351                         ir_node *proj = get_irn_out(pred, i);
2352                         node_t  *node;
2353
2354                         /* skip non-control flow Proj's */
2355                         if (get_irn_mode(proj) != mode_X)
2356                                 continue;
2357
2358                         node = get_irn_node(proj);
2359                         if (node->type.tv == tarval_reachable) {
2360                                 if (++k > 1)
2361                                         return 0;
2362                         }
2363                 }
2364                 return 1;
2365         }
2366         return 0;
2367 }
2368
2369 /**
2370  * Block Post-Walker, apply the analysis results on control flow by
2371  * shortening Phi's and Block inputs.
2372  */
2373 static void apply_cf(ir_node *block, void *ctx) {
2374         environment_t *env = ctx;
2375         node_t        *node = get_irn_node(block);
2376         int           i, j, k, n;
2377         ir_node       **ins, **in_X;
2378         ir_node       *phi, *next;
2379
2380         if (block == get_irg_end_block(current_ir_graph) ||
2381             block == get_irg_start_block(current_ir_graph)) {
2382                 /* the EndBlock is always reachable even if the analysis
2383                    finds out the opposite :-) */
2384                 return;
2385         }
2386         if (node->type.tv == tarval_unreachable) {
2387                 /* mark dead blocks */
2388                 set_Block_dead(block);
2389                 return;
2390         }
2391
2392         n = get_Block_n_cfgpreds(block);
2393
2394         if (n == 1) {
2395                 /* only one predecessor combine */
2396                 ir_node *pred = skip_Proj(get_Block_cfgpred(block, 0));
2397
2398                 if (can_exchange(pred)) {
2399                         exchange(block, get_nodes_block(pred));
2400                         env->modified = 1;
2401                 }
2402                 return;
2403         }
2404
2405         NEW_ARR_A(ir_node *, in_X, n);
2406         k = 0;
2407         for (i = 0; i < n; ++i) {
2408                 ir_node *pred = get_Block_cfgpred(block, i);
2409                 node_t  *node = get_irn_node(pred);
2410
2411                 if (node->type.tv == tarval_reachable) {
2412                         in_X[k++] = pred;
2413                 }
2414         }
2415         if (k >= n)
2416                 return;
2417
2418         NEW_ARR_A(ir_node *, ins, n);
2419         for (phi = get_Block_phis(block); phi != NULL; phi = next) {
2420                 node_t *node = get_irn_node(phi);
2421
2422                 next = get_Phi_next(phi);
2423                 if (is_tarval(node->type.tv) && tarval_is_constant(node->type.tv)) {
2424                         /* this Phi is replaced by a constant */
2425                         tarval  *tv = node->type.tv;
2426                         ir_node *c  = new_r_Const(current_ir_graph, block, get_tarval_mode(tv), tv);
2427
2428                         set_irn_node(c, node);
2429                         node->node = c;
2430                         DB((dbg, LEVEL_1, "%+F is replaced by %+F\n", phi, c));
2431                         exchange(phi, c);
2432                         env->modified = 1;
2433                 } else {
2434                         j = 0;
2435                         for (i = 0; i < n; ++i) {
2436                                 node_t *pred = get_irn_node(get_Block_cfgpred(block, i));
2437
2438                                 if (pred->type.tv == tarval_reachable) {
2439                                         ins[j++] = get_Phi_pred(phi, i);
2440                                 }
2441                         }
2442                         if (j <= 1) {
2443                                 /* this Phi is replaced by a single predecessor */
2444                                 ir_node *s = ins[0];
2445
2446                                 node->node = s;
2447                                 DB((dbg, LEVEL_1, "%+F is replaced by %+F because of cf change\n", phi, s));
2448                                 exchange(phi, s);
2449                                 env->modified = 1;
2450                         } else {
2451                                 set_irn_in(phi, j, ins);
2452                                 env->modified = 1;
2453                         }
2454                 }
2455         }
2456
2457         if (k <= 1) {
2458                 /* this Block has only one live predecessor */
2459                 ir_node *pred = skip_Proj(in_X[0]);
2460
2461                 if (can_exchange(pred)) {
2462                         exchange(block, get_nodes_block(pred));
2463                         env->modified = 1;
2464                 }
2465         } else {
2466                 set_irn_in(block, k, in_X);
2467                 env->modified = 1;
2468         }
2469 }
2470
2471 /**
2472  * Post-Walker, apply the analysis results;
2473  */
2474 static void apply_result(ir_node *irn, void *ctx) {
2475         environment_t *env = ctx;
2476         node_t        *node = get_irn_node(irn);
2477
2478         if (is_Block(irn) || is_End(irn) || is_Bad(irn)) {
2479                 /* blocks already handled, do not touch the End node */
2480         } else {
2481                 node_t *block = get_irn_node(get_nodes_block(irn));
2482
2483                 if (block->type.tv == tarval_unreachable) {
2484                         ir_node *bad = get_irg_bad(current_ir_graph);
2485
2486                         /* here, bad might already have a node, but this can be safely ignored
2487                            as long as bad has at least ONE valid node */
2488                         set_irn_node(bad, node);
2489                         node->node = bad;
2490                         DB((dbg, LEVEL_1, "%+F is unreachable\n", irn));
2491                         exchange(irn, bad);
2492                         env->modified = 1;
2493                 }
2494                 else if (node->type.tv == tarval_unreachable) {
2495                         ir_node *bad = get_irg_bad(current_ir_graph);
2496
2497                         /* see comment above */
2498                         set_irn_node(bad, node);
2499                         node->node = bad;
2500                         DB((dbg, LEVEL_1, "%+F is unreachable\n", irn));
2501                         exchange(irn, bad);
2502                         env->modified = 1;
2503                 }
2504                 else if (get_irn_mode(irn) == mode_X) {
2505                         if (is_Proj(irn)) {
2506                                 /* leave or Jmp */
2507                                 ir_node *cond = get_Proj_pred(irn);
2508
2509                                 if (is_Cond(cond)) {
2510                                         node_t *sel = get_irn_node(get_Cond_selector(cond));
2511
2512                                         if (is_tarval(sel->type.tv) && tarval_is_constant(sel->type.tv)) {
2513                                                 /* Cond selector is a constant, make a Jmp */
2514                                                 ir_node *jmp = new_r_Jmp(current_ir_graph, block->node);
2515                                                 set_irn_node(jmp, node);
2516                                                 node->node = jmp;
2517                                                 DB((dbg, LEVEL_1, "%+F is replaced by %+F\n", irn, jmp));
2518                                                 exchange(irn, jmp);
2519                                                 env->modified = 1;
2520                                         }
2521                                 }
2522                         }
2523                 } else {
2524                         /* normal data node */
2525                         if (is_tarval(node->type.tv) && tarval_is_constant(node->type.tv)) {
2526                                 tarval *tv = node->type.tv;
2527
2528                                 /*
2529                                  * Beware: never replace mode_T nodes by constants. Currently we must mark
2530                                  * mode_T nodes with constants, but do NOT replace them.
2531                                  */
2532                                 if (! is_Const(irn) && get_irn_mode(irn) != mode_T) {
2533                                         /* can be replaced by a constant */
2534                                         ir_node *c = new_r_Const(current_ir_graph, block->node, get_tarval_mode(tv), tv);
2535                                         set_irn_node(c, node);
2536                                         node->node = c;
2537                                         DB((dbg, LEVEL_1, "%+F is replaced by %+F\n", irn, c));
2538                                         exchange(irn, c);
2539                                         env->modified = 1;
2540                                 }
2541                         } else if (is_entity(node->type.sym.entity_p)) {
2542                                 if (! is_SymConst(irn)) {
2543                                         /* can be replaced by a Symconst */
2544                                         ir_node *symc = new_r_SymConst(current_ir_graph, block->node, get_irn_mode(irn), node->type.sym, symconst_addr_ent);
2545                                         set_irn_node(symc, node);
2546                                         node->node = symc;
2547
2548                                         DB((dbg, LEVEL_1, "%+F is replaced by %+F\n", irn, symc));
2549                                         exchange(irn, symc);
2550                                         env->modified = 1;
2551                                 }
2552                         } else {
2553                                 ir_node *leader = get_leader(node);
2554
2555                                 if (leader != irn) {
2556                                         DB((dbg, LEVEL_1, "%+F from part%d is replaced by %+F\n", irn, node->part->nr, leader));
2557                                         exchange(irn, leader);
2558                                         env->modified = 1;
2559                                 }
2560                         }
2561                 }
2562         }
2563 }  /* apply_result */
2564
2565 /**
2566  * Fix the keep-alives by deleting unreachable ones.
2567  */
2568 static void apply_end(ir_node *end, environment_t *env) {
2569         int i, j,  n = get_End_n_keepalives(end);
2570         ir_node **in;
2571
2572         if (n > 0)
2573                 NEW_ARR_A(ir_node *, in, n);
2574
2575         /* fix the keep alive */
2576         for (i = j = 0; i < n; i++) {
2577                 ir_node *ka   = get_End_keepalive(end, i);
2578                 node_t  *node = get_irn_node(ka);
2579
2580                 if (! node->is_flagged) {
2581                         node->is_flagged = 1;
2582
2583                         if (! is_Block(ka))
2584                                 node = get_irn_node(get_nodes_block(ka));
2585
2586                         if (node->type.tv != tarval_unreachable)
2587                                 in[j++] = ka;
2588                 }
2589         }
2590         if (j != n) {
2591                 set_End_keepalives(end, j, in);
2592                 env->modified = 1;
2593         }
2594 }  /* apply_end */
2595
2596 #define SET(code) op_##code->ops.generic = (op_func)compute_##code
2597
2598 /**
2599  * sets the generic functions to compute.
2600  */
2601 static void set_compute_functions(void) {
2602         int i;
2603
2604         /* set the default compute function */
2605         for (i = get_irp_n_opcodes() - 1; i >= 0; --i) {
2606                 ir_op *op = get_irp_opcode(i);
2607                 op->ops.generic = (op_func)default_compute;
2608         }
2609
2610         /* set specific functions */
2611         SET(Block);
2612         SET(Unknown);
2613         SET(Bad);
2614         SET(Jmp);
2615         SET(Phi);
2616         SET(Add);
2617         SET(Sub);
2618         SET(SymConst);
2619         SET(Cmp);
2620         SET(Proj);
2621         SET(Confirm);
2622         SET(End);
2623
2624         if (op_Max != NULL)
2625                 SET(Max);
2626         if (op_Min != NULL)
2627                 SET(Min);
2628
2629 }  /* set_compute_functions */
2630
2631 static int dump_partition_hook(FILE *F, ir_node *n, ir_node *local) {
2632         ir_node *irn = local != NULL ? local : n;
2633         node_t *node = get_irn_node(irn);
2634
2635         ir_fprintf(F, "info2 : \"partition %u type %+F\"\n", node->part->nr, node->type);
2636         return 1;
2637 }
2638
2639 void combo(ir_graph *irg) {
2640         environment_t env;
2641         ir_node       *initial_bl;
2642         node_t        *start;
2643         ir_graph      *rem = current_ir_graph;
2644
2645         current_ir_graph = irg;
2646
2647         /* register a debug mask */
2648         FIRM_DBG_REGISTER(dbg, "firm.opt.combo");
2649         firm_dbg_set_mask(dbg, SET_LEVEL_3);
2650
2651         DB((dbg, LEVEL_1, "Doing COMBO for %+F\n", irg));
2652
2653         obstack_init(&env.obst);
2654         env.worklist       = NULL;
2655         env.cprop          = NULL;
2656         env.touched        = NULL;
2657         env.initial        = NULL;
2658 #ifdef DEBUG_libfirm
2659         env.dbg_list       = NULL;
2660 #endif
2661         env.opcode2id_map  = new_set(cmp_opcode, iro_Last * 4);
2662         env.type2id_map    = pmap_create();
2663         env.end_idx        = get_opt_global_cse() ? 0 : -1;
2664         env.lambda_input   = 0;
2665         env.modified       = 0;
2666
2667         assure_irg_outs(irg);
2668
2669         /* we have our own value_of function */
2670         set_value_of_func(get_node_tarval);
2671
2672         set_compute_functions();
2673         DEBUG_ONLY(part_nr = 0);
2674
2675         /* create the initial partition and place it on the work list */
2676         env.initial = new_partition(&env);
2677         add_to_worklist(env.initial, &env);
2678         irg_walk_graph(irg, init_block_phis, create_initial_partitions, &env);
2679
2680         /* all nodes on the initial partition have type Top */
2681         env.initial->type_is_T_or_C = 1;
2682
2683         /* Place the START Node's partition on cprop.
2684            Place the START Node on its local worklist. */
2685         initial_bl = get_irg_start_block(irg);
2686         start      = get_irn_node(initial_bl);
2687         add_to_cprop(start, &env);
2688
2689         do {
2690                 propagate(&env);
2691                 if (env.worklist != NULL)
2692                         cause_splits(&env);
2693         } while (env.cprop != NULL || env.worklist != NULL);
2694
2695         dump_all_partitions(&env);
2696
2697 #if 0
2698         set_dump_node_vcgattr_hook(dump_partition_hook);
2699         dump_ir_block_graph(irg, "-partition");
2700         set_dump_node_vcgattr_hook(NULL);
2701 #else
2702         (void)dump_partition_hook;
2703 #endif
2704
2705         /* apply the result */
2706         irg_block_walk_graph(irg, NULL, apply_cf, &env);
2707         irg_walk_graph(irg, NULL, apply_result, &env);
2708         apply_end(get_irg_end(irg), &env);
2709
2710         if (env.modified) {
2711                 /* control flow might changed */
2712                 set_irg_outs_inconsistent(irg);
2713                 set_irg_extblk_inconsistent(irg);
2714                 set_irg_doms_inconsistent(irg);
2715                 set_irg_loopinfo_inconsistent(irg);
2716         }
2717
2718         pmap_destroy(env.type2id_map);
2719         del_set(env.opcode2id_map);
2720         obstack_free(&env.obst, NULL);
2721
2722         /* restore value_of() default behavior */
2723         set_value_of_func(NULL);
2724         current_ir_graph = rem;
2725 }  /* combo */