PR tree-optimization/17468
[official-gcc.git] / gcc / tree-ssa-dom.c
blobf090c8738d1abb20c40da5695c20fd433b6e6673
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 "langhooks.h"
45 /* This file implements optimizations on the dominator tree. */
47 /* Hash table with expressions made available during the renaming process.
48 When an assignment of the form X_i = EXPR is found, the statement is
49 stored in this table. If the same expression EXPR is later found on the
50 RHS of another statement, it is replaced with X_i (thus performing
51 global redundancy elimination). Similarly as we pass through conditionals
52 we record the conditional itself as having either a true or false value
53 in this table. */
54 static htab_t avail_exprs;
56 /* Stack of available expressions in AVAIL_EXPRs. Each block pushes any
57 expressions it enters into the hash table along with a marker entry
58 (null). When we finsh processing the block, we pop off entries and
59 remove the expressions from the global hash table until we hit the
60 marker. */
61 static varray_type avail_exprs_stack;
63 /* Stack of statements we need to rescan during finalization for newly
64 exposed variables.
66 Statement rescanning must occur after the current block's available
67 expressions are removed from AVAIL_EXPRS. Else we may change the
68 hash code for an expression and be unable to find/remove it from
69 AVAIL_EXPRS. */
70 varray_type stmts_to_rescan;
72 /* Structure for entries in the expression hash table.
74 This requires more memory for the hash table entries, but allows us
75 to avoid creating silly tree nodes and annotations for conditionals,
76 eliminates 2 global hash tables and two block local varrays.
78 It also allows us to reduce the number of hash table lookups we
79 have to perform in lookup_avail_expr and finally it allows us to
80 significantly reduce the number of calls into the hashing routine
81 itself. */
83 struct expr_hash_elt
85 /* The value (lhs) of this expression. */
86 tree lhs;
88 /* The expression (rhs) we want to record. */
89 tree rhs;
91 /* The annotation if this element corresponds to a statement. */
92 stmt_ann_t ann;
94 /* The hash value for RHS/ann. */
95 hashval_t hash;
98 /* Table of constant values and copies indexed by SSA name. When the
99 renaming pass finds an assignment of a constant (X_i = C) or a copy
100 assignment from another SSA variable (X_i = Y_j), it creates a mapping
101 between X_i and the RHS in this table. This mapping is used later on,
102 when renaming uses of X_i. If an assignment to X_i is found in this
103 table, instead of using X_i, we use the RHS of the statement stored in
104 this table (thus performing very simplistic copy and constant
105 propagation). */
106 static varray_type const_and_copies;
108 /* Bitmap of SSA_NAMEs known to have a nonzero value, even if we do not
109 know their exact value. */
110 static bitmap nonzero_vars;
112 /* Track whether or not we have changed the control flow graph. */
113 static bool cfg_altered;
115 /* Bitmap of blocks that have had EH statements cleaned. We should
116 remove their dead edges eventually. */
117 static bitmap need_eh_cleanup;
119 /* Statistics for dominator optimizations. */
120 struct opt_stats_d
122 long num_stmts;
123 long num_exprs_considered;
124 long num_re;
127 /* Value range propagation record. Each time we encounter a conditional
128 of the form SSA_NAME COND CONST we create a new vrp_element to record
129 how the condition affects the possible values SSA_NAME may have.
131 Each record contains the condition tested (COND), and the the range of
132 values the variable may legitimately have if COND is true. Note the
133 range of values may be a smaller range than COND specifies if we have
134 recorded other ranges for this variable. Each record also contains the
135 block in which the range was recorded for invalidation purposes.
137 Note that the current known range is computed lazily. This allows us
138 to avoid the overhead of computing ranges which are never queried.
140 When we encounter a conditional, we look for records which constrain
141 the SSA_NAME used in the condition. In some cases those records allow
142 us to determine the condition's result at compile time. In other cases
143 they may allow us to simplify the condition.
145 We also use value ranges to do things like transform signed div/mod
146 operations into unsigned div/mod or to simplify ABS_EXPRs.
148 Simple experiments have shown these optimizations to not be all that
149 useful on switch statements (much to my surprise). So switch statement
150 optimizations are not performed.
152 Note carefully we do not propagate information through each statement
153 in the block. ie, if we know variable X has a value defined of
154 [0, 25] and we encounter Y = X + 1, we do not track a value range
155 for Y (which would be [1, 26] if we cared). Similarly we do not
156 constrain values as we encounter narrowing typecasts, etc. */
158 struct vrp_element
160 /* The highest and lowest values the variable in COND may contain when
161 COND is true. Note this may not necessarily be the same values
162 tested by COND if the same variable was used in earlier conditionals.
164 Note this is computed lazily and thus can be NULL indicating that
165 the values have not been computed yet. */
166 tree low;
167 tree high;
169 /* The actual conditional we recorded. This is needed since we compute
170 ranges lazily. */
171 tree cond;
173 /* The basic block where this record was created. We use this to determine
174 when to remove records. */
175 basic_block bb;
178 static struct opt_stats_d opt_stats;
180 /* A virtual array holding value range records for the variable identified
181 by the index, SSA_VERSION. */
182 static varray_type vrp_data;
184 /* Datastructure for block local data used during the dominator walk.
185 We maintain a stack of these as we recursively walk down the
186 dominator tree. */
188 struct dom_walk_block_data
190 /* Array of dest, src pairs that need to be restored during finalization
191 into the global const/copies table during finalization. */
192 varray_type const_and_copies;
194 /* Similarly for the nonzero state of variables that needs to be
195 restored during finalization. */
196 varray_type nonzero_vars;
198 /* Array of variables which have their values constrained by operations
199 in this basic block. We use this during finalization to know
200 which variables need their VRP data updated. */
201 varray_type vrp_variables;
203 /* Array of tree pairs used to restore the global currdefs to its
204 original state after completing optimization of a block and its
205 dominator children. */
206 varray_type block_defs;
209 struct eq_expr_value
211 tree src;
212 tree dst;
215 /* Local functions. */
216 static void optimize_stmt (struct dom_walk_data *,
217 basic_block bb,
218 block_stmt_iterator);
219 static inline tree get_value_for (tree, varray_type table);
220 static inline void set_value_for (tree, tree, varray_type table);
221 static tree lookup_avail_expr (tree, bool);
222 static struct eq_expr_value get_eq_expr_value (tree, int,
223 basic_block, varray_type *);
224 static hashval_t avail_expr_hash (const void *);
225 static hashval_t real_avail_expr_hash (const void *);
226 static int avail_expr_eq (const void *, const void *);
227 static void htab_statistics (FILE *, htab_t);
228 static void record_cond (tree, tree);
229 static void record_dominating_conditions (tree);
230 static void record_const_or_copy (tree, tree, varray_type *);
231 static void record_equality (tree, tree, varray_type *);
232 static tree update_rhs_and_lookup_avail_expr (tree, tree, bool);
233 static tree simplify_rhs_and_lookup_avail_expr (struct dom_walk_data *,
234 tree, int);
235 static tree simplify_cond_and_lookup_avail_expr (tree, stmt_ann_t, int);
236 static tree simplify_switch_and_lookup_avail_expr (tree, int);
237 static tree find_equivalent_equality_comparison (tree);
238 static void record_range (tree, basic_block, varray_type *);
239 static bool extract_range_from_cond (tree, tree *, tree *, int *);
240 static void record_equivalences_from_phis (struct dom_walk_data *, basic_block);
241 static void record_equivalences_from_incoming_edge (struct dom_walk_data *,
242 basic_block);
243 static bool eliminate_redundant_computations (struct dom_walk_data *,
244 tree, stmt_ann_t);
245 static void record_equivalences_from_stmt (tree, varray_type *,
246 int, stmt_ann_t);
247 static void thread_across_edge (struct dom_walk_data *, edge);
248 static void dom_opt_finalize_block (struct dom_walk_data *, basic_block);
249 static void dom_opt_initialize_block_local_data (struct dom_walk_data *,
250 basic_block, bool);
251 static void dom_opt_initialize_block (struct dom_walk_data *, basic_block);
252 static void cprop_into_phis (struct dom_walk_data *, basic_block);
253 static void remove_local_expressions_from_table (void);
254 static void restore_vars_to_original_value (varray_type locals,
255 unsigned limit,
256 varray_type table);
257 static void restore_currdefs_to_original_value (varray_type locals,
258 unsigned limit);
259 static void register_definitions_for_stmt (tree, varray_type *);
260 static edge single_incoming_edge_ignoring_loop_edges (basic_block);
262 /* Local version of fold that doesn't introduce cruft. */
264 static tree
265 local_fold (tree t)
267 t = fold (t);
269 /* Strip away useless type conversions. Both the NON_LVALUE_EXPR that
270 may have been added by fold, and "useless" type conversions that might
271 now be apparent due to propagation. */
272 STRIP_USELESS_TYPE_CONVERSION (t);
274 return t;
277 /* Return the value associated with variable VAR in TABLE. */
279 static inline tree
280 get_value_for (tree var, varray_type table)
282 return VARRAY_TREE (table, SSA_NAME_VERSION (var));
285 /* Associate VALUE to variable VAR in TABLE. */
287 static inline void
288 set_value_for (tree var, tree value, varray_type table)
290 VARRAY_TREE (table, SSA_NAME_VERSION (var)) = value;
293 /* Jump threading, redundancy elimination and const/copy propagation.
295 This pass may expose new symbols that need to be renamed into SSA. For
296 every new symbol exposed, its corresponding bit will be set in
297 VARS_TO_RENAME. */
299 static void
300 tree_ssa_dominator_optimize (void)
302 struct dom_walk_data walk_data;
303 unsigned int i;
305 for (i = 0; i < num_referenced_vars; i++)
306 var_ann (referenced_var (i))->current_def = NULL;
308 /* Mark loop edges so we avoid threading across loop boundaries.
309 This may result in transforming natural loop into irreducible
310 region. */
311 mark_dfs_back_edges ();
313 /* Create our hash tables. */
314 avail_exprs = htab_create (1024, real_avail_expr_hash, avail_expr_eq, free);
315 VARRAY_TREE_INIT (avail_exprs_stack, 20, "Available expression stack");
316 VARRAY_TREE_INIT (const_and_copies, num_ssa_names, "const_and_copies");
317 nonzero_vars = BITMAP_XMALLOC ();
318 VARRAY_GENERIC_PTR_INIT (vrp_data, num_ssa_names, "vrp_data");
319 need_eh_cleanup = BITMAP_XMALLOC ();
320 VARRAY_TREE_INIT (stmts_to_rescan, 20, "Statements to rescan");
322 /* Setup callbacks for the generic dominator tree walker. */
323 walk_data.walk_stmts_backward = false;
324 walk_data.dom_direction = CDI_DOMINATORS;
325 walk_data.initialize_block_local_data = dom_opt_initialize_block_local_data;
326 walk_data.before_dom_children_before_stmts = dom_opt_initialize_block;
327 walk_data.before_dom_children_walk_stmts = optimize_stmt;
328 walk_data.before_dom_children_after_stmts = cprop_into_phis;
329 walk_data.after_dom_children_before_stmts = NULL;
330 walk_data.after_dom_children_walk_stmts = NULL;
331 walk_data.after_dom_children_after_stmts = dom_opt_finalize_block;
332 /* Right now we only attach a dummy COND_EXPR to the global data pointer.
333 When we attach more stuff we'll need to fill this out with a real
334 structure. */
335 walk_data.global_data = NULL;
336 walk_data.block_local_data_size = sizeof (struct dom_walk_block_data);
338 /* Now initialize the dominator walker. */
339 init_walk_dominator_tree (&walk_data);
341 calculate_dominance_info (CDI_DOMINATORS);
343 /* If we prove certain blocks are unreachable, then we want to
344 repeat the dominator optimization process as PHI nodes may
345 have turned into copies which allows better propagation of
346 values. So we repeat until we do not identify any new unreachable
347 blocks. */
350 /* Optimize the dominator tree. */
351 cfg_altered = false;
353 /* Recursively walk the dominator tree optimizing statements. */
354 walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);
356 /* If we exposed any new variables, go ahead and put them into
357 SSA form now, before we handle jump threading. This simplifies
358 interactions between rewriting of _DECL nodes into SSA form
359 and rewriting SSA_NAME nodes into SSA form after block
360 duplication and CFG manipulation. */
361 if (bitmap_first_set_bit (vars_to_rename) >= 0)
363 rewrite_into_ssa (false);
364 bitmap_clear (vars_to_rename);
367 /* Thread jumps, creating duplicate blocks as needed. */
368 cfg_altered = thread_through_all_blocks ();
370 /* Removal of statements may make some EH edges dead. Purge
371 such edges from the CFG as needed. */
372 if (bitmap_first_set_bit (need_eh_cleanup) >= 0)
374 cfg_altered |= tree_purge_all_dead_eh_edges (need_eh_cleanup);
375 bitmap_zero (need_eh_cleanup);
378 free_dominance_info (CDI_DOMINATORS);
379 cfg_altered = cleanup_tree_cfg ();
380 calculate_dominance_info (CDI_DOMINATORS);
382 rewrite_ssa_into_ssa ();
384 if (VARRAY_ACTIVE_SIZE (const_and_copies) <= num_ssa_names)
386 VARRAY_GROW (const_and_copies, num_ssa_names);
387 VARRAY_GROW (vrp_data, num_ssa_names);
390 /* Reinitialize the various tables. */
391 bitmap_clear (nonzero_vars);
392 htab_empty (avail_exprs);
393 VARRAY_CLEAR (const_and_copies);
394 VARRAY_CLEAR (vrp_data);
396 for (i = 0; i < num_referenced_vars; i++)
397 var_ann (referenced_var (i))->current_def = NULL;
399 while (cfg_altered);
401 /* Debugging dumps. */
402 if (dump_file && (dump_flags & TDF_STATS))
403 dump_dominator_optimization_stats (dump_file);
405 /* We emptied the hash table earlier, now delete it completely. */
406 htab_delete (avail_exprs);
408 /* It is not necessary to clear CURRDEFS, REDIRECTION_EDGES, VRP_DATA,
409 CONST_AND_COPIES, and NONZERO_VARS as they all get cleared at the bottom
410 of the do-while loop above. */
412 /* And finalize the dominator walker. */
413 fini_walk_dominator_tree (&walk_data);
415 /* Free nonzero_vars. */
416 BITMAP_XFREE (nonzero_vars);
417 BITMAP_XFREE (need_eh_cleanup);
420 static bool
421 gate_dominator (void)
423 return flag_tree_dom != 0;
426 struct tree_opt_pass pass_dominator =
428 "dom", /* name */
429 gate_dominator, /* gate */
430 tree_ssa_dominator_optimize, /* execute */
431 NULL, /* sub */
432 NULL, /* next */
433 0, /* static_pass_number */
434 TV_TREE_SSA_DOMINATOR_OPTS, /* tv_id */
435 PROP_cfg | PROP_ssa | PROP_alias, /* properties_required */
436 0, /* properties_provided */
437 0, /* properties_destroyed */
438 0, /* todo_flags_start */
439 TODO_dump_func | TODO_rename_vars
440 | TODO_verify_ssa, /* todo_flags_finish */
441 0 /* letter */
445 /* We are exiting BB, see if the target block begins with a conditional
446 jump which has a known value when reached via BB. */
448 static void
449 thread_across_edge (struct dom_walk_data *walk_data, edge e)
451 struct dom_walk_block_data *bd
452 = VARRAY_TOP_GENERIC_PTR (walk_data->block_data_stack);
453 block_stmt_iterator bsi;
454 tree stmt = NULL;
455 tree phi;
457 /* Each PHI creates a temporary equivalence, record them. */
458 for (phi = phi_nodes (e->dest); phi; phi = PHI_CHAIN (phi))
460 tree src = PHI_ARG_DEF_FROM_EDGE (phi, e);
461 tree dst = PHI_RESULT (phi);
462 record_const_or_copy (dst, src, &bd->const_and_copies);
463 register_new_def (dst, &bd->block_defs);
466 for (bsi = bsi_start (e->dest); ! bsi_end_p (bsi); bsi_next (&bsi))
468 tree lhs, cached_lhs;
470 stmt = bsi_stmt (bsi);
472 /* Ignore empty statements and labels. */
473 if (IS_EMPTY_STMT (stmt) || TREE_CODE (stmt) == LABEL_EXPR)
474 continue;
476 /* If this is not a MODIFY_EXPR which sets an SSA_NAME to a new
477 value, then stop our search here. Ideally when we stop a
478 search we stop on a COND_EXPR or SWITCH_EXPR. */
479 if (TREE_CODE (stmt) != MODIFY_EXPR
480 || TREE_CODE (TREE_OPERAND (stmt, 0)) != SSA_NAME)
481 break;
483 /* At this point we have a statement which assigns an RHS to an
484 SSA_VAR on the LHS. We want to prove that the RHS is already
485 available and that its value is held in the current definition
486 of the LHS -- meaning that this assignment is a NOP when
487 reached via edge E. */
488 if (TREE_CODE (TREE_OPERAND (stmt, 1)) == SSA_NAME)
489 cached_lhs = TREE_OPERAND (stmt, 1);
490 else
491 cached_lhs = lookup_avail_expr (stmt, false);
493 lhs = TREE_OPERAND (stmt, 0);
495 /* This can happen if we thread around to the start of a loop. */
496 if (lhs == cached_lhs)
497 break;
499 /* If we did not find RHS in the hash table, then try again after
500 temporarily const/copy propagating the operands. */
501 if (!cached_lhs)
503 /* Copy the operands. */
504 stmt_ann_t ann = stmt_ann (stmt);
505 use_optype uses = USE_OPS (ann);
506 vuse_optype vuses = VUSE_OPS (ann);
507 tree *uses_copy = xcalloc (NUM_USES (uses), sizeof (tree));
508 tree *vuses_copy = xcalloc (NUM_VUSES (vuses), sizeof (tree));
509 unsigned int i;
511 /* Make a copy of the uses into USES_COPY, then cprop into
512 the use operands. */
513 for (i = 0; i < NUM_USES (uses); i++)
515 tree tmp = NULL;
517 uses_copy[i] = USE_OP (uses, i);
518 if (TREE_CODE (USE_OP (uses, i)) == SSA_NAME)
519 tmp = get_value_for (USE_OP (uses, i), const_and_copies);
520 if (tmp)
521 SET_USE_OP (uses, i, tmp);
524 /* Similarly for virtual uses. */
525 for (i = 0; i < NUM_VUSES (vuses); i++)
527 tree tmp = NULL;
529 vuses_copy[i] = VUSE_OP (vuses, i);
530 if (TREE_CODE (VUSE_OP (vuses, i)) == SSA_NAME)
531 tmp = get_value_for (VUSE_OP (vuses, i), const_and_copies);
532 if (tmp)
533 SET_VUSE_OP (vuses, i, tmp);
536 /* Try to lookup the new expression. */
537 cached_lhs = lookup_avail_expr (stmt, false);
539 /* Restore the statement's original uses/defs. */
540 for (i = 0; i < NUM_USES (uses); i++)
541 SET_USE_OP (uses, i, uses_copy[i]);
543 for (i = 0; i < NUM_VUSES (vuses); i++)
544 SET_VUSE_OP (vuses, i, vuses_copy[i]);
546 free (uses_copy);
547 free (vuses_copy);
549 /* If we still did not find the expression in the hash table,
550 then we can not ignore this statement. */
551 if (! cached_lhs)
552 break;
555 /* If the expression in the hash table was not assigned to an
556 SSA_NAME, then we can not ignore this statement. */
557 if (TREE_CODE (cached_lhs) != SSA_NAME)
558 break;
560 /* If we have different underlying variables, then we can not
561 ignore this statement. */
562 if (SSA_NAME_VAR (cached_lhs) != SSA_NAME_VAR (lhs))
563 break;
565 /* If CACHED_LHS does not represent the current value of the undering
566 variable in CACHED_LHS/LHS, then we can not ignore this statement. */
567 if (var_ann (SSA_NAME_VAR (lhs))->current_def != cached_lhs)
568 break;
570 /* If we got here, then we can ignore this statement and continue
571 walking through the statements in the block looking for a threadable
572 COND_EXPR.
574 We want to record an equivalence lhs = cache_lhs so that if
575 the result of this statement is used later we can copy propagate
576 suitably. */
577 record_const_or_copy (lhs, cached_lhs, &bd->const_and_copies);
578 register_new_def (lhs, &bd->block_defs);
581 /* If we stopped at a COND_EXPR or SWITCH_EXPR, then see if we know which
582 arm will be taken. */
583 if (stmt
584 && (TREE_CODE (stmt) == COND_EXPR
585 || TREE_CODE (stmt) == SWITCH_EXPR))
587 tree cond, cached_lhs;
588 edge e1;
590 /* Do not forward entry edges into the loop. In the case loop
591 has multiple entry edges we may end up in constructing irreducible
592 region.
593 ??? We may consider forwarding the edges in the case all incoming
594 edges forward to the same destination block. */
595 if (!e->flags & EDGE_DFS_BACK)
597 for (e1 = e->dest->pred; e; e = e->pred_next)
598 if (e1->flags & EDGE_DFS_BACK)
599 break;
600 if (e1)
601 return;
604 /* Now temporarily cprop the operands and try to find the resulting
605 expression in the hash tables. */
606 if (TREE_CODE (stmt) == COND_EXPR)
607 cond = COND_EXPR_COND (stmt);
608 else
609 cond = SWITCH_COND (stmt);
611 if (TREE_CODE_CLASS (TREE_CODE (cond)) == '<')
613 tree dummy_cond, op0, op1;
614 enum tree_code cond_code;
616 op0 = TREE_OPERAND (cond, 0);
617 op1 = TREE_OPERAND (cond, 1);
618 cond_code = TREE_CODE (cond);
620 /* Get the current value of both operands. */
621 if (TREE_CODE (op0) == SSA_NAME)
623 tree tmp = get_value_for (op0, const_and_copies);
624 if (tmp)
625 op0 = tmp;
628 if (TREE_CODE (op1) == SSA_NAME)
630 tree tmp = get_value_for (op1, const_and_copies);
631 if (tmp)
632 op1 = tmp;
635 /* Stuff the operator and operands into our dummy conditional
636 expression, creating the dummy conditional if necessary. */
637 dummy_cond = walk_data->global_data;
638 if (! dummy_cond)
640 dummy_cond = build (cond_code, boolean_type_node, op0, op1);
641 dummy_cond = build (COND_EXPR, void_type_node,
642 dummy_cond, NULL, NULL);
643 walk_data->global_data = dummy_cond;
645 else
647 TREE_SET_CODE (TREE_OPERAND (dummy_cond, 0), cond_code);
648 TREE_OPERAND (TREE_OPERAND (dummy_cond, 0), 0) = op0;
649 TREE_OPERAND (TREE_OPERAND (dummy_cond, 0), 1) = op1;
652 /* If the conditional folds to an invariant, then we are done,
653 otherwise look it up in the hash tables. */
654 cached_lhs = local_fold (COND_EXPR_COND (dummy_cond));
655 if (! is_gimple_min_invariant (cached_lhs))
656 cached_lhs = lookup_avail_expr (dummy_cond, false);
657 if (!cached_lhs || ! is_gimple_min_invariant (cached_lhs))
659 cached_lhs = simplify_cond_and_lookup_avail_expr (dummy_cond,
660 NULL,
661 false);
664 /* We can have conditionals which just test the state of a
665 variable rather than use a relational operator. These are
666 simpler to handle. */
667 else if (TREE_CODE (cond) == SSA_NAME)
669 cached_lhs = cond;
670 cached_lhs = get_value_for (cached_lhs, const_and_copies);
671 if (cached_lhs && ! is_gimple_min_invariant (cached_lhs))
672 cached_lhs = 0;
674 else
675 cached_lhs = lookup_avail_expr (stmt, false);
677 if (cached_lhs)
679 edge taken_edge = find_taken_edge (e->dest, cached_lhs);
680 basic_block dest = (taken_edge ? taken_edge->dest : NULL);
682 if (dest == e->dest)
683 return;
685 /* If we have a known destination for the conditional, then
686 we can perform this optimization, which saves at least one
687 conditional jump each time it applies since we get to
688 bypass the conditional at our original destination. */
689 if (dest)
691 e->aux = taken_edge;
692 bb_ann (e->dest)->incoming_edge_threaded = true;
699 /* Initialize the local stacks.
701 AVAIL_EXPRS stores all the expressions made available in this block.
703 CONST_AND_COPIES stores var/value pairs to restore at the end of this
704 block.
706 NONZERO_VARS stores the vars which have a nonzero value made in this
707 block.
709 STMTS_TO_RESCAN is a list of statements we will rescan for operands.
711 VRP_VARIABLES is the list of variables which have had their values
712 constrained by an operation in this block.
714 These stacks are cleared in the finalization routine run for each
715 block. */
717 static void
718 dom_opt_initialize_block_local_data (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
719 basic_block bb ATTRIBUTE_UNUSED,
720 bool recycled ATTRIBUTE_UNUSED)
722 struct dom_walk_block_data *bd
723 = (struct dom_walk_block_data *)VARRAY_TOP_GENERIC_PTR (walk_data->block_data_stack);
725 /* We get cleared memory from the allocator, so if the memory is not
726 cleared, then we are re-using a previously allocated entry. In
727 that case, we can also re-use the underlying virtual arrays. Just
728 make sure we clear them before using them! */
729 if (recycled)
731 gcc_assert (!bd->const_and_copies
732 || VARRAY_ACTIVE_SIZE (bd->const_and_copies) == 0);
733 gcc_assert (!bd->nonzero_vars
734 || VARRAY_ACTIVE_SIZE (bd->nonzero_vars) == 0);
735 gcc_assert (!bd->vrp_variables
736 || VARRAY_ACTIVE_SIZE (bd->vrp_variables) == 0);
737 gcc_assert (!bd->block_defs
738 || VARRAY_ACTIVE_SIZE (bd->block_defs) == 0);
742 /* Initialize local stacks for this optimizer and record equivalences
743 upon entry to BB. Equivalences can come from the edge traversed to
744 reach BB or they may come from PHI nodes at the start of BB. */
746 static void
747 dom_opt_initialize_block (struct dom_walk_data *walk_data, basic_block bb)
749 if (dump_file && (dump_flags & TDF_DETAILS))
750 fprintf (dump_file, "\n\nOptimizing block #%d\n\n", bb->index);
752 /* Push a marker on AVAIL_EXPRS_STACK so that we know how far to unwind
753 when we finalize this blcok. */
754 VARRAY_PUSH_TREE (avail_exprs_stack, NULL_TREE);
756 record_equivalences_from_incoming_edge (walk_data, bb);
758 /* PHI nodes can create equivalences too. */
759 record_equivalences_from_phis (walk_data, bb);
762 /* Given an expression EXPR (a relational expression or a statement),
763 initialize the hash table element pointed by by ELEMENT. */
765 static void
766 initialize_hash_element (tree expr, tree lhs, struct expr_hash_elt *element)
768 /* Hash table elements may be based on conditional expressions or statements.
770 For the former case, we have no annotation and we want to hash the
771 conditional expression. In the latter case we have an annotation and
772 we want to record the expression the statement evaluates. */
773 if (TREE_CODE_CLASS (TREE_CODE (expr)) == '<'
774 || TREE_CODE (expr) == TRUTH_NOT_EXPR)
776 element->ann = NULL;
777 element->rhs = expr;
779 else if (TREE_CODE (expr) == COND_EXPR)
781 element->ann = stmt_ann (expr);
782 element->rhs = COND_EXPR_COND (expr);
784 else if (TREE_CODE (expr) == SWITCH_EXPR)
786 element->ann = stmt_ann (expr);
787 element->rhs = SWITCH_COND (expr);
789 else if (TREE_CODE (expr) == RETURN_EXPR && TREE_OPERAND (expr, 0))
791 element->ann = stmt_ann (expr);
792 element->rhs = TREE_OPERAND (TREE_OPERAND (expr, 0), 1);
794 else
796 element->ann = stmt_ann (expr);
797 element->rhs = TREE_OPERAND (expr, 1);
800 element->lhs = lhs;
801 element->hash = avail_expr_hash (element);
804 /* Remove all the expressions in LOCALS from TABLE, stopping when there are
805 LIMIT entries left in LOCALs. */
807 static void
808 remove_local_expressions_from_table (void)
810 /* Remove all the expressions made available in this block. */
811 while (VARRAY_ACTIVE_SIZE (avail_exprs_stack) > 0)
813 struct expr_hash_elt element;
814 tree expr = VARRAY_TOP_TREE (avail_exprs_stack);
815 VARRAY_POP (avail_exprs_stack);
817 if (expr == NULL_TREE)
818 break;
820 initialize_hash_element (expr, NULL, &element);
821 htab_remove_elt_with_hash (avail_exprs, &element, element.hash);
825 /* Use the SSA_NAMES in LOCALS to restore TABLE to its original
826 state, stopping when there are LIMIT entries left in LOCALs. */
828 static void
829 restore_nonzero_vars_to_original_value (varray_type locals,
830 unsigned limit,
831 bitmap table)
833 if (!locals)
834 return;
836 while (VARRAY_ACTIVE_SIZE (locals) > limit)
838 tree name = VARRAY_TOP_TREE (locals);
839 VARRAY_POP (locals);
840 bitmap_clear_bit (table, SSA_NAME_VERSION (name));
844 /* Use the source/dest pairs in LOCALS to restore TABLE to its original
845 state, stopping when there are LIMIT entries left in LOCALs. */
847 static void
848 restore_vars_to_original_value (varray_type locals,
849 unsigned limit,
850 varray_type table)
852 if (! locals)
853 return;
855 while (VARRAY_ACTIVE_SIZE (locals) > limit)
857 tree prev_value, dest;
859 prev_value = VARRAY_TOP_TREE (locals);
860 VARRAY_POP (locals);
861 dest = VARRAY_TOP_TREE (locals);
862 VARRAY_POP (locals);
864 set_value_for (dest, prev_value, table);
868 /* Similar to restore_vars_to_original_value, except that it restores
869 CURRDEFS to its original value. */
870 static void
871 restore_currdefs_to_original_value (varray_type locals, unsigned limit)
873 if (!locals)
874 return;
876 /* Restore CURRDEFS to its original state. */
877 while (VARRAY_ACTIVE_SIZE (locals) > limit)
879 tree tmp = VARRAY_TOP_TREE (locals);
880 tree saved_def, var;
882 VARRAY_POP (locals);
884 /* If we recorded an SSA_NAME, then make the SSA_NAME the current
885 definition of its underlying variable. If we recorded anything
886 else, it must have been an _DECL node and its current reaching
887 definition must have been NULL. */
888 if (TREE_CODE (tmp) == SSA_NAME)
890 saved_def = tmp;
891 var = SSA_NAME_VAR (saved_def);
893 else
895 saved_def = NULL;
896 var = tmp;
899 var_ann (var)->current_def = saved_def;
903 /* We have finished processing the dominator children of BB, perform
904 any finalization actions in preparation for leaving this node in
905 the dominator tree. */
907 static void
908 dom_opt_finalize_block (struct dom_walk_data *walk_data, basic_block bb)
910 struct dom_walk_block_data *bd
911 = VARRAY_TOP_GENERIC_PTR (walk_data->block_data_stack);
912 tree last;
914 /* If we are at a leaf node in the dominator graph, see if we can thread
915 the edge from BB through its successor.
917 Do this before we remove entries from our equivalence tables. */
918 if (bb->succ
919 && ! bb->succ->succ_next
920 && (bb->succ->flags & EDGE_ABNORMAL) == 0
921 && (get_immediate_dominator (CDI_DOMINATORS, bb->succ->dest) != bb
922 || phi_nodes (bb->succ->dest)))
925 thread_across_edge (walk_data, bb->succ);
927 else if ((last = last_stmt (bb))
928 && TREE_CODE (last) == COND_EXPR
929 && (TREE_CODE_CLASS (TREE_CODE (COND_EXPR_COND (last))) == '<'
930 || TREE_CODE (COND_EXPR_COND (last)) == SSA_NAME)
931 && bb->succ
932 && (bb->succ->flags & EDGE_ABNORMAL) == 0
933 && bb->succ->succ_next
934 && (bb->succ->succ_next->flags & EDGE_ABNORMAL) == 0
935 && ! bb->succ->succ_next->succ_next)
937 edge true_edge, false_edge;
938 tree cond, inverted = NULL;
939 enum tree_code cond_code;
941 extract_true_false_edges_from_block (bb, &true_edge, &false_edge);
943 cond = COND_EXPR_COND (last);
944 cond_code = TREE_CODE (cond);
946 if (TREE_CODE_CLASS (cond_code) == '<')
947 inverted = invert_truthvalue (cond);
949 /* If the THEN arm is the end of a dominator tree or has PHI nodes,
950 then try to thread through its edge. */
951 if (get_immediate_dominator (CDI_DOMINATORS, true_edge->dest) != bb
952 || phi_nodes (true_edge->dest))
954 unsigned const_and_copies_limit;
955 unsigned currdefs_limit;
957 const_and_copies_limit
958 = bd->const_and_copies ? VARRAY_ACTIVE_SIZE (bd->const_and_copies)
959 : 0;
960 currdefs_limit
961 = bd->block_defs ? VARRAY_ACTIVE_SIZE (bd->block_defs) : 0;
963 /* Push a marker onto the available expression stack so that we
964 unwind any expressions related to the TRUE arm before processing
965 the false arm below. */
966 VARRAY_PUSH_TREE (avail_exprs_stack, NULL_TREE);
968 /* Record any equivalences created by following this edge. */
969 if (TREE_CODE_CLASS (cond_code) == '<')
971 record_cond (cond, boolean_true_node);
972 record_dominating_conditions (cond);
973 record_cond (inverted, boolean_false_node);
975 else if (cond_code == SSA_NAME)
976 record_const_or_copy (cond, boolean_true_node,
977 &bd->const_and_copies);
979 /* Now thread the edge. */
980 thread_across_edge (walk_data, true_edge);
982 /* And restore the various tables to their state before
983 we threaded this edge. */
984 remove_local_expressions_from_table ();
985 restore_vars_to_original_value (bd->const_and_copies,
986 const_and_copies_limit,
987 const_and_copies);
988 restore_currdefs_to_original_value (bd->block_defs, currdefs_limit);
991 /* Similarly for the ELSE arm. */
992 if (get_immediate_dominator (CDI_DOMINATORS, false_edge->dest) != bb
993 || phi_nodes (false_edge->dest))
995 /* Record any equivalences created by following this edge. */
996 if (TREE_CODE_CLASS (cond_code) == '<')
998 record_cond (cond, boolean_false_node);
999 record_cond (inverted, boolean_true_node);
1000 record_dominating_conditions (inverted);
1002 else if (cond_code == SSA_NAME)
1003 record_const_or_copy (cond, boolean_false_node,
1004 &bd->const_and_copies);
1006 thread_across_edge (walk_data, false_edge);
1008 /* No need to remove local expressions from our tables
1009 or restore vars to their original value as that will
1010 be done immediately below. */
1014 remove_local_expressions_from_table ();
1015 restore_nonzero_vars_to_original_value (bd->nonzero_vars, 0, nonzero_vars);
1016 restore_vars_to_original_value (bd->const_and_copies, 0, const_and_copies);
1017 restore_currdefs_to_original_value (bd->block_defs, 0);
1019 /* Remove VRP records associated with this basic block. They are no
1020 longer valid.
1022 To be efficient, we note which variables have had their values
1023 constrained in this block. So walk over each variable in the
1024 VRP_VARIABLEs array. */
1025 while (bd->vrp_variables && VARRAY_ACTIVE_SIZE (bd->vrp_variables) > 0)
1027 tree var = VARRAY_TOP_TREE (bd->vrp_variables);
1029 /* Each variable has a stack of value range records. We want to
1030 invalidate those associated with our basic block. So we walk
1031 the array backwards popping off records associated with our
1032 block. Once we hit a record not associated with our block
1033 we are done. */
1034 varray_type var_vrp_records = VARRAY_GENERIC_PTR (vrp_data,
1035 SSA_NAME_VERSION (var));
1037 while (VARRAY_ACTIVE_SIZE (var_vrp_records) > 0)
1039 struct vrp_element *element
1040 = (struct vrp_element *)VARRAY_TOP_GENERIC_PTR (var_vrp_records);
1042 if (element->bb != bb)
1043 break;
1045 VARRAY_POP (var_vrp_records);
1048 VARRAY_POP (bd->vrp_variables);
1051 /* If we queued any statements to rescan in this block, then
1052 go ahead and rescan them now. */
1053 while (VARRAY_ACTIVE_SIZE (stmts_to_rescan) > 0)
1055 tree stmt = VARRAY_TOP_TREE (stmts_to_rescan);
1056 basic_block stmt_bb = bb_for_stmt (stmt);
1058 if (stmt_bb != bb)
1059 break;
1061 VARRAY_POP (stmts_to_rescan);
1062 mark_new_vars_to_rename (stmt, vars_to_rename);
1066 /* PHI nodes can create equivalences too.
1068 Ignoring any alternatives which are the same as the result, if
1069 all the alternatives are equal, then the PHI node creates an
1070 equivalence.
1072 Additionally, if all the PHI alternatives are known to have a nonzero
1073 value, then the result of this PHI is known to have a nonzero value,
1074 even if we do not know its exact value. */
1076 static void
1077 record_equivalences_from_phis (struct dom_walk_data *walk_data, basic_block bb)
1079 struct dom_walk_block_data *bd
1080 = VARRAY_TOP_GENERIC_PTR (walk_data->block_data_stack);
1081 tree phi;
1083 for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
1085 tree lhs = PHI_RESULT (phi);
1086 tree rhs = NULL;
1087 int i;
1089 for (i = 0; i < PHI_NUM_ARGS (phi); i++)
1091 tree t = PHI_ARG_DEF (phi, i);
1093 if (TREE_CODE (t) == SSA_NAME || is_gimple_min_invariant (t))
1095 /* Ignore alternatives which are the same as our LHS. */
1096 if (operand_equal_p (lhs, t, 0))
1097 continue;
1099 /* If we have not processed an alternative yet, then set
1100 RHS to this alternative. */
1101 if (rhs == NULL)
1102 rhs = t;
1103 /* If we have processed an alternative (stored in RHS), then
1104 see if it is equal to this one. If it isn't, then stop
1105 the search. */
1106 else if (! operand_equal_p (rhs, t, 0))
1107 break;
1109 else
1110 break;
1113 /* If we had no interesting alternatives, then all the RHS alternatives
1114 must have been the same as LHS. */
1115 if (!rhs)
1116 rhs = lhs;
1118 /* If we managed to iterate through each PHI alternative without
1119 breaking out of the loop, then we have a PHI which may create
1120 a useful equivalence. We do not need to record unwind data for
1121 this, since this is a true assignment and not an equivalence
1122 inferred from a comparison. All uses of this ssa name are dominated
1123 by this assignment, so unwinding just costs time and space. */
1124 if (i == PHI_NUM_ARGS (phi)
1125 && may_propagate_copy (lhs, rhs))
1126 set_value_for (lhs, rhs, const_and_copies);
1128 /* Now see if we know anything about the nonzero property for the
1129 result of this PHI. */
1130 for (i = 0; i < PHI_NUM_ARGS (phi); i++)
1132 if (!PHI_ARG_NONZERO (phi, i))
1133 break;
1136 if (i == PHI_NUM_ARGS (phi))
1137 bitmap_set_bit (nonzero_vars, SSA_NAME_VERSION (PHI_RESULT (phi)));
1139 register_new_def (lhs, &bd->block_defs);
1143 /* Ignoring loop backedges, if BB has precisely one incoming edge then
1144 return that edge. Otherwise return NULL. */
1145 static edge
1146 single_incoming_edge_ignoring_loop_edges (basic_block bb)
1148 edge retval = NULL;
1149 edge e;
1151 for (e = bb->pred; e; e = e->pred_next)
1153 /* A loop back edge can be identified by the destination of
1154 the edge dominating the source of the edge. */
1155 if (dominated_by_p (CDI_DOMINATORS, e->src, e->dest))
1156 continue;
1158 /* If we have already seen a non-loop edge, then we must have
1159 multiple incoming non-loop edges and thus we return NULL. */
1160 if (retval)
1161 return NULL;
1163 /* This is the first non-loop incoming edge we have found. Record
1164 it. */
1165 retval = e;
1168 return retval;
1171 /* Record any equivalences created by the incoming edge to BB. If BB
1172 has more than one incoming edge, then no equivalence is created. */
1174 static void
1175 record_equivalences_from_incoming_edge (struct dom_walk_data *walk_data,
1176 basic_block bb)
1178 int edge_flags;
1179 basic_block parent;
1180 struct eq_expr_value eq_expr_value;
1181 tree parent_block_last_stmt = NULL;
1182 struct dom_walk_block_data *bd
1183 = VARRAY_TOP_GENERIC_PTR (walk_data->block_data_stack);
1185 /* If our parent block ended with a control statment, then we may be
1186 able to record some equivalences based on which outgoing edge from
1187 the parent was followed. */
1188 parent = get_immediate_dominator (CDI_DOMINATORS, bb);
1189 if (parent)
1191 parent_block_last_stmt = last_stmt (parent);
1192 if (parent_block_last_stmt && !is_ctrl_stmt (parent_block_last_stmt))
1193 parent_block_last_stmt = NULL;
1196 eq_expr_value.src = NULL;
1197 eq_expr_value.dst = NULL;
1199 /* If we have a single predecessor (ignoring loop backedges), then extract
1200 EDGE_FLAGS from the single incoming edge. Otherwise just return as
1201 there is nothing to do. */
1202 if (bb->pred
1203 && parent_block_last_stmt)
1205 edge e = single_incoming_edge_ignoring_loop_edges (bb);
1206 if (e && bb_for_stmt (parent_block_last_stmt) == e->src)
1207 edge_flags = e->flags;
1208 else
1209 return;
1211 else
1212 return;
1214 /* If our parent block ended in a COND_EXPR, add any equivalences
1215 created by the COND_EXPR to the hash table and initialize
1216 EQ_EXPR_VALUE appropriately.
1218 EQ_EXPR_VALUE is an assignment expression created when BB's immediate
1219 dominator ends in a COND_EXPR statement whose predicate is of the form
1220 'VAR == VALUE', where VALUE may be another variable or a constant.
1221 This is used to propagate VALUE on the THEN_CLAUSE of that
1222 conditional. This assignment is inserted in CONST_AND_COPIES so that
1223 the copy and constant propagator can find more propagation
1224 opportunities. */
1225 if (TREE_CODE (parent_block_last_stmt) == COND_EXPR
1226 && (edge_flags & (EDGE_TRUE_VALUE | EDGE_FALSE_VALUE)))
1227 eq_expr_value = get_eq_expr_value (parent_block_last_stmt,
1228 (edge_flags & EDGE_TRUE_VALUE) != 0,
1230 &bd->vrp_variables);
1231 /* Similarly when the parent block ended in a SWITCH_EXPR.
1232 We can only know the value of the switch's condition if the dominator
1233 parent is also the only predecessor of this block. */
1234 else if (bb->pred->src == parent
1235 && TREE_CODE (parent_block_last_stmt) == SWITCH_EXPR)
1237 tree switch_cond = SWITCH_COND (parent_block_last_stmt);
1239 /* If the switch's condition is an SSA variable, then we may
1240 know its value at each of the case labels. */
1241 if (TREE_CODE (switch_cond) == SSA_NAME)
1243 tree switch_vec = SWITCH_LABELS (parent_block_last_stmt);
1244 size_t i, n = TREE_VEC_LENGTH (switch_vec);
1245 int case_count = 0;
1246 tree match_case = NULL_TREE;
1248 /* Search the case labels for those whose destination is
1249 the current basic block. */
1250 for (i = 0; i < n; ++i)
1252 tree elt = TREE_VEC_ELT (switch_vec, i);
1253 if (label_to_block (CASE_LABEL (elt)) == bb)
1255 if (++case_count > 1 || CASE_HIGH (elt))
1256 break;
1257 match_case = elt;
1261 /* If we encountered precisely one CASE_LABEL_EXPR and it
1262 was not the default case, or a case range, then we know
1263 the exact value of SWITCH_COND which caused us to get to
1264 this block. Record that equivalence in EQ_EXPR_VALUE. */
1265 if (case_count == 1
1266 && match_case
1267 && CASE_LOW (match_case)
1268 && !CASE_HIGH (match_case))
1270 eq_expr_value.dst = switch_cond;
1271 eq_expr_value.src = fold_convert (TREE_TYPE (switch_cond),
1272 CASE_LOW (match_case));
1277 /* If EQ_EXPR_VALUE (VAR == VALUE) is given, register the VALUE as a
1278 new value for VAR, so that occurrences of VAR can be replaced with
1279 VALUE while re-writing the THEN arm of a COND_EXPR. */
1280 if (eq_expr_value.src && eq_expr_value.dst)
1281 record_equality (eq_expr_value.dst, eq_expr_value.src,
1282 &bd->const_and_copies);
1285 /* Dump SSA statistics on FILE. */
1287 void
1288 dump_dominator_optimization_stats (FILE *file)
1290 long n_exprs;
1292 fprintf (file, "Total number of statements: %6ld\n\n",
1293 opt_stats.num_stmts);
1294 fprintf (file, "Exprs considered for dominator optimizations: %6ld\n",
1295 opt_stats.num_exprs_considered);
1297 n_exprs = opt_stats.num_exprs_considered;
1298 if (n_exprs == 0)
1299 n_exprs = 1;
1301 fprintf (file, " Redundant expressions eliminated: %6ld (%.0f%%)\n",
1302 opt_stats.num_re, PERCENT (opt_stats.num_re,
1303 n_exprs));
1305 fprintf (file, "\nHash table statistics:\n");
1307 fprintf (file, " avail_exprs: ");
1308 htab_statistics (file, avail_exprs);
1312 /* Dump SSA statistics on stderr. */
1314 void
1315 debug_dominator_optimization_stats (void)
1317 dump_dominator_optimization_stats (stderr);
1321 /* Dump statistics for the hash table HTAB. */
1323 static void
1324 htab_statistics (FILE *file, htab_t htab)
1326 fprintf (file, "size %ld, %ld elements, %f collision/search ratio\n",
1327 (long) htab_size (htab),
1328 (long) htab_elements (htab),
1329 htab_collisions (htab));
1332 /* Record the fact that VAR has a nonzero value, though we may not know
1333 its exact value. Note that if VAR is already known to have a nonzero
1334 value, then we do nothing. */
1336 static void
1337 record_var_is_nonzero (tree var, varray_type *block_nonzero_vars_p)
1339 int indx = SSA_NAME_VERSION (var);
1341 if (bitmap_bit_p (nonzero_vars, indx))
1342 return;
1344 /* Mark it in the global table. */
1345 bitmap_set_bit (nonzero_vars, indx);
1347 /* Record this SSA_NAME so that we can reset the global table
1348 when we leave this block. */
1349 if (! *block_nonzero_vars_p)
1350 VARRAY_TREE_INIT (*block_nonzero_vars_p, 2, "block_nonzero_vars");
1351 VARRAY_PUSH_TREE (*block_nonzero_vars_p, var);
1354 /* Enter a statement into the true/false expression hash table indicating
1355 that the condition COND has the value VALUE. */
1357 static void
1358 record_cond (tree cond, tree value)
1360 struct expr_hash_elt *element = xmalloc (sizeof (struct expr_hash_elt));
1361 void **slot;
1363 initialize_hash_element (cond, value, element);
1365 slot = htab_find_slot_with_hash (avail_exprs, (void *)element,
1366 element->hash, true);
1367 if (*slot == NULL)
1369 *slot = (void *) element;
1370 VARRAY_PUSH_TREE (avail_exprs_stack, cond);
1372 else
1373 free (element);
1376 /* COND is a condition which is known to be true. Record variants of
1377 COND which must also be true.
1379 For example, if a < b is true, then a <= b must also be true. */
1381 static void
1382 record_dominating_conditions (tree cond)
1384 switch (TREE_CODE (cond))
1386 case LT_EXPR:
1387 record_cond (build2 (LE_EXPR, boolean_type_node,
1388 TREE_OPERAND (cond, 0),
1389 TREE_OPERAND (cond, 1)),
1390 boolean_true_node);
1391 record_cond (build2 (ORDERED_EXPR, boolean_type_node,
1392 TREE_OPERAND (cond, 0),
1393 TREE_OPERAND (cond, 1)),
1394 boolean_true_node);
1395 record_cond (build2 (NE_EXPR, boolean_type_node,
1396 TREE_OPERAND (cond, 0),
1397 TREE_OPERAND (cond, 1)),
1398 boolean_true_node);
1399 record_cond (build2 (LTGT_EXPR, boolean_type_node,
1400 TREE_OPERAND (cond, 0),
1401 TREE_OPERAND (cond, 1)),
1402 boolean_true_node);
1403 break;
1405 case GT_EXPR:
1406 record_cond (build2 (GE_EXPR, boolean_type_node,
1407 TREE_OPERAND (cond, 0),
1408 TREE_OPERAND (cond, 1)),
1409 boolean_true_node);
1410 record_cond (build2 (ORDERED_EXPR, boolean_type_node,
1411 TREE_OPERAND (cond, 0),
1412 TREE_OPERAND (cond, 1)),
1413 boolean_true_node);
1414 record_cond (build2 (NE_EXPR, boolean_type_node,
1415 TREE_OPERAND (cond, 0),
1416 TREE_OPERAND (cond, 1)),
1417 boolean_true_node);
1418 record_cond (build2 (LTGT_EXPR, boolean_type_node,
1419 TREE_OPERAND (cond, 0),
1420 TREE_OPERAND (cond, 1)),
1421 boolean_true_node);
1422 break;
1424 case GE_EXPR:
1425 case LE_EXPR:
1426 record_cond (build2 (ORDERED_EXPR, boolean_type_node,
1427 TREE_OPERAND (cond, 0),
1428 TREE_OPERAND (cond, 1)),
1429 boolean_true_node);
1430 break;
1432 case EQ_EXPR:
1433 record_cond (build2 (ORDERED_EXPR, boolean_type_node,
1434 TREE_OPERAND (cond, 0),
1435 TREE_OPERAND (cond, 1)),
1436 boolean_true_node);
1437 record_cond (build2 (LE_EXPR, boolean_type_node,
1438 TREE_OPERAND (cond, 0),
1439 TREE_OPERAND (cond, 1)),
1440 boolean_true_node);
1441 record_cond (build2 (GE_EXPR, boolean_type_node,
1442 TREE_OPERAND (cond, 0),
1443 TREE_OPERAND (cond, 1)),
1444 boolean_true_node);
1445 break;
1447 case UNORDERED_EXPR:
1448 record_cond (build2 (NE_EXPR, boolean_type_node,
1449 TREE_OPERAND (cond, 0),
1450 TREE_OPERAND (cond, 1)),
1451 boolean_true_node);
1452 record_cond (build2 (UNLE_EXPR, boolean_type_node,
1453 TREE_OPERAND (cond, 0),
1454 TREE_OPERAND (cond, 1)),
1455 boolean_true_node);
1456 record_cond (build2 (UNGE_EXPR, boolean_type_node,
1457 TREE_OPERAND (cond, 0),
1458 TREE_OPERAND (cond, 1)),
1459 boolean_true_node);
1460 record_cond (build2 (UNEQ_EXPR, boolean_type_node,
1461 TREE_OPERAND (cond, 0),
1462 TREE_OPERAND (cond, 1)),
1463 boolean_true_node);
1464 record_cond (build2 (UNLT_EXPR, boolean_type_node,
1465 TREE_OPERAND (cond, 0),
1466 TREE_OPERAND (cond, 1)),
1467 boolean_true_node);
1468 record_cond (build2 (UNGT_EXPR, boolean_type_node,
1469 TREE_OPERAND (cond, 0),
1470 TREE_OPERAND (cond, 1)),
1471 boolean_true_node);
1472 break;
1474 case UNLT_EXPR:
1475 record_cond (build2 (UNLE_EXPR, boolean_type_node,
1476 TREE_OPERAND (cond, 0),
1477 TREE_OPERAND (cond, 1)),
1478 boolean_true_node);
1479 record_cond (build2 (NE_EXPR, boolean_type_node,
1480 TREE_OPERAND (cond, 0),
1481 TREE_OPERAND (cond, 1)),
1482 boolean_true_node);
1483 break;
1485 case UNGT_EXPR:
1486 record_cond (build2 (UNGE_EXPR, boolean_type_node,
1487 TREE_OPERAND (cond, 0),
1488 TREE_OPERAND (cond, 1)),
1489 boolean_true_node);
1490 record_cond (build2 (NE_EXPR, boolean_type_node,
1491 TREE_OPERAND (cond, 0),
1492 TREE_OPERAND (cond, 1)),
1493 boolean_true_node);
1494 break;
1496 case UNEQ_EXPR:
1497 record_cond (build2 (UNLE_EXPR, boolean_type_node,
1498 TREE_OPERAND (cond, 0),
1499 TREE_OPERAND (cond, 1)),
1500 boolean_true_node);
1501 record_cond (build2 (UNGE_EXPR, boolean_type_node,
1502 TREE_OPERAND (cond, 0),
1503 TREE_OPERAND (cond, 1)),
1504 boolean_true_node);
1505 break;
1507 case LTGT_EXPR:
1508 record_cond (build2 (NE_EXPR, boolean_type_node,
1509 TREE_OPERAND (cond, 0),
1510 TREE_OPERAND (cond, 1)),
1511 boolean_true_node);
1512 record_cond (build2 (ORDERED_EXPR, boolean_type_node,
1513 TREE_OPERAND (cond, 0),
1514 TREE_OPERAND (cond, 1)),
1515 boolean_true_node);
1517 default:
1518 break;
1522 /* A helper function for record_const_or_copy and record_equality.
1523 Do the work of recording the value and undo info. */
1525 static void
1526 record_const_or_copy_1 (tree x, tree y, tree prev_x,
1527 varray_type *block_const_and_copies_p)
1529 set_value_for (x, y, const_and_copies);
1531 if (!*block_const_and_copies_p)
1532 VARRAY_TREE_INIT (*block_const_and_copies_p, 2, "block_const_and_copies");
1533 VARRAY_PUSH_TREE (*block_const_and_copies_p, x);
1534 VARRAY_PUSH_TREE (*block_const_and_copies_p, prev_x);
1537 /* Record that X is equal to Y in const_and_copies. Record undo
1538 information in the block-local varray. */
1540 static void
1541 record_const_or_copy (tree x, tree y, varray_type *block_const_and_copies_p)
1543 tree prev_x = get_value_for (x, const_and_copies);
1545 if (TREE_CODE (y) == SSA_NAME)
1547 tree tmp = get_value_for (y, const_and_copies);
1548 if (tmp)
1549 y = tmp;
1552 record_const_or_copy_1 (x, y, prev_x, block_const_and_copies_p);
1555 /* Similarly, but assume that X and Y are the two operands of an EQ_EXPR.
1556 This constrains the cases in which we may treat this as assignment. */
1558 static void
1559 record_equality (tree x, tree y, varray_type *block_const_and_copies_p)
1561 tree prev_x = NULL, prev_y = NULL;
1563 if (TREE_CODE (x) == SSA_NAME)
1564 prev_x = get_value_for (x, const_and_copies);
1565 if (TREE_CODE (y) == SSA_NAME)
1566 prev_y = get_value_for (y, const_and_copies);
1568 /* If one of the previous values is invariant, then use that.
1569 Otherwise it doesn't matter which value we choose, just so
1570 long as we canonicalize on one value. */
1571 if (TREE_INVARIANT (y))
1573 else if (TREE_INVARIANT (x))
1574 prev_x = x, x = y, y = prev_x, prev_x = prev_y;
1575 else if (prev_x && TREE_INVARIANT (prev_x))
1576 x = y, y = prev_x, prev_x = prev_y;
1577 else if (prev_y)
1578 y = prev_y;
1580 /* After the swapping, we must have one SSA_NAME. */
1581 if (TREE_CODE (x) != SSA_NAME)
1582 return;
1584 /* For IEEE, -0.0 == 0.0, so we don't necessarily know the sign of a
1585 variable compared against zero. If we're honoring signed zeros,
1586 then we cannot record this value unless we know that the value is
1587 nonzero. */
1588 if (HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (x)))
1589 && (TREE_CODE (y) != REAL_CST
1590 || REAL_VALUES_EQUAL (dconst0, TREE_REAL_CST (y))))
1591 return;
1593 record_const_or_copy_1 (x, y, prev_x, block_const_and_copies_p);
1596 /* STMT is a MODIFY_EXPR for which we were unable to find RHS in the
1597 hash tables. Try to simplify the RHS using whatever equivalences
1598 we may have recorded.
1600 If we are able to simplify the RHS, then lookup the simplified form in
1601 the hash table and return the result. Otherwise return NULL. */
1603 static tree
1604 simplify_rhs_and_lookup_avail_expr (struct dom_walk_data *walk_data,
1605 tree stmt, int insert)
1607 tree rhs = TREE_OPERAND (stmt, 1);
1608 enum tree_code rhs_code = TREE_CODE (rhs);
1609 tree result = NULL;
1611 /* If we have lhs = ~x, look and see if we earlier had x = ~y.
1612 In which case we can change this statement to be lhs = y.
1613 Which can then be copy propagated.
1615 Similarly for negation. */
1616 if ((rhs_code == BIT_NOT_EXPR || rhs_code == NEGATE_EXPR)
1617 && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
1619 /* Get the definition statement for our RHS. */
1620 tree rhs_def_stmt = SSA_NAME_DEF_STMT (TREE_OPERAND (rhs, 0));
1622 /* See if the RHS_DEF_STMT has the same form as our statement. */
1623 if (TREE_CODE (rhs_def_stmt) == MODIFY_EXPR
1624 && TREE_CODE (TREE_OPERAND (rhs_def_stmt, 1)) == rhs_code)
1626 tree rhs_def_operand;
1628 rhs_def_operand = TREE_OPERAND (TREE_OPERAND (rhs_def_stmt, 1), 0);
1630 /* Verify that RHS_DEF_OPERAND is a suitable SSA variable. */
1631 if (TREE_CODE (rhs_def_operand) == SSA_NAME
1632 && ! SSA_NAME_OCCURS_IN_ABNORMAL_PHI (rhs_def_operand))
1633 result = update_rhs_and_lookup_avail_expr (stmt,
1634 rhs_def_operand,
1635 insert);
1639 /* If we have z = (x OP C1), see if we earlier had x = y OP C2.
1640 If OP is associative, create and fold (y OP C2) OP C1 which
1641 should result in (y OP C3), use that as the RHS for the
1642 assignment. Add minus to this, as we handle it specially below. */
1643 if ((associative_tree_code (rhs_code) || rhs_code == MINUS_EXPR)
1644 && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME
1645 && is_gimple_min_invariant (TREE_OPERAND (rhs, 1)))
1647 tree rhs_def_stmt = SSA_NAME_DEF_STMT (TREE_OPERAND (rhs, 0));
1649 /* See if the RHS_DEF_STMT has the same form as our statement. */
1650 if (TREE_CODE (rhs_def_stmt) == MODIFY_EXPR)
1652 tree rhs_def_rhs = TREE_OPERAND (rhs_def_stmt, 1);
1653 enum tree_code rhs_def_code = TREE_CODE (rhs_def_rhs);
1655 if (rhs_code == rhs_def_code
1656 || (rhs_code == PLUS_EXPR && rhs_def_code == MINUS_EXPR)
1657 || (rhs_code == MINUS_EXPR && rhs_def_code == PLUS_EXPR))
1659 tree def_stmt_op0 = TREE_OPERAND (rhs_def_rhs, 0);
1660 tree def_stmt_op1 = TREE_OPERAND (rhs_def_rhs, 1);
1662 if (TREE_CODE (def_stmt_op0) == SSA_NAME
1663 && ! SSA_NAME_OCCURS_IN_ABNORMAL_PHI (def_stmt_op0)
1664 && is_gimple_min_invariant (def_stmt_op1))
1666 tree outer_const = TREE_OPERAND (rhs, 1);
1667 tree type = TREE_TYPE (TREE_OPERAND (stmt, 0));
1668 tree t;
1670 /* If we care about correct floating point results, then
1671 don't fold x + c1 - c2. Note that we need to take both
1672 the codes and the signs to figure this out. */
1673 if (FLOAT_TYPE_P (type)
1674 && !flag_unsafe_math_optimizations
1675 && (rhs_def_code == PLUS_EXPR
1676 || rhs_def_code == MINUS_EXPR))
1678 bool neg = false;
1680 neg ^= (rhs_code == MINUS_EXPR);
1681 neg ^= (rhs_def_code == MINUS_EXPR);
1682 neg ^= real_isneg (TREE_REAL_CST_PTR (outer_const));
1683 neg ^= real_isneg (TREE_REAL_CST_PTR (def_stmt_op1));
1685 if (neg)
1686 goto dont_fold_assoc;
1689 /* Ho hum. So fold will only operate on the outermost
1690 thingy that we give it, so we have to build the new
1691 expression in two pieces. This requires that we handle
1692 combinations of plus and minus. */
1693 if (rhs_def_code != rhs_code)
1695 if (rhs_def_code == MINUS_EXPR)
1696 t = build (MINUS_EXPR, type, outer_const, def_stmt_op1);
1697 else
1698 t = build (MINUS_EXPR, type, def_stmt_op1, outer_const);
1699 rhs_code = PLUS_EXPR;
1701 else if (rhs_def_code == MINUS_EXPR)
1702 t = build (PLUS_EXPR, type, def_stmt_op1, outer_const);
1703 else
1704 t = build (rhs_def_code, type, def_stmt_op1, outer_const);
1705 t = local_fold (t);
1706 t = build (rhs_code, type, def_stmt_op0, t);
1707 t = local_fold (t);
1709 /* If the result is a suitable looking gimple expression,
1710 then use it instead of the original for STMT. */
1711 if (TREE_CODE (t) == SSA_NAME
1712 || (TREE_CODE_CLASS (TREE_CODE (t)) == '1'
1713 && TREE_CODE (TREE_OPERAND (t, 0)) == SSA_NAME)
1714 || ((TREE_CODE_CLASS (TREE_CODE (t)) == '2'
1715 || TREE_CODE_CLASS (TREE_CODE (t)) == '<')
1716 && TREE_CODE (TREE_OPERAND (t, 0)) == SSA_NAME
1717 && is_gimple_val (TREE_OPERAND (t, 1))))
1718 result = update_rhs_and_lookup_avail_expr (stmt, t, insert);
1722 dont_fold_assoc:;
1725 /* Transform TRUNC_DIV_EXPR and TRUNC_MOD_EXPR into RSHIFT_EXPR
1726 and BIT_AND_EXPR respectively if the first operand is greater
1727 than zero and the second operand is an exact power of two. */
1728 if ((rhs_code == TRUNC_DIV_EXPR || rhs_code == TRUNC_MOD_EXPR)
1729 && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (rhs, 0)))
1730 && integer_pow2p (TREE_OPERAND (rhs, 1)))
1732 tree val;
1733 tree op = TREE_OPERAND (rhs, 0);
1735 if (TYPE_UNSIGNED (TREE_TYPE (op)))
1737 val = integer_one_node;
1739 else
1741 tree dummy_cond = walk_data->global_data;
1743 if (! dummy_cond)
1745 dummy_cond = build (GT_EXPR, boolean_type_node,
1746 op, integer_zero_node);
1747 dummy_cond = build (COND_EXPR, void_type_node,
1748 dummy_cond, NULL, NULL);
1749 walk_data->global_data = dummy_cond;
1751 else
1753 TREE_SET_CODE (TREE_OPERAND (dummy_cond, 0), GT_EXPR);
1754 TREE_OPERAND (TREE_OPERAND (dummy_cond, 0), 0) = op;
1755 TREE_OPERAND (TREE_OPERAND (dummy_cond, 0), 1)
1756 = integer_zero_node;
1758 val = simplify_cond_and_lookup_avail_expr (dummy_cond, NULL, false);
1761 if (val && integer_onep (val))
1763 tree t;
1764 tree op0 = TREE_OPERAND (rhs, 0);
1765 tree op1 = TREE_OPERAND (rhs, 1);
1767 if (rhs_code == TRUNC_DIV_EXPR)
1768 t = build (RSHIFT_EXPR, TREE_TYPE (op0), op0,
1769 build_int_cst (NULL_TREE, tree_log2 (op1)));
1770 else
1771 t = build (BIT_AND_EXPR, TREE_TYPE (op0), op0,
1772 local_fold (build (MINUS_EXPR, TREE_TYPE (op1),
1773 op1, integer_one_node)));
1775 result = update_rhs_and_lookup_avail_expr (stmt, t, insert);
1779 /* Transform ABS (X) into X or -X as appropriate. */
1780 if (rhs_code == ABS_EXPR
1781 && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (rhs, 0))))
1783 tree val;
1784 tree op = TREE_OPERAND (rhs, 0);
1785 tree type = TREE_TYPE (op);
1787 if (TYPE_UNSIGNED (type))
1789 val = integer_zero_node;
1791 else
1793 tree dummy_cond = walk_data->global_data;
1795 if (! dummy_cond)
1797 dummy_cond = build (LE_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 (TREE_OPERAND (dummy_cond, 0), LE_EXPR);
1806 TREE_OPERAND (TREE_OPERAND (dummy_cond, 0), 0) = op;
1807 TREE_OPERAND (TREE_OPERAND (dummy_cond, 0), 1)
1808 = build_int_cst (type, 0);
1810 val = simplify_cond_and_lookup_avail_expr (dummy_cond, NULL, false);
1812 if (!val)
1814 TREE_SET_CODE (TREE_OPERAND (dummy_cond, 0), GE_EXPR);
1815 TREE_OPERAND (TREE_OPERAND (dummy_cond, 0), 0) = op;
1816 TREE_OPERAND (TREE_OPERAND (dummy_cond, 0), 1)
1817 = build_int_cst (type, 0);
1819 val = simplify_cond_and_lookup_avail_expr (dummy_cond,
1820 NULL, false);
1822 if (val)
1824 if (integer_zerop (val))
1825 val = integer_one_node;
1826 else if (integer_onep (val))
1827 val = integer_zero_node;
1832 if (val
1833 && (integer_onep (val) || integer_zerop (val)))
1835 tree t;
1837 if (integer_onep (val))
1838 t = build1 (NEGATE_EXPR, TREE_TYPE (op), op);
1839 else
1840 t = op;
1842 result = update_rhs_and_lookup_avail_expr (stmt, t, insert);
1846 /* Optimize *"foo" into 'f'. This is done here rather than
1847 in fold to avoid problems with stuff like &*"foo". */
1848 if (TREE_CODE (rhs) == INDIRECT_REF || TREE_CODE (rhs) == ARRAY_REF)
1850 tree t = fold_read_from_constant_string (rhs);
1852 if (t)
1853 result = update_rhs_and_lookup_avail_expr (stmt, t, insert);
1856 return result;
1859 /* COND is a condition of the form:
1861 x == const or x != const
1863 Look back to x's defining statement and see if x is defined as
1865 x = (type) y;
1867 If const is unchanged if we convert it to type, then we can build
1868 the equivalent expression:
1871 y == const or y != const
1873 Which may allow further optimizations.
1875 Return the equivalent comparison or NULL if no such equivalent comparison
1876 was found. */
1878 static tree
1879 find_equivalent_equality_comparison (tree cond)
1881 tree op0 = TREE_OPERAND (cond, 0);
1882 tree op1 = TREE_OPERAND (cond, 1);
1883 tree def_stmt = SSA_NAME_DEF_STMT (op0);
1885 /* OP0 might have been a parameter, so first make sure it
1886 was defined by a MODIFY_EXPR. */
1887 if (def_stmt && TREE_CODE (def_stmt) == MODIFY_EXPR)
1889 tree def_rhs = TREE_OPERAND (def_stmt, 1);
1891 /* Now make sure the RHS of the MODIFY_EXPR is a typecast. */
1892 if ((TREE_CODE (def_rhs) == NOP_EXPR
1893 || TREE_CODE (def_rhs) == CONVERT_EXPR)
1894 && TREE_CODE (TREE_OPERAND (def_rhs, 0)) == SSA_NAME)
1896 tree def_rhs_inner = TREE_OPERAND (def_rhs, 0);
1897 tree def_rhs_inner_type = TREE_TYPE (def_rhs_inner);
1898 tree new;
1900 if (TYPE_PRECISION (def_rhs_inner_type)
1901 > TYPE_PRECISION (TREE_TYPE (def_rhs)))
1902 return NULL;
1904 /* What we want to prove is that if we convert OP1 to
1905 the type of the object inside the NOP_EXPR that the
1906 result is still equivalent to SRC.
1908 If that is true, the build and return new equivalent
1909 condition which uses the source of the typecast and the
1910 new constant (which has only changed its type). */
1911 new = build1 (TREE_CODE (def_rhs), def_rhs_inner_type, op1);
1912 new = local_fold (new);
1913 if (is_gimple_val (new) && tree_int_cst_equal (new, op1))
1914 return build (TREE_CODE (cond), TREE_TYPE (cond),
1915 def_rhs_inner, new);
1918 return NULL;
1921 /* STMT is a COND_EXPR for which we could not trivially determine its
1922 result. This routine attempts to find equivalent forms of the
1923 condition which we may be able to optimize better. It also
1924 uses simple value range propagation to optimize conditionals. */
1926 static tree
1927 simplify_cond_and_lookup_avail_expr (tree stmt,
1928 stmt_ann_t ann,
1929 int insert)
1931 tree cond = COND_EXPR_COND (stmt);
1933 if (TREE_CODE_CLASS (TREE_CODE (cond)) == '<')
1935 tree op0 = TREE_OPERAND (cond, 0);
1936 tree op1 = TREE_OPERAND (cond, 1);
1938 if (TREE_CODE (op0) == SSA_NAME && is_gimple_min_invariant (op1))
1940 int limit;
1941 tree low, high, cond_low, cond_high;
1942 int lowequal, highequal, swapped, no_overlap, subset, cond_inverted;
1943 varray_type vrp_records;
1944 struct vrp_element *element;
1946 /* First see if we have test of an SSA_NAME against a constant
1947 where the SSA_NAME is defined by an earlier typecast which
1948 is irrelevant when performing tests against the given
1949 constant. */
1950 if (TREE_CODE (cond) == EQ_EXPR || TREE_CODE (cond) == NE_EXPR)
1952 tree new_cond = find_equivalent_equality_comparison (cond);
1954 if (new_cond)
1956 /* Update the statement to use the new equivalent
1957 condition. */
1958 COND_EXPR_COND (stmt) = new_cond;
1960 /* If this is not a real stmt, ann will be NULL and we
1961 avoid processing the operands. */
1962 if (ann)
1963 modify_stmt (stmt);
1965 /* Lookup the condition and return its known value if it
1966 exists. */
1967 new_cond = lookup_avail_expr (stmt, insert);
1968 if (new_cond)
1969 return new_cond;
1971 /* The operands have changed, so update op0 and op1. */
1972 op0 = TREE_OPERAND (cond, 0);
1973 op1 = TREE_OPERAND (cond, 1);
1977 /* Consult the value range records for this variable (if they exist)
1978 to see if we can eliminate or simplify this conditional.
1980 Note two tests are necessary to determine no records exist.
1981 First we have to see if the virtual array exists, if it
1982 exists, then we have to check its active size.
1984 Also note the vast majority of conditionals are not testing
1985 a variable which has had its range constrained by an earlier
1986 conditional. So this filter avoids a lot of unnecessary work. */
1987 vrp_records = VARRAY_GENERIC_PTR (vrp_data, SSA_NAME_VERSION (op0));
1988 if (vrp_records == NULL)
1989 return NULL;
1991 limit = VARRAY_ACTIVE_SIZE (vrp_records);
1993 /* If we have no value range records for this variable, or we are
1994 unable to extract a range for this condition, then there is
1995 nothing to do. */
1996 if (limit == 0
1997 || ! extract_range_from_cond (cond, &cond_high,
1998 &cond_low, &cond_inverted))
1999 return NULL;
2001 /* We really want to avoid unnecessary computations of range
2002 info. So all ranges are computed lazily; this avoids a
2003 lot of unnecessary work. ie, we record the conditional,
2004 but do not process how it constrains the variable's
2005 potential values until we know that processing the condition
2006 could be helpful.
2008 However, we do not want to have to walk a potentially long
2009 list of ranges, nor do we want to compute a variable's
2010 range more than once for a given path.
2012 Luckily, each time we encounter a conditional that can not
2013 be otherwise optimized we will end up here and we will
2014 compute the necessary range information for the variable
2015 used in this condition.
2017 Thus you can conclude that there will never be more than one
2018 conditional associated with a variable which has not been
2019 processed. So we never need to merge more than one new
2020 conditional into the current range.
2022 These properties also help us avoid unnecessary work. */
2023 element
2024 = (struct vrp_element *)VARRAY_GENERIC_PTR (vrp_records, limit - 1);
2026 if (element->high && element->low)
2028 /* The last element has been processed, so there is no range
2029 merging to do, we can simply use the high/low values
2030 recorded in the last element. */
2031 low = element->low;
2032 high = element->high;
2034 else
2036 tree tmp_high, tmp_low;
2037 int dummy;
2039 /* The last element has not been processed. Process it now. */
2040 extract_range_from_cond (element->cond, &tmp_high,
2041 &tmp_low, &dummy);
2043 /* If this is the only element, then no merging is necessary,
2044 the high/low values from extract_range_from_cond are all
2045 we need. */
2046 if (limit == 1)
2048 low = tmp_low;
2049 high = tmp_high;
2051 else
2053 /* Get the high/low value from the previous element. */
2054 struct vrp_element *prev
2055 = (struct vrp_element *)VARRAY_GENERIC_PTR (vrp_records,
2056 limit - 2);
2057 low = prev->low;
2058 high = prev->high;
2060 /* Merge in this element's range with the range from the
2061 previous element.
2063 The low value for the merged range is the maximum of
2064 the previous low value and the low value of this record.
2066 Similarly the high value for the merged range is the
2067 minimum of the previous high value and the high value of
2068 this record. */
2069 low = (tree_int_cst_compare (low, tmp_low) == 1
2070 ? low : tmp_low);
2071 high = (tree_int_cst_compare (high, tmp_high) == -1
2072 ? high : tmp_high);
2075 /* And record the computed range. */
2076 element->low = low;
2077 element->high = high;
2081 /* After we have constrained this variable's potential values,
2082 we try to determine the result of the given conditional.
2084 To simplify later tests, first determine if the current
2085 low value is the same low value as the conditional.
2086 Similarly for the current high value and the high value
2087 for the conditional. */
2088 lowequal = tree_int_cst_equal (low, cond_low);
2089 highequal = tree_int_cst_equal (high, cond_high);
2091 if (lowequal && highequal)
2092 return (cond_inverted ? boolean_false_node : boolean_true_node);
2094 /* To simplify the overlap/subset tests below we may want
2095 to swap the two ranges so that the larger of the two
2096 ranges occurs "first". */
2097 swapped = 0;
2098 if (tree_int_cst_compare (low, cond_low) == 1
2099 || (lowequal
2100 && tree_int_cst_compare (cond_high, high) == 1))
2102 tree temp;
2104 swapped = 1;
2105 temp = low;
2106 low = cond_low;
2107 cond_low = temp;
2108 temp = high;
2109 high = cond_high;
2110 cond_high = temp;
2113 /* Now determine if there is no overlap in the ranges
2114 or if the second range is a subset of the first range. */
2115 no_overlap = tree_int_cst_lt (high, cond_low);
2116 subset = tree_int_cst_compare (cond_high, high) != 1;
2118 /* If there was no overlap in the ranges, then this conditional
2119 always has a false value (unless we had to invert this
2120 conditional, in which case it always has a true value). */
2121 if (no_overlap)
2122 return (cond_inverted ? boolean_true_node : boolean_false_node);
2124 /* If the current range is a subset of the condition's range,
2125 then this conditional always has a true value (unless we
2126 had to invert this conditional, in which case it always
2127 has a true value). */
2128 if (subset && swapped)
2129 return (cond_inverted ? boolean_false_node : boolean_true_node);
2131 /* We were unable to determine the result of the conditional.
2132 However, we may be able to simplify the conditional. First
2133 merge the ranges in the same manner as range merging above. */
2134 low = tree_int_cst_compare (low, cond_low) == 1 ? low : cond_low;
2135 high = tree_int_cst_compare (high, cond_high) == -1 ? high : cond_high;
2137 /* If the range has converged to a single point, then turn this
2138 into an equality comparison. */
2139 if (TREE_CODE (cond) != EQ_EXPR
2140 && TREE_CODE (cond) != NE_EXPR
2141 && tree_int_cst_equal (low, high))
2143 TREE_SET_CODE (cond, EQ_EXPR);
2144 TREE_OPERAND (cond, 1) = high;
2148 return 0;
2151 /* STMT is a SWITCH_EXPR for which we could not trivially determine its
2152 result. This routine attempts to find equivalent forms of the
2153 condition which we may be able to optimize better. */
2155 static tree
2156 simplify_switch_and_lookup_avail_expr (tree stmt, int insert)
2158 tree cond = SWITCH_COND (stmt);
2159 tree def, to, ti;
2161 /* The optimization that we really care about is removing unnecessary
2162 casts. That will let us do much better in propagating the inferred
2163 constant at the switch target. */
2164 if (TREE_CODE (cond) == SSA_NAME)
2166 def = SSA_NAME_DEF_STMT (cond);
2167 if (TREE_CODE (def) == MODIFY_EXPR)
2169 def = TREE_OPERAND (def, 1);
2170 if (TREE_CODE (def) == NOP_EXPR)
2172 int need_precision;
2173 bool fail;
2175 def = TREE_OPERAND (def, 0);
2177 #ifdef ENABLE_CHECKING
2178 /* ??? Why was Jeff testing this? We are gimple... */
2179 gcc_assert (is_gimple_val (def));
2180 #endif
2182 to = TREE_TYPE (cond);
2183 ti = TREE_TYPE (def);
2185 /* If we have an extension that preserves value, then we
2186 can copy the source value into the switch. */
2188 need_precision = TYPE_PRECISION (ti);
2189 fail = false;
2190 if (TYPE_UNSIGNED (to) && !TYPE_UNSIGNED (ti))
2191 fail = true;
2192 else if (!TYPE_UNSIGNED (to) && TYPE_UNSIGNED (ti))
2193 need_precision += 1;
2194 if (TYPE_PRECISION (to) < need_precision)
2195 fail = true;
2197 if (!fail)
2199 SWITCH_COND (stmt) = def;
2200 modify_stmt (stmt);
2202 return lookup_avail_expr (stmt, insert);
2208 return 0;
2212 /* CONST_AND_COPIES is a table which maps an SSA_NAME to the current
2213 known value for that SSA_NAME (or NULL if no value is known).
2215 NONZERO_VARS is the set SSA_NAMES known to have a nonzero value,
2216 even if we don't know their precise value.
2218 Propagate values from CONST_AND_COPIES and NONZERO_VARS into the PHI
2219 nodes of the successors of BB. */
2221 static void
2222 cprop_into_successor_phis (basic_block bb,
2223 varray_type const_and_copies,
2224 bitmap nonzero_vars)
2226 edge e;
2228 /* This can get rather expensive if the implementation is naive in
2229 how it finds the phi alternative associated with a particular edge. */
2230 for (e = bb->succ; e; e = e->succ_next)
2232 tree phi;
2233 int phi_num_args;
2234 int hint;
2236 /* If this is an abnormal edge, then we do not want to copy propagate
2237 into the PHI alternative associated with this edge. */
2238 if (e->flags & EDGE_ABNORMAL)
2239 continue;
2241 phi = phi_nodes (e->dest);
2242 if (! phi)
2243 continue;
2245 /* There is no guarantee that for any two PHI nodes in a block that
2246 the phi alternative associated with a particular edge will be
2247 at the same index in the phi alternative array.
2249 However, it is very likely they will be the same. So we keep
2250 track of the index of the alternative where we found the edge in
2251 the previous phi node and check that index first in the next
2252 phi node. If that hint fails, then we actually search all
2253 the entries. */
2254 phi_num_args = PHI_NUM_ARGS (phi);
2255 hint = phi_num_args;
2256 for ( ; phi; phi = PHI_CHAIN (phi))
2258 int i;
2259 tree new;
2260 use_operand_p orig_p;
2261 tree orig;
2263 /* If the hint is valid (!= phi_num_args), see if it points
2264 us to the desired phi alternative. */
2265 if (hint != phi_num_args && PHI_ARG_EDGE (phi, hint) == e)
2267 else
2269 /* The hint was either invalid or did not point to the
2270 correct phi alternative. Search all the alternatives
2271 for the correct one. Update the hint. */
2272 for (i = 0; i < phi_num_args; i++)
2273 if (PHI_ARG_EDGE (phi, i) == e)
2274 break;
2275 hint = i;
2278 /* If we did not find the proper alternative, then something is
2279 horribly wrong. */
2280 gcc_assert (hint != phi_num_args);
2282 /* The alternative may be associated with a constant, so verify
2283 it is an SSA_NAME before doing anything with it. */
2284 orig_p = PHI_ARG_DEF_PTR (phi, hint);
2285 orig = USE_FROM_PTR (orig_p);
2286 if (TREE_CODE (orig) != SSA_NAME)
2287 continue;
2289 /* If the alternative is known to have a nonzero value, record
2290 that fact in the PHI node itself for future use. */
2291 if (bitmap_bit_p (nonzero_vars, SSA_NAME_VERSION (orig)))
2292 PHI_ARG_NONZERO (phi, hint) = true;
2294 /* If we have *ORIG_P in our constant/copy table, then replace
2295 ORIG_P with its value in our constant/copy table. */
2296 new = VARRAY_TREE (const_and_copies, SSA_NAME_VERSION (orig));
2297 if (new
2298 && (TREE_CODE (new) == SSA_NAME
2299 || is_gimple_min_invariant (new))
2300 && may_propagate_copy (orig, new))
2302 propagate_value (orig_p, new);
2309 /* Propagate known constants/copies into PHI nodes of BB's successor
2310 blocks. */
2312 static void
2313 cprop_into_phis (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
2314 basic_block bb)
2316 cprop_into_successor_phis (bb, const_and_copies, nonzero_vars);
2319 /* Search for redundant computations in STMT. If any are found, then
2320 replace them with the variable holding the result of the computation.
2322 If safe, record this expression into the available expression hash
2323 table. */
2325 static bool
2326 eliminate_redundant_computations (struct dom_walk_data *walk_data,
2327 tree stmt, stmt_ann_t ann)
2329 v_may_def_optype v_may_defs = V_MAY_DEF_OPS (ann);
2330 tree *expr_p, def = NULL_TREE;
2331 bool insert = true;
2332 tree cached_lhs;
2333 bool retval = false;
2335 if (TREE_CODE (stmt) == MODIFY_EXPR)
2336 def = TREE_OPERAND (stmt, 0);
2338 /* Certain expressions on the RHS can be optimized away, but can not
2339 themselves be entered into the hash tables. */
2340 if (ann->makes_aliased_stores
2341 || ! def
2342 || TREE_CODE (def) != SSA_NAME
2343 || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (def)
2344 || NUM_V_MAY_DEFS (v_may_defs) != 0)
2345 insert = false;
2347 /* Check if the expression has been computed before. */
2348 cached_lhs = lookup_avail_expr (stmt, insert);
2350 /* If this is an assignment and the RHS was not in the hash table,
2351 then try to simplify the RHS and lookup the new RHS in the
2352 hash table. */
2353 if (! cached_lhs && TREE_CODE (stmt) == MODIFY_EXPR)
2354 cached_lhs = simplify_rhs_and_lookup_avail_expr (walk_data, stmt, insert);
2355 /* Similarly if this is a COND_EXPR and we did not find its
2356 expression in the hash table, simplify the condition and
2357 try again. */
2358 else if (! cached_lhs && TREE_CODE (stmt) == COND_EXPR)
2359 cached_lhs = simplify_cond_and_lookup_avail_expr (stmt, ann, insert);
2360 /* Similarly for a SWITCH_EXPR. */
2361 else if (!cached_lhs && TREE_CODE (stmt) == SWITCH_EXPR)
2362 cached_lhs = simplify_switch_and_lookup_avail_expr (stmt, insert);
2364 opt_stats.num_exprs_considered++;
2366 /* Get a pointer to the expression we are trying to optimize. */
2367 if (TREE_CODE (stmt) == COND_EXPR)
2368 expr_p = &COND_EXPR_COND (stmt);
2369 else if (TREE_CODE (stmt) == SWITCH_EXPR)
2370 expr_p = &SWITCH_COND (stmt);
2371 else if (TREE_CODE (stmt) == RETURN_EXPR && TREE_OPERAND (stmt, 0))
2372 expr_p = &TREE_OPERAND (TREE_OPERAND (stmt, 0), 1);
2373 else
2374 expr_p = &TREE_OPERAND (stmt, 1);
2376 /* It is safe to ignore types here since we have already done
2377 type checking in the hashing and equality routines. In fact
2378 type checking here merely gets in the way of constant
2379 propagation. Also, make sure that it is safe to propagate
2380 CACHED_LHS into *EXPR_P. */
2381 if (cached_lhs
2382 && (TREE_CODE (cached_lhs) != SSA_NAME
2383 || may_propagate_copy (*expr_p, cached_lhs)))
2385 if (dump_file && (dump_flags & TDF_DETAILS))
2387 fprintf (dump_file, " Replaced redundant expr '");
2388 print_generic_expr (dump_file, *expr_p, dump_flags);
2389 fprintf (dump_file, "' with '");
2390 print_generic_expr (dump_file, cached_lhs, dump_flags);
2391 fprintf (dump_file, "'\n");
2394 opt_stats.num_re++;
2396 #if defined ENABLE_CHECKING
2397 gcc_assert (TREE_CODE (cached_lhs) == SSA_NAME
2398 || is_gimple_min_invariant (cached_lhs));
2399 #endif
2401 if (TREE_CODE (cached_lhs) == ADDR_EXPR
2402 || (POINTER_TYPE_P (TREE_TYPE (*expr_p))
2403 && is_gimple_min_invariant (cached_lhs)))
2404 retval = true;
2406 propagate_tree_value (expr_p, cached_lhs);
2407 modify_stmt (stmt);
2409 return retval;
2412 /* STMT, a MODIFY_EXPR, may create certain equivalences, in either
2413 the available expressions table or the const_and_copies table.
2414 Detect and record those equivalences. */
2416 static void
2417 record_equivalences_from_stmt (tree stmt,
2418 varray_type *block_nonzero_vars_p,
2419 int may_optimize_p,
2420 stmt_ann_t ann)
2422 tree lhs = TREE_OPERAND (stmt, 0);
2423 enum tree_code lhs_code = TREE_CODE (lhs);
2424 int i;
2426 if (lhs_code == SSA_NAME)
2428 tree rhs = TREE_OPERAND (stmt, 1);
2430 /* Strip away any useless type conversions. */
2431 STRIP_USELESS_TYPE_CONVERSION (rhs);
2433 /* If the RHS of the assignment is a constant or another variable that
2434 may be propagated, register it in the CONST_AND_COPIES table. We
2435 do not need to record unwind data for this, since this is a true
2436 assignment and not an equivalence inferred from a comparison. All
2437 uses of this ssa name are dominated by this assignment, so unwinding
2438 just costs time and space. */
2439 if (may_optimize_p
2440 && (TREE_CODE (rhs) == SSA_NAME
2441 || is_gimple_min_invariant (rhs)))
2442 set_value_for (lhs, rhs, const_and_copies);
2444 /* alloca never returns zero and the address of a non-weak symbol
2445 is never zero. NOP_EXPRs and CONVERT_EXPRs can be completely
2446 stripped as they do not affect this equivalence. */
2447 while (TREE_CODE (rhs) == NOP_EXPR
2448 || TREE_CODE (rhs) == CONVERT_EXPR)
2449 rhs = TREE_OPERAND (rhs, 0);
2451 if (alloca_call_p (rhs)
2452 || (TREE_CODE (rhs) == ADDR_EXPR
2453 && DECL_P (TREE_OPERAND (rhs, 0))
2454 && ! DECL_WEAK (TREE_OPERAND (rhs, 0))))
2455 record_var_is_nonzero (lhs, block_nonzero_vars_p);
2457 /* IOR of any value with a nonzero value will result in a nonzero
2458 value. Even if we do not know the exact result recording that
2459 the result is nonzero is worth the effort. */
2460 if (TREE_CODE (rhs) == BIT_IOR_EXPR
2461 && integer_nonzerop (TREE_OPERAND (rhs, 1)))
2462 record_var_is_nonzero (lhs, block_nonzero_vars_p);
2465 /* Look at both sides for pointer dereferences. If we find one, then
2466 the pointer must be nonnull and we can enter that equivalence into
2467 the hash tables. */
2468 if (flag_delete_null_pointer_checks)
2469 for (i = 0; i < 2; i++)
2471 tree t = TREE_OPERAND (stmt, i);
2473 /* Strip away any COMPONENT_REFs. */
2474 while (TREE_CODE (t) == COMPONENT_REF)
2475 t = TREE_OPERAND (t, 0);
2477 /* Now see if this is a pointer dereference. */
2478 if (TREE_CODE (t) == INDIRECT_REF)
2480 tree op = TREE_OPERAND (t, 0);
2482 /* If the pointer is a SSA variable, then enter new
2483 equivalences into the hash table. */
2484 while (TREE_CODE (op) == SSA_NAME)
2486 tree def = SSA_NAME_DEF_STMT (op);
2488 record_var_is_nonzero (op, block_nonzero_vars_p);
2490 /* And walk up the USE-DEF chains noting other SSA_NAMEs
2491 which are known to have a nonzero value. */
2492 if (def
2493 && TREE_CODE (def) == MODIFY_EXPR
2494 && TREE_CODE (TREE_OPERAND (def, 1)) == NOP_EXPR)
2495 op = TREE_OPERAND (TREE_OPERAND (def, 1), 0);
2496 else
2497 break;
2502 /* A memory store, even an aliased store, creates a useful
2503 equivalence. By exchanging the LHS and RHS, creating suitable
2504 vops and recording the result in the available expression table,
2505 we may be able to expose more redundant loads. */
2506 if (!ann->has_volatile_ops
2507 && (TREE_CODE (TREE_OPERAND (stmt, 1)) == SSA_NAME
2508 || is_gimple_min_invariant (TREE_OPERAND (stmt, 1)))
2509 && !is_gimple_reg (lhs))
2511 tree rhs = TREE_OPERAND (stmt, 1);
2512 tree new;
2514 /* FIXME: If the LHS of the assignment is a bitfield and the RHS
2515 is a constant, we need to adjust the constant to fit into the
2516 type of the LHS. If the LHS is a bitfield and the RHS is not
2517 a constant, then we can not record any equivalences for this
2518 statement since we would need to represent the widening or
2519 narrowing of RHS. This fixes gcc.c-torture/execute/921016-1.c
2520 and should not be necessary if GCC represented bitfields
2521 properly. */
2522 if (lhs_code == COMPONENT_REF
2523 && DECL_BIT_FIELD (TREE_OPERAND (lhs, 1)))
2525 if (TREE_CONSTANT (rhs))
2526 rhs = widen_bitfield (rhs, TREE_OPERAND (lhs, 1), lhs);
2527 else
2528 rhs = NULL;
2530 /* If the value overflowed, then we can not use this equivalence. */
2531 if (rhs && ! is_gimple_min_invariant (rhs))
2532 rhs = NULL;
2535 if (rhs)
2537 /* Build a new statement with the RHS and LHS exchanged. */
2538 new = build (MODIFY_EXPR, TREE_TYPE (stmt), rhs, lhs);
2540 create_ssa_artficial_load_stmt (&(ann->operands), new);
2542 /* Finally enter the statement into the available expression
2543 table. */
2544 lookup_avail_expr (new, true);
2549 /* Replace *OP_P in STMT with any known equivalent value for *OP_P from
2550 CONST_AND_COPIES. */
2552 static bool
2553 cprop_operand (tree stmt, use_operand_p op_p, varray_type const_and_copies)
2555 bool may_have_exposed_new_symbols = false;
2556 tree val;
2557 tree op = USE_FROM_PTR (op_p);
2559 /* If the operand has a known constant value or it is known to be a
2560 copy of some other variable, use the value or copy stored in
2561 CONST_AND_COPIES. */
2562 val = VARRAY_TREE (const_and_copies, SSA_NAME_VERSION (op));
2563 if (val)
2565 tree op_type, val_type;
2567 /* Do not change the base variable in the virtual operand
2568 tables. That would make it impossible to reconstruct
2569 the renamed virtual operand if we later modify this
2570 statement. Also only allow the new value to be an SSA_NAME
2571 for propagation into virtual operands. */
2572 if (!is_gimple_reg (op)
2573 && (get_virtual_var (val) != get_virtual_var (op)
2574 || TREE_CODE (val) != SSA_NAME))
2575 return false;
2577 /* Get the toplevel type of each operand. */
2578 op_type = TREE_TYPE (op);
2579 val_type = TREE_TYPE (val);
2581 /* While both types are pointers, get the type of the object
2582 pointed to. */
2583 while (POINTER_TYPE_P (op_type) && POINTER_TYPE_P (val_type))
2585 op_type = TREE_TYPE (op_type);
2586 val_type = TREE_TYPE (val_type);
2589 /* Make sure underlying types match before propagating a constant by
2590 converting the constant to the proper type. Note that convert may
2591 return a non-gimple expression, in which case we ignore this
2592 propagation opportunity. */
2593 if (TREE_CODE (val) != SSA_NAME)
2595 if (!lang_hooks.types_compatible_p (op_type, val_type))
2597 val = fold_convert (TREE_TYPE (op), val);
2598 if (!is_gimple_min_invariant (val))
2599 return false;
2603 /* Certain operands are not allowed to be copy propagated due
2604 to their interaction with exception handling and some GCC
2605 extensions. */
2606 else if (!may_propagate_copy (op, val))
2607 return false;
2609 /* Dump details. */
2610 if (dump_file && (dump_flags & TDF_DETAILS))
2612 fprintf (dump_file, " Replaced '");
2613 print_generic_expr (dump_file, op, dump_flags);
2614 fprintf (dump_file, "' with %s '",
2615 (TREE_CODE (val) != SSA_NAME ? "constant" : "variable"));
2616 print_generic_expr (dump_file, val, dump_flags);
2617 fprintf (dump_file, "'\n");
2620 /* If VAL is an ADDR_EXPR or a constant of pointer type, note
2621 that we may have exposed a new symbol for SSA renaming. */
2622 if (TREE_CODE (val) == ADDR_EXPR
2623 || (POINTER_TYPE_P (TREE_TYPE (op))
2624 && is_gimple_min_invariant (val)))
2625 may_have_exposed_new_symbols = true;
2627 propagate_value (op_p, val);
2629 /* And note that we modified this statement. This is now
2630 safe, even if we changed virtual operands since we will
2631 rescan the statement and rewrite its operands again. */
2632 modify_stmt (stmt);
2634 return may_have_exposed_new_symbols;
2637 /* CONST_AND_COPIES is a table which maps an SSA_NAME to the current
2638 known value for that SSA_NAME (or NULL if no value is known).
2640 Propagate values from CONST_AND_COPIES into the uses, vuses and
2641 v_may_def_ops of STMT. */
2643 static bool
2644 cprop_into_stmt (tree stmt, varray_type const_and_copies)
2646 bool may_have_exposed_new_symbols = false;
2647 use_operand_p op_p;
2648 ssa_op_iter iter;
2650 FOR_EACH_SSA_USE_OPERAND (op_p, stmt, iter, SSA_OP_ALL_USES)
2652 if (TREE_CODE (USE_FROM_PTR (op_p)) == SSA_NAME)
2653 may_have_exposed_new_symbols
2654 |= cprop_operand (stmt, op_p, const_and_copies);
2657 return may_have_exposed_new_symbols;
2661 /* Optimize the statement pointed by iterator SI.
2663 We try to perform some simplistic global redundancy elimination and
2664 constant propagation:
2666 1- To detect global redundancy, we keep track of expressions that have
2667 been computed in this block and its dominators. If we find that the
2668 same expression is computed more than once, we eliminate repeated
2669 computations by using the target of the first one.
2671 2- Constant values and copy assignments. This is used to do very
2672 simplistic constant and copy propagation. When a constant or copy
2673 assignment is found, we map the value on the RHS of the assignment to
2674 the variable in the LHS in the CONST_AND_COPIES table. */
2676 static void
2677 optimize_stmt (struct dom_walk_data *walk_data, basic_block bb,
2678 block_stmt_iterator si)
2680 stmt_ann_t ann;
2681 tree stmt;
2682 bool may_optimize_p;
2683 bool may_have_exposed_new_symbols = false;
2684 struct dom_walk_block_data *bd
2685 = VARRAY_TOP_GENERIC_PTR (walk_data->block_data_stack);
2687 stmt = bsi_stmt (si);
2689 get_stmt_operands (stmt);
2690 ann = stmt_ann (stmt);
2691 opt_stats.num_stmts++;
2692 may_have_exposed_new_symbols = false;
2694 if (dump_file && (dump_flags & TDF_DETAILS))
2696 fprintf (dump_file, "Optimizing statement ");
2697 print_generic_stmt (dump_file, stmt, TDF_SLIM);
2700 /* Const/copy propagate into USES, VUSES and the RHS of V_MAY_DEFs. */
2701 may_have_exposed_new_symbols = cprop_into_stmt (stmt, const_and_copies);
2703 /* If the statement has been modified with constant replacements,
2704 fold its RHS before checking for redundant computations. */
2705 if (ann->modified)
2707 /* Try to fold the statement making sure that STMT is kept
2708 up to date. */
2709 if (fold_stmt (bsi_stmt_ptr (si)))
2711 stmt = bsi_stmt (si);
2712 ann = stmt_ann (stmt);
2714 if (dump_file && (dump_flags & TDF_DETAILS))
2716 fprintf (dump_file, " Folded to: ");
2717 print_generic_stmt (dump_file, stmt, TDF_SLIM);
2721 /* Constant/copy propagation above may change the set of
2722 virtual operands associated with this statement. Folding
2723 may remove the need for some virtual operands.
2725 Indicate we will need to rescan and rewrite the statement. */
2726 may_have_exposed_new_symbols = true;
2729 /* Check for redundant computations. Do this optimization only
2730 for assignments that have no volatile ops and conditionals. */
2731 may_optimize_p = (!ann->has_volatile_ops
2732 && ((TREE_CODE (stmt) == RETURN_EXPR
2733 && TREE_OPERAND (stmt, 0)
2734 && TREE_CODE (TREE_OPERAND (stmt, 0)) == MODIFY_EXPR
2735 && ! (TREE_SIDE_EFFECTS
2736 (TREE_OPERAND (TREE_OPERAND (stmt, 0), 1))))
2737 || (TREE_CODE (stmt) == MODIFY_EXPR
2738 && ! TREE_SIDE_EFFECTS (TREE_OPERAND (stmt, 1)))
2739 || TREE_CODE (stmt) == COND_EXPR
2740 || TREE_CODE (stmt) == SWITCH_EXPR));
2742 if (may_optimize_p)
2743 may_have_exposed_new_symbols
2744 |= eliminate_redundant_computations (walk_data, stmt, ann);
2746 /* Record any additional equivalences created by this statement. */
2747 if (TREE_CODE (stmt) == MODIFY_EXPR)
2748 record_equivalences_from_stmt (stmt,
2749 &bd->nonzero_vars,
2750 may_optimize_p,
2751 ann);
2753 register_definitions_for_stmt (stmt, &bd->block_defs);
2755 /* If STMT is a COND_EXPR and it was modified, then we may know
2756 where it goes. If that is the case, then mark the CFG as altered.
2758 This will cause us to later call remove_unreachable_blocks and
2759 cleanup_tree_cfg when it is safe to do so. It is not safe to
2760 clean things up here since removal of edges and such can trigger
2761 the removal of PHI nodes, which in turn can release SSA_NAMEs to
2762 the manager.
2764 That's all fine and good, except that once SSA_NAMEs are released
2765 to the manager, we must not call create_ssa_name until all references
2766 to released SSA_NAMEs have been eliminated.
2768 All references to the deleted SSA_NAMEs can not be eliminated until
2769 we remove unreachable blocks.
2771 We can not remove unreachable blocks until after we have completed
2772 any queued jump threading.
2774 We can not complete any queued jump threads until we have taken
2775 appropriate variables out of SSA form. Taking variables out of
2776 SSA form can call create_ssa_name and thus we lose.
2778 Ultimately I suspect we're going to need to change the interface
2779 into the SSA_NAME manager. */
2781 if (ann->modified)
2783 tree val = NULL;
2785 if (TREE_CODE (stmt) == COND_EXPR)
2786 val = COND_EXPR_COND (stmt);
2787 else if (TREE_CODE (stmt) == SWITCH_EXPR)
2788 val = SWITCH_COND (stmt);
2790 if (val && TREE_CODE (val) == INTEGER_CST && find_taken_edge (bb, val))
2791 cfg_altered = true;
2793 /* If we simplified a statement in such a way as to be shown that it
2794 cannot trap, update the eh information and the cfg to match. */
2795 if (maybe_clean_eh_stmt (stmt))
2797 bitmap_set_bit (need_eh_cleanup, bb->index);
2798 if (dump_file && (dump_flags & TDF_DETAILS))
2799 fprintf (dump_file, " Flagged to clear EH edges.\n");
2803 if (may_have_exposed_new_symbols)
2804 VARRAY_PUSH_TREE (stmts_to_rescan, bsi_stmt (si));
2807 /* Replace the RHS of STMT with NEW_RHS. If RHS can be found in the
2808 available expression hashtable, then return the LHS from the hash
2809 table.
2811 If INSERT is true, then we also update the available expression
2812 hash table to account for the changes made to STMT. */
2814 static tree
2815 update_rhs_and_lookup_avail_expr (tree stmt, tree new_rhs, bool insert)
2817 tree cached_lhs = NULL;
2819 /* Remove the old entry from the hash table. */
2820 if (insert)
2822 struct expr_hash_elt element;
2824 initialize_hash_element (stmt, NULL, &element);
2825 htab_remove_elt_with_hash (avail_exprs, &element, element.hash);
2828 /* Now update the RHS of the assignment. */
2829 TREE_OPERAND (stmt, 1) = new_rhs;
2831 /* Now lookup the updated statement in the hash table. */
2832 cached_lhs = lookup_avail_expr (stmt, insert);
2834 /* We have now called lookup_avail_expr twice with two different
2835 versions of this same statement, once in optimize_stmt, once here.
2837 We know the call in optimize_stmt did not find an existing entry
2838 in the hash table, so a new entry was created. At the same time
2839 this statement was pushed onto the BLOCK_AVAIL_EXPRS varray.
2841 If this call failed to find an existing entry on the hash table,
2842 then the new version of this statement was entered into the
2843 hash table. And this statement was pushed onto BLOCK_AVAIL_EXPR
2844 for the second time. So there are two copies on BLOCK_AVAIL_EXPRs
2846 If this call succeeded, we still have one copy of this statement
2847 on the BLOCK_AVAIL_EXPRs varray.
2849 For both cases, we need to pop the most recent entry off the
2850 BLOCK_AVAIL_EXPRs varray. For the case where we never found this
2851 statement in the hash tables, that will leave precisely one
2852 copy of this statement on BLOCK_AVAIL_EXPRs. For the case where
2853 we found a copy of this statement in the second hash table lookup
2854 we want _no_ copies of this statement in BLOCK_AVAIL_EXPRs. */
2855 if (insert)
2856 VARRAY_POP (avail_exprs_stack);
2858 /* And make sure we record the fact that we modified this
2859 statement. */
2860 modify_stmt (stmt);
2862 return cached_lhs;
2865 /* Search for an existing instance of STMT in the AVAIL_EXPRS table. If
2866 found, return its LHS. Otherwise insert STMT in the table and return
2867 NULL_TREE.
2869 Also, when an expression is first inserted in the AVAIL_EXPRS table, it
2870 is also added to the stack pointed by BLOCK_AVAIL_EXPRS_P, so that they
2871 can be removed when we finish processing this block and its children.
2873 NOTE: This function assumes that STMT is a MODIFY_EXPR node that
2874 contains no CALL_EXPR on its RHS and makes no volatile nor
2875 aliased references. */
2877 static tree
2878 lookup_avail_expr (tree stmt, bool insert)
2880 void **slot;
2881 tree lhs;
2882 tree temp;
2883 struct expr_hash_elt *element = xcalloc (sizeof (struct expr_hash_elt), 1);
2885 lhs = TREE_CODE (stmt) == MODIFY_EXPR ? TREE_OPERAND (stmt, 0) : NULL;
2887 initialize_hash_element (stmt, lhs, element);
2889 /* Don't bother remembering constant assignments and copy operations.
2890 Constants and copy operations are handled by the constant/copy propagator
2891 in optimize_stmt. */
2892 if (TREE_CODE (element->rhs) == SSA_NAME
2893 || is_gimple_min_invariant (element->rhs))
2895 free (element);
2896 return NULL_TREE;
2899 /* If this is an equality test against zero, see if we have recorded a
2900 nonzero value for the variable in question. */
2901 if ((TREE_CODE (element->rhs) == EQ_EXPR
2902 || TREE_CODE (element->rhs) == NE_EXPR)
2903 && TREE_CODE (TREE_OPERAND (element->rhs, 0)) == SSA_NAME
2904 && integer_zerop (TREE_OPERAND (element->rhs, 1)))
2906 int indx = SSA_NAME_VERSION (TREE_OPERAND (element->rhs, 0));
2908 if (bitmap_bit_p (nonzero_vars, indx))
2910 tree t = element->rhs;
2911 free (element);
2913 if (TREE_CODE (t) == EQ_EXPR)
2914 return boolean_false_node;
2915 else
2916 return boolean_true_node;
2920 /* Finally try to find the expression in the main expression hash table. */
2921 slot = htab_find_slot_with_hash (avail_exprs, element, element->hash,
2922 (insert ? INSERT : NO_INSERT));
2923 if (slot == NULL)
2925 free (element);
2926 return NULL_TREE;
2929 if (*slot == NULL)
2931 *slot = (void *) element;
2932 VARRAY_PUSH_TREE (avail_exprs_stack, stmt ? stmt : element->rhs);
2933 return NULL_TREE;
2936 /* Extract the LHS of the assignment so that it can be used as the current
2937 definition of another variable. */
2938 lhs = ((struct expr_hash_elt *)*slot)->lhs;
2940 /* See if the LHS appears in the CONST_AND_COPIES table. If it does, then
2941 use the value from the const_and_copies table. */
2942 if (TREE_CODE (lhs) == SSA_NAME)
2944 temp = get_value_for (lhs, const_and_copies);
2945 if (temp)
2946 lhs = temp;
2949 free (element);
2950 return lhs;
2953 /* Given a condition COND, record into HI_P, LO_P and INVERTED_P the
2954 range of values that result in the conditional having a true value.
2956 Return true if we are successful in extracting a range from COND and
2957 false if we are unsuccessful. */
2959 static bool
2960 extract_range_from_cond (tree cond, tree *hi_p, tree *lo_p, int *inverted_p)
2962 tree op1 = TREE_OPERAND (cond, 1);
2963 tree high, low, type;
2964 int inverted;
2966 /* Experiments have shown that it's rarely, if ever useful to
2967 record ranges for enumerations. Presumably this is due to
2968 the fact that they're rarely used directly. They are typically
2969 cast into an integer type and used that way. */
2970 if (TREE_CODE (TREE_TYPE (op1)) != INTEGER_TYPE)
2971 return 0;
2973 type = TREE_TYPE (op1);
2975 switch (TREE_CODE (cond))
2977 case EQ_EXPR:
2978 high = low = op1;
2979 inverted = 0;
2980 break;
2982 case NE_EXPR:
2983 high = low = op1;
2984 inverted = 1;
2985 break;
2987 case GE_EXPR:
2988 low = op1;
2989 high = TYPE_MAX_VALUE (type);
2990 inverted = 0;
2991 break;
2993 case GT_EXPR:
2994 low = int_const_binop (PLUS_EXPR, op1, integer_one_node, 1);
2995 high = TYPE_MAX_VALUE (type);
2996 inverted = 0;
2997 break;
2999 case LE_EXPR:
3000 high = op1;
3001 low = TYPE_MIN_VALUE (type);
3002 inverted = 0;
3003 break;
3005 case LT_EXPR:
3006 high = int_const_binop (MINUS_EXPR, op1, integer_one_node, 1);
3007 low = TYPE_MIN_VALUE (type);
3008 inverted = 0;
3009 break;
3011 default:
3012 return 0;
3015 *hi_p = high;
3016 *lo_p = low;
3017 *inverted_p = inverted;
3018 return 1;
3021 /* Record a range created by COND for basic block BB. */
3023 static void
3024 record_range (tree cond, basic_block bb, varray_type *vrp_variables_p)
3026 /* We explicitly ignore NE_EXPRs. They rarely allow for meaningful
3027 range optimizations and significantly complicate the implementation. */
3028 if (TREE_CODE_CLASS (TREE_CODE (cond)) == '<'
3029 && TREE_CODE (cond) != NE_EXPR
3030 && TREE_CODE (TREE_TYPE (TREE_OPERAND (cond, 1))) == INTEGER_TYPE)
3032 struct vrp_element *element = ggc_alloc (sizeof (struct vrp_element));
3033 int ssa_version = SSA_NAME_VERSION (TREE_OPERAND (cond, 0));
3035 varray_type *vrp_records_p
3036 = (varray_type *)&VARRAY_GENERIC_PTR (vrp_data, ssa_version);
3038 element->low = NULL;
3039 element->high = NULL;
3040 element->cond = cond;
3041 element->bb = bb;
3043 if (*vrp_records_p == NULL)
3045 VARRAY_GENERIC_PTR_INIT (*vrp_records_p, 2, "vrp records");
3046 VARRAY_GENERIC_PTR (vrp_data, ssa_version) = *vrp_records_p;
3049 VARRAY_PUSH_GENERIC_PTR (*vrp_records_p, element);
3050 if (! *vrp_variables_p)
3051 VARRAY_TREE_INIT (*vrp_variables_p, 2, "vrp_variables");
3052 VARRAY_PUSH_TREE (*vrp_variables_p, TREE_OPERAND (cond, 0));
3056 /* Given a conditional statement IF_STMT, return the assignment 'X = Y'
3057 known to be true depending on which arm of IF_STMT is taken.
3059 Not all conditional statements will result in a useful assignment.
3060 Return NULL_TREE in that case.
3062 Also enter into the available expression table statements of
3063 the form:
3065 TRUE ARM FALSE ARM
3066 1 = cond 1 = cond'
3067 0 = cond' 0 = cond
3069 This allows us to lookup the condition in a dominated block and
3070 get back a constant indicating if the condition is true. */
3072 static struct eq_expr_value
3073 get_eq_expr_value (tree if_stmt,
3074 int true_arm,
3075 basic_block bb,
3076 varray_type *vrp_variables_p)
3078 tree cond;
3079 struct eq_expr_value retval;
3081 cond = COND_EXPR_COND (if_stmt);
3082 retval.src = NULL;
3083 retval.dst = NULL;
3085 /* If the conditional is a single variable 'X', return 'X = 1' for
3086 the true arm and 'X = 0' on the false arm. */
3087 if (TREE_CODE (cond) == SSA_NAME)
3089 retval.dst = cond;
3090 retval.src = constant_boolean_node (true_arm, TREE_TYPE (cond));
3091 return retval;
3094 /* If we have a comparison expression, then record its result into
3095 the available expression table. */
3096 if (TREE_CODE_CLASS (TREE_CODE (cond)) == '<')
3098 tree op0 = TREE_OPERAND (cond, 0);
3099 tree op1 = TREE_OPERAND (cond, 1);
3101 /* Special case comparing booleans against a constant as we know
3102 the value of OP0 on both arms of the branch. ie, we can record
3103 an equivalence for OP0 rather than COND. */
3104 if ((TREE_CODE (cond) == EQ_EXPR || TREE_CODE (cond) == NE_EXPR)
3105 && TREE_CODE (op0) == SSA_NAME
3106 && TREE_CODE (TREE_TYPE (op0)) == BOOLEAN_TYPE
3107 && is_gimple_min_invariant (op1))
3109 if ((TREE_CODE (cond) == EQ_EXPR && true_arm)
3110 || (TREE_CODE (cond) == NE_EXPR && ! true_arm))
3112 retval.src = op1;
3114 else
3116 if (integer_zerop (op1))
3117 retval.src = boolean_true_node;
3118 else
3119 retval.src = boolean_false_node;
3121 retval.dst = op0;
3122 return retval;
3125 if (TREE_CODE (op0) == SSA_NAME
3126 && (is_gimple_min_invariant (op1) || TREE_CODE (op1) == SSA_NAME))
3128 tree inverted = invert_truthvalue (cond);
3130 /* When we find an available expression in the hash table, we replace
3131 the expression with the LHS of the statement in the hash table.
3133 So, we want to build statements such as "1 = <condition>" on the
3134 true arm and "0 = <condition>" on the false arm. That way if we
3135 find the expression in the table, we will replace it with its
3136 known constant value. Also insert inversions of the result and
3137 condition into the hash table. */
3138 if (true_arm)
3140 record_cond (cond, boolean_true_node);
3141 record_dominating_conditions (cond);
3142 record_cond (inverted, boolean_false_node);
3144 if (TREE_CONSTANT (op1))
3145 record_range (cond, bb, vrp_variables_p);
3147 /* If the conditional is of the form 'X == Y', return 'X = Y'
3148 for the true arm. */
3149 if (TREE_CODE (cond) == EQ_EXPR)
3151 retval.dst = op0;
3152 retval.src = op1;
3153 return retval;
3156 else
3159 record_cond (inverted, boolean_true_node);
3160 record_dominating_conditions (inverted);
3161 record_cond (cond, boolean_false_node);
3163 if (TREE_CONSTANT (op1))
3164 record_range (inverted, bb, vrp_variables_p);
3166 /* If the conditional is of the form 'X != Y', return 'X = Y'
3167 for the false arm. */
3168 if (TREE_CODE (cond) == NE_EXPR)
3170 retval.dst = op0;
3171 retval.src = op1;
3172 return retval;
3178 return retval;
3181 /* Hashing and equality functions for AVAIL_EXPRS. The table stores
3182 MODIFY_EXPR statements. We compute a value number for expressions using
3183 the code of the expression and the SSA numbers of its operands. */
3185 static hashval_t
3186 avail_expr_hash (const void *p)
3188 stmt_ann_t ann = ((struct expr_hash_elt *)p)->ann;
3189 tree rhs = ((struct expr_hash_elt *)p)->rhs;
3190 hashval_t val = 0;
3191 size_t i;
3192 vuse_optype vuses;
3194 /* iterative_hash_expr knows how to deal with any expression and
3195 deals with commutative operators as well, so just use it instead
3196 of duplicating such complexities here. */
3197 val = iterative_hash_expr (rhs, val);
3199 /* If the hash table entry is not associated with a statement, then we
3200 can just hash the expression and not worry about virtual operands
3201 and such. */
3202 if (!ann)
3203 return val;
3205 /* Add the SSA version numbers of every vuse operand. This is important
3206 because compound variables like arrays are not renamed in the
3207 operands. Rather, the rename is done on the virtual variable
3208 representing all the elements of the array. */
3209 vuses = VUSE_OPS (ann);
3210 for (i = 0; i < NUM_VUSES (vuses); i++)
3211 val = iterative_hash_expr (VUSE_OP (vuses, i), val);
3213 return val;
3216 static hashval_t
3217 real_avail_expr_hash (const void *p)
3219 return ((const struct expr_hash_elt *)p)->hash;
3222 static int
3223 avail_expr_eq (const void *p1, const void *p2)
3225 stmt_ann_t ann1 = ((struct expr_hash_elt *)p1)->ann;
3226 tree rhs1 = ((struct expr_hash_elt *)p1)->rhs;
3227 stmt_ann_t ann2 = ((struct expr_hash_elt *)p2)->ann;
3228 tree rhs2 = ((struct expr_hash_elt *)p2)->rhs;
3230 /* If they are the same physical expression, return true. */
3231 if (rhs1 == rhs2 && ann1 == ann2)
3232 return true;
3234 /* If their codes are not equal, then quit now. */
3235 if (TREE_CODE (rhs1) != TREE_CODE (rhs2))
3236 return false;
3238 /* In case of a collision, both RHS have to be identical and have the
3239 same VUSE operands. */
3240 if ((TREE_TYPE (rhs1) == TREE_TYPE (rhs2)
3241 || lang_hooks.types_compatible_p (TREE_TYPE (rhs1), TREE_TYPE (rhs2)))
3242 && operand_equal_p (rhs1, rhs2, OEP_PURE_SAME))
3244 vuse_optype ops1 = NULL;
3245 vuse_optype ops2 = NULL;
3246 size_t num_ops1 = 0;
3247 size_t num_ops2 = 0;
3248 size_t i;
3250 if (ann1)
3252 ops1 = VUSE_OPS (ann1);
3253 num_ops1 = NUM_VUSES (ops1);
3256 if (ann2)
3258 ops2 = VUSE_OPS (ann2);
3259 num_ops2 = NUM_VUSES (ops2);
3262 /* If the number of virtual uses is different, then we consider
3263 them not equal. */
3264 if (num_ops1 != num_ops2)
3265 return false;
3267 for (i = 0; i < num_ops1; i++)
3268 if (VUSE_OP (ops1, i) != VUSE_OP (ops2, i))
3269 return false;
3271 gcc_assert (((struct expr_hash_elt *)p1)->hash
3272 == ((struct expr_hash_elt *)p2)->hash);
3273 return true;
3276 return false;
3279 /* Given STMT and a pointer to the block local definitions BLOCK_DEFS_P,
3280 register register all objects set by this statement into BLOCK_DEFS_P
3281 and CURRDEFS. */
3283 static void
3284 register_definitions_for_stmt (tree stmt, varray_type *block_defs_p)
3286 tree def;
3287 ssa_op_iter iter;
3289 FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_ALL_DEFS)
3292 /* FIXME: We shouldn't be registering new defs if the variable
3293 doesn't need to be renamed. */
3294 register_new_def (def, block_defs_p);