* tree.c (operand_equal_for_phi_arg_p): New.
[official-gcc.git] / gcc / tree-ssa-dom.c
bloba2d145922b536289d320a1c89060f156abfb6dea
1 /* SSA Dominator optimizations for trees
2 Copyright (C) 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
3 Contributed by Diego Novillo <dnovillo@redhat.com>
5 This file is part of GCC.
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.
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.
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. */
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"
46 /* This file implements optimizations on the dominator tree. */
49 /* Structure for recording edge equivalences as well as any pending
50 edge redirections during the dominator optimizer.
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.
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. */
63 struct edge_info
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;
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;
77 /* If we can thread this edge this field records the new target. */
78 edge redirection_target;
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;
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;
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.
101 An SSA_NAME indicates that the current definition of the underlying
102 variable should be set to the given SSA_NAME.
104 A _DECL node indicates that the underlying variable has no current
105 definition.
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;
111 /* Stack of statements we need to rescan during finalization for newly
112 exposed variables.
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;
120 /* Structure for entries in the expression hash table.
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.
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. */
131 struct expr_hash_elt
133 /* The value (lhs) of this expression. */
134 tree lhs;
136 /* The expression (rhs) we want to record. */
137 tree rhs;
139 /* The annotation if this element corresponds to a statement. */
140 stmt_ann_t ann;
142 /* The hash value for RHS/ann. */
143 hashval_t hash;
146 /* Stack of dest,src pairs that need to be restored during finalization.
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;
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;
156 /* Stack of SSA_NAMEs which need their NONZERO_VARS property cleared
157 when the current block is finalized.
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;
163 /* Track whether or not we have changed the control flow graph. */
164 static bool cfg_altered;
166 /* Bitmap of blocks that have had EH statements cleaned. We should
167 remove their dead edges eventually. */
168 static bitmap need_eh_cleanup;
170 /* Statistics for dominator optimizations. */
171 struct opt_stats_d
173 long num_stmts;
174 long num_exprs_considered;
175 long num_re;
178 static struct opt_stats_d opt_stats;
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.
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.
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.
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.
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.
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.
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. */
211 struct vrp_element
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.
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;
222 /* The actual conditional we recorded. This is needed since we compute
223 ranges lazily. */
224 tree cond;
226 /* The basic block where this record was created. We use this to determine
227 when to remove records. */
228 basic_block bb;
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;
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
241 tree var;
242 varray_type records;
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. */
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.
253 A NULL entry marks the end of the SSA_NAMEs associated with this block. */
254 static VEC(tree_on_heap) *vrp_variables_stack;
256 struct eq_expr_value
258 tree src;
259 tree dst;
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);
301 /* Local version of fold that doesn't introduce cruft. */
303 static tree
304 local_fold (tree t)
306 t = fold (t);
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);
313 return t;
316 /* Allocate an EDGE_INFO for edge E and attach it to E.
317 Return the new EDGE_INFO structure. */
319 static struct edge_info *
320 allocate_edge_info (edge e)
322 struct edge_info *edge_info;
324 edge_info = xcalloc (1, sizeof (struct edge_info));
326 e->aux = edge_info;
327 return edge_info;
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. */
336 static void
337 free_all_edge_infos (void)
339 basic_block bb;
340 edge_iterator ei;
341 edge e;
343 FOR_EACH_BB (bb)
345 FOR_EACH_EDGE (e, ei, bb->preds)
347 struct edge_info *edge_info = e->aux;
349 if (edge_info)
351 e->aux = edge_info->redirection_target;
352 if (edge_info->cond_equivalences)
353 free (edge_info->cond_equivalences);
354 free (edge_info);
360 /* Jump threading, redundancy elimination and const/copy propagation.
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. */
366 static void
367 tree_ssa_dominator_optimize (void)
369 struct dom_walk_data walk_data;
370 unsigned int i;
372 memset (&opt_stats, 0, sizeof (opt_stats));
374 for (i = 0; i < num_referenced_vars; i++)
375 var_ann (referenced_var (i))->current_def = NULL;
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 ();
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 ();
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;
410 /* Now initialize the dominator walker. */
411 init_walk_dominator_tree (&walk_data);
413 calculate_dominance_info (CDI_DOMINATORS);
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. */
422 /* Optimize the dominator tree. */
423 cfg_altered = false;
425 /* Recursively walk the dominator tree optimizing statements. */
426 walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);
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))
435 rewrite_into_ssa (false);
436 bitmap_clear (vars_to_rename);
439 free_all_edge_infos ();
441 /* Thread jumps, creating duplicate blocks as needed. */
442 cfg_altered = thread_through_all_blocks ();
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))
448 cfg_altered |= tree_purge_all_dead_eh_edges (need_eh_cleanup);
449 bitmap_zero (need_eh_cleanup);
452 free_dominance_info (CDI_DOMINATORS);
453 cfg_altered = cleanup_tree_cfg ();
454 calculate_dominance_info (CDI_DOMINATORS);
456 rewrite_ssa_into_ssa ();
458 /* Reinitialize the various tables. */
459 bitmap_clear (nonzero_vars);
460 htab_empty (avail_exprs);
461 htab_empty (vrp_data);
463 for (i = 0; i < num_referenced_vars; i++)
464 var_ann (referenced_var (i))->current_def = NULL;
466 while (cfg_altered);
468 /* Debugging dumps. */
469 if (dump_file && (dump_flags & TDF_STATS))
470 dump_dominator_optimization_stats (dump_file);
472 /* We emptied the hash table earlier, now delete it completely. */
473 htab_delete (avail_exprs);
474 htab_delete (vrp_data);
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. */
480 /* And finalize the dominator walker. */
481 fini_walk_dominator_tree (&walk_data);
483 /* Free nonzero_vars. */
484 BITMAP_XFREE (nonzero_vars);
485 BITMAP_XFREE (need_eh_cleanup);
487 /* Finally, remove everything except invariants in SSA_NAME_VALUE.
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++)
494 tree name = ssa_name (i);
495 tree value;
497 if (!name)
498 continue;
500 value = SSA_NAME_VALUE (name);
501 if (value && !is_gimple_min_invariant (value))
502 SSA_NAME_VALUE (name) = NULL;
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);
513 static bool
514 gate_dominator (void)
516 return flag_tree_dom != 0;
519 struct tree_opt_pass pass_dominator =
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 */
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. */
541 static void
542 thread_across_edge (struct dom_walk_data *walk_data, edge e)
544 block_stmt_iterator bsi;
545 tree stmt = NULL;
546 tree phi;
548 /* Each PHI creates a temporary equivalence, record them. */
549 for (phi = phi_nodes (e->dest); phi; phi = PHI_CHAIN (phi))
551 tree src = PHI_ARG_DEF_FROM_EDGE (phi, e);
552 tree dst = PHI_RESULT (phi);
553 record_const_or_copy (dst, src);
554 register_new_def (dst, &block_defs_stack);
557 for (bsi = bsi_start (e->dest); ! bsi_end_p (bsi); bsi_next (&bsi))
559 tree lhs, cached_lhs;
561 stmt = bsi_stmt (bsi);
563 /* Ignore empty statements and labels. */
564 if (IS_EMPTY_STMT (stmt) || TREE_CODE (stmt) == LABEL_EXPR)
565 continue;
567 /* If this is not a MODIFY_EXPR which sets an SSA_NAME to a new
568 value, then stop our search here. Ideally when we stop a
569 search we stop on a COND_EXPR or SWITCH_EXPR. */
570 if (TREE_CODE (stmt) != MODIFY_EXPR
571 || TREE_CODE (TREE_OPERAND (stmt, 0)) != SSA_NAME)
572 break;
574 /* At this point we have a statement which assigns an RHS to an
575 SSA_VAR on the LHS. We want to prove that the RHS is already
576 available and that its value is held in the current definition
577 of the LHS -- meaning that this assignment is a NOP when
578 reached via edge E. */
579 if (TREE_CODE (TREE_OPERAND (stmt, 1)) == SSA_NAME)
580 cached_lhs = TREE_OPERAND (stmt, 1);
581 else
582 cached_lhs = lookup_avail_expr (stmt, false);
584 lhs = TREE_OPERAND (stmt, 0);
586 /* This can happen if we thread around to the start of a loop. */
587 if (lhs == cached_lhs)
588 break;
590 /* If we did not find RHS in the hash table, then try again after
591 temporarily const/copy propagating the operands. */
592 if (!cached_lhs)
594 /* Copy the operands. */
595 stmt_ann_t ann = stmt_ann (stmt);
596 use_optype uses = USE_OPS (ann);
597 vuse_optype vuses = VUSE_OPS (ann);
598 tree *uses_copy = xcalloc (NUM_USES (uses), sizeof (tree));
599 tree *vuses_copy = xcalloc (NUM_VUSES (vuses), sizeof (tree));
600 unsigned int i;
602 /* Make a copy of the uses into USES_COPY, then cprop into
603 the use operands. */
604 for (i = 0; i < NUM_USES (uses); i++)
606 tree tmp = NULL;
608 uses_copy[i] = USE_OP (uses, i);
609 if (TREE_CODE (USE_OP (uses, i)) == SSA_NAME)
610 tmp = SSA_NAME_VALUE (USE_OP (uses, i));
611 if (tmp && TREE_CODE (tmp) != VALUE_HANDLE)
612 SET_USE_OP (uses, i, tmp);
615 /* Similarly for virtual uses. */
616 for (i = 0; i < NUM_VUSES (vuses); i++)
618 tree tmp = NULL;
620 vuses_copy[i] = VUSE_OP (vuses, i);
621 if (TREE_CODE (VUSE_OP (vuses, i)) == SSA_NAME)
622 tmp = SSA_NAME_VALUE (VUSE_OP (vuses, i));
623 if (tmp && TREE_CODE (tmp) != VALUE_HANDLE)
624 SET_VUSE_OP (vuses, i, tmp);
627 /* Try to lookup the new expression. */
628 cached_lhs = lookup_avail_expr (stmt, false);
630 /* Restore the statement's original uses/defs. */
631 for (i = 0; i < NUM_USES (uses); i++)
632 SET_USE_OP (uses, i, uses_copy[i]);
634 for (i = 0; i < NUM_VUSES (vuses); i++)
635 SET_VUSE_OP (vuses, i, vuses_copy[i]);
637 free (uses_copy);
638 free (vuses_copy);
640 /* If we still did not find the expression in the hash table,
641 then we can not ignore this statement. */
642 if (! cached_lhs)
643 break;
646 /* If the expression in the hash table was not assigned to an
647 SSA_NAME, then we can not ignore this statement. */
648 if (TREE_CODE (cached_lhs) != SSA_NAME)
649 break;
651 /* If we have different underlying variables, then we can not
652 ignore this statement. */
653 if (SSA_NAME_VAR (cached_lhs) != SSA_NAME_VAR (lhs))
654 break;
656 /* If CACHED_LHS does not represent the current value of the undering
657 variable in CACHED_LHS/LHS, then we can not ignore this statement. */
658 if (var_ann (SSA_NAME_VAR (lhs))->current_def != cached_lhs)
659 break;
661 /* If we got here, then we can ignore this statement and continue
662 walking through the statements in the block looking for a threadable
663 COND_EXPR.
665 We want to record an equivalence lhs = cache_lhs so that if
666 the result of this statement is used later we can copy propagate
667 suitably. */
668 record_const_or_copy (lhs, cached_lhs);
669 register_new_def (lhs, &block_defs_stack);
672 /* If we stopped at a COND_EXPR or SWITCH_EXPR, then see if we know which
673 arm will be taken. */
674 if (stmt
675 && (TREE_CODE (stmt) == COND_EXPR
676 || TREE_CODE (stmt) == SWITCH_EXPR))
678 tree cond, cached_lhs;
679 edge e1;
680 edge_iterator ei;
682 /* Do not forward entry edges into the loop. In the case loop
683 has multiple entry edges we may end up in constructing irreducible
684 region.
685 ??? We may consider forwarding the edges in the case all incoming
686 edges forward to the same destination block. */
687 if (!e->flags & EDGE_DFS_BACK)
689 FOR_EACH_EDGE (e1, ei, e->dest->preds)
690 if (e1->flags & EDGE_DFS_BACK)
691 break;
692 if (e1)
693 return;
696 /* Now temporarily cprop the operands and try to find the resulting
697 expression in the hash tables. */
698 if (TREE_CODE (stmt) == COND_EXPR)
699 cond = COND_EXPR_COND (stmt);
700 else
701 cond = SWITCH_COND (stmt);
703 if (COMPARISON_CLASS_P (cond))
705 tree dummy_cond, op0, op1;
706 enum tree_code cond_code;
708 op0 = TREE_OPERAND (cond, 0);
709 op1 = TREE_OPERAND (cond, 1);
710 cond_code = TREE_CODE (cond);
712 /* Get the current value of both operands. */
713 if (TREE_CODE (op0) == SSA_NAME)
715 tree tmp = SSA_NAME_VALUE (op0);
716 if (tmp && TREE_CODE (tmp) != VALUE_HANDLE)
717 op0 = tmp;
720 if (TREE_CODE (op1) == SSA_NAME)
722 tree tmp = SSA_NAME_VALUE (op1);
723 if (tmp && TREE_CODE (tmp) != VALUE_HANDLE)
724 op1 = tmp;
727 /* Stuff the operator and operands into our dummy conditional
728 expression, creating the dummy conditional if necessary. */
729 dummy_cond = walk_data->global_data;
730 if (! dummy_cond)
732 dummy_cond = build (cond_code, boolean_type_node, op0, op1);
733 dummy_cond = build (COND_EXPR, void_type_node,
734 dummy_cond, NULL, NULL);
735 walk_data->global_data = dummy_cond;
737 else
739 TREE_SET_CODE (COND_EXPR_COND (dummy_cond), cond_code);
740 TREE_OPERAND (COND_EXPR_COND (dummy_cond), 0) = op0;
741 TREE_OPERAND (COND_EXPR_COND (dummy_cond), 1) = op1;
744 /* If the conditional folds to an invariant, then we are done,
745 otherwise look it up in the hash tables. */
746 cached_lhs = local_fold (COND_EXPR_COND (dummy_cond));
747 if (! is_gimple_min_invariant (cached_lhs))
748 cached_lhs = lookup_avail_expr (dummy_cond, false);
749 if (!cached_lhs || ! is_gimple_min_invariant (cached_lhs))
751 cached_lhs = simplify_cond_and_lookup_avail_expr (dummy_cond,
752 NULL,
753 false);
756 /* We can have conditionals which just test the state of a
757 variable rather than use a relational operator. These are
758 simpler to handle. */
759 else if (TREE_CODE (cond) == SSA_NAME)
761 cached_lhs = cond;
762 cached_lhs = SSA_NAME_VALUE (cached_lhs);
763 if (cached_lhs && ! is_gimple_min_invariant (cached_lhs))
764 cached_lhs = 0;
766 else
767 cached_lhs = lookup_avail_expr (stmt, false);
769 if (cached_lhs)
771 edge taken_edge = find_taken_edge (e->dest, cached_lhs);
772 basic_block dest = (taken_edge ? taken_edge->dest : NULL);
774 if (dest == e->dest)
775 return;
777 /* If we have a known destination for the conditional, then
778 we can perform this optimization, which saves at least one
779 conditional jump each time it applies since we get to
780 bypass the conditional at our original destination. */
781 if (dest)
783 struct edge_info *edge_info;
785 update_bb_profile_for_threading (e->dest, EDGE_FREQUENCY (e),
786 e->count, taken_edge);
787 if (e->aux)
788 edge_info = e->aux;
789 else
790 edge_info = allocate_edge_info (e);
791 edge_info->redirection_target = taken_edge;
792 bb_ann (e->dest)->incoming_edge_threaded = true;
799 /* Initialize local stacks for this optimizer and record equivalences
800 upon entry to BB. Equivalences can come from the edge traversed to
801 reach BB or they may come from PHI nodes at the start of BB. */
803 static void
804 dom_opt_initialize_block (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
805 basic_block bb)
807 if (dump_file && (dump_flags & TDF_DETAILS))
808 fprintf (dump_file, "\n\nOptimizing block #%d\n\n", bb->index);
810 /* Push a marker on the stacks of local information so that we know how
811 far to unwind when we finalize this block. */
812 VEC_safe_push (tree_on_heap, avail_exprs_stack, NULL_TREE);
813 VEC_safe_push (tree_on_heap, block_defs_stack, NULL_TREE);
814 VEC_safe_push (tree_on_heap, const_and_copies_stack, NULL_TREE);
815 VEC_safe_push (tree_on_heap, nonzero_vars_stack, NULL_TREE);
816 VEC_safe_push (tree_on_heap, vrp_variables_stack, NULL_TREE);
818 record_equivalences_from_incoming_edge (bb);
820 /* PHI nodes can create equivalences too. */
821 record_equivalences_from_phis (bb);
824 /* Given an expression EXPR (a relational expression or a statement),
825 initialize the hash table element pointed by by ELEMENT. */
827 static void
828 initialize_hash_element (tree expr, tree lhs, struct expr_hash_elt *element)
830 /* Hash table elements may be based on conditional expressions or statements.
832 For the former case, we have no annotation and we want to hash the
833 conditional expression. In the latter case we have an annotation and
834 we want to record the expression the statement evaluates. */
835 if (COMPARISON_CLASS_P (expr) || TREE_CODE (expr) == TRUTH_NOT_EXPR)
837 element->ann = NULL;
838 element->rhs = expr;
840 else if (TREE_CODE (expr) == COND_EXPR)
842 element->ann = stmt_ann (expr);
843 element->rhs = COND_EXPR_COND (expr);
845 else if (TREE_CODE (expr) == SWITCH_EXPR)
847 element->ann = stmt_ann (expr);
848 element->rhs = SWITCH_COND (expr);
850 else if (TREE_CODE (expr) == RETURN_EXPR && TREE_OPERAND (expr, 0))
852 element->ann = stmt_ann (expr);
853 element->rhs = TREE_OPERAND (TREE_OPERAND (expr, 0), 1);
855 else
857 element->ann = stmt_ann (expr);
858 element->rhs = TREE_OPERAND (expr, 1);
861 element->lhs = lhs;
862 element->hash = avail_expr_hash (element);
865 /* Remove all the expressions in LOCALS from TABLE, stopping when there are
866 LIMIT entries left in LOCALs. */
868 static void
869 remove_local_expressions_from_table (void)
871 /* Remove all the expressions made available in this block. */
872 while (VEC_length (tree_on_heap, avail_exprs_stack) > 0)
874 struct expr_hash_elt element;
875 tree expr = VEC_pop (tree_on_heap, avail_exprs_stack);
877 if (expr == NULL_TREE)
878 break;
880 initialize_hash_element (expr, NULL, &element);
881 htab_remove_elt_with_hash (avail_exprs, &element, element.hash);
885 /* Use the SSA_NAMES in LOCALS to restore TABLE to its original
886 state, stopping when there are LIMIT entries left in LOCALs. */
888 static void
889 restore_nonzero_vars_to_original_value (void)
891 while (VEC_length (tree_on_heap, nonzero_vars_stack) > 0)
893 tree name = VEC_pop (tree_on_heap, nonzero_vars_stack);
895 if (name == NULL)
896 break;
898 bitmap_clear_bit (nonzero_vars, SSA_NAME_VERSION (name));
902 /* Use the source/dest pairs in CONST_AND_COPIES_STACK to restore
903 CONST_AND_COPIES to its original state, stopping when we hit a
904 NULL marker. */
906 static void
907 restore_vars_to_original_value (void)
909 while (VEC_length (tree_on_heap, const_and_copies_stack) > 0)
911 tree prev_value, dest;
913 dest = VEC_pop (tree_on_heap, const_and_copies_stack);
915 if (dest == NULL)
916 break;
918 prev_value = VEC_pop (tree_on_heap, const_and_copies_stack);
919 SSA_NAME_VALUE (dest) = prev_value;
923 /* Similar to restore_vars_to_original_value, except that it restores
924 CURRDEFS to its original value. */
925 static void
926 restore_currdefs_to_original_value (void)
928 /* Restore CURRDEFS to its original state. */
929 while (VEC_length (tree_on_heap, block_defs_stack) > 0)
931 tree tmp = VEC_pop (tree_on_heap, block_defs_stack);
932 tree saved_def, var;
934 if (tmp == NULL_TREE)
935 break;
937 /* If we recorded an SSA_NAME, then make the SSA_NAME the current
938 definition of its underlying variable. If we recorded anything
939 else, it must have been an _DECL node and its current reaching
940 definition must have been NULL. */
941 if (TREE_CODE (tmp) == SSA_NAME)
943 saved_def = tmp;
944 var = SSA_NAME_VAR (saved_def);
946 else
948 saved_def = NULL;
949 var = tmp;
952 var_ann (var)->current_def = saved_def;
956 /* We have finished processing the dominator children of BB, perform
957 any finalization actions in preparation for leaving this node in
958 the dominator tree. */
960 static void
961 dom_opt_finalize_block (struct dom_walk_data *walk_data, basic_block bb)
963 tree last;
965 /* If we are at a leaf node in the dominator graph, see if we can thread
966 the edge from BB through its successor.
968 Do this before we remove entries from our equivalence tables. */
969 if (EDGE_COUNT (bb->succs) == 1
970 && (EDGE_SUCC (bb, 0)->flags & EDGE_ABNORMAL) == 0
971 && (get_immediate_dominator (CDI_DOMINATORS, EDGE_SUCC (bb, 0)->dest) != bb
972 || phi_nodes (EDGE_SUCC (bb, 0)->dest)))
975 thread_across_edge (walk_data, EDGE_SUCC (bb, 0));
977 else if ((last = last_stmt (bb))
978 && TREE_CODE (last) == COND_EXPR
979 && (COMPARISON_CLASS_P (COND_EXPR_COND (last))
980 || TREE_CODE (COND_EXPR_COND (last)) == SSA_NAME)
981 && EDGE_COUNT (bb->succs) == 2
982 && (EDGE_SUCC (bb, 0)->flags & EDGE_ABNORMAL) == 0
983 && (EDGE_SUCC (bb, 1)->flags & EDGE_ABNORMAL) == 0)
985 edge true_edge, false_edge;
987 extract_true_false_edges_from_block (bb, &true_edge, &false_edge);
989 /* If the THEN arm is the end of a dominator tree or has PHI nodes,
990 then try to thread through its edge. */
991 if (get_immediate_dominator (CDI_DOMINATORS, true_edge->dest) != bb
992 || phi_nodes (true_edge->dest))
994 struct edge_info *edge_info;
995 unsigned int i;
997 /* Push a marker onto the available expression stack so that we
998 unwind any expressions related to the TRUE arm before processing
999 the false arm below. */
1000 VEC_safe_push (tree_on_heap, avail_exprs_stack, NULL_TREE);
1001 VEC_safe_push (tree_on_heap, block_defs_stack, NULL_TREE);
1002 VEC_safe_push (tree_on_heap, const_and_copies_stack, NULL_TREE);
1004 edge_info = true_edge->aux;
1006 /* If we have info associated with this edge, record it into
1007 our equivalency tables. */
1008 if (edge_info)
1010 tree *cond_equivalences = edge_info->cond_equivalences;
1011 tree lhs = edge_info->lhs;
1012 tree rhs = edge_info->rhs;
1014 /* If we have a simple NAME = VALUE equivalency record it.
1015 Until the jump threading selection code improves, only
1016 do this if both the name and value are SSA_NAMEs with
1017 the same underlying variable to avoid missing threading
1018 opportunities. */
1019 if (lhs
1020 && TREE_CODE (COND_EXPR_COND (last)) == SSA_NAME
1021 && TREE_CODE (edge_info->rhs) == SSA_NAME
1022 && SSA_NAME_VAR (lhs) == SSA_NAME_VAR (rhs))
1023 record_const_or_copy (lhs, rhs);
1025 /* If we have 0 = COND or 1 = COND equivalences, record them
1026 into our expression hash tables. */
1027 if (cond_equivalences)
1028 for (i = 0; i < edge_info->max_cond_equivalences; i += 2)
1030 tree expr = cond_equivalences[i];
1031 tree value = cond_equivalences[i + 1];
1033 record_cond (expr, value);
1037 /* Now thread the edge. */
1038 thread_across_edge (walk_data, true_edge);
1040 /* And restore the various tables to their state before
1041 we threaded this edge. */
1042 remove_local_expressions_from_table ();
1043 restore_vars_to_original_value ();
1044 restore_currdefs_to_original_value ();
1047 /* Similarly for the ELSE arm. */
1048 if (get_immediate_dominator (CDI_DOMINATORS, false_edge->dest) != bb
1049 || phi_nodes (false_edge->dest))
1051 struct edge_info *edge_info;
1052 unsigned int i;
1054 edge_info = false_edge->aux;
1056 /* If we have info associated with this edge, record it into
1057 our equivalency tables. */
1058 if (edge_info)
1060 tree *cond_equivalences = edge_info->cond_equivalences;
1061 tree lhs = edge_info->lhs;
1062 tree rhs = edge_info->rhs;
1064 /* If we have a simple NAME = VALUE equivalency record it.
1065 Until the jump threading selection code improves, only
1066 do this if both the name and value are SSA_NAMEs with
1067 the same underlying variable to avoid missing threading
1068 opportunities. */
1069 if (lhs
1070 && TREE_CODE (COND_EXPR_COND (last)) == SSA_NAME)
1071 record_const_or_copy (lhs, rhs);
1073 /* If we have 0 = COND or 1 = COND equivalences, record them
1074 into our expression hash tables. */
1075 if (cond_equivalences)
1076 for (i = 0; i < edge_info->max_cond_equivalences; i += 2)
1078 tree expr = cond_equivalences[i];
1079 tree value = cond_equivalences[i + 1];
1081 record_cond (expr, value);
1085 thread_across_edge (walk_data, false_edge);
1087 /* No need to remove local expressions from our tables
1088 or restore vars to their original value as that will
1089 be done immediately below. */
1093 remove_local_expressions_from_table ();
1094 restore_nonzero_vars_to_original_value ();
1095 restore_vars_to_original_value ();
1096 restore_currdefs_to_original_value ();
1098 /* Remove VRP records associated with this basic block. They are no
1099 longer valid.
1101 To be efficient, we note which variables have had their values
1102 constrained in this block. So walk over each variable in the
1103 VRP_VARIABLEs array. */
1104 while (VEC_length (tree_on_heap, vrp_variables_stack) > 0)
1106 tree var = VEC_pop (tree_on_heap, vrp_variables_stack);
1107 struct vrp_hash_elt vrp_hash_elt, *vrp_hash_elt_p;
1108 void **slot;
1110 /* Each variable has a stack of value range records. We want to
1111 invalidate those associated with our basic block. So we walk
1112 the array backwards popping off records associated with our
1113 block. Once we hit a record not associated with our block
1114 we are done. */
1115 varray_type var_vrp_records;
1117 if (var == NULL)
1118 break;
1120 vrp_hash_elt.var = var;
1121 vrp_hash_elt.records = NULL;
1123 slot = htab_find_slot (vrp_data, &vrp_hash_elt, NO_INSERT);
1125 vrp_hash_elt_p = (struct vrp_hash_elt *) *slot;
1126 var_vrp_records = vrp_hash_elt_p->records;
1128 while (VARRAY_ACTIVE_SIZE (var_vrp_records) > 0)
1130 struct vrp_element *element
1131 = (struct vrp_element *)VARRAY_TOP_GENERIC_PTR (var_vrp_records);
1133 if (element->bb != bb)
1134 break;
1136 VARRAY_POP (var_vrp_records);
1140 /* If we queued any statements to rescan in this block, then
1141 go ahead and rescan them now. */
1142 while (VEC_length (tree_on_heap, stmts_to_rescan) > 0)
1144 tree stmt = VEC_last (tree_on_heap, stmts_to_rescan);
1145 basic_block stmt_bb = bb_for_stmt (stmt);
1147 if (stmt_bb != bb)
1148 break;
1150 VEC_pop (tree_on_heap, stmts_to_rescan);
1151 mark_new_vars_to_rename (stmt, vars_to_rename);
1155 /* PHI nodes can create equivalences too.
1157 Ignoring any alternatives which are the same as the result, if
1158 all the alternatives are equal, then the PHI node creates an
1159 equivalence.
1161 Additionally, if all the PHI alternatives are known to have a nonzero
1162 value, then the result of this PHI is known to have a nonzero value,
1163 even if we do not know its exact value. */
1165 static void
1166 record_equivalences_from_phis (basic_block bb)
1168 tree phi;
1170 for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
1172 tree lhs = PHI_RESULT (phi);
1173 tree rhs = NULL;
1174 int i;
1176 for (i = 0; i < PHI_NUM_ARGS (phi); i++)
1178 tree t = PHI_ARG_DEF (phi, i);
1180 if (TREE_CODE (t) == SSA_NAME || is_gimple_min_invariant (t))
1182 /* Ignore alternatives which are the same as our LHS. */
1183 if (operand_equal_for_phi_arg_p (lhs, t))
1184 continue;
1186 /* If we have not processed an alternative yet, then set
1187 RHS to this alternative. */
1188 if (rhs == NULL)
1189 rhs = t;
1190 /* If we have processed an alternative (stored in RHS), then
1191 see if it is equal to this one. If it isn't, then stop
1192 the search. */
1193 else if (! operand_equal_for_phi_arg_p (rhs, t))
1194 break;
1196 else
1197 break;
1200 /* If we had no interesting alternatives, then all the RHS alternatives
1201 must have been the same as LHS. */
1202 if (!rhs)
1203 rhs = lhs;
1205 /* If we managed to iterate through each PHI alternative without
1206 breaking out of the loop, then we have a PHI which may create
1207 a useful equivalence. We do not need to record unwind data for
1208 this, since this is a true assignment and not an equivalence
1209 inferred from a comparison. All uses of this ssa name are dominated
1210 by this assignment, so unwinding just costs time and space. */
1211 if (i == PHI_NUM_ARGS (phi)
1212 && may_propagate_copy (lhs, rhs))
1213 SSA_NAME_VALUE (lhs) = rhs;
1215 /* Now see if we know anything about the nonzero property for the
1216 result of this PHI. */
1217 for (i = 0; i < PHI_NUM_ARGS (phi); i++)
1219 if (!PHI_ARG_NONZERO (phi, i))
1220 break;
1223 if (i == PHI_NUM_ARGS (phi))
1224 bitmap_set_bit (nonzero_vars, SSA_NAME_VERSION (PHI_RESULT (phi)));
1226 register_new_def (lhs, &block_defs_stack);
1230 /* Ignoring loop backedges, if BB has precisely one incoming edge then
1231 return that edge. Otherwise return NULL. */
1232 static edge
1233 single_incoming_edge_ignoring_loop_edges (basic_block bb)
1235 edge retval = NULL;
1236 edge e;
1237 edge_iterator ei;
1239 FOR_EACH_EDGE (e, ei, bb->preds)
1241 /* A loop back edge can be identified by the destination of
1242 the edge dominating the source of the edge. */
1243 if (dominated_by_p (CDI_DOMINATORS, e->src, e->dest))
1244 continue;
1246 /* If we have already seen a non-loop edge, then we must have
1247 multiple incoming non-loop edges and thus we return NULL. */
1248 if (retval)
1249 return NULL;
1251 /* This is the first non-loop incoming edge we have found. Record
1252 it. */
1253 retval = e;
1256 return retval;
1259 /* Record any equivalences created by the incoming edge to BB. If BB
1260 has more than one incoming edge, then no equivalence is created. */
1262 static void
1263 record_equivalences_from_incoming_edge (basic_block bb)
1265 edge e;
1266 basic_block parent;
1267 struct edge_info *edge_info;
1269 /* If our parent block ended with a control statment, then we may be
1270 able to record some equivalences based on which outgoing edge from
1271 the parent was followed. */
1272 parent = get_immediate_dominator (CDI_DOMINATORS, bb);
1274 e = single_incoming_edge_ignoring_loop_edges (bb);
1276 /* If we had a single incoming edge from our parent block, then enter
1277 any data associated with the edge into our tables. */
1278 if (e && e->src == parent)
1280 unsigned int i;
1282 edge_info = e->aux;
1284 if (edge_info)
1286 tree lhs = edge_info->lhs;
1287 tree rhs = edge_info->rhs;
1288 tree *cond_equivalences = edge_info->cond_equivalences;
1290 if (lhs)
1291 record_equality (lhs, rhs);
1293 if (cond_equivalences)
1295 bool recorded_range = false;
1296 for (i = 0; i < edge_info->max_cond_equivalences; i += 2)
1298 tree expr = cond_equivalences[i];
1299 tree value = cond_equivalences[i + 1];
1301 record_cond (expr, value);
1303 /* For the first true equivalence, record range
1304 information. We only do this for the first
1305 true equivalence as it should dominate any
1306 later true equivalences. */
1307 if (! recorded_range
1308 && COMPARISON_CLASS_P (expr)
1309 && value == boolean_true_node
1310 && TREE_CONSTANT (TREE_OPERAND (expr, 1)))
1312 record_range (expr, bb);
1313 recorded_range = true;
1321 /* Dump SSA statistics on FILE. */
1323 void
1324 dump_dominator_optimization_stats (FILE *file)
1326 long n_exprs;
1328 fprintf (file, "Total number of statements: %6ld\n\n",
1329 opt_stats.num_stmts);
1330 fprintf (file, "Exprs considered for dominator optimizations: %6ld\n",
1331 opt_stats.num_exprs_considered);
1333 n_exprs = opt_stats.num_exprs_considered;
1334 if (n_exprs == 0)
1335 n_exprs = 1;
1337 fprintf (file, " Redundant expressions eliminated: %6ld (%.0f%%)\n",
1338 opt_stats.num_re, PERCENT (opt_stats.num_re,
1339 n_exprs));
1341 fprintf (file, "\nHash table statistics:\n");
1343 fprintf (file, " avail_exprs: ");
1344 htab_statistics (file, avail_exprs);
1348 /* Dump SSA statistics on stderr. */
1350 void
1351 debug_dominator_optimization_stats (void)
1353 dump_dominator_optimization_stats (stderr);
1357 /* Dump statistics for the hash table HTAB. */
1359 static void
1360 htab_statistics (FILE *file, htab_t htab)
1362 fprintf (file, "size %ld, %ld elements, %f collision/search ratio\n",
1363 (long) htab_size (htab),
1364 (long) htab_elements (htab),
1365 htab_collisions (htab));
1368 /* Record the fact that VAR has a nonzero value, though we may not know
1369 its exact value. Note that if VAR is already known to have a nonzero
1370 value, then we do nothing. */
1372 static void
1373 record_var_is_nonzero (tree var)
1375 int indx = SSA_NAME_VERSION (var);
1377 if (bitmap_bit_p (nonzero_vars, indx))
1378 return;
1380 /* Mark it in the global table. */
1381 bitmap_set_bit (nonzero_vars, indx);
1383 /* Record this SSA_NAME so that we can reset the global table
1384 when we leave this block. */
1385 VEC_safe_push (tree_on_heap, nonzero_vars_stack, var);
1388 /* Enter a statement into the true/false expression hash table indicating
1389 that the condition COND has the value VALUE. */
1391 static void
1392 record_cond (tree cond, tree value)
1394 struct expr_hash_elt *element = xmalloc (sizeof (struct expr_hash_elt));
1395 void **slot;
1397 initialize_hash_element (cond, value, element);
1399 slot = htab_find_slot_with_hash (avail_exprs, (void *)element,
1400 element->hash, true);
1401 if (*slot == NULL)
1403 *slot = (void *) element;
1404 VEC_safe_push (tree_on_heap, avail_exprs_stack, cond);
1406 else
1407 free (element);
1410 /* Build a new conditional using NEW_CODE, OP0 and OP1 and store
1411 the new conditional into *p, then store a boolean_true_node
1412 into the the *(p + 1). */
1414 static void
1415 build_and_record_new_cond (enum tree_code new_code, tree op0, tree op1, tree *p)
1417 *p = build2 (new_code, boolean_type_node, op0, op1);
1418 p++;
1419 *p = boolean_true_node;
1422 /* Record that COND is true and INVERTED is false into the edge information
1423 structure. Also record that any conditions dominated by COND are true
1424 as well.
1426 For example, if a < b is true, then a <= b must also be true. */
1428 static void
1429 record_conditions (struct edge_info *edge_info, tree cond, tree inverted)
1431 tree op0, op1;
1433 if (!COMPARISON_CLASS_P (cond))
1434 return;
1436 op0 = TREE_OPERAND (cond, 0);
1437 op1 = TREE_OPERAND (cond, 1);
1439 switch (TREE_CODE (cond))
1441 case LT_EXPR:
1442 case GT_EXPR:
1443 edge_info->max_cond_equivalences = 12;
1444 edge_info->cond_equivalences = xmalloc (12 * sizeof (tree));
1445 build_and_record_new_cond ((TREE_CODE (cond) == LT_EXPR
1446 ? LE_EXPR : GE_EXPR),
1447 op0, op1, &edge_info->cond_equivalences[4]);
1448 build_and_record_new_cond (ORDERED_EXPR, op0, op1,
1449 &edge_info->cond_equivalences[6]);
1450 build_and_record_new_cond (NE_EXPR, op0, op1,
1451 &edge_info->cond_equivalences[8]);
1452 build_and_record_new_cond (LTGT_EXPR, op0, op1,
1453 &edge_info->cond_equivalences[10]);
1454 break;
1456 case GE_EXPR:
1457 case LE_EXPR:
1458 edge_info->max_cond_equivalences = 6;
1459 edge_info->cond_equivalences = xmalloc (6 * sizeof (tree));
1460 build_and_record_new_cond (ORDERED_EXPR, op0, op1,
1461 &edge_info->cond_equivalences[4]);
1462 break;
1464 case EQ_EXPR:
1465 edge_info->max_cond_equivalences = 10;
1466 edge_info->cond_equivalences = xmalloc (10 * sizeof (tree));
1467 build_and_record_new_cond (ORDERED_EXPR, op0, op1,
1468 &edge_info->cond_equivalences[4]);
1469 build_and_record_new_cond (LE_EXPR, op0, op1,
1470 &edge_info->cond_equivalences[6]);
1471 build_and_record_new_cond (GE_EXPR, op0, op1,
1472 &edge_info->cond_equivalences[8]);
1473 break;
1475 case UNORDERED_EXPR:
1476 edge_info->max_cond_equivalences = 16;
1477 edge_info->cond_equivalences = xmalloc (16 * sizeof (tree));
1478 build_and_record_new_cond (NE_EXPR, op0, op1,
1479 &edge_info->cond_equivalences[4]);
1480 build_and_record_new_cond (UNLE_EXPR, op0, op1,
1481 &edge_info->cond_equivalences[6]);
1482 build_and_record_new_cond (UNGE_EXPR, op0, op1,
1483 &edge_info->cond_equivalences[8]);
1484 build_and_record_new_cond (UNEQ_EXPR, op0, op1,
1485 &edge_info->cond_equivalences[10]);
1486 build_and_record_new_cond (UNLT_EXPR, op0, op1,
1487 &edge_info->cond_equivalences[12]);
1488 build_and_record_new_cond (UNGT_EXPR, op0, op1,
1489 &edge_info->cond_equivalences[14]);
1490 break;
1492 case UNLT_EXPR:
1493 case UNGT_EXPR:
1494 edge_info->max_cond_equivalences = 8;
1495 edge_info->cond_equivalences = xmalloc (8 * sizeof (tree));
1496 build_and_record_new_cond ((TREE_CODE (cond) == UNLT_EXPR
1497 ? UNLE_EXPR : UNGE_EXPR),
1498 op0, op1, &edge_info->cond_equivalences[4]);
1499 build_and_record_new_cond (NE_EXPR, op0, op1,
1500 &edge_info->cond_equivalences[6]);
1501 break;
1503 case UNEQ_EXPR:
1504 edge_info->max_cond_equivalences = 8;
1505 edge_info->cond_equivalences = xmalloc (8 * sizeof (tree));
1506 build_and_record_new_cond (UNLE_EXPR, op0, op1,
1507 &edge_info->cond_equivalences[4]);
1508 build_and_record_new_cond (UNGE_EXPR, op0, op1,
1509 &edge_info->cond_equivalences[6]);
1510 break;
1512 case LTGT_EXPR:
1513 edge_info->max_cond_equivalences = 8;
1514 edge_info->cond_equivalences = xmalloc (8 * sizeof (tree));
1515 build_and_record_new_cond (NE_EXPR, op0, op1,
1516 &edge_info->cond_equivalences[4]);
1517 build_and_record_new_cond (ORDERED_EXPR, op0, op1,
1518 &edge_info->cond_equivalences[6]);
1519 break;
1521 default:
1522 edge_info->max_cond_equivalences = 4;
1523 edge_info->cond_equivalences = xmalloc (4 * sizeof (tree));
1524 break;
1527 /* Now store the original true and false conditions into the first
1528 two slots. */
1529 edge_info->cond_equivalences[0] = cond;
1530 edge_info->cond_equivalences[1] = boolean_true_node;
1531 edge_info->cond_equivalences[2] = inverted;
1532 edge_info->cond_equivalences[3] = boolean_false_node;
1535 /* A helper function for record_const_or_copy and record_equality.
1536 Do the work of recording the value and undo info. */
1538 static void
1539 record_const_or_copy_1 (tree x, tree y, tree prev_x)
1541 SSA_NAME_VALUE (x) = y;
1543 VEC_safe_push (tree_on_heap, const_and_copies_stack, prev_x);
1544 VEC_safe_push (tree_on_heap, const_and_copies_stack, x);
1548 /* Return the loop depth of the basic block of the defining statement of X.
1549 This number should not be treated as absolutely correct because the loop
1550 information may not be completely up-to-date when dom runs. However, it
1551 will be relatively correct, and as more passes are taught to keep loop info
1552 up to date, the result will become more and more accurate. */
1554 static int
1555 loop_depth_of_name (tree x)
1557 tree defstmt;
1558 basic_block defbb;
1560 /* If it's not an SSA_NAME, we have no clue where the definition is. */
1561 if (TREE_CODE (x) != SSA_NAME)
1562 return 0;
1564 /* Otherwise return the loop depth of the defining statement's bb.
1565 Note that there may not actually be a bb for this statement, if the
1566 ssa_name is live on entry. */
1567 defstmt = SSA_NAME_DEF_STMT (x);
1568 defbb = bb_for_stmt (defstmt);
1569 if (!defbb)
1570 return 0;
1572 return defbb->loop_depth;
1576 /* Record that X is equal to Y in const_and_copies. Record undo
1577 information in the block-local vector. */
1579 static void
1580 record_const_or_copy (tree x, tree y)
1582 tree prev_x = SSA_NAME_VALUE (x);
1584 if (TREE_CODE (y) == SSA_NAME)
1586 tree tmp = SSA_NAME_VALUE (y);
1587 if (tmp)
1588 y = tmp;
1591 record_const_or_copy_1 (x, y, prev_x);
1594 /* Similarly, but assume that X and Y are the two operands of an EQ_EXPR.
1595 This constrains the cases in which we may treat this as assignment. */
1597 static void
1598 record_equality (tree x, tree y)
1600 tree prev_x = NULL, prev_y = NULL;
1602 if (TREE_CODE (x) == SSA_NAME)
1603 prev_x = SSA_NAME_VALUE (x);
1604 if (TREE_CODE (y) == SSA_NAME)
1605 prev_y = SSA_NAME_VALUE (y);
1607 /* If one of the previous values is invariant, or invariant in more loops
1608 (by depth), then use that.
1609 Otherwise it doesn't matter which value we choose, just so
1610 long as we canonicalize on one value. */
1611 if (TREE_INVARIANT (y))
1613 else if (TREE_INVARIANT (x) || (loop_depth_of_name (x) <= loop_depth_of_name (y)))
1614 prev_x = x, x = y, y = prev_x, prev_x = prev_y;
1615 else if (prev_x && TREE_INVARIANT (prev_x))
1616 x = y, y = prev_x, prev_x = prev_y;
1617 else if (prev_y && TREE_CODE (prev_y) != VALUE_HANDLE)
1618 y = prev_y;
1620 /* After the swapping, we must have one SSA_NAME. */
1621 if (TREE_CODE (x) != SSA_NAME)
1622 return;
1624 /* For IEEE, -0.0 == 0.0, so we don't necessarily know the sign of a
1625 variable compared against zero. If we're honoring signed zeros,
1626 then we cannot record this value unless we know that the value is
1627 nonzero. */
1628 if (HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (x)))
1629 && (TREE_CODE (y) != REAL_CST
1630 || REAL_VALUES_EQUAL (dconst0, TREE_REAL_CST (y))))
1631 return;
1633 record_const_or_copy_1 (x, y, prev_x);
1636 /* Return true, if it is ok to do folding of an associative expression.
1637 EXP is the tree for the associative expression. */
1639 static inline bool
1640 unsafe_associative_fp_binop (tree exp)
1642 enum tree_code code = TREE_CODE (exp);
1643 return !(!flag_unsafe_math_optimizations
1644 && (code == MULT_EXPR || code == PLUS_EXPR
1645 || code == MINUS_EXPR)
1646 && FLOAT_TYPE_P (TREE_TYPE (exp)));
1649 /* STMT is a MODIFY_EXPR for which we were unable to find RHS in the
1650 hash tables. Try to simplify the RHS using whatever equivalences
1651 we may have recorded.
1653 If we are able to simplify the RHS, then lookup the simplified form in
1654 the hash table and return the result. Otherwise return NULL. */
1656 static tree
1657 simplify_rhs_and_lookup_avail_expr (struct dom_walk_data *walk_data,
1658 tree stmt, int insert)
1660 tree rhs = TREE_OPERAND (stmt, 1);
1661 enum tree_code rhs_code = TREE_CODE (rhs);
1662 tree result = NULL;
1664 /* If we have lhs = ~x, look and see if we earlier had x = ~y.
1665 In which case we can change this statement to be lhs = y.
1666 Which can then be copy propagated.
1668 Similarly for negation. */
1669 if ((rhs_code == BIT_NOT_EXPR || rhs_code == NEGATE_EXPR)
1670 && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
1672 /* Get the definition statement for our RHS. */
1673 tree rhs_def_stmt = SSA_NAME_DEF_STMT (TREE_OPERAND (rhs, 0));
1675 /* See if the RHS_DEF_STMT has the same form as our statement. */
1676 if (TREE_CODE (rhs_def_stmt) == MODIFY_EXPR
1677 && TREE_CODE (TREE_OPERAND (rhs_def_stmt, 1)) == rhs_code)
1679 tree rhs_def_operand;
1681 rhs_def_operand = TREE_OPERAND (TREE_OPERAND (rhs_def_stmt, 1), 0);
1683 /* Verify that RHS_DEF_OPERAND is a suitable SSA variable. */
1684 if (TREE_CODE (rhs_def_operand) == SSA_NAME
1685 && ! SSA_NAME_OCCURS_IN_ABNORMAL_PHI (rhs_def_operand))
1686 result = update_rhs_and_lookup_avail_expr (stmt,
1687 rhs_def_operand,
1688 insert);
1692 /* If we have z = (x OP C1), see if we earlier had x = y OP C2.
1693 If OP is associative, create and fold (y OP C2) OP C1 which
1694 should result in (y OP C3), use that as the RHS for the
1695 assignment. Add minus to this, as we handle it specially below. */
1696 if ((associative_tree_code (rhs_code) || rhs_code == MINUS_EXPR)
1697 && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME
1698 && is_gimple_min_invariant (TREE_OPERAND (rhs, 1)))
1700 tree rhs_def_stmt = SSA_NAME_DEF_STMT (TREE_OPERAND (rhs, 0));
1702 /* See if the RHS_DEF_STMT has the same form as our statement. */
1703 if (TREE_CODE (rhs_def_stmt) == MODIFY_EXPR)
1705 tree rhs_def_rhs = TREE_OPERAND (rhs_def_stmt, 1);
1706 enum tree_code rhs_def_code = TREE_CODE (rhs_def_rhs);
1708 if ((rhs_code == rhs_def_code && unsafe_associative_fp_binop (rhs))
1709 || (rhs_code == PLUS_EXPR && rhs_def_code == MINUS_EXPR)
1710 || (rhs_code == MINUS_EXPR && rhs_def_code == PLUS_EXPR))
1712 tree def_stmt_op0 = TREE_OPERAND (rhs_def_rhs, 0);
1713 tree def_stmt_op1 = TREE_OPERAND (rhs_def_rhs, 1);
1715 if (TREE_CODE (def_stmt_op0) == SSA_NAME
1716 && ! SSA_NAME_OCCURS_IN_ABNORMAL_PHI (def_stmt_op0)
1717 && is_gimple_min_invariant (def_stmt_op1))
1719 tree outer_const = TREE_OPERAND (rhs, 1);
1720 tree type = TREE_TYPE (TREE_OPERAND (stmt, 0));
1721 tree t;
1723 /* If we care about correct floating point results, then
1724 don't fold x + c1 - c2. Note that we need to take both
1725 the codes and the signs to figure this out. */
1726 if (FLOAT_TYPE_P (type)
1727 && !flag_unsafe_math_optimizations
1728 && (rhs_def_code == PLUS_EXPR
1729 || rhs_def_code == MINUS_EXPR))
1731 bool neg = false;
1733 neg ^= (rhs_code == MINUS_EXPR);
1734 neg ^= (rhs_def_code == MINUS_EXPR);
1735 neg ^= real_isneg (TREE_REAL_CST_PTR (outer_const));
1736 neg ^= real_isneg (TREE_REAL_CST_PTR (def_stmt_op1));
1738 if (neg)
1739 goto dont_fold_assoc;
1742 /* Ho hum. So fold will only operate on the outermost
1743 thingy that we give it, so we have to build the new
1744 expression in two pieces. This requires that we handle
1745 combinations of plus and minus. */
1746 if (rhs_def_code != rhs_code)
1748 if (rhs_def_code == MINUS_EXPR)
1749 t = build (MINUS_EXPR, type, outer_const, def_stmt_op1);
1750 else
1751 t = build (MINUS_EXPR, type, def_stmt_op1, outer_const);
1752 rhs_code = PLUS_EXPR;
1754 else if (rhs_def_code == MINUS_EXPR)
1755 t = build (PLUS_EXPR, type, def_stmt_op1, outer_const);
1756 else
1757 t = build (rhs_def_code, type, def_stmt_op1, outer_const);
1758 t = local_fold (t);
1759 t = build (rhs_code, type, def_stmt_op0, t);
1760 t = local_fold (t);
1762 /* If the result is a suitable looking gimple expression,
1763 then use it instead of the original for STMT. */
1764 if (TREE_CODE (t) == SSA_NAME
1765 || (UNARY_CLASS_P (t)
1766 && TREE_CODE (TREE_OPERAND (t, 0)) == SSA_NAME)
1767 || ((BINARY_CLASS_P (t) || COMPARISON_CLASS_P (t))
1768 && TREE_CODE (TREE_OPERAND (t, 0)) == SSA_NAME
1769 && is_gimple_val (TREE_OPERAND (t, 1))))
1770 result = update_rhs_and_lookup_avail_expr (stmt, t, insert);
1774 dont_fold_assoc:;
1777 /* Transform TRUNC_DIV_EXPR and TRUNC_MOD_EXPR into RSHIFT_EXPR
1778 and BIT_AND_EXPR respectively if the first operand is greater
1779 than zero and the second operand is an exact power of two. */
1780 if ((rhs_code == TRUNC_DIV_EXPR || rhs_code == TRUNC_MOD_EXPR)
1781 && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (rhs, 0)))
1782 && integer_pow2p (TREE_OPERAND (rhs, 1)))
1784 tree val;
1785 tree op = TREE_OPERAND (rhs, 0);
1787 if (TYPE_UNSIGNED (TREE_TYPE (op)))
1789 val = integer_one_node;
1791 else
1793 tree dummy_cond = walk_data->global_data;
1795 if (! dummy_cond)
1797 dummy_cond = build (GT_EXPR, boolean_type_node,
1798 op, integer_zero_node);
1799 dummy_cond = build (COND_EXPR, void_type_node,
1800 dummy_cond, NULL, NULL);
1801 walk_data->global_data = dummy_cond;
1803 else
1805 TREE_SET_CODE (COND_EXPR_COND (dummy_cond), GT_EXPR);
1806 TREE_OPERAND (COND_EXPR_COND (dummy_cond), 0) = op;
1807 TREE_OPERAND (COND_EXPR_COND (dummy_cond), 1)
1808 = integer_zero_node;
1810 val = simplify_cond_and_lookup_avail_expr (dummy_cond, NULL, false);
1813 if (val && integer_onep (val))
1815 tree t;
1816 tree op0 = TREE_OPERAND (rhs, 0);
1817 tree op1 = TREE_OPERAND (rhs, 1);
1819 if (rhs_code == TRUNC_DIV_EXPR)
1820 t = build (RSHIFT_EXPR, TREE_TYPE (op0), op0,
1821 build_int_cst (NULL_TREE, tree_log2 (op1)));
1822 else
1823 t = build (BIT_AND_EXPR, TREE_TYPE (op0), op0,
1824 local_fold (build (MINUS_EXPR, TREE_TYPE (op1),
1825 op1, integer_one_node)));
1827 result = update_rhs_and_lookup_avail_expr (stmt, t, insert);
1831 /* Transform ABS (X) into X or -X as appropriate. */
1832 if (rhs_code == ABS_EXPR
1833 && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (rhs, 0))))
1835 tree val;
1836 tree op = TREE_OPERAND (rhs, 0);
1837 tree type = TREE_TYPE (op);
1839 if (TYPE_UNSIGNED (type))
1841 val = integer_zero_node;
1843 else
1845 tree dummy_cond = walk_data->global_data;
1847 if (! dummy_cond)
1849 dummy_cond = build (LE_EXPR, boolean_type_node,
1850 op, integer_zero_node);
1851 dummy_cond = build (COND_EXPR, void_type_node,
1852 dummy_cond, NULL, NULL);
1853 walk_data->global_data = dummy_cond;
1855 else
1857 TREE_SET_CODE (COND_EXPR_COND (dummy_cond), LE_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);
1862 val = simplify_cond_and_lookup_avail_expr (dummy_cond, NULL, false);
1864 if (!val)
1866 TREE_SET_CODE (COND_EXPR_COND (dummy_cond), GE_EXPR);
1867 TREE_OPERAND (COND_EXPR_COND (dummy_cond), 0) = op;
1868 TREE_OPERAND (COND_EXPR_COND (dummy_cond), 1)
1869 = build_int_cst (type, 0);
1871 val = simplify_cond_and_lookup_avail_expr (dummy_cond,
1872 NULL, false);
1874 if (val)
1876 if (integer_zerop (val))
1877 val = integer_one_node;
1878 else if (integer_onep (val))
1879 val = integer_zero_node;
1884 if (val
1885 && (integer_onep (val) || integer_zerop (val)))
1887 tree t;
1889 if (integer_onep (val))
1890 t = build1 (NEGATE_EXPR, TREE_TYPE (op), op);
1891 else
1892 t = op;
1894 result = update_rhs_and_lookup_avail_expr (stmt, t, insert);
1898 /* Optimize *"foo" into 'f'. This is done here rather than
1899 in fold to avoid problems with stuff like &*"foo". */
1900 if (TREE_CODE (rhs) == INDIRECT_REF || TREE_CODE (rhs) == ARRAY_REF)
1902 tree t = fold_read_from_constant_string (rhs);
1904 if (t)
1905 result = update_rhs_and_lookup_avail_expr (stmt, t, insert);
1908 return result;
1911 /* COND is a condition of the form:
1913 x == const or x != const
1915 Look back to x's defining statement and see if x is defined as
1917 x = (type) y;
1919 If const is unchanged if we convert it to type, then we can build
1920 the equivalent expression:
1923 y == const or y != const
1925 Which may allow further optimizations.
1927 Return the equivalent comparison or NULL if no such equivalent comparison
1928 was found. */
1930 static tree
1931 find_equivalent_equality_comparison (tree cond)
1933 tree op0 = TREE_OPERAND (cond, 0);
1934 tree op1 = TREE_OPERAND (cond, 1);
1935 tree def_stmt = SSA_NAME_DEF_STMT (op0);
1937 /* OP0 might have been a parameter, so first make sure it
1938 was defined by a MODIFY_EXPR. */
1939 if (def_stmt && TREE_CODE (def_stmt) == MODIFY_EXPR)
1941 tree def_rhs = TREE_OPERAND (def_stmt, 1);
1943 /* Now make sure the RHS of the MODIFY_EXPR is a typecast. */
1944 if ((TREE_CODE (def_rhs) == NOP_EXPR
1945 || TREE_CODE (def_rhs) == CONVERT_EXPR)
1946 && TREE_CODE (TREE_OPERAND (def_rhs, 0)) == SSA_NAME)
1948 tree def_rhs_inner = TREE_OPERAND (def_rhs, 0);
1949 tree def_rhs_inner_type = TREE_TYPE (def_rhs_inner);
1950 tree new;
1952 if (TYPE_PRECISION (def_rhs_inner_type)
1953 > TYPE_PRECISION (TREE_TYPE (def_rhs)))
1954 return NULL;
1956 /* What we want to prove is that if we convert OP1 to
1957 the type of the object inside the NOP_EXPR that the
1958 result is still equivalent to SRC.
1960 If that is true, the build and return new equivalent
1961 condition which uses the source of the typecast and the
1962 new constant (which has only changed its type). */
1963 new = build1 (TREE_CODE (def_rhs), def_rhs_inner_type, op1);
1964 new = local_fold (new);
1965 if (is_gimple_val (new) && tree_int_cst_equal (new, op1))
1966 return build (TREE_CODE (cond), TREE_TYPE (cond),
1967 def_rhs_inner, new);
1970 return NULL;
1973 /* STMT is a COND_EXPR for which we could not trivially determine its
1974 result. This routine attempts to find equivalent forms of the
1975 condition which we may be able to optimize better. It also
1976 uses simple value range propagation to optimize conditionals. */
1978 static tree
1979 simplify_cond_and_lookup_avail_expr (tree stmt,
1980 stmt_ann_t ann,
1981 int insert)
1983 tree cond = COND_EXPR_COND (stmt);
1985 if (COMPARISON_CLASS_P (cond))
1987 tree op0 = TREE_OPERAND (cond, 0);
1988 tree op1 = TREE_OPERAND (cond, 1);
1990 if (TREE_CODE (op0) == SSA_NAME && is_gimple_min_invariant (op1))
1992 int limit;
1993 tree low, high, cond_low, cond_high;
1994 int lowequal, highequal, swapped, no_overlap, subset, cond_inverted;
1995 varray_type vrp_records;
1996 struct vrp_element *element;
1997 struct vrp_hash_elt vrp_hash_elt, *vrp_hash_elt_p;
1998 void **slot;
2000 /* First see if we have test of an SSA_NAME against a constant
2001 where the SSA_NAME is defined by an earlier typecast which
2002 is irrelevant when performing tests against the given
2003 constant. */
2004 if (TREE_CODE (cond) == EQ_EXPR || TREE_CODE (cond) == NE_EXPR)
2006 tree new_cond = find_equivalent_equality_comparison (cond);
2008 if (new_cond)
2010 /* Update the statement to use the new equivalent
2011 condition. */
2012 COND_EXPR_COND (stmt) = new_cond;
2014 /* If this is not a real stmt, ann will be NULL and we
2015 avoid processing the operands. */
2016 if (ann)
2017 modify_stmt (stmt);
2019 /* Lookup the condition and return its known value if it
2020 exists. */
2021 new_cond = lookup_avail_expr (stmt, insert);
2022 if (new_cond)
2023 return new_cond;
2025 /* The operands have changed, so update op0 and op1. */
2026 op0 = TREE_OPERAND (cond, 0);
2027 op1 = TREE_OPERAND (cond, 1);
2031 /* Consult the value range records for this variable (if they exist)
2032 to see if we can eliminate or simplify this conditional.
2034 Note two tests are necessary to determine no records exist.
2035 First we have to see if the virtual array exists, if it
2036 exists, then we have to check its active size.
2038 Also note the vast majority of conditionals are not testing
2039 a variable which has had its range constrained by an earlier
2040 conditional. So this filter avoids a lot of unnecessary work. */
2041 vrp_hash_elt.var = op0;
2042 vrp_hash_elt.records = NULL;
2043 slot = htab_find_slot (vrp_data, &vrp_hash_elt, NO_INSERT);
2044 if (slot == NULL)
2045 return NULL;
2047 vrp_hash_elt_p = (struct vrp_hash_elt *) *slot;
2048 vrp_records = vrp_hash_elt_p->records;
2049 if (vrp_records == NULL)
2050 return NULL;
2052 limit = VARRAY_ACTIVE_SIZE (vrp_records);
2054 /* If we have no value range records for this variable, or we are
2055 unable to extract a range for this condition, then there is
2056 nothing to do. */
2057 if (limit == 0
2058 || ! extract_range_from_cond (cond, &cond_high,
2059 &cond_low, &cond_inverted))
2060 return NULL;
2062 /* We really want to avoid unnecessary computations of range
2063 info. So all ranges are computed lazily; this avoids a
2064 lot of unnecessary work. i.e., we record the conditional,
2065 but do not process how it constrains the variable's
2066 potential values until we know that processing the condition
2067 could be helpful.
2069 However, we do not want to have to walk a potentially long
2070 list of ranges, nor do we want to compute a variable's
2071 range more than once for a given path.
2073 Luckily, each time we encounter a conditional that can not
2074 be otherwise optimized we will end up here and we will
2075 compute the necessary range information for the variable
2076 used in this condition.
2078 Thus you can conclude that there will never be more than one
2079 conditional associated with a variable which has not been
2080 processed. So we never need to merge more than one new
2081 conditional into the current range.
2083 These properties also help us avoid unnecessary work. */
2084 element
2085 = (struct vrp_element *)VARRAY_GENERIC_PTR (vrp_records, limit - 1);
2087 if (element->high && element->low)
2089 /* The last element has been processed, so there is no range
2090 merging to do, we can simply use the high/low values
2091 recorded in the last element. */
2092 low = element->low;
2093 high = element->high;
2095 else
2097 tree tmp_high, tmp_low;
2098 int dummy;
2100 /* The last element has not been processed. Process it now. */
2101 extract_range_from_cond (element->cond, &tmp_high,
2102 &tmp_low, &dummy);
2104 /* If this is the only element, then no merging is necessary,
2105 the high/low values from extract_range_from_cond are all
2106 we need. */
2107 if (limit == 1)
2109 low = tmp_low;
2110 high = tmp_high;
2112 else
2114 /* Get the high/low value from the previous element. */
2115 struct vrp_element *prev
2116 = (struct vrp_element *)VARRAY_GENERIC_PTR (vrp_records,
2117 limit - 2);
2118 low = prev->low;
2119 high = prev->high;
2121 /* Merge in this element's range with the range from the
2122 previous element.
2124 The low value for the merged range is the maximum of
2125 the previous low value and the low value of this record.
2127 Similarly the high value for the merged range is the
2128 minimum of the previous high value and the high value of
2129 this record. */
2130 low = (tree_int_cst_compare (low, tmp_low) == 1
2131 ? low : tmp_low);
2132 high = (tree_int_cst_compare (high, tmp_high) == -1
2133 ? high : tmp_high);
2136 /* And record the computed range. */
2137 element->low = low;
2138 element->high = high;
2142 /* After we have constrained this variable's potential values,
2143 we try to determine the result of the given conditional.
2145 To simplify later tests, first determine if the current
2146 low value is the same low value as the conditional.
2147 Similarly for the current high value and the high value
2148 for the conditional. */
2149 lowequal = tree_int_cst_equal (low, cond_low);
2150 highequal = tree_int_cst_equal (high, cond_high);
2152 if (lowequal && highequal)
2153 return (cond_inverted ? boolean_false_node : boolean_true_node);
2155 /* To simplify the overlap/subset tests below we may want
2156 to swap the two ranges so that the larger of the two
2157 ranges occurs "first". */
2158 swapped = 0;
2159 if (tree_int_cst_compare (low, cond_low) == 1
2160 || (lowequal
2161 && tree_int_cst_compare (cond_high, high) == 1))
2163 tree temp;
2165 swapped = 1;
2166 temp = low;
2167 low = cond_low;
2168 cond_low = temp;
2169 temp = high;
2170 high = cond_high;
2171 cond_high = temp;
2174 /* Now determine if there is no overlap in the ranges
2175 or if the second range is a subset of the first range. */
2176 no_overlap = tree_int_cst_lt (high, cond_low);
2177 subset = tree_int_cst_compare (cond_high, high) != 1;
2179 /* If there was no overlap in the ranges, then this conditional
2180 always has a false value (unless we had to invert this
2181 conditional, in which case it always has a true value). */
2182 if (no_overlap)
2183 return (cond_inverted ? boolean_true_node : boolean_false_node);
2185 /* If the current range is a subset of the condition's range,
2186 then this conditional always has a true value (unless we
2187 had to invert this conditional, in which case it always
2188 has a true value). */
2189 if (subset && swapped)
2190 return (cond_inverted ? boolean_false_node : boolean_true_node);
2192 /* We were unable to determine the result of the conditional.
2193 However, we may be able to simplify the conditional. First
2194 merge the ranges in the same manner as range merging above. */
2195 low = tree_int_cst_compare (low, cond_low) == 1 ? low : cond_low;
2196 high = tree_int_cst_compare (high, cond_high) == -1 ? high : cond_high;
2198 /* If the range has converged to a single point, then turn this
2199 into an equality comparison. */
2200 if (TREE_CODE (cond) != EQ_EXPR
2201 && TREE_CODE (cond) != NE_EXPR
2202 && tree_int_cst_equal (low, high))
2204 TREE_SET_CODE (cond, EQ_EXPR);
2205 TREE_OPERAND (cond, 1) = high;
2209 return 0;
2212 /* STMT is a SWITCH_EXPR for which we could not trivially determine its
2213 result. This routine attempts to find equivalent forms of the
2214 condition which we may be able to optimize better. */
2216 static tree
2217 simplify_switch_and_lookup_avail_expr (tree stmt, int insert)
2219 tree cond = SWITCH_COND (stmt);
2220 tree def, to, ti;
2222 /* The optimization that we really care about is removing unnecessary
2223 casts. That will let us do much better in propagating the inferred
2224 constant at the switch target. */
2225 if (TREE_CODE (cond) == SSA_NAME)
2227 def = SSA_NAME_DEF_STMT (cond);
2228 if (TREE_CODE (def) == MODIFY_EXPR)
2230 def = TREE_OPERAND (def, 1);
2231 if (TREE_CODE (def) == NOP_EXPR)
2233 int need_precision;
2234 bool fail;
2236 def = TREE_OPERAND (def, 0);
2238 #ifdef ENABLE_CHECKING
2239 /* ??? Why was Jeff testing this? We are gimple... */
2240 gcc_assert (is_gimple_val (def));
2241 #endif
2243 to = TREE_TYPE (cond);
2244 ti = TREE_TYPE (def);
2246 /* If we have an extension that preserves value, then we
2247 can copy the source value into the switch. */
2249 need_precision = TYPE_PRECISION (ti);
2250 fail = false;
2251 if (TYPE_UNSIGNED (to) && !TYPE_UNSIGNED (ti))
2252 fail = true;
2253 else if (!TYPE_UNSIGNED (to) && TYPE_UNSIGNED (ti))
2254 need_precision += 1;
2255 if (TYPE_PRECISION (to) < need_precision)
2256 fail = true;
2258 if (!fail)
2260 SWITCH_COND (stmt) = def;
2261 modify_stmt (stmt);
2263 return lookup_avail_expr (stmt, insert);
2269 return 0;
2273 /* CONST_AND_COPIES is a table which maps an SSA_NAME to the current
2274 known value for that SSA_NAME (or NULL if no value is known).
2276 NONZERO_VARS is the set SSA_NAMES known to have a nonzero value,
2277 even if we don't know their precise value.
2279 Propagate values from CONST_AND_COPIES and NONZERO_VARS into the PHI
2280 nodes of the successors of BB. */
2282 static void
2283 cprop_into_successor_phis (basic_block bb, bitmap nonzero_vars)
2285 edge e;
2286 edge_iterator ei;
2288 /* This can get rather expensive if the implementation is naive in
2289 how it finds the phi alternative associated with a particular edge. */
2290 FOR_EACH_EDGE (e, ei, bb->succs)
2292 tree phi;
2293 int indx;
2295 /* If this is an abnormal edge, then we do not want to copy propagate
2296 into the PHI alternative associated with this edge. */
2297 if (e->flags & EDGE_ABNORMAL)
2298 continue;
2300 phi = phi_nodes (e->dest);
2301 if (! phi)
2302 continue;
2304 indx = e->dest_idx;
2305 for ( ; phi; phi = PHI_CHAIN (phi))
2307 tree new;
2308 use_operand_p orig_p;
2309 tree orig;
2311 /* The alternative may be associated with a constant, so verify
2312 it is an SSA_NAME before doing anything with it. */
2313 orig_p = PHI_ARG_DEF_PTR (phi, indx);
2314 orig = USE_FROM_PTR (orig_p);
2315 if (TREE_CODE (orig) != SSA_NAME)
2316 continue;
2318 /* If the alternative is known to have a nonzero value, record
2319 that fact in the PHI node itself for future use. */
2320 if (bitmap_bit_p (nonzero_vars, SSA_NAME_VERSION (orig)))
2321 PHI_ARG_NONZERO (phi, indx) = true;
2323 /* If we have *ORIG_P in our constant/copy table, then replace
2324 ORIG_P with its value in our constant/copy table. */
2325 new = SSA_NAME_VALUE (orig);
2326 if (new
2327 && (TREE_CODE (new) == SSA_NAME
2328 || is_gimple_min_invariant (new))
2329 && may_propagate_copy (orig, new))
2331 propagate_value (orig_p, new);
2337 /* We have finished optimizing BB, record any information implied by
2338 taking a specific outgoing edge from BB. */
2340 static void
2341 record_edge_info (basic_block bb)
2343 block_stmt_iterator bsi = bsi_last (bb);
2344 struct edge_info *edge_info;
2346 if (! bsi_end_p (bsi))
2348 tree stmt = bsi_stmt (bsi);
2350 if (stmt && TREE_CODE (stmt) == SWITCH_EXPR)
2352 tree cond = SWITCH_COND (stmt);
2354 if (TREE_CODE (cond) == SSA_NAME)
2356 tree labels = SWITCH_LABELS (stmt);
2357 int i, n_labels = TREE_VEC_LENGTH (labels);
2358 tree *info = xcalloc (n_basic_blocks, sizeof (tree));
2359 edge e;
2360 edge_iterator ei;
2362 for (i = 0; i < n_labels; i++)
2364 tree label = TREE_VEC_ELT (labels, i);
2365 basic_block target_bb = label_to_block (CASE_LABEL (label));
2367 if (CASE_HIGH (label)
2368 || !CASE_LOW (label)
2369 || info[target_bb->index])
2370 info[target_bb->index] = error_mark_node;
2371 else
2372 info[target_bb->index] = label;
2375 FOR_EACH_EDGE (e, ei, bb->succs)
2377 basic_block target_bb = e->dest;
2378 tree node = info[target_bb->index];
2380 if (node != NULL && node != error_mark_node)
2382 tree x = fold_convert (TREE_TYPE (cond), CASE_LOW (node));
2383 edge_info = allocate_edge_info (e);
2384 edge_info->lhs = cond;
2385 edge_info->rhs = x;
2388 free (info);
2392 /* A COND_EXPR may create equivalences too. */
2393 if (stmt && TREE_CODE (stmt) == COND_EXPR)
2395 tree cond = COND_EXPR_COND (stmt);
2396 edge true_edge;
2397 edge false_edge;
2399 extract_true_false_edges_from_block (bb, &true_edge, &false_edge);
2401 /* If the conditional is a single variable 'X', record 'X = 1'
2402 for the true edge and 'X = 0' on the false edge. */
2403 if (SSA_VAR_P (cond))
2405 struct edge_info *edge_info;
2407 edge_info = allocate_edge_info (true_edge);
2408 edge_info->lhs = cond;
2409 edge_info->rhs = constant_boolean_node (1, TREE_TYPE (cond));
2411 edge_info = allocate_edge_info (false_edge);
2412 edge_info->lhs = cond;
2413 edge_info->rhs = constant_boolean_node (0, TREE_TYPE (cond));
2415 /* Equality tests may create one or two equivalences. */
2416 else if (COMPARISON_CLASS_P (cond))
2418 tree op0 = TREE_OPERAND (cond, 0);
2419 tree op1 = TREE_OPERAND (cond, 1);
2421 /* Special case comparing booleans against a constant as we
2422 know the value of OP0 on both arms of the branch. i.e., we
2423 can record an equivalence for OP0 rather than COND. */
2424 if ((TREE_CODE (cond) == EQ_EXPR || TREE_CODE (cond) == NE_EXPR)
2425 && TREE_CODE (op0) == SSA_NAME
2426 && TREE_CODE (TREE_TYPE (op0)) == BOOLEAN_TYPE
2427 && is_gimple_min_invariant (op1))
2429 if (TREE_CODE (cond) == EQ_EXPR)
2431 edge_info = allocate_edge_info (true_edge);
2432 edge_info->lhs = op0;
2433 edge_info->rhs = (integer_zerop (op1)
2434 ? boolean_false_node
2435 : boolean_true_node);
2437 edge_info = allocate_edge_info (false_edge);
2438 edge_info->lhs = op0;
2439 edge_info->rhs = (integer_zerop (op1)
2440 ? boolean_true_node
2441 : boolean_false_node);
2443 else
2445 edge_info = allocate_edge_info (true_edge);
2446 edge_info->lhs = op0;
2447 edge_info->rhs = (integer_zerop (op1)
2448 ? boolean_true_node
2449 : boolean_false_node);
2451 edge_info = allocate_edge_info (false_edge);
2452 edge_info->lhs = op0;
2453 edge_info->rhs = (integer_zerop (op1)
2454 ? boolean_false_node
2455 : boolean_true_node);
2459 if (is_gimple_min_invariant (op0)
2460 && (TREE_CODE (op1) == SSA_NAME
2461 || is_gimple_min_invariant (op1)))
2463 tree inverted = invert_truthvalue (cond);
2464 struct edge_info *edge_info;
2466 edge_info = allocate_edge_info (true_edge);
2467 record_conditions (edge_info, cond, inverted);
2469 if (TREE_CODE (cond) == EQ_EXPR)
2471 edge_info->lhs = op1;
2472 edge_info->rhs = op0;
2475 edge_info = allocate_edge_info (false_edge);
2476 record_conditions (edge_info, inverted, cond);
2478 if (TREE_CODE (cond) == NE_EXPR)
2480 edge_info->lhs = op1;
2481 edge_info->rhs = op0;
2485 if (TREE_CODE (op0) == SSA_NAME
2486 && (is_gimple_min_invariant (op1)
2487 || TREE_CODE (op1) == SSA_NAME))
2489 tree inverted = invert_truthvalue (cond);
2490 struct edge_info *edge_info;
2492 edge_info = allocate_edge_info (true_edge);
2493 record_conditions (edge_info, cond, inverted);
2495 if (TREE_CODE (cond) == EQ_EXPR)
2497 edge_info->lhs = op0;
2498 edge_info->rhs = op1;
2501 edge_info = allocate_edge_info (false_edge);
2502 record_conditions (edge_info, inverted, cond);
2504 if (TREE_CODE (cond) == NE_EXPR)
2506 edge_info->lhs = op0;
2507 edge_info->rhs = op1;
2512 /* ??? TRUTH_NOT_EXPR can create an equivalence too. */
2517 /* Propagate information from BB to its outgoing edges.
2519 This can include equivalency information implied by control statements
2520 at the end of BB and const/copy propagation into PHIs in BB's
2521 successor blocks. */
2523 static void
2524 propagate_to_outgoing_edges (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
2525 basic_block bb)
2528 record_edge_info (bb);
2529 cprop_into_successor_phis (bb, nonzero_vars);
2532 /* Search for redundant computations in STMT. If any are found, then
2533 replace them with the variable holding the result of the computation.
2535 If safe, record this expression into the available expression hash
2536 table. */
2538 static bool
2539 eliminate_redundant_computations (struct dom_walk_data *walk_data,
2540 tree stmt, stmt_ann_t ann)
2542 v_may_def_optype v_may_defs = V_MAY_DEF_OPS (ann);
2543 tree *expr_p, def = NULL_TREE;
2544 bool insert = true;
2545 tree cached_lhs;
2546 bool retval = false;
2548 if (TREE_CODE (stmt) == MODIFY_EXPR)
2549 def = TREE_OPERAND (stmt, 0);
2551 /* Certain expressions on the RHS can be optimized away, but can not
2552 themselves be entered into the hash tables. */
2553 if (ann->makes_aliased_stores
2554 || ! def
2555 || TREE_CODE (def) != SSA_NAME
2556 || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (def)
2557 || NUM_V_MAY_DEFS (v_may_defs) != 0)
2558 insert = false;
2560 /* Check if the expression has been computed before. */
2561 cached_lhs = lookup_avail_expr (stmt, insert);
2563 /* If this is an assignment and the RHS was not in the hash table,
2564 then try to simplify the RHS and lookup the new RHS in the
2565 hash table. */
2566 if (! cached_lhs && TREE_CODE (stmt) == MODIFY_EXPR)
2567 cached_lhs = simplify_rhs_and_lookup_avail_expr (walk_data, stmt, insert);
2568 /* Similarly if this is a COND_EXPR and we did not find its
2569 expression in the hash table, simplify the condition and
2570 try again. */
2571 else if (! cached_lhs && TREE_CODE (stmt) == COND_EXPR)
2572 cached_lhs = simplify_cond_and_lookup_avail_expr (stmt, ann, insert);
2573 /* Similarly for a SWITCH_EXPR. */
2574 else if (!cached_lhs && TREE_CODE (stmt) == SWITCH_EXPR)
2575 cached_lhs = simplify_switch_and_lookup_avail_expr (stmt, insert);
2577 opt_stats.num_exprs_considered++;
2579 /* Get a pointer to the expression we are trying to optimize. */
2580 if (TREE_CODE (stmt) == COND_EXPR)
2581 expr_p = &COND_EXPR_COND (stmt);
2582 else if (TREE_CODE (stmt) == SWITCH_EXPR)
2583 expr_p = &SWITCH_COND (stmt);
2584 else if (TREE_CODE (stmt) == RETURN_EXPR && TREE_OPERAND (stmt, 0))
2585 expr_p = &TREE_OPERAND (TREE_OPERAND (stmt, 0), 1);
2586 else
2587 expr_p = &TREE_OPERAND (stmt, 1);
2589 /* It is safe to ignore types here since we have already done
2590 type checking in the hashing and equality routines. In fact
2591 type checking here merely gets in the way of constant
2592 propagation. Also, make sure that it is safe to propagate
2593 CACHED_LHS into *EXPR_P. */
2594 if (cached_lhs
2595 && (TREE_CODE (cached_lhs) != SSA_NAME
2596 || may_propagate_copy (*expr_p, cached_lhs)))
2598 if (dump_file && (dump_flags & TDF_DETAILS))
2600 fprintf (dump_file, " Replaced redundant expr '");
2601 print_generic_expr (dump_file, *expr_p, dump_flags);
2602 fprintf (dump_file, "' with '");
2603 print_generic_expr (dump_file, cached_lhs, dump_flags);
2604 fprintf (dump_file, "'\n");
2607 opt_stats.num_re++;
2609 #if defined ENABLE_CHECKING
2610 gcc_assert (TREE_CODE (cached_lhs) == SSA_NAME
2611 || is_gimple_min_invariant (cached_lhs));
2612 #endif
2614 if (TREE_CODE (cached_lhs) == ADDR_EXPR
2615 || (POINTER_TYPE_P (TREE_TYPE (*expr_p))
2616 && is_gimple_min_invariant (cached_lhs)))
2617 retval = true;
2619 propagate_tree_value (expr_p, cached_lhs);
2620 modify_stmt (stmt);
2622 return retval;
2625 /* STMT, a MODIFY_EXPR, may create certain equivalences, in either
2626 the available expressions table or the const_and_copies table.
2627 Detect and record those equivalences. */
2629 static void
2630 record_equivalences_from_stmt (tree stmt,
2631 int may_optimize_p,
2632 stmt_ann_t ann)
2634 tree lhs = TREE_OPERAND (stmt, 0);
2635 enum tree_code lhs_code = TREE_CODE (lhs);
2636 int i;
2638 if (lhs_code == SSA_NAME)
2640 tree rhs = TREE_OPERAND (stmt, 1);
2642 /* Strip away any useless type conversions. */
2643 STRIP_USELESS_TYPE_CONVERSION (rhs);
2645 /* If the RHS of the assignment is a constant or another variable that
2646 may be propagated, register it in the CONST_AND_COPIES table. We
2647 do not need to record unwind data for this, since this is a true
2648 assignment and not an equivalence inferred from a comparison. All
2649 uses of this ssa name are dominated by this assignment, so unwinding
2650 just costs time and space. */
2651 if (may_optimize_p
2652 && (TREE_CODE (rhs) == SSA_NAME
2653 || is_gimple_min_invariant (rhs)))
2654 SSA_NAME_VALUE (lhs) = rhs;
2656 /* alloca never returns zero and the address of a non-weak symbol
2657 is never zero. NOP_EXPRs and CONVERT_EXPRs can be completely
2658 stripped as they do not affect this equivalence. */
2659 while (TREE_CODE (rhs) == NOP_EXPR
2660 || TREE_CODE (rhs) == CONVERT_EXPR)
2661 rhs = TREE_OPERAND (rhs, 0);
2663 if (alloca_call_p (rhs)
2664 || (TREE_CODE (rhs) == ADDR_EXPR
2665 && DECL_P (TREE_OPERAND (rhs, 0))
2666 && ! DECL_WEAK (TREE_OPERAND (rhs, 0))))
2667 record_var_is_nonzero (lhs);
2669 /* IOR of any value with a nonzero value will result in a nonzero
2670 value. Even if we do not know the exact result recording that
2671 the result is nonzero is worth the effort. */
2672 if (TREE_CODE (rhs) == BIT_IOR_EXPR
2673 && integer_nonzerop (TREE_OPERAND (rhs, 1)))
2674 record_var_is_nonzero (lhs);
2677 /* Look at both sides for pointer dereferences. If we find one, then
2678 the pointer must be nonnull and we can enter that equivalence into
2679 the hash tables. */
2680 if (flag_delete_null_pointer_checks)
2681 for (i = 0; i < 2; i++)
2683 tree t = TREE_OPERAND (stmt, i);
2685 /* Strip away any COMPONENT_REFs. */
2686 while (TREE_CODE (t) == COMPONENT_REF)
2687 t = TREE_OPERAND (t, 0);
2689 /* Now see if this is a pointer dereference. */
2690 if (INDIRECT_REF_P (t))
2692 tree op = TREE_OPERAND (t, 0);
2694 /* If the pointer is a SSA variable, then enter new
2695 equivalences into the hash table. */
2696 while (TREE_CODE (op) == SSA_NAME)
2698 tree def = SSA_NAME_DEF_STMT (op);
2700 record_var_is_nonzero (op);
2702 /* And walk up the USE-DEF chains noting other SSA_NAMEs
2703 which are known to have a nonzero value. */
2704 if (def
2705 && TREE_CODE (def) == MODIFY_EXPR
2706 && TREE_CODE (TREE_OPERAND (def, 1)) == NOP_EXPR)
2707 op = TREE_OPERAND (TREE_OPERAND (def, 1), 0);
2708 else
2709 break;
2714 /* A memory store, even an aliased store, creates a useful
2715 equivalence. By exchanging the LHS and RHS, creating suitable
2716 vops and recording the result in the available expression table,
2717 we may be able to expose more redundant loads. */
2718 if (!ann->has_volatile_ops
2719 && (TREE_CODE (TREE_OPERAND (stmt, 1)) == SSA_NAME
2720 || is_gimple_min_invariant (TREE_OPERAND (stmt, 1)))
2721 && !is_gimple_reg (lhs))
2723 tree rhs = TREE_OPERAND (stmt, 1);
2724 tree new;
2726 /* FIXME: If the LHS of the assignment is a bitfield and the RHS
2727 is a constant, we need to adjust the constant to fit into the
2728 type of the LHS. If the LHS is a bitfield and the RHS is not
2729 a constant, then we can not record any equivalences for this
2730 statement since we would need to represent the widening or
2731 narrowing of RHS. This fixes gcc.c-torture/execute/921016-1.c
2732 and should not be necessary if GCC represented bitfields
2733 properly. */
2734 if (lhs_code == COMPONENT_REF
2735 && DECL_BIT_FIELD (TREE_OPERAND (lhs, 1)))
2737 if (TREE_CONSTANT (rhs))
2738 rhs = widen_bitfield (rhs, TREE_OPERAND (lhs, 1), lhs);
2739 else
2740 rhs = NULL;
2742 /* If the value overflowed, then we can not use this equivalence. */
2743 if (rhs && ! is_gimple_min_invariant (rhs))
2744 rhs = NULL;
2747 if (rhs)
2749 /* Build a new statement with the RHS and LHS exchanged. */
2750 new = build (MODIFY_EXPR, TREE_TYPE (stmt), rhs, lhs);
2752 create_ssa_artficial_load_stmt (&(ann->operands), new);
2754 /* Finally enter the statement into the available expression
2755 table. */
2756 lookup_avail_expr (new, true);
2761 /* Replace *OP_P in STMT with any known equivalent value for *OP_P from
2762 CONST_AND_COPIES. */
2764 static bool
2765 cprop_operand (tree stmt, use_operand_p op_p)
2767 bool may_have_exposed_new_symbols = false;
2768 tree val;
2769 tree op = USE_FROM_PTR (op_p);
2771 /* If the operand has a known constant value or it is known to be a
2772 copy of some other variable, use the value or copy stored in
2773 CONST_AND_COPIES. */
2774 val = SSA_NAME_VALUE (op);
2775 if (val && TREE_CODE (val) != VALUE_HANDLE)
2777 tree op_type, val_type;
2779 /* Do not change the base variable in the virtual operand
2780 tables. That would make it impossible to reconstruct
2781 the renamed virtual operand if we later modify this
2782 statement. Also only allow the new value to be an SSA_NAME
2783 for propagation into virtual operands. */
2784 if (!is_gimple_reg (op)
2785 && (get_virtual_var (val) != get_virtual_var (op)
2786 || TREE_CODE (val) != SSA_NAME))
2787 return false;
2789 /* Do not replace hard register operands in asm statements. */
2790 if (TREE_CODE (stmt) == ASM_EXPR
2791 && !may_propagate_copy_into_asm (op))
2792 return false;
2794 /* Get the toplevel type of each operand. */
2795 op_type = TREE_TYPE (op);
2796 val_type = TREE_TYPE (val);
2798 /* While both types are pointers, get the type of the object
2799 pointed to. */
2800 while (POINTER_TYPE_P (op_type) && POINTER_TYPE_P (val_type))
2802 op_type = TREE_TYPE (op_type);
2803 val_type = TREE_TYPE (val_type);
2806 /* Make sure underlying types match before propagating a constant by
2807 converting the constant to the proper type. Note that convert may
2808 return a non-gimple expression, in which case we ignore this
2809 propagation opportunity. */
2810 if (TREE_CODE (val) != SSA_NAME)
2812 if (!lang_hooks.types_compatible_p (op_type, val_type))
2814 val = fold_convert (TREE_TYPE (op), val);
2815 if (!is_gimple_min_invariant (val))
2816 return false;
2820 /* Certain operands are not allowed to be copy propagated due
2821 to their interaction with exception handling and some GCC
2822 extensions. */
2823 else if (!may_propagate_copy (op, val))
2824 return false;
2826 /* Dump details. */
2827 if (dump_file && (dump_flags & TDF_DETAILS))
2829 fprintf (dump_file, " Replaced '");
2830 print_generic_expr (dump_file, op, dump_flags);
2831 fprintf (dump_file, "' with %s '",
2832 (TREE_CODE (val) != SSA_NAME ? "constant" : "variable"));
2833 print_generic_expr (dump_file, val, dump_flags);
2834 fprintf (dump_file, "'\n");
2837 /* If VAL is an ADDR_EXPR or a constant of pointer type, note
2838 that we may have exposed a new symbol for SSA renaming. */
2839 if (TREE_CODE (val) == ADDR_EXPR
2840 || (POINTER_TYPE_P (TREE_TYPE (op))
2841 && is_gimple_min_invariant (val)))
2842 may_have_exposed_new_symbols = true;
2844 propagate_value (op_p, val);
2846 /* And note that we modified this statement. This is now
2847 safe, even if we changed virtual operands since we will
2848 rescan the statement and rewrite its operands again. */
2849 modify_stmt (stmt);
2851 return may_have_exposed_new_symbols;
2854 /* CONST_AND_COPIES is a table which maps an SSA_NAME to the current
2855 known value for that SSA_NAME (or NULL if no value is known).
2857 Propagate values from CONST_AND_COPIES into the uses, vuses and
2858 v_may_def_ops of STMT. */
2860 static bool
2861 cprop_into_stmt (tree stmt)
2863 bool may_have_exposed_new_symbols = false;
2864 use_operand_p op_p;
2865 ssa_op_iter iter;
2866 tree rhs;
2868 FOR_EACH_SSA_USE_OPERAND (op_p, stmt, iter, SSA_OP_ALL_USES)
2870 if (TREE_CODE (USE_FROM_PTR (op_p)) == SSA_NAME)
2871 may_have_exposed_new_symbols |= cprop_operand (stmt, op_p);
2874 if (may_have_exposed_new_symbols)
2876 rhs = get_rhs (stmt);
2877 if (rhs && TREE_CODE (rhs) == ADDR_EXPR)
2878 recompute_tree_invarant_for_addr_expr (rhs);
2881 return may_have_exposed_new_symbols;
2885 /* Optimize the statement pointed by iterator SI.
2887 We try to perform some simplistic global redundancy elimination and
2888 constant propagation:
2890 1- To detect global redundancy, we keep track of expressions that have
2891 been computed in this block and its dominators. If we find that the
2892 same expression is computed more than once, we eliminate repeated
2893 computations by using the target of the first one.
2895 2- Constant values and copy assignments. This is used to do very
2896 simplistic constant and copy propagation. When a constant or copy
2897 assignment is found, we map the value on the RHS of the assignment to
2898 the variable in the LHS in the CONST_AND_COPIES table. */
2900 static void
2901 optimize_stmt (struct dom_walk_data *walk_data, basic_block bb,
2902 block_stmt_iterator si)
2904 stmt_ann_t ann;
2905 tree stmt;
2906 bool may_optimize_p;
2907 bool may_have_exposed_new_symbols = false;
2909 stmt = bsi_stmt (si);
2911 get_stmt_operands (stmt);
2912 ann = stmt_ann (stmt);
2913 opt_stats.num_stmts++;
2914 may_have_exposed_new_symbols = false;
2916 if (dump_file && (dump_flags & TDF_DETAILS))
2918 fprintf (dump_file, "Optimizing statement ");
2919 print_generic_stmt (dump_file, stmt, TDF_SLIM);
2922 /* Const/copy propagate into USES, VUSES and the RHS of V_MAY_DEFs. */
2923 may_have_exposed_new_symbols = cprop_into_stmt (stmt);
2925 /* If the statement has been modified with constant replacements,
2926 fold its RHS before checking for redundant computations. */
2927 if (ann->modified)
2929 /* Try to fold the statement making sure that STMT is kept
2930 up to date. */
2931 if (fold_stmt (bsi_stmt_ptr (si)))
2933 stmt = bsi_stmt (si);
2934 ann = stmt_ann (stmt);
2936 if (dump_file && (dump_flags & TDF_DETAILS))
2938 fprintf (dump_file, " Folded to: ");
2939 print_generic_stmt (dump_file, stmt, TDF_SLIM);
2943 /* Constant/copy propagation above may change the set of
2944 virtual operands associated with this statement. Folding
2945 may remove the need for some virtual operands.
2947 Indicate we will need to rescan and rewrite the statement. */
2948 may_have_exposed_new_symbols = true;
2951 /* Check for redundant computations. Do this optimization only
2952 for assignments that have no volatile ops and conditionals. */
2953 may_optimize_p = (!ann->has_volatile_ops
2954 && ((TREE_CODE (stmt) == RETURN_EXPR
2955 && TREE_OPERAND (stmt, 0)
2956 && TREE_CODE (TREE_OPERAND (stmt, 0)) == MODIFY_EXPR
2957 && ! (TREE_SIDE_EFFECTS
2958 (TREE_OPERAND (TREE_OPERAND (stmt, 0), 1))))
2959 || (TREE_CODE (stmt) == MODIFY_EXPR
2960 && ! TREE_SIDE_EFFECTS (TREE_OPERAND (stmt, 1)))
2961 || TREE_CODE (stmt) == COND_EXPR
2962 || TREE_CODE (stmt) == SWITCH_EXPR));
2964 if (may_optimize_p)
2965 may_have_exposed_new_symbols
2966 |= eliminate_redundant_computations (walk_data, stmt, ann);
2968 /* Record any additional equivalences created by this statement. */
2969 if (TREE_CODE (stmt) == MODIFY_EXPR)
2970 record_equivalences_from_stmt (stmt,
2971 may_optimize_p,
2972 ann);
2974 register_definitions_for_stmt (stmt);
2976 /* If STMT is a COND_EXPR and it was modified, then we may know
2977 where it goes. If that is the case, then mark the CFG as altered.
2979 This will cause us to later call remove_unreachable_blocks and
2980 cleanup_tree_cfg when it is safe to do so. It is not safe to
2981 clean things up here since removal of edges and such can trigger
2982 the removal of PHI nodes, which in turn can release SSA_NAMEs to
2983 the manager.
2985 That's all fine and good, except that once SSA_NAMEs are released
2986 to the manager, we must not call create_ssa_name until all references
2987 to released SSA_NAMEs have been eliminated.
2989 All references to the deleted SSA_NAMEs can not be eliminated until
2990 we remove unreachable blocks.
2992 We can not remove unreachable blocks until after we have completed
2993 any queued jump threading.
2995 We can not complete any queued jump threads until we have taken
2996 appropriate variables out of SSA form. Taking variables out of
2997 SSA form can call create_ssa_name and thus we lose.
2999 Ultimately I suspect we're going to need to change the interface
3000 into the SSA_NAME manager. */
3002 if (ann->modified)
3004 tree val = NULL;
3006 if (TREE_CODE (stmt) == COND_EXPR)
3007 val = COND_EXPR_COND (stmt);
3008 else if (TREE_CODE (stmt) == SWITCH_EXPR)
3009 val = SWITCH_COND (stmt);
3011 if (val && TREE_CODE (val) == INTEGER_CST && find_taken_edge (bb, val))
3012 cfg_altered = true;
3014 /* If we simplified a statement in such a way as to be shown that it
3015 cannot trap, update the eh information and the cfg to match. */
3016 if (maybe_clean_eh_stmt (stmt))
3018 bitmap_set_bit (need_eh_cleanup, bb->index);
3019 if (dump_file && (dump_flags & TDF_DETAILS))
3020 fprintf (dump_file, " Flagged to clear EH edges.\n");
3024 if (may_have_exposed_new_symbols)
3025 VEC_safe_push (tree_on_heap, stmts_to_rescan, bsi_stmt (si));
3028 /* Replace the RHS of STMT with NEW_RHS. If RHS can be found in the
3029 available expression hashtable, then return the LHS from the hash
3030 table.
3032 If INSERT is true, then we also update the available expression
3033 hash table to account for the changes made to STMT. */
3035 static tree
3036 update_rhs_and_lookup_avail_expr (tree stmt, tree new_rhs, bool insert)
3038 tree cached_lhs = NULL;
3040 /* Remove the old entry from the hash table. */
3041 if (insert)
3043 struct expr_hash_elt element;
3045 initialize_hash_element (stmt, NULL, &element);
3046 htab_remove_elt_with_hash (avail_exprs, &element, element.hash);
3049 /* Now update the RHS of the assignment. */
3050 TREE_OPERAND (stmt, 1) = new_rhs;
3052 /* Now lookup the updated statement in the hash table. */
3053 cached_lhs = lookup_avail_expr (stmt, insert);
3055 /* We have now called lookup_avail_expr twice with two different
3056 versions of this same statement, once in optimize_stmt, once here.
3058 We know the call in optimize_stmt did not find an existing entry
3059 in the hash table, so a new entry was created. At the same time
3060 this statement was pushed onto the AVAIL_EXPRS_STACK vector.
3062 If this call failed to find an existing entry on the hash table,
3063 then the new version of this statement was entered into the
3064 hash table. And this statement was pushed onto BLOCK_AVAIL_EXPR
3065 for the second time. So there are two copies on BLOCK_AVAIL_EXPRs
3067 If this call succeeded, we still have one copy of this statement
3068 on the BLOCK_AVAIL_EXPRs vector.
3070 For both cases, we need to pop the most recent entry off the
3071 BLOCK_AVAIL_EXPRs vector. For the case where we never found this
3072 statement in the hash tables, that will leave precisely one
3073 copy of this statement on BLOCK_AVAIL_EXPRs. For the case where
3074 we found a copy of this statement in the second hash table lookup
3075 we want _no_ copies of this statement in BLOCK_AVAIL_EXPRs. */
3076 if (insert)
3077 VEC_pop (tree_on_heap, avail_exprs_stack);
3079 /* And make sure we record the fact that we modified this
3080 statement. */
3081 modify_stmt (stmt);
3083 return cached_lhs;
3086 /* Search for an existing instance of STMT in the AVAIL_EXPRS table. If
3087 found, return its LHS. Otherwise insert STMT in the table and return
3088 NULL_TREE.
3090 Also, when an expression is first inserted in the AVAIL_EXPRS table, it
3091 is also added to the stack pointed by BLOCK_AVAIL_EXPRS_P, so that they
3092 can be removed when we finish processing this block and its children.
3094 NOTE: This function assumes that STMT is a MODIFY_EXPR node that
3095 contains no CALL_EXPR on its RHS and makes no volatile nor
3096 aliased references. */
3098 static tree
3099 lookup_avail_expr (tree stmt, bool insert)
3101 void **slot;
3102 tree lhs;
3103 tree temp;
3104 struct expr_hash_elt *element = xcalloc (sizeof (struct expr_hash_elt), 1);
3106 lhs = TREE_CODE (stmt) == MODIFY_EXPR ? TREE_OPERAND (stmt, 0) : NULL;
3108 initialize_hash_element (stmt, lhs, element);
3110 /* Don't bother remembering constant assignments and copy operations.
3111 Constants and copy operations are handled by the constant/copy propagator
3112 in optimize_stmt. */
3113 if (TREE_CODE (element->rhs) == SSA_NAME
3114 || is_gimple_min_invariant (element->rhs))
3116 free (element);
3117 return NULL_TREE;
3120 /* If this is an equality test against zero, see if we have recorded a
3121 nonzero value for the variable in question. */
3122 if ((TREE_CODE (element->rhs) == EQ_EXPR
3123 || TREE_CODE (element->rhs) == NE_EXPR)
3124 && TREE_CODE (TREE_OPERAND (element->rhs, 0)) == SSA_NAME
3125 && integer_zerop (TREE_OPERAND (element->rhs, 1)))
3127 int indx = SSA_NAME_VERSION (TREE_OPERAND (element->rhs, 0));
3129 if (bitmap_bit_p (nonzero_vars, indx))
3131 tree t = element->rhs;
3132 free (element);
3134 if (TREE_CODE (t) == EQ_EXPR)
3135 return boolean_false_node;
3136 else
3137 return boolean_true_node;
3141 /* Finally try to find the expression in the main expression hash table. */
3142 slot = htab_find_slot_with_hash (avail_exprs, element, element->hash,
3143 (insert ? INSERT : NO_INSERT));
3144 if (slot == NULL)
3146 free (element);
3147 return NULL_TREE;
3150 if (*slot == NULL)
3152 *slot = (void *) element;
3153 VEC_safe_push (tree_on_heap, avail_exprs_stack,
3154 stmt ? stmt : element->rhs);
3155 return NULL_TREE;
3158 /* Extract the LHS of the assignment so that it can be used as the current
3159 definition of another variable. */
3160 lhs = ((struct expr_hash_elt *)*slot)->lhs;
3162 /* See if the LHS appears in the CONST_AND_COPIES table. If it does, then
3163 use the value from the const_and_copies table. */
3164 if (TREE_CODE (lhs) == SSA_NAME)
3166 temp = SSA_NAME_VALUE (lhs);
3167 if (temp && TREE_CODE (temp) != VALUE_HANDLE)
3168 lhs = temp;
3171 free (element);
3172 return lhs;
3175 /* Given a condition COND, record into HI_P, LO_P and INVERTED_P the
3176 range of values that result in the conditional having a true value.
3178 Return true if we are successful in extracting a range from COND and
3179 false if we are unsuccessful. */
3181 static bool
3182 extract_range_from_cond (tree cond, tree *hi_p, tree *lo_p, int *inverted_p)
3184 tree op1 = TREE_OPERAND (cond, 1);
3185 tree high, low, type;
3186 int inverted;
3188 /* Experiments have shown that it's rarely, if ever useful to
3189 record ranges for enumerations. Presumably this is due to
3190 the fact that they're rarely used directly. They are typically
3191 cast into an integer type and used that way. */
3192 if (TREE_CODE (TREE_TYPE (op1)) != INTEGER_TYPE)
3193 return 0;
3195 type = TREE_TYPE (op1);
3197 switch (TREE_CODE (cond))
3199 case EQ_EXPR:
3200 high = low = op1;
3201 inverted = 0;
3202 break;
3204 case NE_EXPR:
3205 high = low = op1;
3206 inverted = 1;
3207 break;
3209 case GE_EXPR:
3210 low = op1;
3211 high = TYPE_MAX_VALUE (type);
3212 inverted = 0;
3213 break;
3215 case GT_EXPR:
3216 low = int_const_binop (PLUS_EXPR, op1, integer_one_node, 1);
3217 high = TYPE_MAX_VALUE (type);
3218 inverted = 0;
3219 break;
3221 case LE_EXPR:
3222 high = op1;
3223 low = TYPE_MIN_VALUE (type);
3224 inverted = 0;
3225 break;
3227 case LT_EXPR:
3228 high = int_const_binop (MINUS_EXPR, op1, integer_one_node, 1);
3229 low = TYPE_MIN_VALUE (type);
3230 inverted = 0;
3231 break;
3233 default:
3234 return 0;
3237 *hi_p = high;
3238 *lo_p = low;
3239 *inverted_p = inverted;
3240 return 1;
3243 /* Record a range created by COND for basic block BB. */
3245 static void
3246 record_range (tree cond, basic_block bb)
3248 enum tree_code code = TREE_CODE (cond);
3250 /* We explicitly ignore NE_EXPRs and all the unordered comparisons.
3251 They rarely allow for meaningful range optimizations and significantly
3252 complicate the implementation. */
3253 if ((code == LT_EXPR || code == LE_EXPR || code == GT_EXPR
3254 || code == GE_EXPR || code == EQ_EXPR)
3255 && TREE_CODE (TREE_TYPE (TREE_OPERAND (cond, 1))) == INTEGER_TYPE)
3257 struct vrp_hash_elt *vrp_hash_elt;
3258 struct vrp_element *element;
3259 varray_type *vrp_records_p;
3260 void **slot;
3263 vrp_hash_elt = xmalloc (sizeof (struct vrp_hash_elt));
3264 vrp_hash_elt->var = TREE_OPERAND (cond, 0);
3265 vrp_hash_elt->records = NULL;
3266 slot = htab_find_slot (vrp_data, vrp_hash_elt, INSERT);
3268 if (*slot == NULL)
3269 *slot = (void *) vrp_hash_elt;
3270 else
3271 free (vrp_hash_elt);
3273 vrp_hash_elt = (struct vrp_hash_elt *) *slot;
3274 vrp_records_p = &vrp_hash_elt->records;
3276 element = ggc_alloc (sizeof (struct vrp_element));
3277 element->low = NULL;
3278 element->high = NULL;
3279 element->cond = cond;
3280 element->bb = bb;
3282 if (*vrp_records_p == NULL)
3283 VARRAY_GENERIC_PTR_INIT (*vrp_records_p, 2, "vrp records");
3285 VARRAY_PUSH_GENERIC_PTR (*vrp_records_p, element);
3286 VEC_safe_push (tree_on_heap, vrp_variables_stack, TREE_OPERAND (cond, 0));
3290 /* Hashing and equality functions for VRP_DATA.
3292 Since this hash table is addressed by SSA_NAMEs, we can hash on
3293 their version number and equality can be determined with a
3294 pointer comparison. */
3296 static hashval_t
3297 vrp_hash (const void *p)
3299 tree var = ((struct vrp_hash_elt *)p)->var;
3301 return SSA_NAME_VERSION (var);
3304 static int
3305 vrp_eq (const void *p1, const void *p2)
3307 tree var1 = ((struct vrp_hash_elt *)p1)->var;
3308 tree var2 = ((struct vrp_hash_elt *)p2)->var;
3310 return var1 == var2;
3313 /* Hashing and equality functions for AVAIL_EXPRS. The table stores
3314 MODIFY_EXPR statements. We compute a value number for expressions using
3315 the code of the expression and the SSA numbers of its operands. */
3317 static hashval_t
3318 avail_expr_hash (const void *p)
3320 stmt_ann_t ann = ((struct expr_hash_elt *)p)->ann;
3321 tree rhs = ((struct expr_hash_elt *)p)->rhs;
3322 hashval_t val = 0;
3323 size_t i;
3324 vuse_optype vuses;
3326 /* iterative_hash_expr knows how to deal with any expression and
3327 deals with commutative operators as well, so just use it instead
3328 of duplicating such complexities here. */
3329 val = iterative_hash_expr (rhs, val);
3331 /* If the hash table entry is not associated with a statement, then we
3332 can just hash the expression and not worry about virtual operands
3333 and such. */
3334 if (!ann)
3335 return val;
3337 /* Add the SSA version numbers of every vuse operand. This is important
3338 because compound variables like arrays are not renamed in the
3339 operands. Rather, the rename is done on the virtual variable
3340 representing all the elements of the array. */
3341 vuses = VUSE_OPS (ann);
3342 for (i = 0; i < NUM_VUSES (vuses); i++)
3343 val = iterative_hash_expr (VUSE_OP (vuses, i), val);
3345 return val;
3348 static hashval_t
3349 real_avail_expr_hash (const void *p)
3351 return ((const struct expr_hash_elt *)p)->hash;
3354 static int
3355 avail_expr_eq (const void *p1, const void *p2)
3357 stmt_ann_t ann1 = ((struct expr_hash_elt *)p1)->ann;
3358 tree rhs1 = ((struct expr_hash_elt *)p1)->rhs;
3359 stmt_ann_t ann2 = ((struct expr_hash_elt *)p2)->ann;
3360 tree rhs2 = ((struct expr_hash_elt *)p2)->rhs;
3362 /* If they are the same physical expression, return true. */
3363 if (rhs1 == rhs2 && ann1 == ann2)
3364 return true;
3366 /* If their codes are not equal, then quit now. */
3367 if (TREE_CODE (rhs1) != TREE_CODE (rhs2))
3368 return false;
3370 /* In case of a collision, both RHS have to be identical and have the
3371 same VUSE operands. */
3372 if ((TREE_TYPE (rhs1) == TREE_TYPE (rhs2)
3373 || lang_hooks.types_compatible_p (TREE_TYPE (rhs1), TREE_TYPE (rhs2)))
3374 && operand_equal_p (rhs1, rhs2, OEP_PURE_SAME))
3376 vuse_optype ops1 = NULL;
3377 vuse_optype ops2 = NULL;
3378 size_t num_ops1 = 0;
3379 size_t num_ops2 = 0;
3380 size_t i;
3382 if (ann1)
3384 ops1 = VUSE_OPS (ann1);
3385 num_ops1 = NUM_VUSES (ops1);
3388 if (ann2)
3390 ops2 = VUSE_OPS (ann2);
3391 num_ops2 = NUM_VUSES (ops2);
3394 /* If the number of virtual uses is different, then we consider
3395 them not equal. */
3396 if (num_ops1 != num_ops2)
3397 return false;
3399 for (i = 0; i < num_ops1; i++)
3400 if (VUSE_OP (ops1, i) != VUSE_OP (ops2, i))
3401 return false;
3403 gcc_assert (((struct expr_hash_elt *)p1)->hash
3404 == ((struct expr_hash_elt *)p2)->hash);
3405 return true;
3408 return false;
3411 /* Given STMT and a pointer to the block local definitions BLOCK_DEFS_P,
3412 register register all objects set by this statement into BLOCK_DEFS_P
3413 and CURRDEFS. */
3415 static void
3416 register_definitions_for_stmt (tree stmt)
3418 tree def;
3419 ssa_op_iter iter;
3421 FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_ALL_DEFS)
3424 /* FIXME: We shouldn't be registering new defs if the variable
3425 doesn't need to be renamed. */
3426 register_new_def (def, &block_defs_stack);