OSDN Git Service

45ac8740ddabc2bdb03ee1243e24303db4cacb81
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-pre.c
1 /* SSA-PRE for trees.
2    Copyright (C) 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
3    Contributed by Daniel Berlin <dan@dberlin.org> and Steven Bosscher
4    <stevenb@suse.de> 
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2, or (at your option)
11 any later version.
12
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING.  If not, write to
20 the Free Software Foundation, 59 Temple Place - Suite 330,
21 Boston, MA 02111-1307, USA.  */
22
23 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "tm.h"
27 #include "errors.h"
28 #include "ggc.h"
29 #include "tree.h"
30 #include "basic-block.h"
31 #include "diagnostic.h"
32 #include "tree-inline.h"
33 #include "tree-flow.h"
34 #include "tree-gimple.h"
35 #include "tree-dump.h"
36 #include "timevar.h"
37 #include "fibheap.h"
38 #include "hashtab.h"
39 #include "tree-iterator.h"
40 #include "real.h"
41 #include "alloc-pool.h"
42 #include "tree-pass.h"
43 #include "flags.h"
44 #include "splay-tree.h"
45 #include "bitmap.h"
46 #include "langhooks.h"
47
48 /* TODO:
49    
50    1. Implement load value numbering.
51    2. Speed up insert_aux so that we can use it all the time.  It
52       spends most of it's time in quadratic value replacement.
53    3. Avail sets can be shared by making an avail_find_leader that
54       walks up the dominator tree and looks in those avail sets.
55       This might affect code optimality, it's unclear right now.
56    4. Load motion can be performed by value numbering the loads the
57       same as we do other expressions.  This requires iterative
58       hashing the vuses into the values.  Right now we simply assign
59       a new value every time we see a statement with a vuse.
60    5. Strength reduction can be performed by anticipating expressions
61       we can repair later on.
62    6. Our canonicalization of expressions during lookups don't take
63       constants into account very well.  In particular, we don't fold
64       anywhere, so we can get situations where we stupidly think
65       something is a new value (a + 1 + 1 vs a + 2).  This is somewhat
66       expensive to fix, but it does expose a lot more eliminations.
67       It may or not be worth it, depending on how critical you
68       consider PRE vs just plain GRE.
69 */   
70
71 /* For ease of terminology, "expression node" in the below refers to
72    every expression node but MODIFY_EXPR, because MODIFY_EXPR's represent
73    the actual statement containing the expressions we care about, and
74    we cache the value number by putting it in the expression.  */
75
76 /* Basic algorithm
77    
78    First we walk the statements to generate the AVAIL sets, the
79    EXP_GEN sets, and the tmp_gen sets.  EXP_GEN sets represent the
80    generation of values/expressions by a given block.  We use them
81    when computing the ANTIC sets.  The AVAIL sets consist of
82    SSA_NAME's that represent values, so we know what values are
83    available in what blocks.  AVAIL is a forward dataflow problem.  In
84    SSA, values are never killed, so we don't need a kill set, or a
85    fixpoint iteration, in order to calculate the AVAIL sets.  In
86    traditional parlance, AVAIL sets tell us the downsafety of the
87    expressions/values.
88    
89    Next, we generate the ANTIC sets.  These sets represent the
90    anticipatable expressions.  ANTIC is a backwards dataflow
91    problem.An expression is anticipatable in a given block if it could
92    be generated in that block.  This means that if we had to perform
93    an insertion in that block, of the value of that expression, we
94    could.  Calculating the ANTIC sets requires phi translation of
95    expressions, because the flow goes backwards through phis.  We must
96    iterate to a fixpoint of the ANTIC sets, because we have a kill
97    set.  Even in SSA form, values are not live over the entire
98    function, only from their definition point onwards.  So we have to
99    remove values from the ANTIC set once we go past the definition
100    point of the leaders that make them up.
101    compute_antic/compute_antic_aux performs this computation.
102
103    Third, we perform insertions to make partially redundant
104    expressions fully redundant.
105
106    An expression is partially redundant (excluding partial
107    anticipation) if:
108
109    1. It is AVAIL in some, but not all, of the predecessors of a
110       given block.
111    2. It is ANTIC in all the predecessors.
112
113    In order to make it fully redundant, we insert the expression into
114    the predecessors where it is not available, but is ANTIC.
115    insert/insert_aux performs this insertion.
116
117    Fourth, we eliminate fully redundant expressions.
118    This is a simple statement walk that replaces redundant
119    calculations  with the now available values.  */
120
121 /* Representations of value numbers:
122
123    Value numbers are represented using the "value handle" approach.
124    This means that each SSA_NAME (and for other reasons to be
125    disclosed in a moment, expression nodes) has a value handle that
126    can be retrieved through get_value_handle.  This value handle, *is*
127    the value number of the SSA_NAME.  You can pointer compare the
128    value handles for equivalence purposes.
129
130    For debugging reasons, the value handle is internally more than
131    just a number, it is a VAR_DECL named "value.x", where x is a
132    unique number for each value number in use.  This allows
133    expressions with SSA_NAMES replaced by value handles to still be
134    pretty printed in a sane way.  They simply print as "value.3 *
135    value.5", etc.  
136
137    Expression nodes have value handles associated with them as a
138    cache.  Otherwise, we'd have to look them up again in the hash
139    table This makes significant difference (factor of two or more) on
140    some test cases.  They can be thrown away after the pass is
141    finished.  */
142
143 /* Representation of expressions on value numbers: 
144
145    In some portions of this code, you will notice we allocate "fake"
146    analogues to the expression we are value numbering, and replace the
147    operands with the values of the expression.  Since we work on
148    values, and not just names, we canonicalize expressions to value
149    expressions for use in the ANTIC sets, the EXP_GEN set, etc.  
150
151    This is theoretically unnecessary, it just saves a bunch of
152    repeated get_value_handle and find_leader calls in the remainder of
153    the code, trading off temporary memory usage for speed.  The tree
154    nodes aren't actually creating more garbage, since they are
155    allocated in a special pools which are thrown away at the end of
156    this pass.  
157
158    All of this also means that if you print the EXP_GEN or ANTIC sets,
159    you will see "value.5 + value.7" in the set, instead of "a_55 +
160    b_66" or something.  The only thing that actually cares about
161    seeing the value leaders is phi translation, and it needs to be
162    able to find the leader for a value in an arbitrary block, so this
163    "value expression" form is perfect for it (otherwise you'd do
164    get_value_handle->find_leader->translate->get_value_handle->find_leader).*/
165
166
167 /* Representation of sets:
168
169    Sets are represented as doubly linked lists kept in topological
170    order, with an optional supporting bitmap of values present in the
171    set.  The sets represent values, and the elements can be values or
172    expressions.  The elements can appear in different sets, but each
173    element can only appear once in each set.
174
175    Since each node in the set represents a value, we also want to be
176    able to map expression, set pairs to something that tells us
177    whether the value is present is a set.  We use a per-set bitmap for
178    that.  The value handles also point to a linked list of the
179    expressions they represent via a tree annotation.  This is mainly
180    useful only for debugging, since we don't do identity lookups.  */
181
182
183 /* A value set element.  Basically a single linked list of
184    expressions/values.  */
185 typedef struct value_set_node
186 {
187   /* An expression.  */
188   tree expr;
189
190   /* A pointer to the next element of the value set.  */
191   struct value_set_node *next;
192 } *value_set_node_t;
193
194
195 /* A value set.  This is a singly linked list of value_set_node
196    elements with a possible bitmap that tells us what values exist in
197    the set.  This set must be kept in topologically sorted order.  */
198 typedef struct value_set
199 {
200   /* The head of the list.  Used for iterating over the list in
201      order.  */
202   value_set_node_t head;
203
204   /* The tail of the list.  Used for tail insertions, which are
205      necessary to keep the set in topologically sorted order because
206      of how the set is built.  */
207   value_set_node_t tail;
208   
209   /* The length of the list.  */
210   size_t length;
211   
212   /* True if the set is indexed, which means it contains a backing
213      bitmap for quick determination of whether certain values exist in the
214      set.  */
215   bool indexed;
216   
217   /* The bitmap of values that exist in the set.  May be NULL in an
218      empty or non-indexed set.  */
219   bitmap values;
220   
221 } *value_set_t;
222
223 /* All of the following sets, except for TMP_GEN, are indexed.
224    TMP_GEN is only ever iterated over, we never check what values
225    exist in it.  */
226
227 typedef struct bb_value_sets
228 {
229   /* The EXP_GEN set, which represents expressions/values generated in
230      a basic block.  */
231   value_set_t exp_gen;
232
233   /* The PHI_GEN set, which represents PHI results generated in a
234      basic block.  */
235   value_set_t phi_gen;
236
237   /* The TMP_GEN set, which represents results/temporaries genererated
238      in a basic block. IE the LHS of an expression.  */
239   value_set_t tmp_gen;
240
241   /* The AVAIL_OUT set, which represents which values are available in
242      a given basic block.  */
243   value_set_t avail_out;
244
245   /* The ANTIC_IN set, which represents which values are anticiptable
246      in a given basic block.  */
247   value_set_t antic_in;
248
249   /* The NEW_SETS set, which is used during insertion to augment the
250      AVAIL_OUT set of blocks with the new insertions performed during
251      the current iteration.  */
252   value_set_t new_sets;
253 } *bb_value_sets_t;
254
255 #define EXP_GEN(BB)     ((bb_value_sets_t) ((BB)->aux))->exp_gen
256 #define PHI_GEN(BB)     ((bb_value_sets_t) ((BB)->aux))->phi_gen
257 #define TMP_GEN(BB)     ((bb_value_sets_t) ((BB)->aux))->tmp_gen
258 #define AVAIL_OUT(BB)   ((bb_value_sets_t) ((BB)->aux))->avail_out
259 #define ANTIC_IN(BB)    ((bb_value_sets_t) ((BB)->aux))->antic_in
260 #define NEW_SETS(BB)    ((bb_value_sets_t) ((BB)->aux))->new_sets
261
262 /* This structure is used to keep track of statistics on what
263    optimization PRE was able to perform.  */
264 static struct
265 {
266   /* The number of RHS computations eliminated by PRE.  */
267   int eliminations;
268
269   /* The number of new expressions/temporaries generated by PRE.  */
270   int insertions;
271
272   /* The number of new PHI nodes added by PRE.  */
273   int phis;
274 } pre_stats;
275
276 static tree find_leader (value_set_t, tree);
277 static void value_insert_into_set (value_set_t, tree);
278 static void insert_into_set (value_set_t, tree);
279 static value_set_t set_new  (bool);
280 static bool is_undefined_value (tree);
281 static tree create_expression_by_pieces (basic_block, tree, tree);
282
283 /* We can add and remove elements and entries to and from sets
284    and hash tables, so we use alloc pools for them.  */
285
286 static alloc_pool value_set_pool;
287 static alloc_pool value_set_node_pool;
288 static alloc_pool binary_node_pool;
289 static alloc_pool unary_node_pool;
290
291
292 /* The phi_translate_table caches phi translations for a given
293    expression and predecessor.  */
294
295 static htab_t phi_translate_table;
296
297 /* A three tuple {e, pred, v} used to cache phi translations in the
298    phi_translate_table.  */
299
300 typedef struct expr_pred_trans_d
301 {
302   /* The expression. */
303   tree e;
304
305   /* The predecessor block along which we translated the expression.  */
306   basic_block pred;
307
308   /* The value that resulted from the translation.  */
309   tree v;
310
311   /* The hashcode for the expression, pred pair. This is cached for
312      speed reasons.  */
313   hashval_t hashcode;
314 } *expr_pred_trans_t;
315
316 /* Return the hash value for a phi translation table entry.  */
317
318 static hashval_t
319 expr_pred_trans_hash (const void *p)
320 {
321   const expr_pred_trans_t ve = (expr_pred_trans_t) p;
322   return ve->hashcode;
323 }
324
325 /* Return true if two phi translation table entries are the same.
326    P1 and P2 should point to the expr_pred_trans_t's to be compared.*/
327
328 static int
329 expr_pred_trans_eq (const void *p1, const void *p2)
330 {
331   const expr_pred_trans_t ve1 = (expr_pred_trans_t) p1;
332   const expr_pred_trans_t ve2 = (expr_pred_trans_t) p2;
333   basic_block b1 = ve1->pred;
334   basic_block b2 = ve2->pred;
335
336   
337   /* If they are not translations for the same basic block, they can't
338      be equal.  */
339   if (b1 != b2)
340     return false;
341
342   /* If they are for the same basic block, determine if the
343      expressions are equal.   */  
344   if (expressions_equal_p (ve1->e, ve2->e))
345     return true;
346   
347   return false;
348 }
349
350 /* Search in the phi translation table for the translation of
351    expression E in basic block PRED. Return the translated value, if
352    found, NULL otherwise. */ 
353
354 static inline tree
355 phi_trans_lookup (tree e, basic_block pred)
356 {
357   void **slot;
358   struct expr_pred_trans_d ept;
359   ept.e = e;
360   ept.pred = pred;
361   ept.hashcode = vn_compute (e, (unsigned long) pred);
362   slot = htab_find_slot_with_hash (phi_translate_table, &ept, ept.hashcode,
363                                    NO_INSERT);
364   if (!slot)
365     return NULL;
366   else
367     return ((expr_pred_trans_t) *slot)->v;
368 }
369
370
371 /* Add the tuple mapping from {expression E, basic block PRED} to
372    value V, to the phi translation table.  */
373
374 static inline void
375 phi_trans_add (tree e, tree v, basic_block pred)
376 {
377   void **slot;
378   expr_pred_trans_t new_pair = xmalloc (sizeof (*new_pair));
379   new_pair->e = e;
380   new_pair->pred = pred;
381   new_pair->v = v;
382   new_pair->hashcode = vn_compute (e, (unsigned long) pred);
383   slot = htab_find_slot_with_hash (phi_translate_table, new_pair,
384                                    new_pair->hashcode, INSERT);
385   if (*slot)
386     free (*slot);
387   *slot = (void *) new_pair;
388 }
389
390 /* Add expression E to the expression set of value V.  */
391
392 void
393 add_to_value (tree v, tree e)
394 {
395   /* For values representing non-CST nodes, but still function
396      invariant things we mark TREE_CONSTANT as true and set the tree
397      chain to the actual constant.  This is because unlike values
398      involving expressions, which are only available to use where the
399      expressions are live, a function invariant can be remade
400      anywhere, and thus, is available everywhere, just like a constant.  */
401   if (TREE_CODE_CLASS (TREE_CODE (v)) == 'c')
402     return;
403   else if (is_gimple_min_invariant (v))
404     {
405       TREE_CONSTANT (v) = true;
406       TREE_CHAIN (v) = e;
407       return;
408     }
409
410   if (VALUE_HANDLE_EXPR_SET (v) == NULL)
411     VALUE_HANDLE_EXPR_SET (v) = set_new (false);
412
413   insert_into_set (VALUE_HANDLE_EXPR_SET (v), e);
414 }
415
416
417 /* Return true if value V exists in the bitmap for SET.  */
418
419 static inline bool
420 value_exists_in_set_bitmap (value_set_t set, tree v)
421 {
422   if (!set->values)
423     return false;
424
425   return bitmap_bit_p (set->values, VALUE_HANDLE_ID (v));
426 }
427
428
429 /* Remove value V from the bitmap for SET.  */
430
431 static void
432 value_remove_from_set_bitmap (value_set_t set, tree v)
433 {
434 #ifdef ENABLE_CHECKING
435   if (!set->indexed)
436     abort ();
437 #endif
438
439   if (!set->values)
440     return;
441
442   bitmap_clear_bit (set->values, VALUE_HANDLE_ID (v));
443 }
444
445
446 /* Insert the value number V into the bitmap of values existing in
447    SET.  */
448
449 static inline void
450 value_insert_into_set_bitmap (value_set_t set, tree v)
451 {
452 #ifdef ENABLE_CHECKING
453   if (!set->indexed)
454     abort ();
455 #endif
456
457   if (set->values == NULL)
458     {
459       set->values = BITMAP_GGC_ALLOC ();
460       bitmap_clear (set->values);
461     }
462
463   bitmap_set_bit (set->values, VALUE_HANDLE_ID (v));
464 }
465
466
467 /* Create a new set.  */
468
469 static value_set_t
470 set_new  (bool indexed)
471 {
472   value_set_t ret;
473   ret = pool_alloc (value_set_pool);
474   ret->head = ret->tail = NULL;
475   ret->length = 0;
476   ret->indexed = indexed;
477   ret->values = NULL;
478   return ret;
479 }
480
481
482 /* Insert EXPR into SET.  */
483
484 static void
485 insert_into_set (value_set_t set, tree expr)
486 {
487   value_set_node_t newnode = pool_alloc (value_set_node_pool);
488   tree val = get_value_handle (expr);
489   
490   if (val == NULL)
491     abort ();
492
493   /* For indexed sets, insert the value into the set value bitmap.
494      For all sets, add it to the linked list and increment the list
495      length.  */
496   if (set->indexed)
497     value_insert_into_set_bitmap (set, val);
498
499   newnode->next = NULL;
500   newnode->expr = expr;
501   set->length ++;
502   if (set->head == NULL)
503     {
504       set->head = set->tail = newnode;
505     }
506   else
507     {
508       set->tail->next = newnode;
509       set->tail = newnode;
510     }
511 }
512
513 /* Copy the set ORIG to the set DEST.  */
514
515 static void
516 set_copy (value_set_t dest, value_set_t orig)
517 {
518   value_set_node_t node;
519  
520   if (!orig || !orig->head)
521     return;
522
523   for (node = orig->head;
524        node;
525        node = node->next)
526     {
527       insert_into_set (dest, node->expr);
528     }
529 }
530
531 /* Remove EXPR from SET.  */
532
533 static void
534 set_remove (value_set_t set, tree expr)
535 {
536   value_set_node_t node, prev;
537
538   /* Remove the value of EXPR from the bitmap, decrement the set
539      length, and remove it from the actual double linked list.  */ 
540   value_remove_from_set_bitmap (set, get_value_handle (expr));
541   set->length--;
542   prev = NULL;
543   for (node = set->head; 
544        node != NULL; 
545        prev = node, node = node->next)
546     {
547       if (node->expr == expr)
548         {
549           if (prev == NULL)
550             set->head = node->next;
551           else
552             prev->next= node->next;
553  
554           if (node == set->tail)
555             set->tail = prev;
556           pool_free (value_set_node_pool, node);
557           return;
558         }
559     }
560 }
561
562 /* Return true if SET contains the value VAL.  */
563
564 static bool
565 set_contains_value (value_set_t set, tree val)
566 {
567   /* All true constants are in every set.  */
568   if (TREE_CODE_CLASS (TREE_CODE (val)) == 'c')
569     return true;
570   /* This is only referring to the flag above that we set on
571      values referring to invariants, because we know that we
572      are dealing with one of the value handles we created.  */
573
574   if (TREE_CONSTANT (val))
575     return true;
576   
577   if (set->length == 0)
578     return false;
579   
580   return value_exists_in_set_bitmap (set, val);
581 }
582
583 /* Replace the leader for the value LOOKFOR in SET with EXPR.  */
584
585 static void
586 set_replace_value (value_set_t set, tree lookfor, tree expr)
587 {
588   value_set_node_t node = set->head;
589
590   /* The lookup is probably more expensive than walking the linked
591      list when we have only a small number of nodes.  */
592   if (!set_contains_value (set, lookfor))
593     return;
594
595   for (node = set->head;
596        node;
597        node = node->next)
598     {
599       if (get_value_handle (node->expr) == lookfor)
600         {
601           node->expr = expr;
602           return;
603         }
604     }
605 }
606
607 /* Return true if the set contains expression (not value) EXPR.  */
608
609 static bool
610 set_contains (value_set_t set, tree expr)
611 {
612   value_set_node_t node;
613   
614   for (node = set->head;
615        node;
616        node = node->next)
617     {
618       if (operand_equal_p (node->expr, expr, 0))
619         return true;
620     }
621   return false;
622 }
623
624 /* Subtract set B from set A, and return the new set.  */
625
626 static value_set_t
627 set_subtract (value_set_t a, value_set_t b, bool indexed)
628 {
629   value_set_t ret = set_new (indexed);
630   value_set_node_t node;
631   for (node = a->head;
632        node;
633        node = node->next)
634     {
635       if (!set_contains (b, node->expr))
636         insert_into_set (ret, node->expr);
637     }
638   return ret;
639 }
640
641 /* Return true if two sets are equal. */
642
643 static bool
644 set_equal (value_set_t a, value_set_t b)
645 {
646   value_set_node_t node;
647
648   if (a->length != b->length)
649     return false;
650   for (node = a->head;
651        node;
652        node = node->next)
653     {
654       if (!set_contains_value (b, get_value_handle (node->expr)))
655         return false;
656     }
657   return true;
658 }
659
660 /* Replace the value for EXPR in SET with EXPR.  */
661 static void
662 value_replace_in_set (value_set_t set, tree expr)
663 {
664   tree val = get_value_handle (expr);
665
666   if (set->length == 0)
667     return;
668   
669   set_replace_value (set, val, expr);
670 }
671
672 /* Insert the value for EXPR into SET, if it doesn't exist already.  */
673
674 static void
675 value_insert_into_set (value_set_t set, tree expr)
676 {
677   tree val = get_value_handle (expr);
678
679   /* Constant and invariant values exist everywhere, and thus,
680      actually keeping them in the sets is pointless.  */
681   if (TREE_CONSTANT (val))
682     return;
683
684   if (!set_contains_value (set, val))
685     insert_into_set (set, expr);
686 }
687
688
689 /* Print out the value_set SET to OUTFILE.  */
690
691 static void
692 print_value_set (FILE *outfile, value_set_t set,
693                  const char *setname, int blockindex)
694 {
695   value_set_node_t node;
696   fprintf (outfile, "%s[%d] := { ", setname, blockindex);
697   if (set)
698     {
699       for (node = set->head;
700            node;
701            node = node->next)
702         {
703           print_generic_expr (outfile, node->expr, 0);
704           
705           fprintf (outfile, " (");
706           print_generic_expr (outfile, get_value_handle (node->expr), 0);
707           fprintf (outfile, ") ");
708                      
709           if (node->next)
710             fprintf (outfile, ", ");
711         }
712     }
713
714   fprintf (outfile, " }\n");
715 }
716
717 /* Print out the expressions that have VAL to OUTFILE.  */
718
719 void
720 print_value_expressions (FILE *outfile, tree val)
721 {
722   if (VALUE_HANDLE_EXPR_SET (val))
723     {
724       char s[10];
725       sprintf (s, "VH.%04d", VALUE_HANDLE_ID (val));
726       print_value_set (outfile, VALUE_HANDLE_EXPR_SET (val), s, 0);
727     }
728 }
729
730
731 void
732 debug_value_expressions (tree val)
733 {
734   print_value_expressions (stderr, val);
735 }
736
737   
738 void debug_value_set (value_set_t, const char *, int);
739
740 void
741 debug_value_set (value_set_t set, const char *setname, int blockindex)
742 {
743   print_value_set (stderr, set, setname, blockindex);
744 }
745
746 /* Translate EXPR using phis in PHIBLOCK, so that it has the values of
747    the phis in PRED.  Return NULL if we can't find a leader for each
748    part of the translated expression.  */
749
750 static tree
751 phi_translate (tree expr, value_set_t set,  basic_block pred,
752                basic_block phiblock)
753 {
754   tree phitrans = NULL;
755   tree oldexpr = expr;
756   
757   if (expr == NULL)
758     return NULL;
759
760   /* Phi translations of a given expression don't change,  */
761   phitrans = phi_trans_lookup (expr, pred);
762   if (phitrans)
763     return phitrans;
764   
765   
766   switch (TREE_CODE_CLASS (TREE_CODE (expr)))
767     {
768     case '2':
769       {
770         tree oldop1 = TREE_OPERAND (expr, 0);
771         tree oldop2 = TREE_OPERAND (expr, 1);
772         tree newop1;
773         tree newop2;
774         tree newexpr;
775         
776         newop1 = phi_translate (find_leader (set, oldop1),
777                                 set, pred, phiblock);
778         if (newop1 == NULL)
779           return NULL;
780         newop2 = phi_translate (find_leader (set, oldop2),
781                                 set, pred, phiblock);
782         if (newop2 == NULL)
783           return NULL;
784         if (newop1 != oldop1 || newop2 != oldop2)
785           {
786             newexpr = pool_alloc (binary_node_pool);
787             memcpy (newexpr, expr, tree_size (expr));
788             create_tree_ann (newexpr);
789             TREE_OPERAND (newexpr, 0) = newop1 == oldop1 ? oldop1 : get_value_handle (newop1);
790             TREE_OPERAND (newexpr, 1) = newop2 == oldop2 ? oldop2 : get_value_handle (newop2);
791             vn_lookup_or_add (newexpr);
792             expr = newexpr;
793             phi_trans_add (oldexpr, newexpr, pred);         
794           }
795       }
796       break;
797       /* XXX: Until we have PRE of loads working, none will be ANTIC.
798        */
799     case 'r':
800       return NULL;
801       break;
802     case '1':
803       {
804         tree oldop1 = TREE_OPERAND (expr, 0);
805         tree newop1;
806         tree newexpr;
807
808         newop1 = phi_translate (find_leader (set, oldop1),
809                                 set, pred, phiblock);
810         if (newop1 == NULL)
811           return NULL;
812         if (newop1 != oldop1)
813           {
814             newexpr = pool_alloc (unary_node_pool);
815             memcpy (newexpr, expr, tree_size (expr));
816             create_tree_ann (newexpr);   
817             TREE_OPERAND (newexpr, 0) = get_value_handle (newop1);
818             vn_lookup_or_add (newexpr);
819             expr = newexpr;
820             phi_trans_add (oldexpr, newexpr, pred);
821           }
822       }
823       break;
824     case 'd':
825       abort ();
826     case 'x':
827       {
828         tree phi = NULL;
829         int i;
830         if (TREE_CODE (expr) != SSA_NAME)
831           abort ();
832         if (TREE_CODE (SSA_NAME_DEF_STMT (expr)) == PHI_NODE)
833           phi = SSA_NAME_DEF_STMT (expr);
834         else
835           return expr;
836         
837         for (i = 0; i < PHI_NUM_ARGS (phi); i++)
838           if (PHI_ARG_EDGE (phi, i)->src == pred)
839             {
840               tree val;
841               if (is_undefined_value (PHI_ARG_DEF (phi, i)))
842                 return NULL;
843               val = vn_lookup_or_add (PHI_ARG_DEF (phi, i));
844               return PHI_ARG_DEF (phi, i);
845             }
846       }
847       break;
848     }
849   return expr;
850 }
851
852 static void
853 phi_translate_set (value_set_t dest, value_set_t set, basic_block pred,
854                    basic_block phiblock)
855 {
856   value_set_node_t node;
857   for (node = set->head;
858        node;
859        node = node->next)
860     {
861       tree translated;
862       translated = phi_translate (node->expr, set, pred, phiblock);
863       phi_trans_add (node->expr, translated, pred);
864       
865       if (translated != NULL)
866         value_insert_into_set (dest, translated);
867     } 
868 }
869
870 /* Find the leader for a value (IE the name representing that
871    value) in a given set, and return it.  Return NULL if no leader is
872    found.  */
873
874 static tree
875 find_leader (value_set_t set, tree val)
876 {
877   value_set_node_t node;
878
879   if (val == NULL)
880     return NULL;
881   /* True constants represent themselves.  */
882   if (TREE_CODE_CLASS (TREE_CODE (val)) == 'c')
883     return val;
884   /* Invariants are still represented by values, since they may be
885      more than a single _CST node.  */  
886   if (TREE_CONSTANT (val))
887     return TREE_CHAIN (val);
888
889   if (set->length == 0)
890     return NULL;
891   
892   if (value_exists_in_set_bitmap (set, val))
893     {
894       for (node = set->head;
895            node;
896            node = node->next)
897         {
898           if (get_value_handle (node->expr) == val)
899             return node->expr;
900         }
901     }
902   return NULL;
903 }
904
905 /* Determine if the expression EXPR is valid in SET.  This means that
906    we have a leader for each part of the expression (if it consists of
907    values), or the expression is an SSA_NAME.  
908
909    NB:  We never should run into a case where we have SSA_NAME +
910    SSA_NAME or SSA_NAME + value.  The sets valid_in_set is called on,
911    the ANTIC sets, will only ever have SSA_NAME's or binary value
912    expression (IE VALUE1 + VALUE2)  */
913
914 static bool
915 valid_in_set (value_set_t set, tree expr)
916 {
917   switch (TREE_CODE_CLASS (TREE_CODE (expr)))
918     {
919     case '2':
920       {
921         tree op1 = TREE_OPERAND (expr, 0);
922         tree op2 = TREE_OPERAND (expr, 1);
923         return set_contains_value (set, op1) && set_contains_value (set, op2);
924       }
925       break;
926     case '1':
927       {
928         tree op1 = TREE_OPERAND (expr, 0);
929         return set_contains_value (set, op1);
930       }
931       break;
932       /* XXX: Until PRE of loads works, no reference nodes are ANTIC.
933        */
934     case 'r':
935       {
936         return false;
937       }
938     case 'x':
939       {
940         if (TREE_CODE (expr) == SSA_NAME)
941           return true;
942         abort ();
943       }
944     case 'c':
945       abort ();
946     }
947   return false;
948 }
949
950 /* Clean the set of expressions that are no longer valid in SET.  This
951    means expressions that are made up of values we have no leaders for
952    in SET.  */
953
954 static void
955 clean (value_set_t set)
956 {
957   value_set_node_t node;
958   value_set_node_t next;
959   node = set->head;
960   while (node)
961     {
962       next = node->next;
963       if (!valid_in_set (set, node->expr))      
964         set_remove (set, node->expr);
965       node = next;
966     }
967 }
968
969 /* Compute the ANTIC set for BLOCK.
970
971 ANTIC_OUT[BLOCK] = intersection of ANTIC_IN[b] for all succ(BLOCK), if
972 succs(BLOCK) > 1
973 ANTIC_OUT[BLOCK] = phi_translate (ANTIC_IN[succ(BLOCK)]) if
974 succs(BLOCK) == 1
975
976 ANTIC_IN[BLOCK] = clean(ANTIC_OUT[BLOCK] U EXP_GEN[BLOCK] -
977 TMP_GEN[BLOCK])
978
979 Iterate until fixpointed.
980
981 XXX: It would be nice to either write a set_clear, and use it for
982 antic_out, or to mark the antic_out set as deleted at the end
983 of this routine, so that the pool can hand the same memory back out
984 again for the next antic_out.  */
985
986
987 static bool
988 compute_antic_aux (basic_block block)
989 {
990   basic_block son;
991   edge e;
992   bool changed = false;
993   value_set_t S, old, ANTIC_OUT;
994   value_set_node_t node;
995   
996   ANTIC_OUT = S = NULL;
997   /* If any edges from predecessors are abnormal, antic_in is empty, so
998      punt.  Remember that the block has an incoming abnormal edge by
999      setting the BB_VISITED flag.  */
1000   if (! (block->flags & BB_VISITED))
1001     {
1002       for (e = block->pred; e; e = e->pred_next)
1003         if (e->flags & EDGE_ABNORMAL)
1004           {
1005             block->flags |= BB_VISITED;
1006             break;
1007           }
1008     }
1009   if (block->flags & BB_VISITED)
1010     {
1011       S = NULL;
1012       goto visit_sons;
1013     }
1014   
1015
1016   old = set_new (false);
1017   set_copy (old, ANTIC_IN (block));
1018   ANTIC_OUT = set_new (true);
1019
1020   /* If the block has no successors, ANTIC_OUT is empty, because it is
1021      the exit block.  */
1022   if (block->succ == NULL);
1023
1024   /* If we have one successor, we could have some phi nodes to
1025      translate through.  */
1026   else if (block->succ->succ_next == NULL)
1027     {
1028       phi_translate_set (ANTIC_OUT, ANTIC_IN(block->succ->dest),
1029                          block, block->succ->dest);
1030     }
1031   /* If we have multiple successors, we take the intersection of all of
1032      them.  */
1033   else
1034     {
1035       varray_type worklist;
1036       edge e;
1037       size_t i;
1038       basic_block bprime, first;
1039
1040       VARRAY_BB_INIT (worklist, 1, "succ");
1041       e = block->succ;
1042       while (e)
1043         {
1044           VARRAY_PUSH_BB (worklist, e->dest);
1045           e = e->succ_next;
1046         }
1047       first = VARRAY_BB (worklist, 0);
1048       set_copy (ANTIC_OUT, ANTIC_IN (first));
1049
1050       for (i = 1; i < VARRAY_ACTIVE_SIZE (worklist); i++)
1051         {
1052           bprime = VARRAY_BB (worklist, i);
1053           node = ANTIC_OUT->head;
1054           while (node)
1055             {
1056               tree val;
1057               value_set_node_t next = node->next;
1058               val = get_value_handle (node->expr);
1059               if (!set_contains_value (ANTIC_IN (bprime), val))
1060                 set_remove (ANTIC_OUT, node->expr);
1061               node = next;
1062             }
1063         }
1064       VARRAY_CLEAR (worklist);
1065     }
1066
1067   /* Generate ANTIC_OUT - TMP_GEN */
1068   S = set_subtract (ANTIC_OUT, TMP_GEN (block), false);
1069
1070   /* Start ANTIC_IN with EXP_GEN - TMP_GEN */
1071   ANTIC_IN (block) = set_subtract (EXP_GEN (block),TMP_GEN (block), true);
1072   
1073   /* Then union in the ANTIC_OUT - TMP_GEN values, to get ANTIC_OUT U
1074      EXP_GEN - TMP_GEN */
1075   for (node = S->head;
1076        node;
1077        node = node->next)
1078     {
1079       value_insert_into_set (ANTIC_IN (block), node->expr);
1080     }
1081   clean (ANTIC_IN (block));
1082   
1083
1084   if (!set_equal (old, ANTIC_IN (block)))
1085     changed = true;
1086
1087  visit_sons:
1088   if (dump_file && (dump_flags & TDF_DETAILS))
1089     {
1090       if (ANTIC_OUT)
1091         print_value_set (dump_file, ANTIC_OUT, "ANTIC_OUT", block->index);
1092       print_value_set (dump_file, ANTIC_IN (block), "ANTIC_IN", block->index);
1093       if (S)
1094         print_value_set (dump_file, S, "S", block->index);
1095
1096     }
1097
1098   for (son = first_dom_son (CDI_POST_DOMINATORS, block);
1099        son;
1100        son = next_dom_son (CDI_POST_DOMINATORS, son))
1101     {
1102       changed |= compute_antic_aux (son);
1103     }
1104   return changed;
1105 }
1106
1107 /* Compute ANTIC sets.  */
1108
1109 static void
1110 compute_antic (void)
1111 {
1112   bool changed = true;
1113   basic_block bb;
1114   int num_iterations = 0;
1115   FOR_ALL_BB (bb)
1116     {
1117       ANTIC_IN (bb) = set_new (true);
1118       if (bb->flags & BB_VISITED)
1119         abort ();
1120     }
1121
1122   while (changed)
1123     {
1124       num_iterations++;
1125       changed = false;
1126       changed = compute_antic_aux (EXIT_BLOCK_PTR);
1127     }
1128   FOR_ALL_BB (bb)
1129     {
1130       bb->flags &= ~BB_VISITED;
1131     }
1132   if (num_iterations > 2 && dump_file && (dump_flags & TDF_STATS))
1133     fprintf (dump_file, "compute_antic required %d iterations\n", num_iterations);
1134 }
1135
1136
1137 /* Find a leader for an expression, or generate one using
1138    create_expression_by_pieces if it's ANTIC but
1139    complex.  
1140    BLOCK is the basic_block we are looking for leaders in.
1141    EXPR is the expression to find a leader or generate for. 
1142    STMTS is the statement list to put the inserted expressions on.
1143    Returns the SSA_NAME of the LHS of the generated expression or the
1144    leader.  */
1145
1146 static tree
1147 find_or_generate_expression (basic_block block, tree expr, tree stmts)
1148 {
1149   tree genop;
1150   genop = find_leader (AVAIL_OUT (block), expr);
1151   /* Depending on the order we process DOM branches in, the value
1152      may not have propagated to all the dom children yet during
1153      this iteration.  In this case, the value will always be in
1154      the NEW_SETS for us already, having been propagated from our
1155      dominator.  */
1156   if (genop == NULL)
1157     genop = find_leader (NEW_SETS (block), expr);
1158   /* If it's still NULL, see if it is a complex expression, and if
1159      so, generate it recursively, otherwise, abort, because it's
1160      not really .  */
1161   if (genop == NULL)
1162     {
1163       genop = VALUE_HANDLE_EXPR_SET (expr)->head->expr;
1164       if (TREE_CODE_CLASS (TREE_CODE (genop)) != '1'
1165           && TREE_CODE_CLASS (TREE_CODE (genop)) != '2')
1166         abort ();
1167       genop = create_expression_by_pieces (block, genop, stmts);
1168     }
1169   return genop;
1170 }
1171
1172   
1173 /* Create an expression in pieces, so that we can handle very complex
1174    expressions that may be ANTIC, but not necessary GIMPLE.  
1175    BLOCK is the basic block the expression will be inserted into,
1176    EXPR is the expression to insert (in value form)
1177    STMTS is a statement list to append the necessary insertions into.
1178
1179    This function will abort if we hit some value that shouldn't be
1180    ANTIC but is (IE there is no leader for it, or its components).
1181    This function may also generate expressions that are themselves
1182    partially or fully redundant.  Those that are will be either made
1183    fully redundant during the next iteration of insert (for partially
1184    redundant ones), or eliminated by eliminate (for fully redundant
1185    ones).  */
1186
1187 static tree
1188 create_expression_by_pieces (basic_block block, tree expr, tree stmts)
1189 {
1190   tree name = NULL_TREE;
1191   tree newexpr = NULL_TREE;
1192   tree v;
1193   
1194   switch (TREE_CODE_CLASS (TREE_CODE (expr)))
1195     {
1196     case '2':
1197       {
1198         tree_stmt_iterator tsi;
1199         tree genop1, genop2;
1200         tree temp;
1201         tree op1 = TREE_OPERAND (expr, 0);
1202         tree op2 = TREE_OPERAND (expr, 1);
1203         genop1 = find_or_generate_expression (block, op1, stmts);
1204         genop2 = find_or_generate_expression (block, op2, stmts);
1205         temp = create_tmp_var (TREE_TYPE (expr), "pretmp");
1206         add_referenced_tmp_var (temp);
1207         newexpr = build (TREE_CODE (expr), TREE_TYPE (expr), 
1208                          genop1, genop2);
1209         newexpr = build (MODIFY_EXPR, TREE_TYPE (expr),
1210                          temp, newexpr);
1211         name = make_ssa_name (temp, newexpr);
1212         TREE_OPERAND (newexpr, 0) = name;
1213         tsi = tsi_last (stmts);
1214         tsi_link_after (&tsi, newexpr, TSI_CONTINUE_LINKING);
1215         pre_stats.insertions++;
1216         break;
1217       }
1218     case '1':
1219       {
1220         tree_stmt_iterator tsi;
1221         tree genop1;
1222         tree temp;
1223         tree op1 = TREE_OPERAND (expr, 0);
1224         genop1 = find_or_generate_expression (block, op1, stmts);
1225         temp = create_tmp_var (TREE_TYPE (expr), "pretmp");
1226         add_referenced_tmp_var (temp);
1227         newexpr = build (TREE_CODE (expr), TREE_TYPE (expr), 
1228                          genop1);
1229         newexpr = build (MODIFY_EXPR, TREE_TYPE (expr),
1230                          temp, newexpr);
1231         name = make_ssa_name (temp, newexpr);
1232         TREE_OPERAND (newexpr, 0) = name;
1233         tsi = tsi_last (stmts);
1234         tsi_link_after (&tsi, newexpr, TSI_CONTINUE_LINKING);
1235         pre_stats.insertions++;
1236
1237         break;
1238       }
1239     default:
1240       abort ();
1241       
1242     }
1243   v = get_value_handle (expr);
1244   vn_add (name, v);
1245   insert_into_set (NEW_SETS (block), name);
1246   value_insert_into_set (AVAIL_OUT (block), name);
1247   if (dump_file && (dump_flags & TDF_DETAILS))
1248     {                               
1249       fprintf (dump_file, "Inserted ");
1250       print_generic_expr (dump_file, newexpr, 0);
1251       fprintf (dump_file, " in predecessor %d\n", block->index);
1252     }
1253   return name;
1254 }
1255       
1256 /* Perform insertion of partially redundant values.
1257    For BLOCK, do the following:
1258    1.  Propagate the NEW_SETS of the dominator into the current block.
1259    If the block has multiple predecessors, 
1260        2a. Iterate over the ANTIC expressions for the block to see if
1261            any of them are partially redundant.
1262        2b. If so, insert them into the necessary predecessors to make
1263            the expression fully redundant.
1264        2c. Insert a new PHI merging the values of the predecessors.
1265        2d. Insert the new PHI, and the new expressions, into the
1266            NEW_SETS set.  
1267    3. Recursively call ourselves on the dominator children of BLOCK.
1268
1269 */
1270 static bool
1271 insert_aux (basic_block block)
1272 {
1273   basic_block son;
1274   bool new_stuff = false;
1275
1276   if (block)
1277     {
1278       value_set_node_t e;
1279       basic_block dom;
1280       dom = get_immediate_dominator (CDI_DOMINATORS, block);
1281       if (dom)
1282         {
1283           e = NEW_SETS (dom)->head;
1284           while (e)
1285             {
1286               insert_into_set (NEW_SETS (block), e->expr);
1287               value_replace_in_set (AVAIL_OUT (block), e->expr);
1288               e = e->next;
1289             }
1290           if (block->pred->pred_next)
1291             {
1292               value_set_node_t node;
1293               for (node = ANTIC_IN (block)->head;
1294                    node;
1295                    node = node->next)
1296                 {
1297                   if (TREE_CODE_CLASS (TREE_CODE (node->expr)) == '2'
1298                       || TREE_CODE_CLASS (TREE_CODE (node->expr)) == '1')
1299                     {
1300                       tree *avail;
1301                       tree val;
1302                       bool by_some = false;
1303                       bool cant_insert = false;
1304                       bool all_same = true;
1305                       tree first_s = NULL;
1306                       edge pred;
1307                       basic_block bprime;
1308                       tree eprime;
1309
1310                       val = get_value_handle (node->expr);
1311                       if (set_contains_value (PHI_GEN (block), val))
1312                         continue; 
1313                       if (set_contains_value (AVAIL_OUT (dom), val))
1314                         {
1315                           if (dump_file && (dump_flags & TDF_DETAILS))
1316                             fprintf (dump_file, "Found fully redundant value\n");
1317                           continue;
1318                         }
1319                                     
1320                       avail = xcalloc (last_basic_block, sizeof (tree));
1321                       for (pred = block->pred;
1322                            pred;
1323                            pred = pred->pred_next)
1324                         {
1325                           tree vprime;
1326                           tree edoubleprime;
1327                           bprime = pred->src;
1328                           eprime = phi_translate (node->expr,
1329                                                   ANTIC_IN (block),
1330                                                   bprime, block);
1331
1332                           /* eprime will generally only be NULL if the
1333                              value of the expression, translated
1334                              through the PHI for this predecessor, is
1335                              undefined.  If that is the case, we can't
1336                              make the expression fully redundant,
1337                              because its value is undefined along a
1338                              predecessor path.  We can thus break out
1339                              early because it doesn't matter what the
1340                              rest of the results are.  */
1341                           if (eprime == NULL)
1342                             {
1343                               cant_insert = true;
1344                               break;
1345                             }
1346
1347                           vprime = get_value_handle (eprime);
1348                           if (!vprime)
1349                             abort ();                     
1350                           edoubleprime = find_leader (AVAIL_OUT (bprime),
1351                                                       vprime);
1352                           if (edoubleprime == NULL)
1353                             {
1354                               avail[bprime->index] = eprime;
1355                               all_same = false;
1356                             }
1357                           else
1358                             {
1359                               avail[bprime->index] = edoubleprime;
1360                               by_some = true; 
1361                               if (first_s == NULL)
1362                                 first_s = edoubleprime;
1363                               else if (first_s != edoubleprime)
1364                                 all_same = false;
1365                               if (first_s != edoubleprime 
1366                                   && operand_equal_p (first_s, edoubleprime, 0))
1367                                 abort ();
1368                             }
1369                         }
1370                       /* If we can insert it, it's not the same value
1371                          already existing along every predecessor, and
1372                          it's defined by some predecessor, it is
1373                          partially redundant.  */
1374                       if (!cant_insert && !all_same && by_some)
1375                         {
1376                           tree type = TREE_TYPE (avail[block->pred->src->index]);
1377                           tree temp;
1378                           if (dump_file && (dump_flags & TDF_DETAILS))
1379                             {
1380                               fprintf (dump_file, "Found partial redundancy for expression ");
1381                               print_generic_expr (dump_file, node->expr, 0);
1382                               fprintf (dump_file, "\n");
1383                             }
1384
1385                           /* Make the necessary insertions. */
1386                           for (pred = block->pred;
1387                                pred;
1388                                pred = pred->pred_next)
1389                             {
1390                               tree stmts = alloc_stmt_list ();
1391                               tree builtexpr;
1392                               bprime = pred->src;
1393                               eprime = avail[bprime->index];
1394                               if (TREE_CODE_CLASS (TREE_CODE (eprime)) == '2'
1395                                   || TREE_CODE_CLASS (TREE_CODE (eprime)) == '1')
1396                                 {
1397                                   builtexpr = create_expression_by_pieces (bprime,
1398                                                                            eprime,
1399                                                                            stmts);
1400                                   bsi_insert_on_edge (pred, stmts);
1401                                   bsi_commit_edge_inserts (NULL);
1402                                   avail[bprime->index] = builtexpr;
1403                                 }                             
1404                             } 
1405                           /* Now build a phi for the new variable.  */
1406                           temp = create_tmp_var (type, "prephitmp");
1407                           add_referenced_tmp_var (temp);
1408                           temp = create_phi_node (temp, block);
1409                           vn_add (PHI_RESULT (temp), val);
1410
1411 #if 0
1412                           if (!set_contains_value (AVAIL_OUT (block), val))
1413                             insert_into_set (AVAIL_OUT (block), 
1414                                              PHI_RESULT (temp));
1415                           else
1416 #endif
1417                             value_replace_in_set (AVAIL_OUT (block), 
1418                                                  PHI_RESULT (temp));
1419                           for (pred = block->pred;
1420                                pred;
1421                                pred = pred->pred_next)
1422                             {
1423                               add_phi_arg (&temp, avail[pred->src->index],
1424                                            pred);
1425                             }
1426                           if (dump_file && (dump_flags & TDF_DETAILS))
1427                             {
1428                               fprintf (dump_file, "Created phi ");
1429                               print_generic_expr (dump_file, temp, 0);
1430                               fprintf (dump_file, " in block %d\n", block->index);
1431                             }
1432                           pre_stats.phis++;
1433                           new_stuff = true;
1434                           insert_into_set (NEW_SETS (block),
1435                                            PHI_RESULT (temp));
1436                           insert_into_set (PHI_GEN (block),
1437                                            PHI_RESULT (temp));
1438                         }
1439
1440                       free (avail);
1441                     }
1442                 }
1443             }
1444         }
1445     }
1446   for (son = first_dom_son (CDI_DOMINATORS, block);
1447        son;
1448        son = next_dom_son (CDI_DOMINATORS, son))
1449     {
1450       new_stuff |= insert_aux (son);
1451     }
1452
1453   return new_stuff;
1454 }
1455
1456 /* Perform insertion of partially redundant values.  */
1457
1458 static void
1459 insert (void)
1460 {
1461   bool new_stuff = true;
1462   basic_block bb;
1463   int num_iterations = 0;
1464
1465   FOR_ALL_BB (bb)
1466     NEW_SETS (bb) = set_new (true);
1467   
1468   while (new_stuff)
1469     {
1470       num_iterations++;
1471       new_stuff = false;
1472       new_stuff = insert_aux (ENTRY_BLOCK_PTR);
1473     }
1474   if (num_iterations > 2 && dump_file && (dump_flags & TDF_STATS))
1475     fprintf (dump_file, "insert required %d iterations\n", num_iterations);
1476 }
1477
1478
1479 /* Return true if EXPR has no defining statement in this procedure,
1480    *AND* isn't a live-on-entry parameter.  */
1481
1482 static bool
1483 is_undefined_value (tree expr)
1484 {  
1485 #ifdef ENABLE_CHECKING
1486   /* We should never be handed DECL's  */
1487   if (DECL_P (expr))
1488     abort ();
1489 #endif
1490
1491   if (TREE_CODE (expr) == SSA_NAME)
1492     {
1493       /* XXX: Is this the correct test?  */
1494       if (TREE_CODE (SSA_NAME_VAR (expr)) == PARM_DECL)
1495         return false;
1496       if (IS_EMPTY_STMT (SSA_NAME_DEF_STMT (expr)))
1497         return true;
1498     }
1499
1500   return false;
1501 }
1502
1503 /* Compute the AVAIL set for BLOCK.
1504    This function performs value numbering of the statements in BLOCK. 
1505    The AVAIL sets are built from information we glean while doing this
1506    value numbering, since the AVAIL sets contain only entry per
1507    value.
1508
1509    
1510    AVAIL_IN[BLOCK] = AVAIL_OUT[dom(BLOCK)].
1511    AVAIL_OUT[BLOCK] = AVAIL_IN[BLOCK] U PHI_GEN[BLOCK] U
1512    TMP_GEN[BLOCK].
1513 */
1514
1515 static void
1516 compute_avail (basic_block block)
1517 {
1518   basic_block son;
1519   
1520   /* For arguments with default definitions, we pretend they are
1521      defined in the entry block.  */
1522   if (block == ENTRY_BLOCK_PTR)
1523     {
1524       tree param;
1525       for (param = DECL_ARGUMENTS (current_function_decl);
1526            param;
1527            param = TREE_CHAIN (param))
1528         {
1529           if (default_def (param) != NULL)
1530             {
1531               tree val;
1532               tree def = default_def (param);
1533               val = vn_lookup_or_add (def);
1534               insert_into_set (TMP_GEN (block), def);
1535               value_insert_into_set (AVAIL_OUT (block), def);
1536             }
1537         }
1538     }
1539   else if (block)
1540     {
1541       block_stmt_iterator bsi;
1542       tree stmt, phi;
1543       basic_block dom;
1544
1545       dom = get_immediate_dominator (CDI_DOMINATORS, block);
1546       if (dom)
1547         set_copy (AVAIL_OUT (block), AVAIL_OUT (dom));
1548
1549       for (phi = phi_nodes (block); phi; phi = PHI_CHAIN (phi))
1550         {
1551           /* Ignore virtual PHIs until we can do PRE on expressions
1552              with virtual operands.  */
1553           if (!is_gimple_reg (SSA_NAME_VAR (PHI_RESULT (phi))))
1554             continue;
1555
1556           vn_lookup_or_add (PHI_RESULT (phi));
1557           value_insert_into_set (AVAIL_OUT (block), PHI_RESULT (phi));
1558           insert_into_set (PHI_GEN (block), PHI_RESULT (phi));
1559         }
1560
1561       for (bsi = bsi_start (block); !bsi_end_p (bsi); bsi_next (&bsi))
1562         {
1563           tree op0, op1;
1564           stmt = bsi_stmt (bsi);
1565           get_stmt_operands (stmt);
1566           
1567           if (NUM_VUSES (STMT_VUSE_OPS (stmt))
1568               || NUM_V_MUST_DEFS (STMT_V_MUST_DEF_OPS (stmt))
1569               || NUM_V_MAY_DEFS (STMT_V_MAY_DEF_OPS (stmt))
1570               || stmt_ann (stmt)->has_volatile_ops)
1571             {
1572               size_t j;
1573               for (j = 0; j < NUM_DEFS (STMT_DEF_OPS (stmt)); j++)
1574                 {
1575                   tree def = DEF_OP (STMT_DEF_OPS (stmt), j);
1576                   vn_lookup_or_add (def);
1577                   insert_into_set (TMP_GEN (block), def);
1578                   value_insert_into_set (AVAIL_OUT (block), def);
1579                 }
1580               for (j = 0; j < NUM_USES (STMT_USE_OPS (stmt)); j++)
1581                 {
1582                   tree use = USE_OP (STMT_USE_OPS (stmt), j);
1583                   if (TREE_CODE (use) == SSA_NAME)
1584                     {
1585                       vn_lookup_or_add (use);
1586                       insert_into_set (TMP_GEN (block), use);
1587                       value_insert_into_set (AVAIL_OUT (block), use);
1588                     }
1589                 }
1590               continue;
1591             }
1592
1593           if (TREE_CODE (stmt) == MODIFY_EXPR)
1594             {
1595               op0 = TREE_OPERAND (stmt, 0);
1596               if (TREE_CODE (op0) != SSA_NAME)
1597                 continue;
1598               if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op0))
1599                 continue;
1600               op1 = TREE_OPERAND (stmt, 1);
1601               STRIP_USELESS_TYPE_CONVERSION (op1);
1602               if (is_gimple_min_invariant (op1))
1603                 {
1604                   vn_add (op0, vn_lookup_or_add (op1));
1605                   insert_into_set (TMP_GEN (block), op0);
1606                   value_insert_into_set (AVAIL_OUT (block), op0);
1607                 }
1608               else if (TREE_CODE_CLASS (TREE_CODE (op1)) == '2')
1609                 {
1610                   tree bop1, bop2;
1611                   tree val, val1, val2;
1612                   tree newt;
1613                   bop1 = TREE_OPERAND (op1, 0);
1614                   bop2 = TREE_OPERAND (op1, 1);
1615                   val1 = vn_lookup_or_add (bop1);
1616                   val2 = vn_lookup_or_add (bop2);
1617  
1618                   newt = pool_alloc (binary_node_pool);
1619                   memcpy (newt, op1, tree_size (op1));
1620                   TREE_OPERAND (newt, 0) = val1;
1621                   TREE_OPERAND (newt, 1) = val2;
1622                   val = vn_lookup_or_add (newt);
1623                   vn_add (op0, val);
1624                   if (!is_undefined_value (bop1))
1625                     value_insert_into_set (EXP_GEN (block), bop1);
1626                   if (!is_undefined_value (bop2))
1627                     value_insert_into_set (EXP_GEN (block), bop2);
1628                   value_insert_into_set (EXP_GEN (block), newt);
1629                   insert_into_set (TMP_GEN (block), op0);
1630                   value_insert_into_set (AVAIL_OUT (block), op0);  
1631                 }
1632               else if (TREE_CODE_CLASS (TREE_CODE (op1)) == '1'
1633                        && !is_gimple_cast (op1))
1634                 {
1635                   tree uop;
1636                   tree val, val1;
1637                   tree newt;
1638                   uop = TREE_OPERAND (op1, 0);
1639                   val1 = vn_lookup_or_add (uop);
1640                   newt = pool_alloc (unary_node_pool);
1641                   memcpy (newt, op1, tree_size (op1));
1642                   TREE_OPERAND (newt, 0) = val1;
1643                   val = vn_lookup_or_add (newt);
1644                   vn_add (op0, val);
1645                   if (!is_undefined_value (uop))
1646                     value_insert_into_set (EXP_GEN (block), uop);
1647                   value_insert_into_set (EXP_GEN (block), newt);
1648                   insert_into_set (TMP_GEN (block), op0);
1649                   value_insert_into_set (AVAIL_OUT (block), op0);
1650                 }
1651               else if (TREE_CODE (op1) == SSA_NAME)
1652                 {
1653                   tree val = vn_lookup_or_add (op1);
1654                   vn_add (op0, val);
1655                   if (!is_undefined_value (op1))
1656                     value_insert_into_set (EXP_GEN (block), op1);
1657                   insert_into_set (TMP_GEN (block), op0);
1658                   value_insert_into_set (AVAIL_OUT (block), op0);
1659                 }
1660               else
1661                 {
1662                   size_t j;
1663                   for (j = 0; j < NUM_DEFS (STMT_DEF_OPS (stmt)); j++)
1664                     {
1665                       tree def = DEF_OP (STMT_DEF_OPS (stmt), j);
1666                       vn_lookup_or_add (def);
1667                       insert_into_set (TMP_GEN (block), def);
1668                       value_insert_into_set (AVAIL_OUT (block), def);
1669                       if (def != op0)
1670                         abort ();
1671                     }
1672                   for (j = 0; j < NUM_USES (STMT_USE_OPS (stmt)); j++)
1673                     {
1674                       tree use = USE_OP (STMT_USE_OPS (stmt), j);
1675                       if (TREE_CODE (use) == SSA_NAME)
1676                         {
1677                           vn_lookup_or_add (use);
1678                           insert_into_set (TMP_GEN (block), use);
1679                           value_insert_into_set (AVAIL_OUT (block), use);
1680                         }
1681                     }
1682                 }
1683             }
1684           else
1685             {
1686               size_t j;
1687               for (j = 0; j < NUM_DEFS (STMT_DEF_OPS (stmt)); j++)
1688                 {
1689                   tree def = DEF_OP (STMT_DEF_OPS (stmt), j);
1690                   vn_lookup_or_add (def);
1691                   insert_into_set (TMP_GEN (block), def);
1692                   value_insert_into_set (AVAIL_OUT (block), def);
1693                 }
1694               for (j = 0; j < NUM_USES (STMT_USE_OPS (stmt)); j++)
1695                 {
1696                   tree use = USE_OP (STMT_USE_OPS (stmt), j);
1697                   if (TREE_CODE (use) == SSA_NAME)
1698                     {
1699                       vn_lookup_or_add (use);
1700                       insert_into_set (TMP_GEN (block), use);
1701                       value_insert_into_set (AVAIL_OUT (block), use);
1702                     }
1703                 }
1704             }
1705         }
1706     }
1707
1708   for (son = first_dom_son (CDI_DOMINATORS, block);
1709        son;
1710        son = next_dom_son (CDI_DOMINATORS, son))
1711     compute_avail (son);
1712 }
1713
1714
1715 /* Eliminate fully redundant computations.  */
1716
1717 static void
1718 eliminate (void)
1719 {
1720   basic_block b;
1721
1722   FOR_EACH_BB (b)
1723     {
1724       block_stmt_iterator i;
1725       
1726       for (i = bsi_start (b); !bsi_end_p (i); bsi_next (&i))
1727         {
1728           tree stmt = bsi_stmt (i);
1729
1730           if (NUM_VUSES (STMT_VUSE_OPS (stmt))
1731               || NUM_V_MUST_DEFS (STMT_V_MUST_DEF_OPS (stmt))
1732               || NUM_V_MAY_DEFS (STMT_V_MAY_DEF_OPS (stmt))
1733               || stmt_ann (stmt)->has_volatile_ops)
1734             continue;
1735
1736           /* Lookup the RHS of the expression, see if we have an
1737              available computation for it. If so, replace the RHS with
1738              the available computation.  */
1739           if (TREE_CODE (stmt) == MODIFY_EXPR)
1740             {
1741               tree t = TREE_OPERAND (stmt, 0);
1742               tree expr = TREE_OPERAND (stmt, 1);
1743               tree sprime;
1744               /* There is no point in eliminating NOP_EXPR, it isn't
1745                  supposed to generate any code.  */
1746               if (TREE_CODE (expr) == NOP_EXPR
1747                   || (TREE_CODE_CLASS (TREE_CODE (expr)) != '2' 
1748                    && TREE_CODE_CLASS (TREE_CODE (expr)) != '1'))
1749                 continue;
1750
1751               sprime = find_leader (AVAIL_OUT (b), vn_lookup (t));
1752               if (sprime 
1753                   && sprime != t 
1754                   && may_propagate_copy (sprime, TREE_OPERAND (stmt, 1)))
1755                 {
1756                   if (dump_file && (dump_flags & TDF_DETAILS))
1757                     {
1758                       fprintf (dump_file, "Replaced ");
1759                       print_generic_expr (dump_file, expr, 0);
1760                       fprintf (dump_file, " with ");
1761                       print_generic_expr (dump_file, sprime, 0);
1762                       fprintf (dump_file, " in ");
1763                       print_generic_stmt (dump_file, stmt, 0);
1764                     }
1765                   pre_stats.eliminations++;
1766                   propagate_tree_value (&TREE_OPERAND (stmt, 1), sprime);
1767                   modify_stmt (stmt);
1768                 }
1769             }
1770         }
1771     }
1772 }
1773
1774
1775 /* Main entry point to the SSA-PRE pass.
1776
1777    PHASE indicates which dump file from the DUMP_FILES array to use when
1778    dumping debugging information.  */
1779
1780 static void
1781 execute_pre (void)
1782 {
1783   size_t tsize;
1784   basic_block bb;
1785   memset (&pre_stats, 0, sizeof (pre_stats));
1786   FOR_ALL_BB (bb)
1787     {
1788       bb->aux = xcalloc (1, sizeof (struct bb_value_sets));
1789     }
1790   phi_translate_table = htab_create (511, expr_pred_trans_hash,
1791                                      expr_pred_trans_eq,
1792                                      free);
1793   value_set_pool = create_alloc_pool ("Value sets",
1794                                       sizeof (struct value_set), 30);
1795   value_set_node_pool = create_alloc_pool ("Value set nodes",
1796                                        sizeof (struct value_set_node), 30);
1797   calculate_dominance_info (CDI_POST_DOMINATORS);
1798   calculate_dominance_info (CDI_DOMINATORS);
1799   tsize = tree_size (build (PLUS_EXPR, void_type_node, NULL_TREE,
1800                             NULL_TREE));
1801   binary_node_pool = create_alloc_pool ("Binary tree nodes", tsize, 30);
1802   tsize = tree_size (build1 (NEGATE_EXPR, void_type_node, NULL_TREE));
1803   unary_node_pool = create_alloc_pool ("Unary tree nodes", tsize, 30);
1804
1805   FOR_ALL_BB (bb)
1806     {
1807       EXP_GEN (bb) = set_new (true);
1808       PHI_GEN (bb) = set_new (true);
1809       TMP_GEN (bb) = set_new (false);
1810       AVAIL_OUT (bb) = set_new (true);
1811     }
1812
1813   compute_avail (ENTRY_BLOCK_PTR);
1814
1815   if (dump_file && (dump_flags & TDF_DETAILS))
1816     {
1817       FOR_ALL_BB (bb)
1818         {
1819           print_value_set (dump_file, EXP_GEN (bb), "exp_gen", bb->index);
1820           print_value_set (dump_file, TMP_GEN (bb), "tmp_gen", bb->index);
1821           print_value_set (dump_file, AVAIL_OUT (bb), "avail_out", bb->index);
1822         }
1823     }
1824
1825   /* Insert can get quite slow on an incredibly large number of basic
1826      blocks due to some quadratic behavior.  Until this behavior is
1827      fixed, don't run it when he have an incredibly large number of
1828      bb's.  If we aren't going to run insert, there is no point in
1829      computing ANTIC, either, even though it's plenty fast.  */
1830  
1831   if (n_basic_blocks < 4000)
1832     {
1833       compute_antic ();
1834       
1835       insert ();
1836     }
1837   eliminate ();
1838   
1839   if (dump_file && (dump_flags & TDF_STATS))
1840     {
1841       fprintf (dump_file, "Insertions:%d\n", pre_stats.insertions);
1842       fprintf (dump_file, "New PHIs:%d\n", pre_stats.phis);
1843       fprintf (dump_file, "Eliminated:%d\n", pre_stats.eliminations);
1844     }
1845
1846   free_alloc_pool (value_set_pool);
1847   free_alloc_pool (value_set_node_pool);
1848   free_alloc_pool (binary_node_pool);
1849   free_alloc_pool (unary_node_pool);
1850   htab_delete (phi_translate_table);
1851   
1852   FOR_ALL_BB (bb)
1853     {
1854       free (bb->aux);
1855       bb->aux = NULL;
1856     }
1857   free_dominance_info (CDI_POST_DOMINATORS);
1858 }
1859
1860 static bool
1861 gate_pre (void)
1862 {
1863   return flag_tree_pre != 0;
1864 }
1865
1866 struct tree_opt_pass pass_pre =
1867 {
1868   "pre",                                /* name */
1869   gate_pre,                             /* gate */
1870   execute_pre,                          /* execute */
1871   NULL,                                 /* sub */
1872   NULL,                                 /* next */
1873   0,                                    /* static_pass_number */
1874   TV_TREE_PRE,                          /* tv_id */
1875   PROP_no_crit_edges | PROP_cfg | PROP_ssa,/* properties_required */
1876   0,                                    /* properties_provided */
1877   0,                                    /* properties_destroyed */
1878   0,                                    /* todo_flags_start */
1879   TODO_dump_func | TODO_ggc_collect | TODO_verify_ssa /* todo_flags_finish */
1880 };