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