OSDN Git Service

* vec.h: Update API to separate allocation mechanism from type.
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-dom.c
1 /* SSA Dominator optimizations for trees
2    Copyright (C) 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
3    Contributed by Diego Novillo <dnovillo@redhat.com>
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING.  If not, write to
19 the Free Software Foundation, 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "tree.h"
27 #include "flags.h"
28 #include "rtl.h"
29 #include "tm_p.h"
30 #include "ggc.h"
31 #include "basic-block.h"
32 #include "cfgloop.h"
33 #include "output.h"
34 #include "errors.h"
35 #include "expr.h"
36 #include "function.h"
37 #include "diagnostic.h"
38 #include "timevar.h"
39 #include "tree-dump.h"
40 #include "tree-flow.h"
41 #include "domwalk.h"
42 #include "real.h"
43 #include "tree-pass.h"
44 #include "tree-ssa-propagate.h"
45 #include "langhooks.h"
46
47 /* This file implements optimizations on the dominator tree.  */
48
49
50 /* Structure for recording edge equivalences as well as any pending
51    edge redirections during the dominator optimizer.
52
53    Computing and storing the edge equivalences instead of creating
54    them on-demand can save significant amounts of time, particularly
55    for pathological cases involving switch statements.  
56
57    These structures live for a single iteration of the dominator
58    optimizer in the edge's AUX field.  At the end of an iteration we
59    free each of these structures and update the AUX field to point
60    to any requested redirection target (the code for updating the
61    CFG and SSA graph for edge redirection expects redirection edge
62    targets to be in the AUX field for each edge.  */
63
64 struct edge_info
65 {
66   /* If this edge creates a simple equivalence, the LHS and RHS of
67      the equivalence will be stored here.  */
68   tree lhs;
69   tree rhs;
70
71   /* Traversing an edge may also indicate one or more particular conditions
72      are true or false.  The number of recorded conditions can vary, but
73      can be determined by the condition's code.  So we have an array
74      and its maximum index rather than use a varray.  */
75   tree *cond_equivalences;
76   unsigned int max_cond_equivalences;
77
78   /* If we can thread this edge this field records the new target.  */
79   edge redirection_target;
80 };
81
82
83 /* Hash table with expressions made available during the renaming process.
84    When an assignment of the form X_i = EXPR is found, the statement is
85    stored in this table.  If the same expression EXPR is later found on the
86    RHS of another statement, it is replaced with X_i (thus performing
87    global redundancy elimination).  Similarly as we pass through conditionals
88    we record the conditional itself as having either a true or false value
89    in this table.  */
90 static htab_t avail_exprs;
91
92 /* Stack of available expressions in AVAIL_EXPRs.  Each block pushes any
93    expressions it enters into the hash table along with a marker entry
94    (null).  When we finish processing the block, we pop off entries and
95    remove the expressions from the global hash table until we hit the
96    marker.  */
97 static VEC(tree,heap) *avail_exprs_stack;
98
99 /* Stack of trees used to restore the global currdefs to its original
100    state after completing optimization of a block and its dominator children.
101
102    An SSA_NAME indicates that the current definition of the underlying
103    variable should be set to the given SSA_NAME.
104
105    A _DECL node indicates that the underlying variable has no current
106    definition.
107
108    A NULL node is used to mark the last node associated with the
109    current block.  */
110 static VEC(tree,heap) *block_defs_stack;
111
112 /* Stack of statements we need to rescan during finalization for newly
113    exposed variables.
114
115    Statement rescanning must occur after the current block's available
116    expressions are removed from AVAIL_EXPRS.  Else we may change the
117    hash code for an expression and be unable to find/remove it from
118    AVAIL_EXPRS.  */
119 static VEC(tree,heap) *stmts_to_rescan;
120
121 /* Structure for entries in the expression hash table.
122
123    This requires more memory for the hash table entries, but allows us
124    to avoid creating silly tree nodes and annotations for conditionals,
125    eliminates 2 global hash tables and two block local varrays.
126    
127    It also allows us to reduce the number of hash table lookups we
128    have to perform in lookup_avail_expr and finally it allows us to
129    significantly reduce the number of calls into the hashing routine
130    itself.  */
131
132 struct expr_hash_elt
133 {
134   /* The value (lhs) of this expression.  */
135   tree lhs;
136
137   /* The expression (rhs) we want to record.  */
138   tree rhs;
139
140   /* The annotation if this element corresponds to a statement.  */
141   stmt_ann_t ann;
142
143   /* The hash value for RHS/ann.  */
144   hashval_t hash;
145 };
146
147 /* Stack of dest,src pairs that need to be restored during finalization.
148
149    A NULL entry is used to mark the end of pairs which need to be
150    restored during finalization of this block.  */
151 static VEC(tree,heap) *const_and_copies_stack;
152
153 /* Bitmap of SSA_NAMEs known to have a nonzero value, even if we do not
154    know their exact value.  */
155 static bitmap nonzero_vars;
156
157 /* Stack of SSA_NAMEs which need their NONZERO_VARS property cleared
158    when the current block is finalized. 
159
160    A NULL entry is used to mark the end of names needing their 
161    entry in NONZERO_VARS cleared during finalization of this block.  */
162 static VEC(tree,heap) *nonzero_vars_stack;
163
164 /* Track whether or not we have changed the control flow graph.  */
165 static bool cfg_altered;
166
167 /* Bitmap of blocks that have had EH statements cleaned.  We should
168    remove their dead edges eventually.  */
169 static bitmap need_eh_cleanup;
170
171 /* Statistics for dominator optimizations.  */
172 struct opt_stats_d
173 {
174   long num_stmts;
175   long num_exprs_considered;
176   long num_re;
177   long num_const_prop;
178   long num_copy_prop;
179 };
180
181 static struct opt_stats_d opt_stats;
182
183 /* Value range propagation record.  Each time we encounter a conditional
184    of the form SSA_NAME COND CONST we create a new vrp_element to record
185    how the condition affects the possible values SSA_NAME may have.
186
187    Each record contains the condition tested (COND), and the range of
188    values the variable may legitimately have if COND is true.  Note the
189    range of values may be a smaller range than COND specifies if we have
190    recorded other ranges for this variable.  Each record also contains the
191    block in which the range was recorded for invalidation purposes.
192
193    Note that the current known range is computed lazily.  This allows us
194    to avoid the overhead of computing ranges which are never queried.
195
196    When we encounter a conditional, we look for records which constrain
197    the SSA_NAME used in the condition.  In some cases those records allow
198    us to determine the condition's result at compile time.  In other cases
199    they may allow us to simplify the condition.
200
201    We also use value ranges to do things like transform signed div/mod
202    operations into unsigned div/mod or to simplify ABS_EXPRs. 
203
204    Simple experiments have shown these optimizations to not be all that
205    useful on switch statements (much to my surprise).  So switch statement
206    optimizations are not performed.
207
208    Note carefully we do not propagate information through each statement
209    in the block.  i.e., if we know variable X has a value defined of
210    [0, 25] and we encounter Y = X + 1, we do not track a value range
211    for Y (which would be [1, 26] if we cared).  Similarly we do not
212    constrain values as we encounter narrowing typecasts, etc.  */
213
214 struct vrp_element
215 {
216   /* The highest and lowest values the variable in COND may contain when
217      COND is true.  Note this may not necessarily be the same values
218      tested by COND if the same variable was used in earlier conditionals. 
219
220      Note this is computed lazily and thus can be NULL indicating that
221      the values have not been computed yet.  */
222   tree low;
223   tree high;
224
225   /* The actual conditional we recorded.  This is needed since we compute
226      ranges lazily.  */
227   tree cond;
228
229   /* The basic block where this record was created.  We use this to determine
230      when to remove records.  */
231   basic_block bb;
232 };
233
234 /* A hash table holding value range records (VRP_ELEMENTs) for a given
235    SSA_NAME.  We used to use a varray indexed by SSA_NAME_VERSION, but
236    that gets awful wasteful, particularly since the density objects
237    with useful information is very low.  */
238 static htab_t vrp_data;
239
240 /* An entry in the VRP_DATA hash table.  We record the variable and a
241    varray of VRP_ELEMENT records associated with that variable.  */
242 struct vrp_hash_elt
243 {
244   tree var;
245   varray_type records;
246 };
247
248 /* Array of variables which have their values constrained by operations
249    in this basic block.  We use this during finalization to know
250    which variables need their VRP data updated.  */
251
252 /* Stack of SSA_NAMEs which had their values constrained by operations
253    in this basic block.  During finalization of this block we use this
254    list to determine which variables need their VRP data updated.
255
256    A NULL entry marks the end of the SSA_NAMEs associated with this block.  */
257 static VEC(tree,heap) *vrp_variables_stack;
258
259 struct eq_expr_value
260 {
261   tree src;
262   tree dst;
263 };
264
265 /* Local functions.  */
266 static void optimize_stmt (struct dom_walk_data *, 
267                            basic_block bb,
268                            block_stmt_iterator);
269 static tree lookup_avail_expr (tree, bool);
270 static hashval_t vrp_hash (const void *);
271 static int vrp_eq (const void *, const void *);
272 static hashval_t avail_expr_hash (const void *);
273 static hashval_t real_avail_expr_hash (const void *);
274 static int avail_expr_eq (const void *, const void *);
275 static void htab_statistics (FILE *, htab_t);
276 static void record_cond (tree, tree);
277 static void record_const_or_copy (tree, tree);
278 static void record_equality (tree, tree);
279 static tree update_rhs_and_lookup_avail_expr (tree, tree, bool);
280 static tree simplify_rhs_and_lookup_avail_expr (struct dom_walk_data *,
281                                                 tree, int);
282 static tree simplify_cond_and_lookup_avail_expr (tree, stmt_ann_t, int);
283 static tree simplify_switch_and_lookup_avail_expr (tree, int);
284 static tree find_equivalent_equality_comparison (tree);
285 static void record_range (tree, basic_block);
286 static bool extract_range_from_cond (tree, tree *, tree *, int *);
287 static void record_equivalences_from_phis (basic_block);
288 static void record_equivalences_from_incoming_edge (basic_block);
289 static bool eliminate_redundant_computations (struct dom_walk_data *,
290                                               tree, stmt_ann_t);
291 static void record_equivalences_from_stmt (tree, int, stmt_ann_t);
292 static void thread_across_edge (struct dom_walk_data *, edge);
293 static void dom_opt_finalize_block (struct dom_walk_data *, basic_block);
294 static void dom_opt_initialize_block (struct dom_walk_data *, basic_block);
295 static void propagate_to_outgoing_edges (struct dom_walk_data *, basic_block);
296 static void remove_local_expressions_from_table (void);
297 static void restore_vars_to_original_value (void);
298 static void restore_currdefs_to_original_value (void);
299 static void register_definitions_for_stmt (tree);
300 static edge single_incoming_edge_ignoring_loop_edges (basic_block);
301 static void restore_nonzero_vars_to_original_value (void);
302 static inline bool unsafe_associative_fp_binop (tree);
303
304
305 /* Local version of fold that doesn't introduce cruft.  */
306
307 static tree
308 local_fold (tree t)
309 {
310   t = fold (t);
311
312   /* Strip away useless type conversions.  Both the NON_LVALUE_EXPR that
313      may have been added by fold, and "useless" type conversions that might
314      now be apparent due to propagation.  */
315   STRIP_USELESS_TYPE_CONVERSION (t);
316
317   return t;
318 }
319
320 /* Allocate an EDGE_INFO for edge E and attach it to E.
321    Return the new EDGE_INFO structure.  */
322
323 static struct edge_info *
324 allocate_edge_info (edge e)
325 {
326   struct edge_info *edge_info;
327
328   edge_info = xcalloc (1, sizeof (struct edge_info));
329
330   e->aux = edge_info;
331   return edge_info;
332 }
333
334 /* Free all EDGE_INFO structures associated with edges in the CFG.
335    If a particular edge can be threaded, copy the redirection
336    target from the EDGE_INFO structure into the edge's AUX field
337    as required by code to update the CFG and SSA graph for
338    jump threading.  */
339
340 static void
341 free_all_edge_infos (void)
342 {
343   basic_block bb;
344   edge_iterator ei;
345   edge e;
346
347   FOR_EACH_BB (bb)
348     {
349       FOR_EACH_EDGE (e, ei, bb->preds)
350         {
351          struct edge_info *edge_info = e->aux;
352
353           if (edge_info)
354             {
355               e->aux = edge_info->redirection_target;
356               if (edge_info->cond_equivalences)
357                 free (edge_info->cond_equivalences);
358               free (edge_info);
359             }
360         }
361     }
362 }
363
364 /* Jump threading, redundancy elimination and const/copy propagation. 
365
366    This pass may expose new symbols that need to be renamed into SSA.  For
367    every new symbol exposed, its corresponding bit will be set in
368    VARS_TO_RENAME.  */
369
370 static void
371 tree_ssa_dominator_optimize (void)
372 {
373   struct dom_walk_data walk_data;
374   unsigned int i;
375   struct loops loops_info;
376
377   memset (&opt_stats, 0, sizeof (opt_stats));
378
379   for (i = 0; i < num_referenced_vars; i++)
380     var_ann (referenced_var (i))->current_def = NULL;
381
382   /* Create our hash tables.  */
383   avail_exprs = htab_create (1024, real_avail_expr_hash, avail_expr_eq, free);
384   vrp_data = htab_create (ceil_log2 (num_ssa_names), vrp_hash, vrp_eq, free);
385   avail_exprs_stack = VEC_alloc (tree, heap, 20);
386   block_defs_stack = VEC_alloc (tree, heap, 20);
387   const_and_copies_stack = VEC_alloc (tree, heap, 20);
388   nonzero_vars_stack = VEC_alloc (tree, heap, 20);
389   vrp_variables_stack = VEC_alloc (tree, heap, 20);
390   stmts_to_rescan = VEC_alloc (tree, heap, 20);
391   nonzero_vars = BITMAP_ALLOC (NULL);
392   need_eh_cleanup = BITMAP_ALLOC (NULL);
393
394   /* Setup callbacks for the generic dominator tree walker.  */
395   walk_data.walk_stmts_backward = false;
396   walk_data.dom_direction = CDI_DOMINATORS;
397   walk_data.initialize_block_local_data = NULL;
398   walk_data.before_dom_children_before_stmts = dom_opt_initialize_block;
399   walk_data.before_dom_children_walk_stmts = optimize_stmt;
400   walk_data.before_dom_children_after_stmts = propagate_to_outgoing_edges;
401   walk_data.after_dom_children_before_stmts = NULL;
402   walk_data.after_dom_children_walk_stmts = NULL;
403   walk_data.after_dom_children_after_stmts = dom_opt_finalize_block;
404   /* Right now we only attach a dummy COND_EXPR to the global data pointer.
405      When we attach more stuff we'll need to fill this out with a real
406      structure.  */
407   walk_data.global_data = NULL;
408   walk_data.block_local_data_size = 0;
409   walk_data.interesting_blocks = NULL;
410
411   /* Now initialize the dominator walker.  */
412   init_walk_dominator_tree (&walk_data);
413
414   calculate_dominance_info (CDI_DOMINATORS);
415
416   /* We need to know which edges exit loops so that we can
417      aggressively thread through loop headers to an exit
418      edge.  */
419   flow_loops_find (&loops_info);
420   mark_loop_exit_edges (&loops_info);
421   flow_loops_free (&loops_info);
422
423   /* Clean up the CFG so that any forwarder blocks created by loop
424      canonicalization are removed.  */
425   cleanup_tree_cfg ();
426
427   /* If we prove certain blocks are unreachable, then we want to
428      repeat the dominator optimization process as PHI nodes may
429      have turned into copies which allows better propagation of
430      values.  So we repeat until we do not identify any new unreachable
431      blocks.  */
432   do
433     {
434       /* Optimize the dominator tree.  */
435       cfg_altered = false;
436
437       /* We need accurate information regarding back edges in the CFG
438          for jump threading.  */
439       mark_dfs_back_edges ();
440
441       /* Recursively walk the dominator tree optimizing statements.  */
442       walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);
443
444       /* If we exposed any new variables, go ahead and put them into
445          SSA form now, before we handle jump threading.  This simplifies
446          interactions between rewriting of _DECL nodes into SSA form
447          and rewriting SSA_NAME nodes into SSA form after block
448          duplication and CFG manipulation.  */
449       update_ssa (TODO_update_ssa);
450
451       free_all_edge_infos ();
452
453   {
454     block_stmt_iterator bsi;
455     basic_block bb;
456     FOR_EACH_BB (bb)
457       {
458         for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
459           {
460             update_stmt_if_modified (bsi_stmt (bsi));
461           }
462       }
463   }
464       /* Thread jumps, creating duplicate blocks as needed.  */
465       cfg_altered |= thread_through_all_blocks ();
466
467       /* Removal of statements may make some EH edges dead.  Purge
468          such edges from the CFG as needed.  */
469       if (!bitmap_empty_p (need_eh_cleanup))
470         {
471           cfg_altered |= tree_purge_all_dead_eh_edges (need_eh_cleanup);
472           bitmap_zero (need_eh_cleanup);
473         }
474
475       if (cfg_altered)
476         free_dominance_info (CDI_DOMINATORS);
477
478       cfg_altered |= cleanup_tree_cfg ();
479
480       if (rediscover_loops_after_threading)
481         {
482           /* Rerun basic loop analysis to discover any newly
483              created loops and update the set of exit edges.  */
484           rediscover_loops_after_threading = false;
485           flow_loops_find (&loops_info);
486           mark_loop_exit_edges (&loops_info);
487           flow_loops_free (&loops_info);
488
489           /* Remove any forwarder blocks inserted by loop
490              header canonicalization.  */
491           cleanup_tree_cfg ();
492         }
493
494       calculate_dominance_info (CDI_DOMINATORS);
495
496       rewrite_ssa_into_ssa ();
497
498       /* Reinitialize the various tables.  */
499       bitmap_clear (nonzero_vars);
500       htab_empty (avail_exprs);
501       htab_empty (vrp_data);
502
503       for (i = 0; i < num_referenced_vars; i++)
504         var_ann (referenced_var (i))->current_def = NULL;
505
506       /* Finally, remove everything except invariants in SSA_NAME_VALUE.
507
508          This must be done before we iterate as we might have a
509          reference to an SSA_NAME which was removed by the call to
510          rewrite_ssa_into_ssa.
511
512          Long term we will be able to let everything in SSA_NAME_VALUE
513          persist.  However, for now, we know this is the safe thing to do.  */
514       for (i = 0; i < num_ssa_names; i++)
515         {
516           tree name = ssa_name (i);
517           tree value;
518
519           if (!name)
520             continue;
521
522           value = SSA_NAME_VALUE (name);
523           if (value && !is_gimple_min_invariant (value))
524             SSA_NAME_VALUE (name) = NULL;
525         }
526     }
527   while (optimize > 1 && cfg_altered);
528
529   /* Debugging dumps.  */
530   if (dump_file && (dump_flags & TDF_STATS))
531     dump_dominator_optimization_stats (dump_file);
532
533   /* We emptied the hash table earlier, now delete it completely.  */
534   htab_delete (avail_exprs);
535   htab_delete (vrp_data);
536
537   /* It is not necessary to clear CURRDEFS, REDIRECTION_EDGES, VRP_DATA,
538      CONST_AND_COPIES, and NONZERO_VARS as they all get cleared at the bottom
539      of the do-while loop above.  */
540
541   /* And finalize the dominator walker.  */
542   fini_walk_dominator_tree (&walk_data);
543
544   /* Free nonzero_vars.  */
545   BITMAP_FREE (nonzero_vars);
546   BITMAP_FREE (need_eh_cleanup);
547   
548   VEC_free (tree, heap, block_defs_stack);
549   VEC_free (tree, heap, avail_exprs_stack);
550   VEC_free (tree, heap, const_and_copies_stack);
551   VEC_free (tree, heap, nonzero_vars_stack);
552   VEC_free (tree, heap, vrp_variables_stack);
553   VEC_free (tree, heap, stmts_to_rescan);
554 }
555
556 static bool
557 gate_dominator (void)
558 {
559   return flag_tree_dom != 0;
560 }
561
562 struct tree_opt_pass pass_dominator = 
563 {
564   "dom",                                /* name */
565   gate_dominator,                       /* gate */
566   tree_ssa_dominator_optimize,          /* execute */
567   NULL,                                 /* sub */
568   NULL,                                 /* next */
569   0,                                    /* static_pass_number */
570   TV_TREE_SSA_DOMINATOR_OPTS,           /* tv_id */
571   PROP_cfg | PROP_ssa | PROP_alias,     /* properties_required */
572   0,                                    /* properties_provided */
573   0,                                    /* properties_destroyed */
574   0,                                    /* todo_flags_start */
575   TODO_dump_func
576     | TODO_update_ssa
577     | TODO_verify_ssa,                  /* todo_flags_finish */
578   0                                     /* letter */
579 };
580
581
582 /* We are exiting BB, see if the target block begins with a conditional
583    jump which has a known value when reached via BB.  */
584
585 static void
586 thread_across_edge (struct dom_walk_data *walk_data, edge e)
587 {
588   block_stmt_iterator bsi;
589   tree stmt = NULL;
590   tree phi;
591
592   /* Each PHI creates a temporary equivalence, record them.  */
593   for (phi = phi_nodes (e->dest); phi; phi = PHI_CHAIN (phi))
594     {
595       tree src = PHI_ARG_DEF_FROM_EDGE (phi, e);
596       tree dst = PHI_RESULT (phi);
597
598       /* If the desired argument is not the same as this PHI's result 
599          and it is set by a PHI in this block, then we can not thread
600          through this block.  */
601       if (src != dst
602           && TREE_CODE (src) == SSA_NAME
603           && TREE_CODE (SSA_NAME_DEF_STMT (src)) == PHI_NODE
604           && bb_for_stmt (SSA_NAME_DEF_STMT (src)) == e->dest)
605         return;
606
607       record_const_or_copy (dst, src);
608       register_new_def (dst, &block_defs_stack);
609     }
610
611   for (bsi = bsi_start (e->dest); ! bsi_end_p (bsi); bsi_next (&bsi))
612     {
613       tree lhs, cached_lhs;
614
615       stmt = bsi_stmt (bsi);
616
617       /* Ignore empty statements and labels.  */
618       if (IS_EMPTY_STMT (stmt) || TREE_CODE (stmt) == LABEL_EXPR)
619         continue;
620
621       /* If this is not a MODIFY_EXPR which sets an SSA_NAME to a new
622          value, then stop our search here.  Ideally when we stop a
623          search we stop on a COND_EXPR or SWITCH_EXPR.  */
624       if (TREE_CODE (stmt) != MODIFY_EXPR
625           || TREE_CODE (TREE_OPERAND (stmt, 0)) != SSA_NAME)
626         break;
627
628       /* At this point we have a statement which assigns an RHS to an
629          SSA_VAR on the LHS.  We want to prove that the RHS is already
630          available and that its value is held in the current definition
631          of the LHS -- meaning that this assignment is a NOP when
632          reached via edge E.  */
633       if (TREE_CODE (TREE_OPERAND (stmt, 1)) == SSA_NAME)
634         cached_lhs = TREE_OPERAND (stmt, 1);
635       else
636         cached_lhs = lookup_avail_expr (stmt, false);
637
638       lhs = TREE_OPERAND (stmt, 0);
639
640       /* This can happen if we thread around to the start of a loop.  */
641       if (lhs == cached_lhs)
642         break;
643
644       /* If we did not find RHS in the hash table, then try again after
645          temporarily const/copy propagating the operands.  */
646       if (!cached_lhs)
647         {
648           /* Copy the operands.  */
649           stmt_ann_t ann = stmt_ann (stmt);
650           use_optype uses = USE_OPS (ann);
651           vuse_optype vuses = VUSE_OPS (ann);
652           tree *uses_copy = xmalloc (NUM_USES (uses) * sizeof (tree));
653           tree *vuses_copy = xmalloc (NUM_VUSES (vuses) * sizeof (tree));
654           unsigned int i;
655
656           /* Make a copy of the uses into USES_COPY, then cprop into
657              the use operands.  */
658           for (i = 0; i < NUM_USES (uses); i++)
659             {
660               tree tmp = NULL;
661
662               uses_copy[i] = USE_OP (uses, i);
663               if (TREE_CODE (USE_OP (uses, i)) == SSA_NAME)
664                 tmp = SSA_NAME_VALUE (USE_OP (uses, i));
665               if (tmp && TREE_CODE (tmp) != VALUE_HANDLE)
666                 SET_USE_OP (uses, i, tmp);
667             }
668
669           /* Similarly for virtual uses.  */
670           for (i = 0; i < NUM_VUSES (vuses); i++)
671             {
672               tree tmp = NULL;
673
674               vuses_copy[i] = VUSE_OP (vuses, i);
675               if (TREE_CODE (VUSE_OP (vuses, i)) == SSA_NAME)
676                 tmp = SSA_NAME_VALUE (VUSE_OP (vuses, i));
677               if (tmp && TREE_CODE (tmp) != VALUE_HANDLE)
678                 SET_VUSE_OP (vuses, i, tmp);
679             }
680
681           /* Try to lookup the new expression.  */
682           cached_lhs = lookup_avail_expr (stmt, false);
683
684           /* Restore the statement's original uses/defs.  */
685           for (i = 0; i < NUM_USES (uses); i++)
686             SET_USE_OP (uses, i, uses_copy[i]);
687
688           for (i = 0; i < NUM_VUSES (vuses); i++)
689             SET_VUSE_OP (vuses, i, vuses_copy[i]);
690
691           free (uses_copy);
692           free (vuses_copy);
693
694           /* If we still did not find the expression in the hash table,
695              then we can not ignore this statement.  */
696           if (! cached_lhs)
697             break;
698         }
699
700       /* If the expression in the hash table was not assigned to an
701          SSA_NAME, then we can not ignore this statement.  */
702       if (TREE_CODE (cached_lhs) != SSA_NAME)
703         break;
704
705       /* If we have different underlying variables, then we can not
706          ignore this statement.  */
707       if (SSA_NAME_VAR (cached_lhs) != SSA_NAME_VAR (lhs))
708         break;
709
710       /* If CACHED_LHS does not represent the current value of the underlying
711          variable in CACHED_LHS/LHS, then we can not ignore this statement.  */
712       if (var_ann (SSA_NAME_VAR (lhs))->current_def != cached_lhs)
713         break;
714
715       /* If we got here, then we can ignore this statement and continue
716          walking through the statements in the block looking for a threadable
717          COND_EXPR.
718
719          We want to record an equivalence lhs = cache_lhs so that if
720          the result of this statement is used later we can copy propagate
721          suitably.  */
722       record_const_or_copy (lhs, cached_lhs);
723       register_new_def (lhs, &block_defs_stack);
724     }
725
726   /* If we stopped at a COND_EXPR or SWITCH_EXPR, then see if we know which
727      arm will be taken.  */
728   if (stmt
729       && (TREE_CODE (stmt) == COND_EXPR
730           || TREE_CODE (stmt) == SWITCH_EXPR
731           || TREE_CODE (stmt) == GOTO_EXPR))
732     {
733       tree cond, cached_lhs;
734
735       /* Now temporarily cprop the operands and try to find the resulting
736          expression in the hash tables.  */
737       if (TREE_CODE (stmt) == COND_EXPR)
738         cond = COND_EXPR_COND (stmt);
739       else if (TREE_CODE (stmt) == GOTO_EXPR)
740         cond = GOTO_DESTINATION (stmt);
741       else
742         cond = SWITCH_COND (stmt);
743
744       if (COMPARISON_CLASS_P (cond))
745         {
746           tree dummy_cond, op0, op1;
747           enum tree_code cond_code;
748
749           op0 = TREE_OPERAND (cond, 0);
750           op1 = TREE_OPERAND (cond, 1);
751           cond_code = TREE_CODE (cond);
752
753           /* Get the current value of both operands.  */
754           if (TREE_CODE (op0) == SSA_NAME)
755             {
756               tree tmp = SSA_NAME_VALUE (op0);
757               if (tmp && TREE_CODE (tmp) != VALUE_HANDLE)
758                 op0 = tmp;
759             }
760
761           if (TREE_CODE (op1) == SSA_NAME)
762             {
763               tree tmp = SSA_NAME_VALUE (op1);
764               if (tmp && TREE_CODE (tmp) != VALUE_HANDLE)
765                 op1 = tmp;
766             }
767
768           /* Stuff the operator and operands into our dummy conditional
769              expression, creating the dummy conditional if necessary.  */
770           dummy_cond = walk_data->global_data;
771           if (! dummy_cond)
772             {
773               dummy_cond = build (cond_code, boolean_type_node, op0, op1);
774               dummy_cond = build (COND_EXPR, void_type_node,
775                                   dummy_cond, NULL, NULL);
776               walk_data->global_data = dummy_cond;
777             }
778           else
779             {
780               TREE_SET_CODE (COND_EXPR_COND (dummy_cond), cond_code);
781               TREE_OPERAND (COND_EXPR_COND (dummy_cond), 0) = op0;
782               TREE_OPERAND (COND_EXPR_COND (dummy_cond), 1) = op1;
783             }
784
785           /* If the conditional folds to an invariant, then we are done,
786              otherwise look it up in the hash tables.  */
787           cached_lhs = local_fold (COND_EXPR_COND (dummy_cond));
788           if (! is_gimple_min_invariant (cached_lhs))
789             {
790               cached_lhs = lookup_avail_expr (dummy_cond, false);
791               if (!cached_lhs || ! is_gimple_min_invariant (cached_lhs))
792                 cached_lhs = simplify_cond_and_lookup_avail_expr (dummy_cond,
793                                                                   NULL,
794                                                                   false);
795             }
796         }
797       /* We can have conditionals which just test the state of a
798          variable rather than use a relational operator.  These are
799          simpler to handle.  */
800       else if (TREE_CODE (cond) == SSA_NAME)
801         {
802           cached_lhs = cond;
803           cached_lhs = SSA_NAME_VALUE (cached_lhs);
804           if (cached_lhs && ! is_gimple_min_invariant (cached_lhs))
805             cached_lhs = 0;
806         }
807       else
808         cached_lhs = lookup_avail_expr (stmt, false);
809
810       if (cached_lhs)
811         {
812           edge taken_edge = find_taken_edge (e->dest, cached_lhs);
813           basic_block dest = (taken_edge ? taken_edge->dest : NULL);
814
815           if (dest == e->dest)
816             return;
817
818           /* If we have a known destination for the conditional, then
819              we can perform this optimization, which saves at least one
820              conditional jump each time it applies since we get to
821              bypass the conditional at our original destination.  */
822           if (dest)
823             {
824               struct edge_info *edge_info;
825
826               update_bb_profile_for_threading (e->dest, EDGE_FREQUENCY (e),
827                                                e->count, taken_edge);
828               if (e->aux)
829                 edge_info = e->aux;
830               else
831                 edge_info = allocate_edge_info (e);
832               edge_info->redirection_target = taken_edge;
833               bb_ann (e->dest)->incoming_edge_threaded = true;
834             }
835         }
836     }
837 }
838
839
840 /* Initialize local stacks for this optimizer and record equivalences
841    upon entry to BB.  Equivalences can come from the edge traversed to
842    reach BB or they may come from PHI nodes at the start of BB.  */
843
844 static void
845 dom_opt_initialize_block (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
846                           basic_block bb)
847 {
848   if (dump_file && (dump_flags & TDF_DETAILS))
849     fprintf (dump_file, "\n\nOptimizing block #%d\n\n", bb->index);
850
851   /* Push a marker on the stacks of local information so that we know how
852      far to unwind when we finalize this block.  */
853   VEC_safe_push (tree, heap, avail_exprs_stack, NULL_TREE);
854   VEC_safe_push (tree, heap, block_defs_stack, NULL_TREE);
855   VEC_safe_push (tree, heap, const_and_copies_stack, NULL_TREE);
856   VEC_safe_push (tree, heap, nonzero_vars_stack, NULL_TREE);
857   VEC_safe_push (tree, heap, vrp_variables_stack, NULL_TREE);
858
859   record_equivalences_from_incoming_edge (bb);
860
861   /* PHI nodes can create equivalences too.  */
862   record_equivalences_from_phis (bb);
863 }
864
865 /* Given an expression EXPR (a relational expression or a statement), 
866    initialize the hash table element pointed by by ELEMENT.  */
867
868 static void
869 initialize_hash_element (tree expr, tree lhs, struct expr_hash_elt *element)
870 {
871   /* Hash table elements may be based on conditional expressions or statements.
872
873      For the former case, we have no annotation and we want to hash the
874      conditional expression.  In the latter case we have an annotation and
875      we want to record the expression the statement evaluates.  */
876   if (COMPARISON_CLASS_P (expr) || TREE_CODE (expr) == TRUTH_NOT_EXPR)
877     {
878       element->ann = NULL;
879       element->rhs = expr;
880     }
881   else if (TREE_CODE (expr) == COND_EXPR)
882     {
883       element->ann = stmt_ann (expr);
884       element->rhs = COND_EXPR_COND (expr);
885     }
886   else if (TREE_CODE (expr) == SWITCH_EXPR)
887     {
888       element->ann = stmt_ann (expr);
889       element->rhs = SWITCH_COND (expr);
890     }
891   else if (TREE_CODE (expr) == RETURN_EXPR && TREE_OPERAND (expr, 0))
892     {
893       element->ann = stmt_ann (expr);
894       element->rhs = TREE_OPERAND (TREE_OPERAND (expr, 0), 1);
895     }
896   else
897     {
898       element->ann = stmt_ann (expr);
899       element->rhs = TREE_OPERAND (expr, 1);
900     }
901
902   element->lhs = lhs;
903   element->hash = avail_expr_hash (element);
904 }
905
906 /* Remove all the expressions in LOCALS from TABLE, stopping when there are
907    LIMIT entries left in LOCALs.  */
908
909 static void
910 remove_local_expressions_from_table (void)
911 {
912   /* Remove all the expressions made available in this block.  */
913   while (VEC_length (tree, avail_exprs_stack) > 0)
914     {
915       struct expr_hash_elt element;
916       tree expr = VEC_pop (tree, avail_exprs_stack);
917
918       if (expr == NULL_TREE)
919         break;
920
921       initialize_hash_element (expr, NULL, &element);
922       htab_remove_elt_with_hash (avail_exprs, &element, element.hash);
923     }
924 }
925
926 /* Use the SSA_NAMES in LOCALS to restore TABLE to its original
927    state, stopping when there are LIMIT entries left in LOCALs.  */
928
929 static void
930 restore_nonzero_vars_to_original_value (void)
931 {
932   while (VEC_length (tree, nonzero_vars_stack) > 0)
933     {
934       tree name = VEC_pop (tree, nonzero_vars_stack);
935
936       if (name == NULL)
937         break;
938
939       bitmap_clear_bit (nonzero_vars, SSA_NAME_VERSION (name));
940     }
941 }
942
943 /* Use the source/dest pairs in CONST_AND_COPIES_STACK to restore
944    CONST_AND_COPIES to its original state, stopping when we hit a
945    NULL marker.  */
946
947 static void
948 restore_vars_to_original_value (void)
949 {
950   while (VEC_length (tree, const_and_copies_stack) > 0)
951     {
952       tree prev_value, dest;
953
954       dest = VEC_pop (tree, const_and_copies_stack);
955
956       if (dest == NULL)
957         break;
958
959       prev_value = VEC_pop (tree, const_and_copies_stack);
960       SSA_NAME_VALUE (dest) =  prev_value;
961     }
962 }
963
964 /* Similar to restore_vars_to_original_value, except that it restores 
965    CURRDEFS to its original value.  */
966 static void
967 restore_currdefs_to_original_value (void)
968 {
969   /* Restore CURRDEFS to its original state.  */
970   while (VEC_length (tree, block_defs_stack) > 0)
971     {
972       tree tmp = VEC_pop (tree, block_defs_stack);
973       tree saved_def, var;
974
975       if (tmp == NULL_TREE)
976         break;
977
978       /* If we recorded an SSA_NAME, then make the SSA_NAME the current
979          definition of its underlying variable.  If we recorded anything
980          else, it must have been an _DECL node and its current reaching
981          definition must have been NULL.  */
982       if (TREE_CODE (tmp) == SSA_NAME)
983         {
984           saved_def = tmp;
985           var = SSA_NAME_VAR (saved_def);
986         }
987       else
988         {
989           saved_def = NULL;
990           var = tmp;
991         }
992                                                                                 
993       var_ann (var)->current_def = saved_def;
994     }
995 }
996
997 /* We have finished processing the dominator children of BB, perform
998    any finalization actions in preparation for leaving this node in
999    the dominator tree.  */
1000
1001 static void
1002 dom_opt_finalize_block (struct dom_walk_data *walk_data, basic_block bb)
1003 {
1004   tree last;
1005
1006   /* If we are at a leaf node in the dominator tree, see if we can thread
1007      the edge from BB through its successor.
1008
1009      Do this before we remove entries from our equivalence tables.  */
1010   if (single_succ_p (bb)
1011       && (single_succ_edge (bb)->flags & EDGE_ABNORMAL) == 0
1012       && (get_immediate_dominator (CDI_DOMINATORS, single_succ (bb)) != bb
1013           || phi_nodes (single_succ (bb))))
1014         
1015     {
1016       thread_across_edge (walk_data, single_succ_edge (bb));
1017     }
1018   else if ((last = last_stmt (bb))
1019            && TREE_CODE (last) == GOTO_EXPR
1020            && TREE_CODE (TREE_OPERAND (last, 0)) == SSA_NAME)
1021     {
1022       edge_iterator ei;
1023       edge e;
1024
1025       FOR_EACH_EDGE (e, ei, bb->succs)
1026         {
1027           thread_across_edge (walk_data, e);
1028         }
1029     }
1030   else if ((last = last_stmt (bb))
1031            && TREE_CODE (last) == COND_EXPR
1032            && (COMPARISON_CLASS_P (COND_EXPR_COND (last))
1033                || TREE_CODE (COND_EXPR_COND (last)) == SSA_NAME)
1034            && EDGE_COUNT (bb->succs) == 2
1035            && (EDGE_SUCC (bb, 0)->flags & EDGE_ABNORMAL) == 0
1036            && (EDGE_SUCC (bb, 1)->flags & EDGE_ABNORMAL) == 0)
1037     {
1038       edge true_edge, false_edge;
1039
1040       extract_true_false_edges_from_block (bb, &true_edge, &false_edge);
1041
1042       /* If the THEN arm is the end of a dominator tree or has PHI nodes,
1043          then try to thread through its edge.  */
1044       if (get_immediate_dominator (CDI_DOMINATORS, true_edge->dest) != bb
1045           || phi_nodes (true_edge->dest))
1046         {
1047           struct edge_info *edge_info;
1048           unsigned int i;
1049
1050           /* Push a marker onto the available expression stack so that we
1051              unwind any expressions related to the TRUE arm before processing
1052              the false arm below.  */
1053           VEC_safe_push (tree, heap, avail_exprs_stack, NULL_TREE);
1054           VEC_safe_push (tree, heap, block_defs_stack, NULL_TREE);
1055           VEC_safe_push (tree, heap, const_and_copies_stack, NULL_TREE);
1056
1057           edge_info = true_edge->aux;
1058
1059           /* If we have info associated with this edge, record it into
1060              our equivalency tables.  */
1061           if (edge_info)
1062             {
1063               tree *cond_equivalences = edge_info->cond_equivalences;
1064               tree lhs = edge_info->lhs;
1065               tree rhs = edge_info->rhs;
1066
1067               /* If we have a simple NAME = VALUE equivalency record it.
1068                  Until the jump threading selection code improves, only
1069                  do this if both the name and value are SSA_NAMEs with
1070                  the same underlying variable to avoid missing threading
1071                  opportunities.  */
1072               if (lhs
1073                   && TREE_CODE (COND_EXPR_COND (last)) == SSA_NAME
1074                   && TREE_CODE (edge_info->rhs) == SSA_NAME
1075                   && SSA_NAME_VAR (lhs) == SSA_NAME_VAR (rhs))
1076                 record_const_or_copy (lhs, rhs);
1077
1078               /* If we have 0 = COND or 1 = COND equivalences, record them
1079                  into our expression hash tables.  */
1080               if (cond_equivalences)
1081                 for (i = 0; i < edge_info->max_cond_equivalences; i += 2)
1082                   {
1083                     tree expr = cond_equivalences[i];
1084                     tree value = cond_equivalences[i + 1];
1085
1086                     record_cond (expr, value);
1087                   }
1088             }
1089
1090           /* Now thread the edge.  */
1091           thread_across_edge (walk_data, true_edge);
1092
1093           /* And restore the various tables to their state before
1094              we threaded this edge.  */
1095           remove_local_expressions_from_table ();
1096           restore_vars_to_original_value ();
1097           restore_currdefs_to_original_value ();
1098         }
1099
1100       /* Similarly for the ELSE arm.  */
1101       if (get_immediate_dominator (CDI_DOMINATORS, false_edge->dest) != bb
1102           || phi_nodes (false_edge->dest))
1103         {
1104           struct edge_info *edge_info;
1105           unsigned int i;
1106
1107           edge_info = false_edge->aux;
1108
1109           /* If we have info associated with this edge, record it into
1110              our equivalency tables.  */
1111           if (edge_info)
1112             {
1113               tree *cond_equivalences = edge_info->cond_equivalences;
1114               tree lhs = edge_info->lhs;
1115               tree rhs = edge_info->rhs;
1116
1117               /* If we have a simple NAME = VALUE equivalency record it.
1118                  Until the jump threading selection code improves, only
1119                  do this if both the name and value are SSA_NAMEs with
1120                  the same underlying variable to avoid missing threading
1121                  opportunities.  */
1122               if (lhs
1123                   && TREE_CODE (COND_EXPR_COND (last)) == SSA_NAME)
1124                 record_const_or_copy (lhs, rhs);
1125
1126               /* If we have 0 = COND or 1 = COND equivalences, record them
1127                  into our expression hash tables.  */
1128               if (cond_equivalences)
1129                 for (i = 0; i < edge_info->max_cond_equivalences; i += 2)
1130                   {
1131                     tree expr = cond_equivalences[i];
1132                     tree value = cond_equivalences[i + 1];
1133
1134                     record_cond (expr, value);
1135                   }
1136             }
1137
1138           thread_across_edge (walk_data, false_edge);
1139
1140           /* No need to remove local expressions from our tables
1141              or restore vars to their original value as that will
1142              be done immediately below.  */
1143         }
1144     }
1145
1146   remove_local_expressions_from_table ();
1147   restore_nonzero_vars_to_original_value ();
1148   restore_vars_to_original_value ();
1149   restore_currdefs_to_original_value ();
1150
1151   /* Remove VRP records associated with this basic block.  They are no
1152      longer valid.
1153
1154      To be efficient, we note which variables have had their values
1155      constrained in this block.  So walk over each variable in the
1156      VRP_VARIABLEs array.  */
1157   while (VEC_length (tree, vrp_variables_stack) > 0)
1158     {
1159       tree var = VEC_pop (tree, vrp_variables_stack);
1160       struct vrp_hash_elt vrp_hash_elt, *vrp_hash_elt_p;
1161       void **slot;
1162
1163       /* Each variable has a stack of value range records.  We want to
1164          invalidate those associated with our basic block.  So we walk
1165          the array backwards popping off records associated with our
1166          block.  Once we hit a record not associated with our block
1167          we are done.  */
1168       varray_type var_vrp_records;
1169
1170       if (var == NULL)
1171         break;
1172
1173       vrp_hash_elt.var = var;
1174       vrp_hash_elt.records = NULL;
1175
1176       slot = htab_find_slot (vrp_data, &vrp_hash_elt, NO_INSERT);
1177
1178       vrp_hash_elt_p = (struct vrp_hash_elt *) *slot;
1179       var_vrp_records = vrp_hash_elt_p->records;
1180
1181       while (VARRAY_ACTIVE_SIZE (var_vrp_records) > 0)
1182         {
1183           struct vrp_element *element
1184             = (struct vrp_element *)VARRAY_TOP_GENERIC_PTR (var_vrp_records);
1185
1186           if (element->bb != bb)
1187             break;
1188   
1189           VARRAY_POP (var_vrp_records);
1190         }
1191     }
1192
1193   /* If we queued any statements to rescan in this block, then
1194      go ahead and rescan them now.  */
1195   while (VEC_length (tree, stmts_to_rescan) > 0)
1196     {
1197       tree stmt = VEC_last (tree, stmts_to_rescan);
1198       basic_block stmt_bb = bb_for_stmt (stmt);
1199
1200       if (stmt_bb != bb)
1201         break;
1202
1203       VEC_pop (tree, stmts_to_rescan);
1204       mark_new_vars_to_rename (stmt);
1205     }
1206 }
1207
1208 /* PHI nodes can create equivalences too.
1209
1210    Ignoring any alternatives which are the same as the result, if
1211    all the alternatives are equal, then the PHI node creates an
1212    equivalence.
1213
1214    Additionally, if all the PHI alternatives are known to have a nonzero
1215    value, then the result of this PHI is known to have a nonzero value,
1216    even if we do not know its exact value.  */
1217
1218 static void
1219 record_equivalences_from_phis (basic_block bb)
1220 {
1221   tree phi;
1222
1223   for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
1224     {
1225       tree lhs = PHI_RESULT (phi);
1226       tree rhs = NULL;
1227       int i;
1228
1229       for (i = 0; i < PHI_NUM_ARGS (phi); i++)
1230         {
1231           tree t = PHI_ARG_DEF (phi, i);
1232
1233           /* Ignore alternatives which are the same as our LHS.  Since
1234              LHS is a PHI_RESULT, it is known to be a SSA_NAME, so we
1235              can simply compare pointers.  */
1236           if (lhs == t)
1237             continue;
1238
1239           /* If we have not processed an alternative yet, then set
1240              RHS to this alternative.  */
1241           if (rhs == NULL)
1242             rhs = t;
1243           /* If we have processed an alternative (stored in RHS), then
1244              see if it is equal to this one.  If it isn't, then stop
1245              the search.  */
1246           else if (! operand_equal_for_phi_arg_p (rhs, t))
1247             break;
1248         }
1249
1250       /* If we had no interesting alternatives, then all the RHS alternatives
1251          must have been the same as LHS.  */
1252       if (!rhs)
1253         rhs = lhs;
1254
1255       /* If we managed to iterate through each PHI alternative without
1256          breaking out of the loop, then we have a PHI which may create
1257          a useful equivalence.  We do not need to record unwind data for
1258          this, since this is a true assignment and not an equivalence
1259          inferred from a comparison.  All uses of this ssa name are dominated
1260          by this assignment, so unwinding just costs time and space.  */
1261       if (i == PHI_NUM_ARGS (phi)
1262           && may_propagate_copy (lhs, rhs))
1263         SSA_NAME_VALUE (lhs) = rhs;
1264
1265       /* Now see if we know anything about the nonzero property for the
1266          result of this PHI.  */
1267       for (i = 0; i < PHI_NUM_ARGS (phi); i++)
1268         {
1269           if (!PHI_ARG_NONZERO (phi, i))
1270             break;
1271         }
1272
1273       if (i == PHI_NUM_ARGS (phi))
1274         bitmap_set_bit (nonzero_vars, SSA_NAME_VERSION (PHI_RESULT (phi)));
1275
1276       register_new_def (lhs, &block_defs_stack);
1277     }
1278 }
1279
1280 /* Ignoring loop backedges, if BB has precisely one incoming edge then
1281    return that edge.  Otherwise return NULL.  */
1282 static edge
1283 single_incoming_edge_ignoring_loop_edges (basic_block bb)
1284 {
1285   edge retval = NULL;
1286   edge e;
1287   edge_iterator ei;
1288
1289   FOR_EACH_EDGE (e, ei, bb->preds)
1290     {
1291       /* A loop back edge can be identified by the destination of
1292          the edge dominating the source of the edge.  */
1293       if (dominated_by_p (CDI_DOMINATORS, e->src, e->dest))
1294         continue;
1295
1296       /* If we have already seen a non-loop edge, then we must have
1297          multiple incoming non-loop edges and thus we return NULL.  */
1298       if (retval)
1299         return NULL;
1300
1301       /* This is the first non-loop incoming edge we have found.  Record
1302          it.  */
1303       retval = e;
1304     }
1305
1306   return retval;
1307 }
1308
1309 /* Record any equivalences created by the incoming edge to BB.  If BB
1310    has more than one incoming edge, then no equivalence is created.  */
1311
1312 static void
1313 record_equivalences_from_incoming_edge (basic_block bb)
1314 {
1315   edge e;
1316   basic_block parent;
1317   struct edge_info *edge_info;
1318
1319   /* If our parent block ended with a control statement, then we may be
1320      able to record some equivalences based on which outgoing edge from
1321      the parent was followed.  */
1322   parent = get_immediate_dominator (CDI_DOMINATORS, bb);
1323
1324   e = single_incoming_edge_ignoring_loop_edges (bb);
1325
1326   /* If we had a single incoming edge from our parent block, then enter
1327      any data associated with the edge into our tables.  */
1328   if (e && e->src == parent)
1329     {
1330       unsigned int i;
1331
1332       edge_info = e->aux;
1333
1334       if (edge_info)
1335         {
1336           tree lhs = edge_info->lhs;
1337           tree rhs = edge_info->rhs;
1338           tree *cond_equivalences = edge_info->cond_equivalences;
1339
1340           if (lhs)
1341             record_equality (lhs, rhs);
1342
1343           if (cond_equivalences)
1344             {
1345               bool recorded_range = false;
1346               for (i = 0; i < edge_info->max_cond_equivalences; i += 2)
1347                 {
1348                   tree expr = cond_equivalences[i];
1349                   tree value = cond_equivalences[i + 1];
1350
1351                   record_cond (expr, value);
1352
1353                   /* For the first true equivalence, record range
1354                      information.  We only do this for the first
1355                      true equivalence as it should dominate any
1356                      later true equivalences.  */
1357                   if (! recorded_range 
1358                       && COMPARISON_CLASS_P (expr)
1359                       && value == boolean_true_node
1360                       && TREE_CONSTANT (TREE_OPERAND (expr, 1)))
1361                     {
1362                       record_range (expr, bb);
1363                       recorded_range = true;
1364                     }
1365                 }
1366             }
1367         }
1368     }
1369 }
1370
1371 /* Dump SSA statistics on FILE.  */
1372
1373 void
1374 dump_dominator_optimization_stats (FILE *file)
1375 {
1376   long n_exprs;
1377
1378   fprintf (file, "Total number of statements:                   %6ld\n\n",
1379            opt_stats.num_stmts);
1380   fprintf (file, "Exprs considered for dominator optimizations: %6ld\n",
1381            opt_stats.num_exprs_considered);
1382
1383   n_exprs = opt_stats.num_exprs_considered;
1384   if (n_exprs == 0)
1385     n_exprs = 1;
1386
1387   fprintf (file, "    Redundant expressions eliminated:         %6ld (%.0f%%)\n",
1388            opt_stats.num_re, PERCENT (opt_stats.num_re,
1389                                       n_exprs));
1390   fprintf (file, "    Constants propagated:                     %6ld\n",
1391            opt_stats.num_const_prop);
1392   fprintf (file, "    Copies propagated:                        %6ld\n",
1393            opt_stats.num_copy_prop);
1394
1395   fprintf (file, "\nHash table statistics:\n");
1396
1397   fprintf (file, "    avail_exprs: ");
1398   htab_statistics (file, avail_exprs);
1399 }
1400
1401
1402 /* Dump SSA statistics on stderr.  */
1403
1404 void
1405 debug_dominator_optimization_stats (void)
1406 {
1407   dump_dominator_optimization_stats (stderr);
1408 }
1409
1410
1411 /* Dump statistics for the hash table HTAB.  */
1412
1413 static void
1414 htab_statistics (FILE *file, htab_t htab)
1415 {
1416   fprintf (file, "size %ld, %ld elements, %f collision/search ratio\n",
1417            (long) htab_size (htab),
1418            (long) htab_elements (htab),
1419            htab_collisions (htab));
1420 }
1421
1422 /* Record the fact that VAR has a nonzero value, though we may not know
1423    its exact value.  Note that if VAR is already known to have a nonzero
1424    value, then we do nothing.  */
1425
1426 static void
1427 record_var_is_nonzero (tree var)
1428 {
1429   int indx = SSA_NAME_VERSION (var);
1430
1431   if (bitmap_bit_p (nonzero_vars, indx))
1432     return;
1433
1434   /* Mark it in the global table.  */
1435   bitmap_set_bit (nonzero_vars, indx);
1436
1437   /* Record this SSA_NAME so that we can reset the global table
1438      when we leave this block.  */
1439   VEC_safe_push (tree, heap, nonzero_vars_stack, var);
1440 }
1441
1442 /* Enter a statement into the true/false expression hash table indicating
1443    that the condition COND has the value VALUE.  */
1444
1445 static void
1446 record_cond (tree cond, tree value)
1447 {
1448   struct expr_hash_elt *element = xmalloc (sizeof (struct expr_hash_elt));
1449   void **slot;
1450
1451   initialize_hash_element (cond, value, element);
1452
1453   slot = htab_find_slot_with_hash (avail_exprs, (void *)element,
1454                                    element->hash, INSERT);
1455   if (*slot == NULL)
1456     {
1457       *slot = (void *) element;
1458       VEC_safe_push (tree, heap, avail_exprs_stack, cond);
1459     }
1460   else
1461     free (element);
1462 }
1463
1464 /* Build a new conditional using NEW_CODE, OP0 and OP1 and store
1465    the new conditional into *p, then store a boolean_true_node
1466    into *(p + 1).  */
1467    
1468 static void
1469 build_and_record_new_cond (enum tree_code new_code, tree op0, tree op1, tree *p)
1470 {
1471   *p = build2 (new_code, boolean_type_node, op0, op1);
1472   p++;
1473   *p = boolean_true_node;
1474 }
1475
1476 /* Record that COND is true and INVERTED is false into the edge information
1477    structure.  Also record that any conditions dominated by COND are true
1478    as well.
1479
1480    For example, if a < b is true, then a <= b must also be true.  */
1481
1482 static void
1483 record_conditions (struct edge_info *edge_info, tree cond, tree inverted)
1484 {
1485   tree op0, op1;
1486
1487   if (!COMPARISON_CLASS_P (cond))
1488     return;
1489
1490   op0 = TREE_OPERAND (cond, 0);
1491   op1 = TREE_OPERAND (cond, 1);
1492
1493   switch (TREE_CODE (cond))
1494     {
1495     case LT_EXPR:
1496     case GT_EXPR:
1497       edge_info->max_cond_equivalences = 12;
1498       edge_info->cond_equivalences = xmalloc (12 * sizeof (tree));
1499       build_and_record_new_cond ((TREE_CODE (cond) == LT_EXPR
1500                                   ? LE_EXPR : GE_EXPR),
1501                                  op0, op1, &edge_info->cond_equivalences[4]);
1502       build_and_record_new_cond (ORDERED_EXPR, op0, op1,
1503                                  &edge_info->cond_equivalences[6]);
1504       build_and_record_new_cond (NE_EXPR, op0, op1,
1505                                  &edge_info->cond_equivalences[8]);
1506       build_and_record_new_cond (LTGT_EXPR, op0, op1,
1507                                  &edge_info->cond_equivalences[10]);
1508       break;
1509
1510     case GE_EXPR:
1511     case LE_EXPR:
1512       edge_info->max_cond_equivalences = 6;
1513       edge_info->cond_equivalences = xmalloc (6 * sizeof (tree));
1514       build_and_record_new_cond (ORDERED_EXPR, op0, op1,
1515                                  &edge_info->cond_equivalences[4]);
1516       break;
1517
1518     case EQ_EXPR:
1519       edge_info->max_cond_equivalences = 10;
1520       edge_info->cond_equivalences = xmalloc (10 * sizeof (tree));
1521       build_and_record_new_cond (ORDERED_EXPR, op0, op1,
1522                                  &edge_info->cond_equivalences[4]);
1523       build_and_record_new_cond (LE_EXPR, op0, op1,
1524                                  &edge_info->cond_equivalences[6]);
1525       build_and_record_new_cond (GE_EXPR, op0, op1,
1526                                  &edge_info->cond_equivalences[8]);
1527       break;
1528
1529     case UNORDERED_EXPR:
1530       edge_info->max_cond_equivalences = 16;
1531       edge_info->cond_equivalences = xmalloc (16 * sizeof (tree));
1532       build_and_record_new_cond (NE_EXPR, op0, op1,
1533                                  &edge_info->cond_equivalences[4]);
1534       build_and_record_new_cond (UNLE_EXPR, op0, op1,
1535                                  &edge_info->cond_equivalences[6]);
1536       build_and_record_new_cond (UNGE_EXPR, op0, op1,
1537                                  &edge_info->cond_equivalences[8]);
1538       build_and_record_new_cond (UNEQ_EXPR, op0, op1,
1539                                  &edge_info->cond_equivalences[10]);
1540       build_and_record_new_cond (UNLT_EXPR, op0, op1,
1541                                  &edge_info->cond_equivalences[12]);
1542       build_and_record_new_cond (UNGT_EXPR, op0, op1,
1543                                  &edge_info->cond_equivalences[14]);
1544       break;
1545
1546     case UNLT_EXPR:
1547     case UNGT_EXPR:
1548       edge_info->max_cond_equivalences = 8;
1549       edge_info->cond_equivalences = xmalloc (8 * sizeof (tree));
1550       build_and_record_new_cond ((TREE_CODE (cond) == UNLT_EXPR
1551                                   ? UNLE_EXPR : UNGE_EXPR),
1552                                  op0, op1, &edge_info->cond_equivalences[4]);
1553       build_and_record_new_cond (NE_EXPR, op0, op1,
1554                                  &edge_info->cond_equivalences[6]);
1555       break;
1556
1557     case UNEQ_EXPR:
1558       edge_info->max_cond_equivalences = 8;
1559       edge_info->cond_equivalences = xmalloc (8 * sizeof (tree));
1560       build_and_record_new_cond (UNLE_EXPR, op0, op1,
1561                                  &edge_info->cond_equivalences[4]);
1562       build_and_record_new_cond (UNGE_EXPR, op0, op1,
1563                                  &edge_info->cond_equivalences[6]);
1564       break;
1565
1566     case LTGT_EXPR:
1567       edge_info->max_cond_equivalences = 8;
1568       edge_info->cond_equivalences = xmalloc (8 * sizeof (tree));
1569       build_and_record_new_cond (NE_EXPR, op0, op1,
1570                                  &edge_info->cond_equivalences[4]);
1571       build_and_record_new_cond (ORDERED_EXPR, op0, op1,
1572                                  &edge_info->cond_equivalences[6]);
1573       break;
1574
1575     default:
1576       edge_info->max_cond_equivalences = 4;
1577       edge_info->cond_equivalences = xmalloc (4 * sizeof (tree));
1578       break;
1579     }
1580
1581   /* Now store the original true and false conditions into the first
1582      two slots.  */
1583   edge_info->cond_equivalences[0] = cond;
1584   edge_info->cond_equivalences[1] = boolean_true_node;
1585   edge_info->cond_equivalences[2] = inverted;
1586   edge_info->cond_equivalences[3] = boolean_false_node;
1587 }
1588
1589 /* A helper function for record_const_or_copy and record_equality.
1590    Do the work of recording the value and undo info.  */
1591
1592 static void
1593 record_const_or_copy_1 (tree x, tree y, tree prev_x)
1594 {
1595   SSA_NAME_VALUE (x) = y;
1596
1597   VEC_reserve (tree, heap, const_and_copies_stack, 2);
1598   VEC_quick_push (tree, const_and_copies_stack, prev_x);
1599   VEC_quick_push (tree, const_and_copies_stack, x);
1600 }
1601
1602
1603 /* Return the loop depth of the basic block of the defining statement of X.
1604    This number should not be treated as absolutely correct because the loop
1605    information may not be completely up-to-date when dom runs.  However, it
1606    will be relatively correct, and as more passes are taught to keep loop info
1607    up to date, the result will become more and more accurate.  */
1608
1609 int
1610 loop_depth_of_name (tree x)
1611 {
1612   tree defstmt;
1613   basic_block defbb;
1614
1615   /* If it's not an SSA_NAME, we have no clue where the definition is.  */
1616   if (TREE_CODE (x) != SSA_NAME)
1617     return 0;
1618
1619   /* Otherwise return the loop depth of the defining statement's bb.
1620      Note that there may not actually be a bb for this statement, if the
1621      ssa_name is live on entry.  */
1622   defstmt = SSA_NAME_DEF_STMT (x);
1623   defbb = bb_for_stmt (defstmt);
1624   if (!defbb)
1625     return 0;
1626
1627   return defbb->loop_depth;
1628 }
1629
1630
1631 /* Record that X is equal to Y in const_and_copies.  Record undo
1632    information in the block-local vector.  */
1633
1634 static void
1635 record_const_or_copy (tree x, tree y)
1636 {
1637   tree prev_x = SSA_NAME_VALUE (x);
1638
1639   if (TREE_CODE (y) == SSA_NAME)
1640     {
1641       tree tmp = SSA_NAME_VALUE (y);
1642       if (tmp)
1643         y = tmp;
1644     }
1645
1646   record_const_or_copy_1 (x, y, prev_x);
1647 }
1648
1649 /* Similarly, but assume that X and Y are the two operands of an EQ_EXPR.
1650    This constrains the cases in which we may treat this as assignment.  */
1651
1652 static void
1653 record_equality (tree x, tree y)
1654 {
1655   tree prev_x = NULL, prev_y = NULL;
1656
1657   if (TREE_CODE (x) == SSA_NAME)
1658     prev_x = SSA_NAME_VALUE (x);
1659   if (TREE_CODE (y) == SSA_NAME)
1660     prev_y = SSA_NAME_VALUE (y);
1661
1662   /* If one of the previous values is invariant, or invariant in more loops
1663      (by depth), then use that.
1664      Otherwise it doesn't matter which value we choose, just so
1665      long as we canonicalize on one value.  */
1666   if (TREE_INVARIANT (y))
1667     ;
1668   else if (TREE_INVARIANT (x) || (loop_depth_of_name (x) <= loop_depth_of_name (y)))
1669     prev_x = x, x = y, y = prev_x, prev_x = prev_y;
1670   else if (prev_x && TREE_INVARIANT (prev_x))
1671     x = y, y = prev_x, prev_x = prev_y;
1672   else if (prev_y && TREE_CODE (prev_y) != VALUE_HANDLE)
1673     y = prev_y;
1674
1675   /* After the swapping, we must have one SSA_NAME.  */
1676   if (TREE_CODE (x) != SSA_NAME)
1677     return;
1678
1679   /* For IEEE, -0.0 == 0.0, so we don't necessarily know the sign of a
1680      variable compared against zero.  If we're honoring signed zeros,
1681      then we cannot record this value unless we know that the value is
1682      nonzero.  */
1683   if (HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (x)))
1684       && (TREE_CODE (y) != REAL_CST
1685           || REAL_VALUES_EQUAL (dconst0, TREE_REAL_CST (y))))
1686     return;
1687
1688   record_const_or_copy_1 (x, y, prev_x);
1689 }
1690
1691 /* Return true, if it is ok to do folding of an associative expression.
1692    EXP is the tree for the associative expression.  */ 
1693
1694 static inline bool
1695 unsafe_associative_fp_binop (tree exp)
1696 {
1697   enum tree_code code = TREE_CODE (exp);
1698   return !(!flag_unsafe_math_optimizations
1699            && (code == MULT_EXPR || code == PLUS_EXPR
1700                || code == MINUS_EXPR)
1701            && FLOAT_TYPE_P (TREE_TYPE (exp)));
1702 }
1703
1704 /* Returns true when STMT is a simple iv increment.  It detects the
1705    following situation:
1706    
1707    i_1 = phi (..., i_2)
1708    i_2 = i_1 +/- ...  */
1709
1710 static bool
1711 simple_iv_increment_p (tree stmt)
1712 {
1713   tree lhs, rhs, preinc, phi;
1714   unsigned i;
1715
1716   if (TREE_CODE (stmt) != MODIFY_EXPR)
1717     return false;
1718
1719   lhs = TREE_OPERAND (stmt, 0);
1720   if (TREE_CODE (lhs) != SSA_NAME)
1721     return false;
1722
1723   rhs = TREE_OPERAND (stmt, 1);
1724
1725   if (TREE_CODE (rhs) != PLUS_EXPR
1726       && TREE_CODE (rhs) != MINUS_EXPR)
1727     return false;
1728
1729   preinc = TREE_OPERAND (rhs, 0);
1730   if (TREE_CODE (preinc) != SSA_NAME)
1731     return false;
1732
1733   phi = SSA_NAME_DEF_STMT (preinc);
1734   if (TREE_CODE (phi) != PHI_NODE)
1735     return false;
1736
1737   for (i = 0; i < (unsigned) PHI_NUM_ARGS (phi); i++)
1738     if (PHI_ARG_DEF (phi, i) == lhs)
1739       return true;
1740
1741   return false;
1742 }
1743
1744 /* STMT is a MODIFY_EXPR for which we were unable to find RHS in the
1745    hash tables.  Try to simplify the RHS using whatever equivalences
1746    we may have recorded.
1747
1748    If we are able to simplify the RHS, then lookup the simplified form in
1749    the hash table and return the result.  Otherwise return NULL.  */
1750
1751 static tree
1752 simplify_rhs_and_lookup_avail_expr (struct dom_walk_data *walk_data,
1753                                     tree stmt, int insert)
1754 {
1755   tree rhs = TREE_OPERAND (stmt, 1);
1756   enum tree_code rhs_code = TREE_CODE (rhs);
1757   tree result = NULL;
1758
1759   /* If we have lhs = ~x, look and see if we earlier had x = ~y.
1760      In which case we can change this statement to be lhs = y.
1761      Which can then be copy propagated. 
1762
1763      Similarly for negation.  */
1764   if ((rhs_code == BIT_NOT_EXPR || rhs_code == NEGATE_EXPR)
1765       && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
1766     {
1767       /* Get the definition statement for our RHS.  */
1768       tree rhs_def_stmt = SSA_NAME_DEF_STMT (TREE_OPERAND (rhs, 0));
1769
1770       /* See if the RHS_DEF_STMT has the same form as our statement.  */
1771       if (TREE_CODE (rhs_def_stmt) == MODIFY_EXPR
1772           && TREE_CODE (TREE_OPERAND (rhs_def_stmt, 1)) == rhs_code)
1773         {
1774           tree rhs_def_operand;
1775
1776           rhs_def_operand = TREE_OPERAND (TREE_OPERAND (rhs_def_stmt, 1), 0);
1777
1778           /* Verify that RHS_DEF_OPERAND is a suitable SSA variable.  */
1779           if (TREE_CODE (rhs_def_operand) == SSA_NAME
1780               && ! SSA_NAME_OCCURS_IN_ABNORMAL_PHI (rhs_def_operand))
1781             result = update_rhs_and_lookup_avail_expr (stmt,
1782                                                        rhs_def_operand,
1783                                                        insert);
1784         }
1785     }
1786
1787   /* If we have z = (x OP C1), see if we earlier had x = y OP C2.
1788      If OP is associative, create and fold (y OP C2) OP C1 which
1789      should result in (y OP C3), use that as the RHS for the
1790      assignment.  Add minus to this, as we handle it specially below.  */
1791   if ((associative_tree_code (rhs_code) || rhs_code == MINUS_EXPR)
1792       && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME
1793       && is_gimple_min_invariant (TREE_OPERAND (rhs, 1)))
1794     {
1795       tree rhs_def_stmt = SSA_NAME_DEF_STMT (TREE_OPERAND (rhs, 0));
1796
1797       /* If the statement defines an induction variable, do not propagate
1798          its value, so that we do not create overlapping life ranges.  */
1799       if (simple_iv_increment_p (rhs_def_stmt))
1800         goto dont_fold_assoc;
1801
1802       /* See if the RHS_DEF_STMT has the same form as our statement.  */
1803       if (TREE_CODE (rhs_def_stmt) == MODIFY_EXPR)
1804         {
1805           tree rhs_def_rhs = TREE_OPERAND (rhs_def_stmt, 1);
1806           enum tree_code rhs_def_code = TREE_CODE (rhs_def_rhs);
1807
1808           if ((rhs_code == rhs_def_code && unsafe_associative_fp_binop (rhs))
1809               || (rhs_code == PLUS_EXPR && rhs_def_code == MINUS_EXPR)
1810               || (rhs_code == MINUS_EXPR && rhs_def_code == PLUS_EXPR))
1811             {
1812               tree def_stmt_op0 = TREE_OPERAND (rhs_def_rhs, 0);
1813               tree def_stmt_op1 = TREE_OPERAND (rhs_def_rhs, 1);
1814
1815               if (TREE_CODE (def_stmt_op0) == SSA_NAME
1816                   && ! SSA_NAME_OCCURS_IN_ABNORMAL_PHI (def_stmt_op0)
1817                   && is_gimple_min_invariant (def_stmt_op1))
1818                 {
1819                   tree outer_const = TREE_OPERAND (rhs, 1);
1820                   tree type = TREE_TYPE (TREE_OPERAND (stmt, 0));
1821                   tree t;
1822
1823                   /* If we care about correct floating point results, then
1824                      don't fold x + c1 - c2.  Note that we need to take both
1825                      the codes and the signs to figure this out.  */
1826                   if (FLOAT_TYPE_P (type)
1827                       && !flag_unsafe_math_optimizations
1828                       && (rhs_def_code == PLUS_EXPR
1829                           || rhs_def_code == MINUS_EXPR))
1830                     {
1831                       bool neg = false;
1832
1833                       neg ^= (rhs_code == MINUS_EXPR);
1834                       neg ^= (rhs_def_code == MINUS_EXPR);
1835                       neg ^= real_isneg (TREE_REAL_CST_PTR (outer_const));
1836                       neg ^= real_isneg (TREE_REAL_CST_PTR (def_stmt_op1));
1837
1838                       if (neg)
1839                         goto dont_fold_assoc;
1840                     }
1841
1842                   /* Ho hum.  So fold will only operate on the outermost
1843                      thingy that we give it, so we have to build the new
1844                      expression in two pieces.  This requires that we handle
1845                      combinations of plus and minus.  */
1846                   if (rhs_def_code != rhs_code)
1847                     {
1848                       if (rhs_def_code == MINUS_EXPR)
1849                         t = build (MINUS_EXPR, type, outer_const, def_stmt_op1);
1850                       else
1851                         t = build (MINUS_EXPR, type, def_stmt_op1, outer_const);
1852                       rhs_code = PLUS_EXPR;
1853                     }
1854                   else if (rhs_def_code == MINUS_EXPR)
1855                     t = build (PLUS_EXPR, type, def_stmt_op1, outer_const);
1856                   else
1857                     t = build (rhs_def_code, type, def_stmt_op1, outer_const);
1858                   t = local_fold (t);
1859                   t = build (rhs_code, type, def_stmt_op0, t);
1860                   t = local_fold (t);
1861
1862                   /* If the result is a suitable looking gimple expression,
1863                      then use it instead of the original for STMT.  */
1864                   if (TREE_CODE (t) == SSA_NAME
1865                       || (UNARY_CLASS_P (t)
1866                           && TREE_CODE (TREE_OPERAND (t, 0)) == SSA_NAME)
1867                       || ((BINARY_CLASS_P (t) || COMPARISON_CLASS_P (t))
1868                           && TREE_CODE (TREE_OPERAND (t, 0)) == SSA_NAME
1869                           && is_gimple_val (TREE_OPERAND (t, 1))))
1870                     result = update_rhs_and_lookup_avail_expr (stmt, t, insert);
1871                 }
1872             }
1873         }
1874  dont_fold_assoc:;
1875     }
1876
1877   /* Transform TRUNC_DIV_EXPR and TRUNC_MOD_EXPR into RSHIFT_EXPR
1878      and BIT_AND_EXPR respectively if the first operand is greater
1879      than zero and the second operand is an exact power of two.  */
1880   if ((rhs_code == TRUNC_DIV_EXPR || rhs_code == TRUNC_MOD_EXPR)
1881       && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (rhs, 0)))
1882       && integer_pow2p (TREE_OPERAND (rhs, 1)))
1883     {
1884       tree val;
1885       tree op = TREE_OPERAND (rhs, 0);
1886
1887       if (TYPE_UNSIGNED (TREE_TYPE (op)))
1888         {
1889           val = integer_one_node;
1890         }
1891       else
1892         {
1893           tree dummy_cond = walk_data->global_data;
1894
1895           if (! dummy_cond)
1896             {
1897               dummy_cond = build (GT_EXPR, boolean_type_node,
1898                                   op, integer_zero_node);
1899               dummy_cond = build (COND_EXPR, void_type_node,
1900                                   dummy_cond, NULL, NULL);
1901               walk_data->global_data = dummy_cond;
1902             }
1903           else
1904             {
1905               TREE_SET_CODE (COND_EXPR_COND (dummy_cond), GT_EXPR);
1906               TREE_OPERAND (COND_EXPR_COND (dummy_cond), 0) = op;
1907               TREE_OPERAND (COND_EXPR_COND (dummy_cond), 1)
1908                 = integer_zero_node;
1909             }
1910           val = simplify_cond_and_lookup_avail_expr (dummy_cond, NULL, false);
1911         }
1912
1913       if (val && integer_onep (val))
1914         {
1915           tree t;
1916           tree op0 = TREE_OPERAND (rhs, 0);
1917           tree op1 = TREE_OPERAND (rhs, 1);
1918
1919           if (rhs_code == TRUNC_DIV_EXPR)
1920             t = build (RSHIFT_EXPR, TREE_TYPE (op0), op0,
1921                        build_int_cst (NULL_TREE, tree_log2 (op1)));
1922           else
1923             t = build (BIT_AND_EXPR, TREE_TYPE (op0), op0,
1924                        local_fold (build (MINUS_EXPR, TREE_TYPE (op1),
1925                                           op1, integer_one_node)));
1926
1927           result = update_rhs_and_lookup_avail_expr (stmt, t, insert);
1928         }
1929     }
1930
1931   /* Transform ABS (X) into X or -X as appropriate.  */
1932   if (rhs_code == ABS_EXPR
1933       && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (rhs, 0))))
1934     {
1935       tree val;
1936       tree op = TREE_OPERAND (rhs, 0);
1937       tree type = TREE_TYPE (op);
1938
1939       if (TYPE_UNSIGNED (type))
1940         {
1941           val = integer_zero_node;
1942         }
1943       else
1944         {
1945           tree dummy_cond = walk_data->global_data;
1946
1947           if (! dummy_cond)
1948             {
1949               dummy_cond = build (LE_EXPR, boolean_type_node,
1950                                   op, integer_zero_node);
1951               dummy_cond = build (COND_EXPR, void_type_node,
1952                                   dummy_cond, NULL, NULL);
1953               walk_data->global_data = dummy_cond;
1954             }
1955           else
1956             {
1957               TREE_SET_CODE (COND_EXPR_COND (dummy_cond), LE_EXPR);
1958               TREE_OPERAND (COND_EXPR_COND (dummy_cond), 0) = op;
1959               TREE_OPERAND (COND_EXPR_COND (dummy_cond), 1)
1960                 = build_int_cst (type, 0);
1961             }
1962           val = simplify_cond_and_lookup_avail_expr (dummy_cond, NULL, false);
1963
1964           if (!val)
1965             {
1966               TREE_SET_CODE (COND_EXPR_COND (dummy_cond), GE_EXPR);
1967               TREE_OPERAND (COND_EXPR_COND (dummy_cond), 0) = op;
1968               TREE_OPERAND (COND_EXPR_COND (dummy_cond), 1)
1969                 = build_int_cst (type, 0);
1970
1971               val = simplify_cond_and_lookup_avail_expr (dummy_cond,
1972                                                          NULL, false);
1973
1974               if (val)
1975                 {
1976                   if (integer_zerop (val))
1977                     val = integer_one_node;
1978                   else if (integer_onep (val))
1979                     val = integer_zero_node;
1980                 }
1981             }
1982         }
1983
1984       if (val
1985           && (integer_onep (val) || integer_zerop (val)))
1986         {
1987           tree t;
1988
1989           if (integer_onep (val))
1990             t = build1 (NEGATE_EXPR, TREE_TYPE (op), op);
1991           else
1992             t = op;
1993
1994           result = update_rhs_and_lookup_avail_expr (stmt, t, insert);
1995         }
1996     }
1997
1998   /* Optimize *"foo" into 'f'.  This is done here rather than
1999      in fold to avoid problems with stuff like &*"foo".  */
2000   if (TREE_CODE (rhs) == INDIRECT_REF || TREE_CODE (rhs) == ARRAY_REF)
2001     {
2002       tree t = fold_read_from_constant_string (rhs);
2003
2004       if (t)
2005         result = update_rhs_and_lookup_avail_expr (stmt, t, insert);
2006     }
2007
2008   return result;
2009 }
2010
2011 /* COND is a condition of the form:
2012
2013      x == const or x != const
2014
2015    Look back to x's defining statement and see if x is defined as
2016
2017      x = (type) y;
2018
2019    If const is unchanged if we convert it to type, then we can build
2020    the equivalent expression:
2021
2022
2023       y == const or y != const
2024
2025    Which may allow further optimizations.
2026
2027    Return the equivalent comparison or NULL if no such equivalent comparison
2028    was found.  */
2029
2030 static tree
2031 find_equivalent_equality_comparison (tree cond)
2032 {
2033   tree op0 = TREE_OPERAND (cond, 0);
2034   tree op1 = TREE_OPERAND (cond, 1);
2035   tree def_stmt = SSA_NAME_DEF_STMT (op0);
2036
2037   /* OP0 might have been a parameter, so first make sure it
2038      was defined by a MODIFY_EXPR.  */
2039   if (def_stmt && TREE_CODE (def_stmt) == MODIFY_EXPR)
2040     {
2041       tree def_rhs = TREE_OPERAND (def_stmt, 1);
2042
2043       /* Now make sure the RHS of the MODIFY_EXPR is a typecast.  */
2044       if ((TREE_CODE (def_rhs) == NOP_EXPR
2045            || TREE_CODE (def_rhs) == CONVERT_EXPR)
2046           && TREE_CODE (TREE_OPERAND (def_rhs, 0)) == SSA_NAME)
2047         {
2048           tree def_rhs_inner = TREE_OPERAND (def_rhs, 0);
2049           tree def_rhs_inner_type = TREE_TYPE (def_rhs_inner);
2050           tree new;
2051
2052           if (TYPE_PRECISION (def_rhs_inner_type)
2053               > TYPE_PRECISION (TREE_TYPE (def_rhs)))
2054             return NULL;
2055
2056           /* What we want to prove is that if we convert OP1 to
2057              the type of the object inside the NOP_EXPR that the
2058              result is still equivalent to SRC. 
2059
2060              If that is true, the build and return new equivalent
2061              condition which uses the source of the typecast and the
2062              new constant (which has only changed its type).  */
2063           new = build1 (TREE_CODE (def_rhs), def_rhs_inner_type, op1);
2064           new = local_fold (new);
2065           if (is_gimple_val (new) && tree_int_cst_equal (new, op1))
2066             return build (TREE_CODE (cond), TREE_TYPE (cond),
2067                           def_rhs_inner, new);
2068         }
2069     }
2070   return NULL;
2071 }
2072
2073 /* STMT is a COND_EXPR for which we could not trivially determine its
2074    result.  This routine attempts to find equivalent forms of the
2075    condition which we may be able to optimize better.  It also 
2076    uses simple value range propagation to optimize conditionals.  */
2077
2078 static tree
2079 simplify_cond_and_lookup_avail_expr (tree stmt,
2080                                      stmt_ann_t ann,
2081                                      int insert)
2082 {
2083   tree cond = COND_EXPR_COND (stmt);
2084
2085   if (COMPARISON_CLASS_P (cond))
2086     {
2087       tree op0 = TREE_OPERAND (cond, 0);
2088       tree op1 = TREE_OPERAND (cond, 1);
2089
2090       if (TREE_CODE (op0) == SSA_NAME && is_gimple_min_invariant (op1))
2091         {
2092           int limit;
2093           tree low, high, cond_low, cond_high;
2094           int lowequal, highequal, swapped, no_overlap, subset, cond_inverted;
2095           varray_type vrp_records;
2096           struct vrp_element *element;
2097           struct vrp_hash_elt vrp_hash_elt, *vrp_hash_elt_p;
2098           void **slot;
2099
2100           /* First see if we have test of an SSA_NAME against a constant
2101              where the SSA_NAME is defined by an earlier typecast which
2102              is irrelevant when performing tests against the given
2103              constant.  */
2104           if (TREE_CODE (cond) == EQ_EXPR || TREE_CODE (cond) == NE_EXPR)
2105             {
2106               tree new_cond = find_equivalent_equality_comparison (cond);
2107
2108               if (new_cond)
2109                 {
2110                   /* Update the statement to use the new equivalent
2111                      condition.  */
2112                   COND_EXPR_COND (stmt) = new_cond;
2113
2114                   /* If this is not a real stmt, ann will be NULL and we
2115                      avoid processing the operands.  */
2116                   if (ann)
2117                     mark_stmt_modified (stmt);
2118
2119                   /* Lookup the condition and return its known value if it
2120                      exists.  */
2121                   new_cond = lookup_avail_expr (stmt, insert);
2122                   if (new_cond)
2123                     return new_cond;
2124
2125                   /* The operands have changed, so update op0 and op1.  */
2126                   op0 = TREE_OPERAND (cond, 0);
2127                   op1 = TREE_OPERAND (cond, 1);
2128                 }
2129             }
2130
2131           /* Consult the value range records for this variable (if they exist)
2132              to see if we can eliminate or simplify this conditional. 
2133
2134              Note two tests are necessary to determine no records exist.
2135              First we have to see if the virtual array exists, if it 
2136              exists, then we have to check its active size. 
2137
2138              Also note the vast majority of conditionals are not testing
2139              a variable which has had its range constrained by an earlier
2140              conditional.  So this filter avoids a lot of unnecessary work.  */
2141           vrp_hash_elt.var = op0;
2142           vrp_hash_elt.records = NULL;
2143           slot = htab_find_slot (vrp_data, &vrp_hash_elt, NO_INSERT);
2144           if (slot == NULL)
2145             return NULL;
2146
2147           vrp_hash_elt_p = (struct vrp_hash_elt *) *slot;
2148           vrp_records = vrp_hash_elt_p->records;
2149           if (vrp_records == NULL)
2150             return NULL;
2151
2152           limit = VARRAY_ACTIVE_SIZE (vrp_records);
2153
2154           /* If we have no value range records for this variable, or we are
2155              unable to extract a range for this condition, then there is
2156              nothing to do.  */
2157           if (limit == 0
2158               || ! extract_range_from_cond (cond, &cond_high,
2159                                             &cond_low, &cond_inverted))
2160             return NULL;
2161
2162           /* We really want to avoid unnecessary computations of range
2163              info.  So all ranges are computed lazily; this avoids a
2164              lot of unnecessary work.  i.e., we record the conditional,
2165              but do not process how it constrains the variable's 
2166              potential values until we know that processing the condition
2167              could be helpful.
2168
2169              However, we do not want to have to walk a potentially long
2170              list of ranges, nor do we want to compute a variable's
2171              range more than once for a given path.
2172
2173              Luckily, each time we encounter a conditional that can not
2174              be otherwise optimized we will end up here and we will
2175              compute the necessary range information for the variable
2176              used in this condition.
2177
2178              Thus you can conclude that there will never be more than one
2179              conditional associated with a variable which has not been
2180              processed.  So we never need to merge more than one new
2181              conditional into the current range. 
2182
2183              These properties also help us avoid unnecessary work.  */
2184            element
2185              = (struct vrp_element *)VARRAY_GENERIC_PTR (vrp_records, limit - 1);
2186
2187           if (element->high && element->low)
2188             {
2189               /* The last element has been processed, so there is no range
2190                  merging to do, we can simply use the high/low values
2191                  recorded in the last element.  */
2192               low = element->low;
2193               high = element->high;
2194             }
2195           else
2196             {
2197               tree tmp_high, tmp_low;
2198               int dummy;
2199
2200               /* The last element has not been processed.  Process it now.
2201                  record_range should ensure for cond inverted is not set.
2202                  This call can only fail if cond is x < min or x > max,
2203                  which fold should have optimized into false.
2204                  If that doesn't happen, just pretend all values are
2205                  in the range.  */
2206               if (! extract_range_from_cond (element->cond, &tmp_high,
2207                                              &tmp_low, &dummy))
2208                 gcc_unreachable ();
2209               else
2210                 gcc_assert (dummy == 0);
2211
2212               /* If this is the only element, then no merging is necessary, 
2213                  the high/low values from extract_range_from_cond are all
2214                  we need.  */
2215               if (limit == 1)
2216                 {
2217                   low = tmp_low;
2218                   high = tmp_high;
2219                 }
2220               else
2221                 {
2222                   /* Get the high/low value from the previous element.  */
2223                   struct vrp_element *prev
2224                     = (struct vrp_element *)VARRAY_GENERIC_PTR (vrp_records,
2225                                                                 limit - 2);
2226                   low = prev->low;
2227                   high = prev->high;
2228
2229                   /* Merge in this element's range with the range from the
2230                      previous element.
2231
2232                      The low value for the merged range is the maximum of
2233                      the previous low value and the low value of this record.
2234
2235                      Similarly the high value for the merged range is the
2236                      minimum of the previous high value and the high value of
2237                      this record.  */
2238                   low = (low && tree_int_cst_compare (low, tmp_low) == 1
2239                          ? low : tmp_low);
2240                   high = (high && tree_int_cst_compare (high, tmp_high) == -1
2241                           ? high : tmp_high);
2242                 }
2243
2244               /* And record the computed range.  */
2245               element->low = low;
2246               element->high = high;
2247
2248             }
2249
2250           /* After we have constrained this variable's potential values,
2251              we try to determine the result of the given conditional.
2252
2253              To simplify later tests, first determine if the current
2254              low value is the same low value as the conditional.
2255              Similarly for the current high value and the high value
2256              for the conditional.  */
2257           lowequal = tree_int_cst_equal (low, cond_low);
2258           highequal = tree_int_cst_equal (high, cond_high);
2259
2260           if (lowequal && highequal)
2261             return (cond_inverted ? boolean_false_node : boolean_true_node);
2262
2263           /* To simplify the overlap/subset tests below we may want
2264              to swap the two ranges so that the larger of the two
2265              ranges occurs "first".  */
2266           swapped = 0;
2267           if (tree_int_cst_compare (low, cond_low) == 1
2268               || (lowequal 
2269                   && tree_int_cst_compare (cond_high, high) == 1))
2270             {
2271               tree temp;
2272
2273               swapped = 1;
2274               temp = low;
2275               low = cond_low;
2276               cond_low = temp;
2277               temp = high;
2278               high = cond_high;
2279               cond_high = temp;
2280             }
2281
2282           /* Now determine if there is no overlap in the ranges
2283              or if the second range is a subset of the first range.  */
2284           no_overlap = tree_int_cst_lt (high, cond_low);
2285           subset = tree_int_cst_compare (cond_high, high) != 1;
2286
2287           /* If there was no overlap in the ranges, then this conditional
2288              always has a false value (unless we had to invert this
2289              conditional, in which case it always has a true value).  */
2290           if (no_overlap)
2291             return (cond_inverted ? boolean_true_node : boolean_false_node);
2292
2293           /* If the current range is a subset of the condition's range,
2294              then this conditional always has a true value (unless we
2295              had to invert this conditional, in which case it always
2296              has a true value).  */
2297           if (subset && swapped)
2298             return (cond_inverted ? boolean_false_node : boolean_true_node);
2299
2300           /* We were unable to determine the result of the conditional.
2301              However, we may be able to simplify the conditional.  First
2302              merge the ranges in the same manner as range merging above.  */
2303           low = tree_int_cst_compare (low, cond_low) == 1 ? low : cond_low;
2304           high = tree_int_cst_compare (high, cond_high) == -1 ? high : cond_high;
2305           
2306           /* If the range has converged to a single point, then turn this
2307              into an equality comparison.  */
2308           if (TREE_CODE (cond) != EQ_EXPR
2309               && TREE_CODE (cond) != NE_EXPR
2310               && tree_int_cst_equal (low, high))
2311             {
2312               TREE_SET_CODE (cond, EQ_EXPR);
2313               TREE_OPERAND (cond, 1) = high;
2314             }
2315         }
2316     }
2317   return 0;
2318 }
2319
2320 /* STMT is a SWITCH_EXPR for which we could not trivially determine its
2321    result.  This routine attempts to find equivalent forms of the
2322    condition which we may be able to optimize better.  */
2323
2324 static tree
2325 simplify_switch_and_lookup_avail_expr (tree stmt, int insert)
2326 {
2327   tree cond = SWITCH_COND (stmt);
2328   tree def, to, ti;
2329
2330   /* The optimization that we really care about is removing unnecessary
2331      casts.  That will let us do much better in propagating the inferred
2332      constant at the switch target.  */
2333   if (TREE_CODE (cond) == SSA_NAME)
2334     {
2335       def = SSA_NAME_DEF_STMT (cond);
2336       if (TREE_CODE (def) == MODIFY_EXPR)
2337         {
2338           def = TREE_OPERAND (def, 1);
2339           if (TREE_CODE (def) == NOP_EXPR)
2340             {
2341               int need_precision;
2342               bool fail;
2343
2344               def = TREE_OPERAND (def, 0);
2345
2346 #ifdef ENABLE_CHECKING
2347               /* ??? Why was Jeff testing this?  We are gimple...  */
2348               gcc_assert (is_gimple_val (def));
2349 #endif
2350
2351               to = TREE_TYPE (cond);
2352               ti = TREE_TYPE (def);
2353
2354               /* If we have an extension that preserves value, then we
2355                  can copy the source value into the switch.  */
2356
2357               need_precision = TYPE_PRECISION (ti);
2358               fail = false;
2359               if (TYPE_UNSIGNED (to) && !TYPE_UNSIGNED (ti))
2360                 fail = true;
2361               else if (!TYPE_UNSIGNED (to) && TYPE_UNSIGNED (ti))
2362                 need_precision += 1;
2363               if (TYPE_PRECISION (to) < need_precision)
2364                 fail = true;
2365
2366               if (!fail)
2367                 {
2368                   SWITCH_COND (stmt) = def;
2369                   mark_stmt_modified (stmt);
2370
2371                   return lookup_avail_expr (stmt, insert);
2372                 }
2373             }
2374         }
2375     }
2376
2377   return 0;
2378 }
2379
2380
2381 /* CONST_AND_COPIES is a table which maps an SSA_NAME to the current
2382    known value for that SSA_NAME (or NULL if no value is known).  
2383
2384    NONZERO_VARS is the set SSA_NAMES known to have a nonzero value,
2385    even if we don't know their precise value.
2386
2387    Propagate values from CONST_AND_COPIES and NONZERO_VARS into the PHI
2388    nodes of the successors of BB.  */
2389
2390 static void
2391 cprop_into_successor_phis (basic_block bb, bitmap nonzero_vars)
2392 {
2393   edge e;
2394   edge_iterator ei;
2395
2396   FOR_EACH_EDGE (e, ei, bb->succs)
2397     {
2398       tree phi;
2399       int indx;
2400
2401       /* If this is an abnormal edge, then we do not want to copy propagate
2402          into the PHI alternative associated with this edge.  */
2403       if (e->flags & EDGE_ABNORMAL)
2404         continue;
2405
2406       phi = phi_nodes (e->dest);
2407       if (! phi)
2408         continue;
2409
2410       indx = e->dest_idx;
2411       for ( ; phi; phi = PHI_CHAIN (phi))
2412         {
2413           tree new;
2414           use_operand_p orig_p;
2415           tree orig;
2416
2417           /* The alternative may be associated with a constant, so verify
2418              it is an SSA_NAME before doing anything with it.  */
2419           orig_p = PHI_ARG_DEF_PTR (phi, indx);
2420           orig = USE_FROM_PTR (orig_p);
2421           if (TREE_CODE (orig) != SSA_NAME)
2422             continue;
2423
2424           /* If the alternative is known to have a nonzero value, record
2425              that fact in the PHI node itself for future use.  */
2426           if (bitmap_bit_p (nonzero_vars, SSA_NAME_VERSION (orig)))
2427             PHI_ARG_NONZERO (phi, indx) = true;
2428
2429           /* If we have *ORIG_P in our constant/copy table, then replace
2430              ORIG_P with its value in our constant/copy table.  */
2431           new = SSA_NAME_VALUE (orig);
2432           if (new
2433               && new != orig
2434               && (TREE_CODE (new) == SSA_NAME
2435                   || is_gimple_min_invariant (new))
2436               && may_propagate_copy (orig, new))
2437             propagate_value (orig_p, new);
2438         }
2439     }
2440 }
2441
2442 /* We have finished optimizing BB, record any information implied by
2443    taking a specific outgoing edge from BB.  */
2444
2445 static void
2446 record_edge_info (basic_block bb)
2447 {
2448   block_stmt_iterator bsi = bsi_last (bb);
2449   struct edge_info *edge_info;
2450
2451   if (! bsi_end_p (bsi))
2452     {
2453       tree stmt = bsi_stmt (bsi);
2454
2455       if (stmt && TREE_CODE (stmt) == SWITCH_EXPR)
2456         {
2457           tree cond = SWITCH_COND (stmt);
2458
2459           if (TREE_CODE (cond) == SSA_NAME)
2460             {
2461               tree labels = SWITCH_LABELS (stmt);
2462               int i, n_labels = TREE_VEC_LENGTH (labels);
2463               tree *info = xcalloc (n_basic_blocks, sizeof (tree));
2464               edge e;
2465               edge_iterator ei;
2466
2467               for (i = 0; i < n_labels; i++)
2468                 {
2469                   tree label = TREE_VEC_ELT (labels, i);
2470                   basic_block target_bb = label_to_block (CASE_LABEL (label));
2471
2472                   if (CASE_HIGH (label)
2473                       || !CASE_LOW (label)
2474                       || info[target_bb->index])
2475                     info[target_bb->index] = error_mark_node;
2476                   else
2477                     info[target_bb->index] = label;
2478                 }
2479
2480               FOR_EACH_EDGE (e, ei, bb->succs)
2481                 {
2482                   basic_block target_bb = e->dest;
2483                   tree node = info[target_bb->index];
2484
2485                   if (node != NULL && node != error_mark_node)
2486                     {
2487                       tree x = fold_convert (TREE_TYPE (cond), CASE_LOW (node));
2488                       edge_info = allocate_edge_info (e);
2489                       edge_info->lhs = cond;
2490                       edge_info->rhs = x;
2491                     }
2492                 }
2493               free (info);
2494             }
2495         }
2496
2497       /* A COND_EXPR may create equivalences too.  */
2498       if (stmt && TREE_CODE (stmt) == COND_EXPR)
2499         {
2500           tree cond = COND_EXPR_COND (stmt);
2501           edge true_edge;
2502           edge false_edge;
2503
2504           extract_true_false_edges_from_block (bb, &true_edge, &false_edge);
2505
2506           /* If the conditional is a single variable 'X', record 'X = 1'
2507              for the true edge and 'X = 0' on the false edge.  */
2508           if (SSA_VAR_P (cond))
2509             {
2510               struct edge_info *edge_info;
2511
2512               edge_info = allocate_edge_info (true_edge);
2513               edge_info->lhs = cond;
2514               edge_info->rhs = constant_boolean_node (1, TREE_TYPE (cond));
2515
2516               edge_info = allocate_edge_info (false_edge);
2517               edge_info->lhs = cond;
2518               edge_info->rhs = constant_boolean_node (0, TREE_TYPE (cond));
2519             }
2520           /* Equality tests may create one or two equivalences.  */
2521           else if (COMPARISON_CLASS_P (cond))
2522             {
2523               tree op0 = TREE_OPERAND (cond, 0);
2524               tree op1 = TREE_OPERAND (cond, 1);
2525
2526               /* Special case comparing booleans against a constant as we
2527                  know the value of OP0 on both arms of the branch.  i.e., we
2528                  can record an equivalence for OP0 rather than COND.  */
2529               if ((TREE_CODE (cond) == EQ_EXPR || TREE_CODE (cond) == NE_EXPR)
2530                   && TREE_CODE (op0) == SSA_NAME
2531                   && TREE_CODE (TREE_TYPE (op0)) == BOOLEAN_TYPE
2532                   && is_gimple_min_invariant (op1))
2533                 {
2534                   if (TREE_CODE (cond) == EQ_EXPR)
2535                     {
2536                       edge_info = allocate_edge_info (true_edge);
2537                       edge_info->lhs = op0;
2538                       edge_info->rhs = (integer_zerop (op1)
2539                                             ? boolean_false_node
2540                                             : boolean_true_node);
2541
2542                       edge_info = allocate_edge_info (false_edge);
2543                       edge_info->lhs = op0;
2544                       edge_info->rhs = (integer_zerop (op1)
2545                                             ? boolean_true_node
2546                                             : boolean_false_node);
2547                     }
2548                   else
2549                     {
2550                       edge_info = allocate_edge_info (true_edge);
2551                       edge_info->lhs = op0;
2552                       edge_info->rhs = (integer_zerop (op1)
2553                                             ? boolean_true_node
2554                                             : boolean_false_node);
2555
2556                       edge_info = allocate_edge_info (false_edge);
2557                       edge_info->lhs = op0;
2558                       edge_info->rhs = (integer_zerop (op1)
2559                                             ? boolean_false_node
2560                                             : boolean_true_node);
2561                     }
2562                 }
2563
2564               else if (is_gimple_min_invariant (op0)
2565                        && (TREE_CODE (op1) == SSA_NAME
2566                            || is_gimple_min_invariant (op1)))
2567                 {
2568                   tree inverted = invert_truthvalue (cond);
2569                   struct edge_info *edge_info;
2570
2571                   edge_info = allocate_edge_info (true_edge);
2572                   record_conditions (edge_info, cond, inverted);
2573
2574                   if (TREE_CODE (cond) == EQ_EXPR)
2575                     {
2576                       edge_info->lhs = op1;
2577                       edge_info->rhs = op0;
2578                     }
2579
2580                   edge_info = allocate_edge_info (false_edge);
2581                   record_conditions (edge_info, inverted, cond);
2582
2583                   if (TREE_CODE (cond) == NE_EXPR)
2584                     {
2585                       edge_info->lhs = op1;
2586                       edge_info->rhs = op0;
2587                     }
2588                 }
2589
2590               else if (TREE_CODE (op0) == SSA_NAME
2591                        && (is_gimple_min_invariant (op1)
2592                            || TREE_CODE (op1) == SSA_NAME))
2593                 {
2594                   tree inverted = invert_truthvalue (cond);
2595                   struct edge_info *edge_info;
2596
2597                   edge_info = allocate_edge_info (true_edge);
2598                   record_conditions (edge_info, cond, inverted);
2599
2600                   if (TREE_CODE (cond) == EQ_EXPR)
2601                     {
2602                       edge_info->lhs = op0;
2603                       edge_info->rhs = op1;
2604                     }
2605
2606                   edge_info = allocate_edge_info (false_edge);
2607                   record_conditions (edge_info, inverted, cond);
2608
2609                   if (TREE_CODE (cond) == NE_EXPR)
2610                     {
2611                       edge_info->lhs = op0;
2612                       edge_info->rhs = op1;
2613                     }
2614                 }
2615             }
2616
2617           /* ??? TRUTH_NOT_EXPR can create an equivalence too.  */
2618         }
2619     }
2620 }
2621
2622 /* Propagate information from BB to its outgoing edges.
2623
2624    This can include equivalency information implied by control statements
2625    at the end of BB and const/copy propagation into PHIs in BB's
2626    successor blocks.  */
2627
2628 static void
2629 propagate_to_outgoing_edges (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
2630                              basic_block bb)
2631 {
2632   record_edge_info (bb);
2633   cprop_into_successor_phis (bb, nonzero_vars);
2634 }
2635
2636 /* Search for redundant computations in STMT.  If any are found, then
2637    replace them with the variable holding the result of the computation.
2638
2639    If safe, record this expression into the available expression hash
2640    table.  */
2641
2642 static bool
2643 eliminate_redundant_computations (struct dom_walk_data *walk_data,
2644                                   tree stmt, stmt_ann_t ann)
2645 {
2646   v_may_def_optype v_may_defs = V_MAY_DEF_OPS (ann);
2647   tree *expr_p, def = NULL_TREE;
2648   bool insert = true;
2649   tree cached_lhs;
2650   bool retval = false;
2651
2652   if (TREE_CODE (stmt) == MODIFY_EXPR)
2653     def = TREE_OPERAND (stmt, 0);
2654
2655   /* Certain expressions on the RHS can be optimized away, but can not
2656      themselves be entered into the hash tables.  */
2657   if (ann->makes_aliased_stores
2658       || ! def
2659       || TREE_CODE (def) != SSA_NAME
2660       || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (def)
2661       || NUM_V_MAY_DEFS (v_may_defs) != 0
2662       /* Do not record equivalences for increments of ivs.  This would create
2663          overlapping live ranges for a very questionable gain.  */
2664       || simple_iv_increment_p (stmt))
2665     insert = false;
2666
2667   /* Check if the expression has been computed before.  */
2668   cached_lhs = lookup_avail_expr (stmt, insert);
2669
2670   /* If this is an assignment and the RHS was not in the hash table,
2671      then try to simplify the RHS and lookup the new RHS in the
2672      hash table.  */
2673   if (! cached_lhs && TREE_CODE (stmt) == MODIFY_EXPR)
2674     cached_lhs = simplify_rhs_and_lookup_avail_expr (walk_data, stmt, insert);
2675   /* Similarly if this is a COND_EXPR and we did not find its
2676      expression in the hash table, simplify the condition and
2677      try again.  */
2678   else if (! cached_lhs && TREE_CODE (stmt) == COND_EXPR)
2679     cached_lhs = simplify_cond_and_lookup_avail_expr (stmt, ann, insert);
2680   /* Similarly for a SWITCH_EXPR.  */
2681   else if (!cached_lhs && TREE_CODE (stmt) == SWITCH_EXPR)
2682     cached_lhs = simplify_switch_and_lookup_avail_expr (stmt, insert);
2683
2684   opt_stats.num_exprs_considered++;
2685
2686   /* Get a pointer to the expression we are trying to optimize.  */
2687   if (TREE_CODE (stmt) == COND_EXPR)
2688     expr_p = &COND_EXPR_COND (stmt);
2689   else if (TREE_CODE (stmt) == SWITCH_EXPR)
2690     expr_p = &SWITCH_COND (stmt);
2691   else if (TREE_CODE (stmt) == RETURN_EXPR && TREE_OPERAND (stmt, 0))
2692     expr_p = &TREE_OPERAND (TREE_OPERAND (stmt, 0), 1);
2693   else
2694     expr_p = &TREE_OPERAND (stmt, 1);
2695
2696   /* It is safe to ignore types here since we have already done
2697      type checking in the hashing and equality routines.  In fact
2698      type checking here merely gets in the way of constant
2699      propagation.  Also, make sure that it is safe to propagate
2700      CACHED_LHS into *EXPR_P.  */
2701   if (cached_lhs
2702       && (TREE_CODE (cached_lhs) != SSA_NAME
2703           || may_propagate_copy (*expr_p, cached_lhs)))
2704     {
2705       if (dump_file && (dump_flags & TDF_DETAILS))
2706         {
2707           fprintf (dump_file, "  Replaced redundant expr '");
2708           print_generic_expr (dump_file, *expr_p, dump_flags);
2709           fprintf (dump_file, "' with '");
2710           print_generic_expr (dump_file, cached_lhs, dump_flags);
2711            fprintf (dump_file, "'\n");
2712         }
2713
2714       opt_stats.num_re++;
2715
2716 #if defined ENABLE_CHECKING
2717       gcc_assert (TREE_CODE (cached_lhs) == SSA_NAME
2718                   || is_gimple_min_invariant (cached_lhs));
2719 #endif
2720
2721       if (TREE_CODE (cached_lhs) == ADDR_EXPR
2722           || (POINTER_TYPE_P (TREE_TYPE (*expr_p))
2723               && is_gimple_min_invariant (cached_lhs)))
2724         retval = true;
2725
2726       propagate_tree_value (expr_p, cached_lhs);
2727       mark_stmt_modified (stmt);
2728     }
2729   return retval;
2730 }
2731
2732 /* STMT, a MODIFY_EXPR, may create certain equivalences, in either
2733    the available expressions table or the const_and_copies table.
2734    Detect and record those equivalences.  */
2735
2736 static void
2737 record_equivalences_from_stmt (tree stmt,
2738                                int may_optimize_p,
2739                                stmt_ann_t ann)
2740 {
2741   tree lhs = TREE_OPERAND (stmt, 0);
2742   enum tree_code lhs_code = TREE_CODE (lhs);
2743   int i;
2744
2745   if (lhs_code == SSA_NAME)
2746     {
2747       tree rhs = TREE_OPERAND (stmt, 1);
2748
2749       /* Strip away any useless type conversions.  */
2750       STRIP_USELESS_TYPE_CONVERSION (rhs);
2751
2752       /* If the RHS of the assignment is a constant or another variable that
2753          may be propagated, register it in the CONST_AND_COPIES table.  We
2754          do not need to record unwind data for this, since this is a true
2755          assignment and not an equivalence inferred from a comparison.  All
2756          uses of this ssa name are dominated by this assignment, so unwinding
2757          just costs time and space.  */
2758       if (may_optimize_p
2759           && (TREE_CODE (rhs) == SSA_NAME
2760               || is_gimple_min_invariant (rhs)))
2761         SSA_NAME_VALUE (lhs) = rhs;
2762
2763       if (expr_computes_nonzero (rhs))
2764         record_var_is_nonzero (lhs);
2765     }
2766
2767   /* Look at both sides for pointer dereferences.  If we find one, then
2768      the pointer must be nonnull and we can enter that equivalence into
2769      the hash tables.  */
2770   if (flag_delete_null_pointer_checks)
2771     for (i = 0; i < 2; i++)
2772       {
2773         tree t = TREE_OPERAND (stmt, i);
2774
2775         /* Strip away any COMPONENT_REFs.  */
2776         while (TREE_CODE (t) == COMPONENT_REF)
2777           t = TREE_OPERAND (t, 0);
2778
2779         /* Now see if this is a pointer dereference.  */
2780         if (INDIRECT_REF_P (t))
2781           {
2782             tree op = TREE_OPERAND (t, 0);
2783
2784             /* If the pointer is a SSA variable, then enter new
2785                equivalences into the hash table.  */
2786             while (TREE_CODE (op) == SSA_NAME)
2787               {
2788                 tree def = SSA_NAME_DEF_STMT (op);
2789
2790                 record_var_is_nonzero (op);
2791
2792                 /* And walk up the USE-DEF chains noting other SSA_NAMEs
2793                    which are known to have a nonzero value.  */
2794                 if (def
2795                     && TREE_CODE (def) == MODIFY_EXPR
2796                     && TREE_CODE (TREE_OPERAND (def, 1)) == NOP_EXPR)
2797                   op = TREE_OPERAND (TREE_OPERAND (def, 1), 0);
2798                 else
2799                   break;
2800               }
2801           }
2802       }
2803
2804   /* A memory store, even an aliased store, creates a useful
2805      equivalence.  By exchanging the LHS and RHS, creating suitable
2806      vops and recording the result in the available expression table,
2807      we may be able to expose more redundant loads.  */
2808   if (!ann->has_volatile_ops
2809       && (TREE_CODE (TREE_OPERAND (stmt, 1)) == SSA_NAME
2810           || is_gimple_min_invariant (TREE_OPERAND (stmt, 1)))
2811       && !is_gimple_reg (lhs))
2812     {
2813       tree rhs = TREE_OPERAND (stmt, 1);
2814       tree new;
2815
2816       /* FIXME: If the LHS of the assignment is a bitfield and the RHS
2817          is a constant, we need to adjust the constant to fit into the
2818          type of the LHS.  If the LHS is a bitfield and the RHS is not
2819          a constant, then we can not record any equivalences for this
2820          statement since we would need to represent the widening or
2821          narrowing of RHS.  This fixes gcc.c-torture/execute/921016-1.c
2822          and should not be necessary if GCC represented bitfields
2823          properly.  */
2824       if (lhs_code == COMPONENT_REF
2825           && DECL_BIT_FIELD (TREE_OPERAND (lhs, 1)))
2826         {
2827           if (TREE_CONSTANT (rhs))
2828             rhs = widen_bitfield (rhs, TREE_OPERAND (lhs, 1), lhs);
2829           else
2830             rhs = NULL;
2831
2832           /* If the value overflowed, then we can not use this equivalence.  */
2833           if (rhs && ! is_gimple_min_invariant (rhs))
2834             rhs = NULL;
2835         }
2836
2837       if (rhs)
2838         {
2839           /* Build a new statement with the RHS and LHS exchanged.  */
2840           new = build (MODIFY_EXPR, TREE_TYPE (stmt), rhs, lhs);
2841
2842           create_ssa_artficial_load_stmt (&(ann->operands), new);
2843
2844           /* Finally enter the statement into the available expression
2845              table.  */
2846           lookup_avail_expr (new, true);
2847         }
2848     }
2849 }
2850
2851 /* Replace *OP_P in STMT with any known equivalent value for *OP_P from
2852    CONST_AND_COPIES.  */
2853
2854 static bool
2855 cprop_operand (tree stmt, use_operand_p op_p)
2856 {
2857   bool may_have_exposed_new_symbols = false;
2858   tree val;
2859   tree op = USE_FROM_PTR (op_p);
2860
2861   /* If the operand has a known constant value or it is known to be a
2862      copy of some other variable, use the value or copy stored in
2863      CONST_AND_COPIES.  */
2864   val = SSA_NAME_VALUE (op);
2865   if (val && val != op && TREE_CODE (val) != VALUE_HANDLE)
2866     {
2867       tree op_type, val_type;
2868
2869       /* Do not change the base variable in the virtual operand
2870          tables.  That would make it impossible to reconstruct
2871          the renamed virtual operand if we later modify this
2872          statement.  Also only allow the new value to be an SSA_NAME
2873          for propagation into virtual operands.  */
2874       if (!is_gimple_reg (op)
2875           && (TREE_CODE (val) != SSA_NAME
2876               || is_gimple_reg (val)
2877               || get_virtual_var (val) != get_virtual_var (op)))
2878         return false;
2879
2880       /* Do not replace hard register operands in asm statements.  */
2881       if (TREE_CODE (stmt) == ASM_EXPR
2882           && !may_propagate_copy_into_asm (op))
2883         return false;
2884
2885       /* Get the toplevel type of each operand.  */
2886       op_type = TREE_TYPE (op);
2887       val_type = TREE_TYPE (val);
2888
2889       /* While both types are pointers, get the type of the object
2890          pointed to.  */
2891       while (POINTER_TYPE_P (op_type) && POINTER_TYPE_P (val_type))
2892         {
2893           op_type = TREE_TYPE (op_type);
2894           val_type = TREE_TYPE (val_type);
2895         }
2896
2897       /* Make sure underlying types match before propagating a constant by
2898          converting the constant to the proper type.  Note that convert may
2899          return a non-gimple expression, in which case we ignore this
2900          propagation opportunity.  */
2901       if (TREE_CODE (val) != SSA_NAME)
2902         {
2903           if (!lang_hooks.types_compatible_p (op_type, val_type))
2904             {
2905               val = fold_convert (TREE_TYPE (op), val);
2906               if (!is_gimple_min_invariant (val))
2907                 return false;
2908             }
2909         }
2910
2911       /* Certain operands are not allowed to be copy propagated due
2912          to their interaction with exception handling and some GCC
2913          extensions.  */
2914       else if (!may_propagate_copy (op, val))
2915         return false;
2916       
2917       /* Do not propagate copies if the propagated value is at a deeper loop
2918          depth than the propagatee.  Otherwise, this may move loop variant
2919          variables outside of their loops and prevent coalescing
2920          opportunities.  If the value was loop invariant, it will be hoisted
2921          by LICM and exposed for copy propagation.  */
2922       if (loop_depth_of_name (val) > loop_depth_of_name (op))
2923         return false;
2924
2925       /* Dump details.  */
2926       if (dump_file && (dump_flags & TDF_DETAILS))
2927         {
2928           fprintf (dump_file, "  Replaced '");
2929           print_generic_expr (dump_file, op, dump_flags);
2930           fprintf (dump_file, "' with %s '",
2931                    (TREE_CODE (val) != SSA_NAME ? "constant" : "variable"));
2932           print_generic_expr (dump_file, val, dump_flags);
2933           fprintf (dump_file, "'\n");
2934         }
2935
2936       /* If VAL is an ADDR_EXPR or a constant of pointer type, note
2937          that we may have exposed a new symbol for SSA renaming.  */
2938       if (TREE_CODE (val) == ADDR_EXPR
2939           || (POINTER_TYPE_P (TREE_TYPE (op))
2940               && is_gimple_min_invariant (val)))
2941         may_have_exposed_new_symbols = true;
2942
2943       if (TREE_CODE (val) != SSA_NAME)
2944         opt_stats.num_const_prop++;
2945       else
2946         opt_stats.num_copy_prop++;
2947
2948       propagate_value (op_p, val);
2949
2950       /* And note that we modified this statement.  This is now
2951          safe, even if we changed virtual operands since we will
2952          rescan the statement and rewrite its operands again.  */
2953       mark_stmt_modified (stmt);
2954     }
2955   return may_have_exposed_new_symbols;
2956 }
2957
2958 /* CONST_AND_COPIES is a table which maps an SSA_NAME to the current
2959    known value for that SSA_NAME (or NULL if no value is known).  
2960
2961    Propagate values from CONST_AND_COPIES into the uses, vuses and
2962    v_may_def_ops of STMT.  */
2963
2964 static bool
2965 cprop_into_stmt (tree stmt)
2966 {
2967   bool may_have_exposed_new_symbols = false;
2968   use_operand_p op_p;
2969   ssa_op_iter iter;
2970   tree rhs;
2971
2972   FOR_EACH_SSA_USE_OPERAND (op_p, stmt, iter, SSA_OP_ALL_USES)
2973     {
2974       if (TREE_CODE (USE_FROM_PTR (op_p)) == SSA_NAME)
2975         may_have_exposed_new_symbols |= cprop_operand (stmt, op_p);
2976     }
2977
2978   if (may_have_exposed_new_symbols)
2979     {
2980       rhs = get_rhs (stmt);
2981       if (rhs && TREE_CODE (rhs) == ADDR_EXPR)
2982         recompute_tree_invarant_for_addr_expr (rhs);
2983     }
2984
2985   return may_have_exposed_new_symbols;
2986 }
2987
2988
2989 /* Optimize the statement pointed by iterator SI.
2990    
2991    We try to perform some simplistic global redundancy elimination and
2992    constant propagation:
2993
2994    1- To detect global redundancy, we keep track of expressions that have
2995       been computed in this block and its dominators.  If we find that the
2996       same expression is computed more than once, we eliminate repeated
2997       computations by using the target of the first one.
2998
2999    2- Constant values and copy assignments.  This is used to do very
3000       simplistic constant and copy propagation.  When a constant or copy
3001       assignment is found, we map the value on the RHS of the assignment to
3002       the variable in the LHS in the CONST_AND_COPIES table.  */
3003
3004 static void
3005 optimize_stmt (struct dom_walk_data *walk_data, basic_block bb,
3006                block_stmt_iterator si)
3007 {
3008   stmt_ann_t ann;
3009   tree stmt;
3010   bool may_optimize_p;
3011   bool may_have_exposed_new_symbols = false;
3012
3013   stmt = bsi_stmt (si);
3014
3015   update_stmt_if_modified (stmt);
3016   ann = stmt_ann (stmt);
3017   opt_stats.num_stmts++;
3018   may_have_exposed_new_symbols = false;
3019
3020   if (dump_file && (dump_flags & TDF_DETAILS))
3021     {
3022       fprintf (dump_file, "Optimizing statement ");
3023       print_generic_stmt (dump_file, stmt, TDF_SLIM);
3024     }
3025
3026   /* Const/copy propagate into USES, VUSES and the RHS of V_MAY_DEFs.  */
3027   may_have_exposed_new_symbols = cprop_into_stmt (stmt);
3028
3029   /* If the statement has been modified with constant replacements,
3030      fold its RHS before checking for redundant computations.  */
3031   if (ann->modified)
3032     {
3033       /* Try to fold the statement making sure that STMT is kept
3034          up to date.  */
3035       if (fold_stmt (bsi_stmt_ptr (si)))
3036         {
3037           stmt = bsi_stmt (si);
3038           ann = stmt_ann (stmt);
3039
3040           if (dump_file && (dump_flags & TDF_DETAILS))
3041             {
3042               fprintf (dump_file, "  Folded to: ");
3043               print_generic_stmt (dump_file, stmt, TDF_SLIM);
3044             }
3045         }
3046
3047       /* Constant/copy propagation above may change the set of 
3048          virtual operands associated with this statement.  Folding
3049          may remove the need for some virtual operands.
3050
3051          Indicate we will need to rescan and rewrite the statement.  */
3052       may_have_exposed_new_symbols = true;
3053     }
3054
3055   /* Check for redundant computations.  Do this optimization only
3056      for assignments that have no volatile ops and conditionals.  */
3057   may_optimize_p = (!ann->has_volatile_ops
3058                     && ((TREE_CODE (stmt) == RETURN_EXPR
3059                          && TREE_OPERAND (stmt, 0)
3060                          && TREE_CODE (TREE_OPERAND (stmt, 0)) == MODIFY_EXPR
3061                          && ! (TREE_SIDE_EFFECTS
3062                                (TREE_OPERAND (TREE_OPERAND (stmt, 0), 1))))
3063                         || (TREE_CODE (stmt) == MODIFY_EXPR
3064                             && ! TREE_SIDE_EFFECTS (TREE_OPERAND (stmt, 1)))
3065                         || TREE_CODE (stmt) == COND_EXPR
3066                         || TREE_CODE (stmt) == SWITCH_EXPR));
3067
3068   if (may_optimize_p)
3069     may_have_exposed_new_symbols
3070       |= eliminate_redundant_computations (walk_data, stmt, ann);
3071
3072   /* Record any additional equivalences created by this statement.  */
3073   if (TREE_CODE (stmt) == MODIFY_EXPR)
3074     record_equivalences_from_stmt (stmt,
3075                                    may_optimize_p,
3076                                    ann);
3077
3078   register_definitions_for_stmt (stmt);
3079
3080   /* If STMT is a COND_EXPR and it was modified, then we may know
3081      where it goes.  If that is the case, then mark the CFG as altered.
3082
3083      This will cause us to later call remove_unreachable_blocks and
3084      cleanup_tree_cfg when it is safe to do so.  It is not safe to 
3085      clean things up here since removal of edges and such can trigger
3086      the removal of PHI nodes, which in turn can release SSA_NAMEs to
3087      the manager.
3088
3089      That's all fine and good, except that once SSA_NAMEs are released
3090      to the manager, we must not call create_ssa_name until all references
3091      to released SSA_NAMEs have been eliminated.
3092
3093      All references to the deleted SSA_NAMEs can not be eliminated until
3094      we remove unreachable blocks.
3095
3096      We can not remove unreachable blocks until after we have completed
3097      any queued jump threading.
3098
3099      We can not complete any queued jump threads until we have taken
3100      appropriate variables out of SSA form.  Taking variables out of
3101      SSA form can call create_ssa_name and thus we lose.
3102
3103      Ultimately I suspect we're going to need to change the interface
3104      into the SSA_NAME manager.  */
3105
3106   if (ann->modified)
3107     {
3108       tree val = NULL;
3109
3110       if (TREE_CODE (stmt) == COND_EXPR)
3111         val = COND_EXPR_COND (stmt);
3112       else if (TREE_CODE (stmt) == SWITCH_EXPR)
3113         val = SWITCH_COND (stmt);
3114
3115       if (val && TREE_CODE (val) == INTEGER_CST && find_taken_edge (bb, val))
3116         cfg_altered = true;
3117
3118       /* If we simplified a statement in such a way as to be shown that it
3119          cannot trap, update the eh information and the cfg to match.  */
3120       if (maybe_clean_eh_stmt (stmt))
3121         {
3122           bitmap_set_bit (need_eh_cleanup, bb->index);
3123           if (dump_file && (dump_flags & TDF_DETAILS))
3124             fprintf (dump_file, "  Flagged to clear EH edges.\n");
3125         }
3126     }
3127
3128   if (may_have_exposed_new_symbols)
3129     VEC_safe_push (tree, heap, stmts_to_rescan, bsi_stmt (si));
3130 }
3131
3132 /* Replace the RHS of STMT with NEW_RHS.  If RHS can be found in the
3133    available expression hashtable, then return the LHS from the hash
3134    table.
3135
3136    If INSERT is true, then we also update the available expression
3137    hash table to account for the changes made to STMT.  */
3138
3139 static tree
3140 update_rhs_and_lookup_avail_expr (tree stmt, tree new_rhs, bool insert)
3141 {
3142   tree cached_lhs = NULL;
3143
3144   /* Remove the old entry from the hash table.  */
3145   if (insert)
3146     {
3147       struct expr_hash_elt element;
3148
3149       initialize_hash_element (stmt, NULL, &element);
3150       htab_remove_elt_with_hash (avail_exprs, &element, element.hash);
3151     }
3152
3153   /* Now update the RHS of the assignment.  */
3154   TREE_OPERAND (stmt, 1) = new_rhs;
3155
3156   /* Now lookup the updated statement in the hash table.  */
3157   cached_lhs = lookup_avail_expr (stmt, insert);
3158
3159   /* We have now called lookup_avail_expr twice with two different
3160      versions of this same statement, once in optimize_stmt, once here.
3161
3162      We know the call in optimize_stmt did not find an existing entry
3163      in the hash table, so a new entry was created.  At the same time
3164      this statement was pushed onto the AVAIL_EXPRS_STACK vector. 
3165
3166      If this call failed to find an existing entry on the hash table,
3167      then the new version of this statement was entered into the
3168      hash table.  And this statement was pushed onto BLOCK_AVAIL_EXPR
3169      for the second time.  So there are two copies on BLOCK_AVAIL_EXPRs
3170
3171      If this call succeeded, we still have one copy of this statement
3172      on the BLOCK_AVAIL_EXPRs vector.
3173
3174      For both cases, we need to pop the most recent entry off the
3175      BLOCK_AVAIL_EXPRs vector.  For the case where we never found this
3176      statement in the hash tables, that will leave precisely one
3177      copy of this statement on BLOCK_AVAIL_EXPRs.  For the case where
3178      we found a copy of this statement in the second hash table lookup
3179      we want _no_ copies of this statement in BLOCK_AVAIL_EXPRs.  */
3180   if (insert)
3181     VEC_pop (tree, avail_exprs_stack);
3182
3183   /* And make sure we record the fact that we modified this
3184      statement.  */
3185   mark_stmt_modified (stmt);
3186
3187   return cached_lhs;
3188 }
3189
3190 /* Search for an existing instance of STMT in the AVAIL_EXPRS table.  If
3191    found, return its LHS. Otherwise insert STMT in the table and return
3192    NULL_TREE.
3193
3194    Also, when an expression is first inserted in the AVAIL_EXPRS table, it
3195    is also added to the stack pointed by BLOCK_AVAIL_EXPRS_P, so that they
3196    can be removed when we finish processing this block and its children.
3197
3198    NOTE: This function assumes that STMT is a MODIFY_EXPR node that
3199    contains no CALL_EXPR on its RHS and makes no volatile nor
3200    aliased references.  */
3201
3202 static tree
3203 lookup_avail_expr (tree stmt, bool insert)
3204 {
3205   void **slot;
3206   tree lhs;
3207   tree temp;
3208   struct expr_hash_elt *element = xmalloc (sizeof (struct expr_hash_elt));
3209
3210   lhs = TREE_CODE (stmt) == MODIFY_EXPR ? TREE_OPERAND (stmt, 0) : NULL;
3211
3212   initialize_hash_element (stmt, lhs, element);
3213
3214   /* Don't bother remembering constant assignments and copy operations.
3215      Constants and copy operations are handled by the constant/copy propagator
3216      in optimize_stmt.  */
3217   if (TREE_CODE (element->rhs) == SSA_NAME
3218       || is_gimple_min_invariant (element->rhs))
3219     {
3220       free (element);
3221       return NULL_TREE;
3222     }
3223
3224   /* If this is an equality test against zero, see if we have recorded a
3225      nonzero value for the variable in question.  */
3226   if ((TREE_CODE (element->rhs) == EQ_EXPR
3227        || TREE_CODE  (element->rhs) == NE_EXPR)
3228       && TREE_CODE (TREE_OPERAND (element->rhs, 0)) == SSA_NAME
3229       && integer_zerop (TREE_OPERAND (element->rhs, 1)))
3230     {
3231       int indx = SSA_NAME_VERSION (TREE_OPERAND (element->rhs, 0));
3232
3233       if (bitmap_bit_p (nonzero_vars, indx))
3234         {
3235           tree t = element->rhs;
3236           free (element);
3237
3238           if (TREE_CODE (t) == EQ_EXPR)
3239             return boolean_false_node;
3240           else
3241             return boolean_true_node;
3242         }
3243     }
3244
3245   /* Finally try to find the expression in the main expression hash table.  */
3246   slot = htab_find_slot_with_hash (avail_exprs, element, element->hash,
3247                                    (insert ? INSERT : NO_INSERT));
3248   if (slot == NULL)
3249     {
3250       free (element);
3251       return NULL_TREE;
3252     }
3253
3254   if (*slot == NULL)
3255     {
3256       *slot = (void *) element;
3257       VEC_safe_push (tree, heap, avail_exprs_stack,
3258                      stmt ? stmt : element->rhs);
3259       return NULL_TREE;
3260     }
3261
3262   /* Extract the LHS of the assignment so that it can be used as the current
3263      definition of another variable.  */
3264   lhs = ((struct expr_hash_elt *)*slot)->lhs;
3265
3266   /* See if the LHS appears in the CONST_AND_COPIES table.  If it does, then
3267      use the value from the const_and_copies table.  */
3268   if (TREE_CODE (lhs) == SSA_NAME)
3269     {
3270       temp = SSA_NAME_VALUE (lhs);
3271       if (temp && TREE_CODE (temp) != VALUE_HANDLE)
3272         lhs = temp;
3273     }
3274
3275   free (element);
3276   return lhs;
3277 }
3278
3279 /* Given a condition COND, record into HI_P, LO_P and INVERTED_P the
3280    range of values that result in the conditional having a true value.
3281
3282    Return true if we are successful in extracting a range from COND and
3283    false if we are unsuccessful.  */
3284
3285 static bool
3286 extract_range_from_cond (tree cond, tree *hi_p, tree *lo_p, int *inverted_p)
3287 {
3288   tree op1 = TREE_OPERAND (cond, 1);
3289   tree high, low, type;
3290   int inverted;
3291
3292   type = TREE_TYPE (op1);
3293
3294   /* Experiments have shown that it's rarely, if ever useful to
3295      record ranges for enumerations.  Presumably this is due to
3296      the fact that they're rarely used directly.  They are typically
3297      cast into an integer type and used that way.  */
3298   if (TREE_CODE (type) != INTEGER_TYPE
3299       /* We don't know how to deal with types with variable bounds.  */
3300       || TREE_CODE (TYPE_MIN_VALUE (type)) != INTEGER_CST
3301       || TREE_CODE (TYPE_MAX_VALUE (type)) != INTEGER_CST)
3302     return 0;
3303
3304   switch (TREE_CODE (cond))
3305     {
3306     case EQ_EXPR:
3307       high = low = op1;
3308       inverted = 0;
3309       break;
3310
3311     case NE_EXPR:
3312       high = low = op1;
3313       inverted = 1;
3314       break;
3315
3316     case GE_EXPR:
3317       low = op1;
3318       high = TYPE_MAX_VALUE (type);
3319       inverted = 0;
3320       break;
3321
3322     case GT_EXPR:
3323       high = TYPE_MAX_VALUE (type);
3324       if (!tree_int_cst_lt (op1, high))
3325         return 0;
3326       low = int_const_binop (PLUS_EXPR, op1, integer_one_node, 1);
3327       inverted = 0;
3328       break;
3329
3330     case LE_EXPR:
3331       high = op1;
3332       low = TYPE_MIN_VALUE (type);
3333       inverted = 0;
3334       break;
3335
3336     case LT_EXPR:
3337       low = TYPE_MIN_VALUE (type);
3338       if (!tree_int_cst_lt (low, op1))
3339         return 0;
3340       high = int_const_binop (MINUS_EXPR, op1, integer_one_node, 1);
3341       inverted = 0;
3342       break;
3343
3344     default:
3345       return 0;
3346     }
3347
3348   *hi_p = high;
3349   *lo_p = low;
3350   *inverted_p = inverted;
3351   return 1;
3352 }
3353
3354 /* Record a range created by COND for basic block BB.  */
3355
3356 static void
3357 record_range (tree cond, basic_block bb)
3358 {
3359   enum tree_code code = TREE_CODE (cond);
3360
3361   /* We explicitly ignore NE_EXPRs and all the unordered comparisons.
3362      They rarely allow for meaningful range optimizations and significantly
3363      complicate the implementation.  */
3364   if ((code == LT_EXPR || code == LE_EXPR || code == GT_EXPR
3365        || code == GE_EXPR || code == EQ_EXPR)
3366       && TREE_CODE (TREE_TYPE (TREE_OPERAND (cond, 1))) == INTEGER_TYPE)
3367     {
3368       struct vrp_hash_elt *vrp_hash_elt;
3369       struct vrp_element *element;
3370       varray_type *vrp_records_p;
3371       void **slot;
3372
3373
3374       vrp_hash_elt = xmalloc (sizeof (struct vrp_hash_elt));
3375       vrp_hash_elt->var = TREE_OPERAND (cond, 0);
3376       vrp_hash_elt->records = NULL;
3377       slot = htab_find_slot (vrp_data, vrp_hash_elt, INSERT);
3378
3379       if (*slot == NULL)
3380         *slot = (void *) vrp_hash_elt;
3381       else
3382         free (vrp_hash_elt);
3383
3384       vrp_hash_elt = (struct vrp_hash_elt *) *slot;
3385       vrp_records_p = &vrp_hash_elt->records;
3386
3387       element = ggc_alloc (sizeof (struct vrp_element));
3388       element->low = NULL;
3389       element->high = NULL;
3390       element->cond = cond;
3391       element->bb = bb;
3392
3393       if (*vrp_records_p == NULL)
3394         VARRAY_GENERIC_PTR_INIT (*vrp_records_p, 2, "vrp records");
3395       
3396       VARRAY_PUSH_GENERIC_PTR (*vrp_records_p, element);
3397       VEC_safe_push (tree, heap, vrp_variables_stack, TREE_OPERAND (cond, 0));
3398     }
3399 }
3400
3401 /* Hashing and equality functions for VRP_DATA.
3402
3403    Since this hash table is addressed by SSA_NAMEs, we can hash on
3404    their version number and equality can be determined with a 
3405    pointer comparison.  */
3406
3407 static hashval_t
3408 vrp_hash (const void *p)
3409 {
3410   tree var = ((struct vrp_hash_elt *)p)->var;
3411
3412   return SSA_NAME_VERSION (var);
3413 }
3414
3415 static int
3416 vrp_eq (const void *p1, const void *p2)
3417 {
3418   tree var1 = ((struct vrp_hash_elt *)p1)->var;
3419   tree var2 = ((struct vrp_hash_elt *)p2)->var;
3420
3421   return var1 == var2;
3422 }
3423
3424 /* Hashing and equality functions for AVAIL_EXPRS.  The table stores
3425    MODIFY_EXPR statements.  We compute a value number for expressions using
3426    the code of the expression and the SSA numbers of its operands.  */
3427
3428 static hashval_t
3429 avail_expr_hash (const void *p)
3430 {
3431   stmt_ann_t ann = ((struct expr_hash_elt *)p)->ann;
3432   tree rhs = ((struct expr_hash_elt *)p)->rhs;
3433   hashval_t val = 0;
3434   size_t i;
3435   vuse_optype vuses;
3436
3437   /* iterative_hash_expr knows how to deal with any expression and
3438      deals with commutative operators as well, so just use it instead
3439      of duplicating such complexities here.  */
3440   val = iterative_hash_expr (rhs, val);
3441
3442   /* If the hash table entry is not associated with a statement, then we
3443      can just hash the expression and not worry about virtual operands
3444      and such.  */
3445   if (!ann)
3446     return val;
3447
3448   /* Add the SSA version numbers of every vuse operand.  This is important
3449      because compound variables like arrays are not renamed in the
3450      operands.  Rather, the rename is done on the virtual variable
3451      representing all the elements of the array.  */
3452   vuses = VUSE_OPS (ann);
3453   for (i = 0; i < NUM_VUSES (vuses); i++)
3454     val = iterative_hash_expr (VUSE_OP (vuses, i), val);
3455
3456   return val;
3457 }
3458
3459 static hashval_t
3460 real_avail_expr_hash (const void *p)
3461 {
3462   return ((const struct expr_hash_elt *)p)->hash;
3463 }
3464
3465 static int
3466 avail_expr_eq (const void *p1, const void *p2)
3467 {
3468   stmt_ann_t ann1 = ((struct expr_hash_elt *)p1)->ann;
3469   tree rhs1 = ((struct expr_hash_elt *)p1)->rhs;
3470   stmt_ann_t ann2 = ((struct expr_hash_elt *)p2)->ann;
3471   tree rhs2 = ((struct expr_hash_elt *)p2)->rhs;
3472
3473   /* If they are the same physical expression, return true.  */
3474   if (rhs1 == rhs2 && ann1 == ann2)
3475     return true;
3476
3477   /* If their codes are not equal, then quit now.  */
3478   if (TREE_CODE (rhs1) != TREE_CODE (rhs2))
3479     return false;
3480
3481   /* In case of a collision, both RHS have to be identical and have the
3482      same VUSE operands.  */
3483   if ((TREE_TYPE (rhs1) == TREE_TYPE (rhs2)
3484        || lang_hooks.types_compatible_p (TREE_TYPE (rhs1), TREE_TYPE (rhs2)))
3485       && operand_equal_p (rhs1, rhs2, OEP_PURE_SAME))
3486     {
3487       vuse_optype ops1 = NULL;
3488       vuse_optype ops2 = NULL;
3489       size_t num_ops1 = 0;
3490       size_t num_ops2 = 0;
3491       size_t i;
3492
3493       if (ann1)
3494         {
3495           ops1 = VUSE_OPS (ann1);
3496           num_ops1 = NUM_VUSES (ops1);
3497         }
3498
3499       if (ann2)
3500         {
3501           ops2 = VUSE_OPS (ann2);
3502           num_ops2 = NUM_VUSES (ops2);
3503         }
3504
3505       /* If the number of virtual uses is different, then we consider
3506          them not equal.  */
3507       if (num_ops1 != num_ops2)
3508         return false;
3509
3510       for (i = 0; i < num_ops1; i++)
3511         if (VUSE_OP (ops1, i) != VUSE_OP (ops2, i))
3512           return false;
3513
3514       gcc_assert (((struct expr_hash_elt *)p1)->hash
3515                   == ((struct expr_hash_elt *)p2)->hash);
3516       return true;
3517     }
3518
3519   return false;
3520 }
3521
3522 /* Given STMT and a pointer to the block local definitions BLOCK_DEFS_P,
3523    register register all objects set by this statement into BLOCK_DEFS_P
3524    and CURRDEFS.  */
3525
3526 static void
3527 register_definitions_for_stmt (tree stmt)
3528 {
3529   tree def;
3530   ssa_op_iter iter;
3531
3532   FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_ALL_DEFS)
3533     {
3534
3535       /* FIXME: We shouldn't be registering new defs if the variable
3536          doesn't need to be renamed.  */
3537       register_new_def (def, &block_defs_stack);
3538     }
3539 }
3540