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