* common.opt (flag_force_mem): Remove.
[official-gcc.git] / gcc / tree-ssa-dom.c
blob73ddc0a9dbacea7bf463ead39bf82dafc6079dc1
1 /* SSA Dominator optimizations for trees
2 Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006
3 Free Software Foundation, Inc.
4 Contributed by Diego Novillo <dnovillo@redhat.com>
6 This file is part of GCC.
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2, or (at your option)
11 any later version.
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING. If not, write to
20 the Free Software Foundation, 51 Franklin Street, Fifth Floor,
21 Boston, MA 02110-1301, USA. */
23 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "tm.h"
27 #include "tree.h"
28 #include "flags.h"
29 #include "rtl.h"
30 #include "tm_p.h"
31 #include "ggc.h"
32 #include "basic-block.h"
33 #include "cfgloop.h"
34 #include "output.h"
35 #include "expr.h"
36 #include "function.h"
37 #include "diagnostic.h"
38 #include "timevar.h"
39 #include "tree-dump.h"
40 #include "tree-flow.h"
41 #include "domwalk.h"
42 #include "real.h"
43 #include "tree-pass.h"
44 #include "tree-ssa-propagate.h"
45 #include "langhooks.h"
46 #include "params.h"
48 /* This file implements optimizations on the dominator tree. */
51 /* Structure for recording edge equivalences as well as any pending
52 edge redirections during the dominator optimizer.
54 Computing and storing the edge equivalences instead of creating
55 them on-demand can save significant amounts of time, particularly
56 for pathological cases involving switch statements.
58 These structures live for a single iteration of the dominator
59 optimizer in the edge's AUX field. At the end of an iteration we
60 free each of these structures and update the AUX field to point
61 to any requested redirection target (the code for updating the
62 CFG and SSA graph for edge redirection expects redirection edge
63 targets to be in the AUX field for each edge. */
65 struct edge_info
67 /* If this edge creates a simple equivalence, the LHS and RHS of
68 the equivalence will be stored here. */
69 tree lhs;
70 tree rhs;
72 /* Traversing an edge may also indicate one or more particular conditions
73 are true or false. The number of recorded conditions can vary, but
74 can be determined by the condition's code. So we have an array
75 and its maximum index rather than use a varray. */
76 tree *cond_equivalences;
77 unsigned int max_cond_equivalences;
81 /* Hash table with expressions made available during the renaming process.
82 When an assignment of the form X_i = EXPR is found, the statement is
83 stored in this table. If the same expression EXPR is later found on the
84 RHS of another statement, it is replaced with X_i (thus performing
85 global redundancy elimination). Similarly as we pass through conditionals
86 we record the conditional itself as having either a true or false value
87 in this table. */
88 static htab_t avail_exprs;
90 /* Stack of available expressions in AVAIL_EXPRs. Each block pushes any
91 expressions it enters into the hash table along with a marker entry
92 (null). When we finish processing the block, we pop off entries and
93 remove the expressions from the global hash table until we hit the
94 marker. */
95 static VEC(tree,heap) *avail_exprs_stack;
97 /* Stack of statements we need to rescan during finalization for newly
98 exposed variables.
100 Statement rescanning must occur after the current block's available
101 expressions are removed from AVAIL_EXPRS. Else we may change the
102 hash code for an expression and be unable to find/remove it from
103 AVAIL_EXPRS. */
104 typedef tree *tree_p;
105 DEF_VEC_P(tree_p);
106 DEF_VEC_ALLOC_P(tree_p,heap);
108 static VEC(tree_p,heap) *stmts_to_rescan;
110 /* Structure for entries in the expression hash table.
112 This requires more memory for the hash table entries, but allows us
113 to avoid creating silly tree nodes and annotations for conditionals,
114 eliminates 2 global hash tables and two block local varrays.
116 It also allows us to reduce the number of hash table lookups we
117 have to perform in lookup_avail_expr and finally it allows us to
118 significantly reduce the number of calls into the hashing routine
119 itself. */
121 struct expr_hash_elt
123 /* The value (lhs) of this expression. */
124 tree lhs;
126 /* The expression (rhs) we want to record. */
127 tree rhs;
129 /* The stmt pointer if this element corresponds to a statement. */
130 tree stmt;
132 /* The hash value for RHS/ann. */
133 hashval_t hash;
136 /* Stack of dest,src pairs that need to be restored during finalization.
138 A NULL entry is used to mark the end of pairs which need to be
139 restored during finalization of this block. */
140 static VEC(tree,heap) *const_and_copies_stack;
142 /* Track whether or not we have changed the control flow graph. */
143 static bool cfg_altered;
145 /* Bitmap of blocks that have had EH statements cleaned. We should
146 remove their dead edges eventually. */
147 static bitmap need_eh_cleanup;
149 /* Statistics for dominator optimizations. */
150 struct opt_stats_d
152 long num_stmts;
153 long num_exprs_considered;
154 long num_re;
155 long num_const_prop;
156 long num_copy_prop;
159 static struct opt_stats_d opt_stats;
161 struct eq_expr_value
163 tree src;
164 tree dst;
167 /* Local functions. */
168 static void optimize_stmt (struct dom_walk_data *,
169 basic_block bb,
170 block_stmt_iterator);
171 static tree lookup_avail_expr (tree, bool);
172 static hashval_t avail_expr_hash (const void *);
173 static hashval_t real_avail_expr_hash (const void *);
174 static int avail_expr_eq (const void *, const void *);
175 static void htab_statistics (FILE *, htab_t);
176 static void record_cond (tree, tree);
177 static void record_const_or_copy (tree, tree);
178 static void record_equality (tree, tree);
179 static void record_equivalences_from_phis (basic_block);
180 static void record_equivalences_from_incoming_edge (basic_block);
181 static bool eliminate_redundant_computations (tree);
182 static void record_equivalences_from_stmt (tree, int, stmt_ann_t);
183 static void dom_thread_across_edge (struct dom_walk_data *, edge);
184 static void dom_opt_finalize_block (struct dom_walk_data *, basic_block);
185 static void dom_opt_initialize_block (struct dom_walk_data *, basic_block);
186 static void propagate_to_outgoing_edges (struct dom_walk_data *, basic_block);
187 static void remove_local_expressions_from_table (void);
188 static void restore_vars_to_original_value (void);
189 static edge single_incoming_edge_ignoring_loop_edges (basic_block);
192 /* Allocate an EDGE_INFO for edge E and attach it to E.
193 Return the new EDGE_INFO structure. */
195 static struct edge_info *
196 allocate_edge_info (edge e)
198 struct edge_info *edge_info;
200 edge_info = XCNEW (struct edge_info);
202 e->aux = edge_info;
203 return edge_info;
206 /* Free all EDGE_INFO structures associated with edges in the CFG.
207 If a particular edge can be threaded, copy the redirection
208 target from the EDGE_INFO structure into the edge's AUX field
209 as required by code to update the CFG and SSA graph for
210 jump threading. */
212 static void
213 free_all_edge_infos (void)
215 basic_block bb;
216 edge_iterator ei;
217 edge e;
219 FOR_EACH_BB (bb)
221 FOR_EACH_EDGE (e, ei, bb->preds)
223 struct edge_info *edge_info = (struct edge_info *) e->aux;
225 if (edge_info)
227 if (edge_info->cond_equivalences)
228 free (edge_info->cond_equivalences);
229 free (edge_info);
230 e->aux = NULL;
236 /* Jump threading, redundancy elimination and const/copy propagation.
238 This pass may expose new symbols that need to be renamed into SSA. For
239 every new symbol exposed, its corresponding bit will be set in
240 VARS_TO_RENAME. */
242 static unsigned int
243 tree_ssa_dominator_optimize (void)
245 struct dom_walk_data walk_data;
246 unsigned int i;
248 memset (&opt_stats, 0, sizeof (opt_stats));
250 /* Create our hash tables. */
251 avail_exprs = htab_create (1024, real_avail_expr_hash, avail_expr_eq, free);
252 avail_exprs_stack = VEC_alloc (tree, heap, 20);
253 const_and_copies_stack = VEC_alloc (tree, heap, 20);
254 stmts_to_rescan = VEC_alloc (tree_p, heap, 20);
255 need_eh_cleanup = BITMAP_ALLOC (NULL);
257 /* Setup callbacks for the generic dominator tree walker. */
258 walk_data.walk_stmts_backward = false;
259 walk_data.dom_direction = CDI_DOMINATORS;
260 walk_data.initialize_block_local_data = NULL;
261 walk_data.before_dom_children_before_stmts = dom_opt_initialize_block;
262 walk_data.before_dom_children_walk_stmts = optimize_stmt;
263 walk_data.before_dom_children_after_stmts = propagate_to_outgoing_edges;
264 walk_data.after_dom_children_before_stmts = NULL;
265 walk_data.after_dom_children_walk_stmts = NULL;
266 walk_data.after_dom_children_after_stmts = dom_opt_finalize_block;
267 /* Right now we only attach a dummy COND_EXPR to the global data pointer.
268 When we attach more stuff we'll need to fill this out with a real
269 structure. */
270 walk_data.global_data = NULL;
271 walk_data.block_local_data_size = 0;
272 walk_data.interesting_blocks = NULL;
274 /* Now initialize the dominator walker. */
275 init_walk_dominator_tree (&walk_data);
277 calculate_dominance_info (CDI_DOMINATORS);
279 /* We need to know which edges exit loops so that we can
280 aggressively thread through loop headers to an exit
281 edge. */
282 loop_optimizer_init (0);
283 if (current_loops)
285 mark_loop_exit_edges ();
286 loop_optimizer_finalize ();
289 /* Clean up the CFG so that any forwarder blocks created by loop
290 canonicalization are removed. */
291 cleanup_tree_cfg ();
292 calculate_dominance_info (CDI_DOMINATORS);
294 /* We need accurate information regarding back edges in the CFG
295 for jump threading. */
296 mark_dfs_back_edges ();
298 /* Recursively walk the dominator tree optimizing statements. */
299 walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);
302 block_stmt_iterator bsi;
303 basic_block bb;
304 FOR_EACH_BB (bb)
306 for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
307 update_stmt_if_modified (bsi_stmt (bsi));
311 /* If we exposed any new variables, go ahead and put them into
312 SSA form now, before we handle jump threading. This simplifies
313 interactions between rewriting of _DECL nodes into SSA form
314 and rewriting SSA_NAME nodes into SSA form after block
315 duplication and CFG manipulation. */
316 update_ssa (TODO_update_ssa);
318 free_all_edge_infos ();
320 /* Thread jumps, creating duplicate blocks as needed. */
321 cfg_altered |= thread_through_all_blocks ();
323 /* Removal of statements may make some EH edges dead. Purge
324 such edges from the CFG as needed. */
325 if (!bitmap_empty_p (need_eh_cleanup))
327 cfg_altered |= tree_purge_all_dead_eh_edges (need_eh_cleanup);
328 bitmap_zero (need_eh_cleanup);
331 if (cfg_altered)
332 free_dominance_info (CDI_DOMINATORS);
334 /* Finally, remove everything except invariants in SSA_NAME_VALUE.
336 Long term we will be able to let everything in SSA_NAME_VALUE
337 persist. However, for now, we know this is the safe thing to do. */
338 for (i = 0; i < num_ssa_names; i++)
340 tree name = ssa_name (i);
341 tree value;
343 if (!name)
344 continue;
346 value = SSA_NAME_VALUE (name);
347 if (value && !is_gimple_min_invariant (value))
348 SSA_NAME_VALUE (name) = NULL;
351 /* Debugging dumps. */
352 if (dump_file && (dump_flags & TDF_STATS))
353 dump_dominator_optimization_stats (dump_file);
355 /* Delete our main hashtable. */
356 htab_delete (avail_exprs);
358 /* And finalize the dominator walker. */
359 fini_walk_dominator_tree (&walk_data);
361 /* Free asserted bitmaps and stacks. */
362 BITMAP_FREE (need_eh_cleanup);
364 VEC_free (tree, heap, avail_exprs_stack);
365 VEC_free (tree, heap, const_and_copies_stack);
366 VEC_free (tree_p, heap, stmts_to_rescan);
367 return 0;
370 static bool
371 gate_dominator (void)
373 return flag_tree_dom != 0;
376 struct tree_opt_pass pass_dominator =
378 "dom", /* name */
379 gate_dominator, /* gate */
380 tree_ssa_dominator_optimize, /* execute */
381 NULL, /* sub */
382 NULL, /* next */
383 0, /* static_pass_number */
384 TV_TREE_SSA_DOMINATOR_OPTS, /* tv_id */
385 PROP_cfg | PROP_ssa | PROP_alias, /* properties_required */
386 0, /* properties_provided */
387 0, /* properties_destroyed */
388 0, /* todo_flags_start */
389 TODO_dump_func
390 | TODO_update_ssa
391 | TODO_cleanup_cfg
392 | TODO_verify_ssa
393 | TODO_update_smt_usage, /* todo_flags_finish */
394 0 /* letter */
398 /* Given a stmt CONDSTMT containing a COND_EXPR, canonicalize the
399 COND_EXPR into a canonical form. */
401 static void
402 canonicalize_comparison (tree condstmt)
404 tree cond = COND_EXPR_COND (condstmt);
405 tree op0;
406 tree op1;
407 enum tree_code code = TREE_CODE (cond);
409 if (!COMPARISON_CLASS_P (cond))
410 return;
412 op0 = TREE_OPERAND (cond, 0);
413 op1 = TREE_OPERAND (cond, 1);
415 /* If it would be profitable to swap the operands, then do so to
416 canonicalize the statement, enabling better optimization.
418 By placing canonicalization of such expressions here we
419 transparently keep statements in canonical form, even
420 when the statement is modified. */
421 if (tree_swap_operands_p (op0, op1, false))
423 /* For relationals we need to swap the operands
424 and change the code. */
425 if (code == LT_EXPR
426 || code == GT_EXPR
427 || code == LE_EXPR
428 || code == GE_EXPR)
430 TREE_SET_CODE (cond, swap_tree_comparison (code));
431 swap_tree_operands (condstmt,
432 &TREE_OPERAND (cond, 0),
433 &TREE_OPERAND (cond, 1));
434 /* If one operand was in the operand cache, but the other is
435 not, because it is a constant, this is a case that the
436 internal updating code of swap_tree_operands can't handle
437 properly. */
438 if (TREE_CODE_CLASS (TREE_CODE (op0))
439 != TREE_CODE_CLASS (TREE_CODE (op1)))
440 update_stmt (condstmt);
445 /* Initialize local stacks for this optimizer and record equivalences
446 upon entry to BB. Equivalences can come from the edge traversed to
447 reach BB or they may come from PHI nodes at the start of BB. */
449 static void
450 dom_opt_initialize_block (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
451 basic_block bb)
453 if (dump_file && (dump_flags & TDF_DETAILS))
454 fprintf (dump_file, "\n\nOptimizing block #%d\n\n", bb->index);
456 /* Push a marker on the stacks of local information so that we know how
457 far to unwind when we finalize this block. */
458 VEC_safe_push (tree, heap, avail_exprs_stack, NULL_TREE);
459 VEC_safe_push (tree, heap, const_and_copies_stack, NULL_TREE);
461 record_equivalences_from_incoming_edge (bb);
463 /* PHI nodes can create equivalences too. */
464 record_equivalences_from_phis (bb);
467 /* Given an expression EXPR (a relational expression or a statement),
468 initialize the hash table element pointed to by ELEMENT. */
470 static void
471 initialize_hash_element (tree expr, tree lhs, struct expr_hash_elt *element)
473 /* Hash table elements may be based on conditional expressions or statements.
475 For the former case, we have no annotation and we want to hash the
476 conditional expression. In the latter case we have an annotation and
477 we want to record the expression the statement evaluates. */
478 if (COMPARISON_CLASS_P (expr) || TREE_CODE (expr) == TRUTH_NOT_EXPR)
480 element->stmt = NULL;
481 element->rhs = expr;
483 else if (TREE_CODE (expr) == COND_EXPR)
485 element->stmt = expr;
486 element->rhs = COND_EXPR_COND (expr);
488 else if (TREE_CODE (expr) == SWITCH_EXPR)
490 element->stmt = expr;
491 element->rhs = SWITCH_COND (expr);
493 else if (TREE_CODE (expr) == RETURN_EXPR && TREE_OPERAND (expr, 0))
495 element->stmt = expr;
496 element->rhs = GIMPLE_STMT_OPERAND (TREE_OPERAND (expr, 0), 1);
498 else if (TREE_CODE (expr) == GOTO_EXPR)
500 element->stmt = expr;
501 element->rhs = GOTO_DESTINATION (expr);
503 else
505 element->stmt = expr;
506 element->rhs = GENERIC_TREE_OPERAND (expr, 1);
509 element->lhs = lhs;
510 element->hash = avail_expr_hash (element);
513 /* Remove all the expressions in LOCALS from TABLE, stopping when there are
514 LIMIT entries left in LOCALs. */
516 static void
517 remove_local_expressions_from_table (void)
519 /* Remove all the expressions made available in this block. */
520 while (VEC_length (tree, avail_exprs_stack) > 0)
522 struct expr_hash_elt element;
523 tree expr = VEC_pop (tree, avail_exprs_stack);
525 if (expr == NULL_TREE)
526 break;
528 initialize_hash_element (expr, NULL, &element);
529 htab_remove_elt_with_hash (avail_exprs, &element, element.hash);
533 /* Use the source/dest pairs in CONST_AND_COPIES_STACK to restore
534 CONST_AND_COPIES to its original state, stopping when we hit a
535 NULL marker. */
537 static void
538 restore_vars_to_original_value (void)
540 while (VEC_length (tree, const_and_copies_stack) > 0)
542 tree prev_value, dest;
544 dest = VEC_pop (tree, const_and_copies_stack);
546 if (dest == NULL)
547 break;
549 prev_value = VEC_pop (tree, const_and_copies_stack);
550 SSA_NAME_VALUE (dest) = prev_value;
554 /* A trivial wrapper so that we can present the generic jump
555 threading code with a simple API for simplifying statements. */
556 static tree
557 simplify_stmt_for_jump_threading (tree stmt)
559 return lookup_avail_expr (stmt, false);
562 /* Wrapper for common code to attempt to thread an edge. For example,
563 it handles lazily building the dummy condition and the bookkeeping
564 when jump threading is successful. */
566 static void
567 dom_thread_across_edge (struct dom_walk_data *walk_data, edge e)
569 /* If we don't already have a dummy condition, build it now. */
570 if (! walk_data->global_data)
572 tree dummy_cond = build2 (NE_EXPR, boolean_type_node,
573 integer_zero_node, integer_zero_node);
574 dummy_cond = build3 (COND_EXPR, void_type_node, dummy_cond, NULL, NULL);
575 walk_data->global_data = dummy_cond;
578 thread_across_edge (walk_data->global_data, e, false,
579 &const_and_copies_stack,
580 simplify_stmt_for_jump_threading);
583 /* We have finished processing the dominator children of BB, perform
584 any finalization actions in preparation for leaving this node in
585 the dominator tree. */
587 static void
588 dom_opt_finalize_block (struct dom_walk_data *walk_data, basic_block bb)
590 tree last;
593 /* If we have an outgoing edge to a block with multiple incoming and
594 outgoing edges, then we may be able to thread the edge. ie, we
595 may be able to statically determine which of the outgoing edges
596 will be traversed when the incoming edge from BB is traversed. */
597 if (single_succ_p (bb)
598 && (single_succ_edge (bb)->flags & EDGE_ABNORMAL) == 0
599 && potentially_threadable_block (single_succ (bb)))
601 dom_thread_across_edge (walk_data, single_succ_edge (bb));
603 else if ((last = last_stmt (bb))
604 && TREE_CODE (last) == COND_EXPR
605 && (COMPARISON_CLASS_P (COND_EXPR_COND (last))
606 || TREE_CODE (COND_EXPR_COND (last)) == SSA_NAME)
607 && EDGE_COUNT (bb->succs) == 2
608 && (EDGE_SUCC (bb, 0)->flags & EDGE_ABNORMAL) == 0
609 && (EDGE_SUCC (bb, 1)->flags & EDGE_ABNORMAL) == 0)
611 edge true_edge, false_edge;
613 extract_true_false_edges_from_block (bb, &true_edge, &false_edge);
615 /* Only try to thread the edge if it reaches a target block with
616 more than one predecessor and more than one successor. */
617 if (potentially_threadable_block (true_edge->dest))
619 struct edge_info *edge_info;
620 unsigned int i;
622 /* Push a marker onto the available expression stack so that we
623 unwind any expressions related to the TRUE arm before processing
624 the false arm below. */
625 VEC_safe_push (tree, heap, avail_exprs_stack, NULL_TREE);
626 VEC_safe_push (tree, heap, const_and_copies_stack, NULL_TREE);
628 edge_info = (struct edge_info *) true_edge->aux;
630 /* If we have info associated with this edge, record it into
631 our equivalency tables. */
632 if (edge_info)
634 tree *cond_equivalences = edge_info->cond_equivalences;
635 tree lhs = edge_info->lhs;
636 tree rhs = edge_info->rhs;
638 /* If we have a simple NAME = VALUE equivalency record it. */
639 if (lhs && TREE_CODE (lhs) == SSA_NAME)
640 record_const_or_copy (lhs, rhs);
642 /* If we have 0 = COND or 1 = COND equivalences, record them
643 into our expression hash tables. */
644 if (cond_equivalences)
645 for (i = 0; i < edge_info->max_cond_equivalences; i += 2)
647 tree expr = cond_equivalences[i];
648 tree value = cond_equivalences[i + 1];
650 record_cond (expr, value);
654 dom_thread_across_edge (walk_data, true_edge);
656 /* And restore the various tables to their state before
657 we threaded this edge. */
658 remove_local_expressions_from_table ();
661 /* Similarly for the ELSE arm. */
662 if (potentially_threadable_block (false_edge->dest))
664 struct edge_info *edge_info;
665 unsigned int i;
667 VEC_safe_push (tree, heap, const_and_copies_stack, NULL_TREE);
668 edge_info = (struct edge_info *) false_edge->aux;
670 /* If we have info associated with this edge, record it into
671 our equivalency tables. */
672 if (edge_info)
674 tree *cond_equivalences = edge_info->cond_equivalences;
675 tree lhs = edge_info->lhs;
676 tree rhs = edge_info->rhs;
678 /* If we have a simple NAME = VALUE equivalency record it. */
679 if (lhs && TREE_CODE (lhs) == SSA_NAME)
680 record_const_or_copy (lhs, rhs);
682 /* If we have 0 = COND or 1 = COND equivalences, record them
683 into our expression hash tables. */
684 if (cond_equivalences)
685 for (i = 0; i < edge_info->max_cond_equivalences; i += 2)
687 tree expr = cond_equivalences[i];
688 tree value = cond_equivalences[i + 1];
690 record_cond (expr, value);
694 /* Now thread the edge. */
695 dom_thread_across_edge (walk_data, false_edge);
697 /* No need to remove local expressions from our tables
698 or restore vars to their original value as that will
699 be done immediately below. */
703 remove_local_expressions_from_table ();
704 restore_vars_to_original_value ();
706 /* If we queued any statements to rescan in this block, then
707 go ahead and rescan them now. */
708 while (VEC_length (tree_p, stmts_to_rescan) > 0)
710 tree *stmt_p = VEC_last (tree_p, stmts_to_rescan);
711 tree stmt = *stmt_p;
712 basic_block stmt_bb = bb_for_stmt (stmt);
714 if (stmt_bb != bb)
715 break;
717 VEC_pop (tree_p, stmts_to_rescan);
718 pop_stmt_changes (stmt_p);
722 /* PHI nodes can create equivalences too.
724 Ignoring any alternatives which are the same as the result, if
725 all the alternatives are equal, then the PHI node creates an
726 equivalence. */
728 static void
729 record_equivalences_from_phis (basic_block bb)
731 tree phi;
733 for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
735 tree lhs = PHI_RESULT (phi);
736 tree rhs = NULL;
737 int i;
739 for (i = 0; i < PHI_NUM_ARGS (phi); i++)
741 tree t = PHI_ARG_DEF (phi, i);
743 /* Ignore alternatives which are the same as our LHS. Since
744 LHS is a PHI_RESULT, it is known to be a SSA_NAME, so we
745 can simply compare pointers. */
746 if (lhs == t)
747 continue;
749 /* If we have not processed an alternative yet, then set
750 RHS to this alternative. */
751 if (rhs == NULL)
752 rhs = t;
753 /* If we have processed an alternative (stored in RHS), then
754 see if it is equal to this one. If it isn't, then stop
755 the search. */
756 else if (! operand_equal_for_phi_arg_p (rhs, t))
757 break;
760 /* If we had no interesting alternatives, then all the RHS alternatives
761 must have been the same as LHS. */
762 if (!rhs)
763 rhs = lhs;
765 /* If we managed to iterate through each PHI alternative without
766 breaking out of the loop, then we have a PHI which may create
767 a useful equivalence. We do not need to record unwind data for
768 this, since this is a true assignment and not an equivalence
769 inferred from a comparison. All uses of this ssa name are dominated
770 by this assignment, so unwinding just costs time and space. */
771 if (i == PHI_NUM_ARGS (phi)
772 && may_propagate_copy (lhs, rhs))
773 SSA_NAME_VALUE (lhs) = rhs;
777 /* Ignoring loop backedges, if BB has precisely one incoming edge then
778 return that edge. Otherwise return NULL. */
779 static edge
780 single_incoming_edge_ignoring_loop_edges (basic_block bb)
782 edge retval = NULL;
783 edge e;
784 edge_iterator ei;
786 FOR_EACH_EDGE (e, ei, bb->preds)
788 /* A loop back edge can be identified by the destination of
789 the edge dominating the source of the edge. */
790 if (dominated_by_p (CDI_DOMINATORS, e->src, e->dest))
791 continue;
793 /* If we have already seen a non-loop edge, then we must have
794 multiple incoming non-loop edges and thus we return NULL. */
795 if (retval)
796 return NULL;
798 /* This is the first non-loop incoming edge we have found. Record
799 it. */
800 retval = e;
803 return retval;
806 /* Record any equivalences created by the incoming edge to BB. If BB
807 has more than one incoming edge, then no equivalence is created. */
809 static void
810 record_equivalences_from_incoming_edge (basic_block bb)
812 edge e;
813 basic_block parent;
814 struct edge_info *edge_info;
816 /* If our parent block ended with a control statement, then we may be
817 able to record some equivalences based on which outgoing edge from
818 the parent was followed. */
819 parent = get_immediate_dominator (CDI_DOMINATORS, bb);
821 e = single_incoming_edge_ignoring_loop_edges (bb);
823 /* If we had a single incoming edge from our parent block, then enter
824 any data associated with the edge into our tables. */
825 if (e && e->src == parent)
827 unsigned int i;
829 edge_info = (struct edge_info *) e->aux;
831 if (edge_info)
833 tree lhs = edge_info->lhs;
834 tree rhs = edge_info->rhs;
835 tree *cond_equivalences = edge_info->cond_equivalences;
837 if (lhs)
838 record_equality (lhs, rhs);
840 if (cond_equivalences)
842 for (i = 0; i < edge_info->max_cond_equivalences; i += 2)
844 tree expr = cond_equivalences[i];
845 tree value = cond_equivalences[i + 1];
847 record_cond (expr, value);
854 /* Dump SSA statistics on FILE. */
856 void
857 dump_dominator_optimization_stats (FILE *file)
859 long n_exprs;
861 fprintf (file, "Total number of statements: %6ld\n\n",
862 opt_stats.num_stmts);
863 fprintf (file, "Exprs considered for dominator optimizations: %6ld\n",
864 opt_stats.num_exprs_considered);
866 n_exprs = opt_stats.num_exprs_considered;
867 if (n_exprs == 0)
868 n_exprs = 1;
870 fprintf (file, " Redundant expressions eliminated: %6ld (%.0f%%)\n",
871 opt_stats.num_re, PERCENT (opt_stats.num_re,
872 n_exprs));
873 fprintf (file, " Constants propagated: %6ld\n",
874 opt_stats.num_const_prop);
875 fprintf (file, " Copies propagated: %6ld\n",
876 opt_stats.num_copy_prop);
878 fprintf (file, "\nHash table statistics:\n");
880 fprintf (file, " avail_exprs: ");
881 htab_statistics (file, avail_exprs);
885 /* Dump SSA statistics on stderr. */
887 void
888 debug_dominator_optimization_stats (void)
890 dump_dominator_optimization_stats (stderr);
894 /* Dump statistics for the hash table HTAB. */
896 static void
897 htab_statistics (FILE *file, htab_t htab)
899 fprintf (file, "size %ld, %ld elements, %f collision/search ratio\n",
900 (long) htab_size (htab),
901 (long) htab_elements (htab),
902 htab_collisions (htab));
905 /* Enter a statement into the true/false expression hash table indicating
906 that the condition COND has the value VALUE. */
908 static void
909 record_cond (tree cond, tree value)
911 struct expr_hash_elt *element = XCNEW (struct expr_hash_elt);
912 void **slot;
914 initialize_hash_element (cond, value, element);
916 slot = htab_find_slot_with_hash (avail_exprs, (void *)element,
917 element->hash, INSERT);
918 if (*slot == NULL)
920 *slot = (void *) element;
921 VEC_safe_push (tree, heap, avail_exprs_stack, cond);
923 else
924 free (element);
927 /* Build a new conditional using NEW_CODE, OP0 and OP1 and store
928 the new conditional into *p, then store a boolean_true_node
929 into *(p + 1). */
931 static void
932 build_and_record_new_cond (enum tree_code new_code, tree op0, tree op1, tree *p)
934 *p = build2 (new_code, boolean_type_node, op0, op1);
935 p++;
936 *p = boolean_true_node;
939 /* Record that COND is true and INVERTED is false into the edge information
940 structure. Also record that any conditions dominated by COND are true
941 as well.
943 For example, if a < b is true, then a <= b must also be true. */
945 static void
946 record_conditions (struct edge_info *edge_info, tree cond, tree inverted)
948 tree op0, op1;
950 if (!COMPARISON_CLASS_P (cond))
951 return;
953 op0 = TREE_OPERAND (cond, 0);
954 op1 = TREE_OPERAND (cond, 1);
956 switch (TREE_CODE (cond))
958 case LT_EXPR:
959 case GT_EXPR:
960 if (FLOAT_TYPE_P (TREE_TYPE (op0)))
962 edge_info->max_cond_equivalences = 12;
963 edge_info->cond_equivalences = XNEWVEC (tree, 12);
964 build_and_record_new_cond (ORDERED_EXPR, op0, op1,
965 &edge_info->cond_equivalences[8]);
966 build_and_record_new_cond (LTGT_EXPR, op0, op1,
967 &edge_info->cond_equivalences[10]);
969 else
971 edge_info->max_cond_equivalences = 8;
972 edge_info->cond_equivalences = XNEWVEC (tree, 8);
975 build_and_record_new_cond ((TREE_CODE (cond) == LT_EXPR
976 ? LE_EXPR : GE_EXPR),
977 op0, op1, &edge_info->cond_equivalences[4]);
978 build_and_record_new_cond (NE_EXPR, op0, op1,
979 &edge_info->cond_equivalences[6]);
980 break;
982 case GE_EXPR:
983 case LE_EXPR:
984 if (FLOAT_TYPE_P (TREE_TYPE (op0)))
986 edge_info->max_cond_equivalences = 6;
987 edge_info->cond_equivalences = XNEWVEC (tree, 6);
988 build_and_record_new_cond (ORDERED_EXPR, op0, op1,
989 &edge_info->cond_equivalences[4]);
991 else
993 edge_info->max_cond_equivalences = 4;
994 edge_info->cond_equivalences = XNEWVEC (tree, 4);
996 break;
998 case EQ_EXPR:
999 if (FLOAT_TYPE_P (TREE_TYPE (op0)))
1001 edge_info->max_cond_equivalences = 10;
1002 edge_info->cond_equivalences = XNEWVEC (tree, 10);
1003 build_and_record_new_cond (ORDERED_EXPR, op0, op1,
1004 &edge_info->cond_equivalences[8]);
1006 else
1008 edge_info->max_cond_equivalences = 8;
1009 edge_info->cond_equivalences = XNEWVEC (tree, 8);
1011 build_and_record_new_cond (LE_EXPR, op0, op1,
1012 &edge_info->cond_equivalences[4]);
1013 build_and_record_new_cond (GE_EXPR, op0, op1,
1014 &edge_info->cond_equivalences[6]);
1015 break;
1017 case UNORDERED_EXPR:
1018 edge_info->max_cond_equivalences = 16;
1019 edge_info->cond_equivalences = XNEWVEC (tree, 16);
1020 build_and_record_new_cond (NE_EXPR, op0, op1,
1021 &edge_info->cond_equivalences[4]);
1022 build_and_record_new_cond (UNLE_EXPR, op0, op1,
1023 &edge_info->cond_equivalences[6]);
1024 build_and_record_new_cond (UNGE_EXPR, op0, op1,
1025 &edge_info->cond_equivalences[8]);
1026 build_and_record_new_cond (UNEQ_EXPR, op0, op1,
1027 &edge_info->cond_equivalences[10]);
1028 build_and_record_new_cond (UNLT_EXPR, op0, op1,
1029 &edge_info->cond_equivalences[12]);
1030 build_and_record_new_cond (UNGT_EXPR, op0, op1,
1031 &edge_info->cond_equivalences[14]);
1032 break;
1034 case UNLT_EXPR:
1035 case UNGT_EXPR:
1036 edge_info->max_cond_equivalences = 8;
1037 edge_info->cond_equivalences = XNEWVEC (tree, 8);
1038 build_and_record_new_cond ((TREE_CODE (cond) == UNLT_EXPR
1039 ? UNLE_EXPR : UNGE_EXPR),
1040 op0, op1, &edge_info->cond_equivalences[4]);
1041 build_and_record_new_cond (NE_EXPR, op0, op1,
1042 &edge_info->cond_equivalences[6]);
1043 break;
1045 case UNEQ_EXPR:
1046 edge_info->max_cond_equivalences = 8;
1047 edge_info->cond_equivalences = XNEWVEC (tree, 8);
1048 build_and_record_new_cond (UNLE_EXPR, op0, op1,
1049 &edge_info->cond_equivalences[4]);
1050 build_and_record_new_cond (UNGE_EXPR, op0, op1,
1051 &edge_info->cond_equivalences[6]);
1052 break;
1054 case LTGT_EXPR:
1055 edge_info->max_cond_equivalences = 8;
1056 edge_info->cond_equivalences = XNEWVEC (tree, 8);
1057 build_and_record_new_cond (NE_EXPR, op0, op1,
1058 &edge_info->cond_equivalences[4]);
1059 build_and_record_new_cond (ORDERED_EXPR, op0, op1,
1060 &edge_info->cond_equivalences[6]);
1061 break;
1063 default:
1064 edge_info->max_cond_equivalences = 4;
1065 edge_info->cond_equivalences = XNEWVEC (tree, 4);
1066 break;
1069 /* Now store the original true and false conditions into the first
1070 two slots. */
1071 edge_info->cond_equivalences[0] = cond;
1072 edge_info->cond_equivalences[1] = boolean_true_node;
1073 edge_info->cond_equivalences[2] = inverted;
1074 edge_info->cond_equivalences[3] = boolean_false_node;
1077 /* A helper function for record_const_or_copy and record_equality.
1078 Do the work of recording the value and undo info. */
1080 static void
1081 record_const_or_copy_1 (tree x, tree y, tree prev_x)
1083 SSA_NAME_VALUE (x) = y;
1085 VEC_reserve (tree, heap, const_and_copies_stack, 2);
1086 VEC_quick_push (tree, const_and_copies_stack, prev_x);
1087 VEC_quick_push (tree, const_and_copies_stack, x);
1091 /* Return the loop depth of the basic block of the defining statement of X.
1092 This number should not be treated as absolutely correct because the loop
1093 information may not be completely up-to-date when dom runs. However, it
1094 will be relatively correct, and as more passes are taught to keep loop info
1095 up to date, the result will become more and more accurate. */
1098 loop_depth_of_name (tree x)
1100 tree defstmt;
1101 basic_block defbb;
1103 /* If it's not an SSA_NAME, we have no clue where the definition is. */
1104 if (TREE_CODE (x) != SSA_NAME)
1105 return 0;
1107 /* Otherwise return the loop depth of the defining statement's bb.
1108 Note that there may not actually be a bb for this statement, if the
1109 ssa_name is live on entry. */
1110 defstmt = SSA_NAME_DEF_STMT (x);
1111 defbb = bb_for_stmt (defstmt);
1112 if (!defbb)
1113 return 0;
1115 return defbb->loop_depth;
1119 /* Record that X is equal to Y in const_and_copies. Record undo
1120 information in the block-local vector. */
1122 static void
1123 record_const_or_copy (tree x, tree y)
1125 tree prev_x = SSA_NAME_VALUE (x);
1127 if (TREE_CODE (y) == SSA_NAME)
1129 tree tmp = SSA_NAME_VALUE (y);
1130 if (tmp)
1131 y = tmp;
1134 record_const_or_copy_1 (x, y, prev_x);
1137 /* Similarly, but assume that X and Y are the two operands of an EQ_EXPR.
1138 This constrains the cases in which we may treat this as assignment. */
1140 static void
1141 record_equality (tree x, tree y)
1143 tree prev_x = NULL, prev_y = NULL;
1145 if (TREE_CODE (x) == SSA_NAME)
1146 prev_x = SSA_NAME_VALUE (x);
1147 if (TREE_CODE (y) == SSA_NAME)
1148 prev_y = SSA_NAME_VALUE (y);
1150 /* If one of the previous values is invariant, or invariant in more loops
1151 (by depth), then use that.
1152 Otherwise it doesn't matter which value we choose, just so
1153 long as we canonicalize on one value. */
1154 if (TREE_INVARIANT (y))
1156 else if (TREE_INVARIANT (x) || (loop_depth_of_name (x) <= loop_depth_of_name (y)))
1157 prev_x = x, x = y, y = prev_x, prev_x = prev_y;
1158 else if (prev_x && TREE_INVARIANT (prev_x))
1159 x = y, y = prev_x, prev_x = prev_y;
1160 else if (prev_y && TREE_CODE (prev_y) != VALUE_HANDLE)
1161 y = prev_y;
1163 /* After the swapping, we must have one SSA_NAME. */
1164 if (TREE_CODE (x) != SSA_NAME)
1165 return;
1167 /* For IEEE, -0.0 == 0.0, so we don't necessarily know the sign of a
1168 variable compared against zero. If we're honoring signed zeros,
1169 then we cannot record this value unless we know that the value is
1170 nonzero. */
1171 if (HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (x)))
1172 && (TREE_CODE (y) != REAL_CST
1173 || REAL_VALUES_EQUAL (dconst0, TREE_REAL_CST (y))))
1174 return;
1176 record_const_or_copy_1 (x, y, prev_x);
1179 /* Returns true when STMT is a simple iv increment. It detects the
1180 following situation:
1182 i_1 = phi (..., i_2)
1183 i_2 = i_1 +/- ... */
1185 static bool
1186 simple_iv_increment_p (tree stmt)
1188 tree lhs, rhs, preinc, phi;
1189 unsigned i;
1191 if (TREE_CODE (stmt) != GIMPLE_MODIFY_STMT)
1192 return false;
1194 lhs = GIMPLE_STMT_OPERAND (stmt, 0);
1195 if (TREE_CODE (lhs) != SSA_NAME)
1196 return false;
1198 rhs = GIMPLE_STMT_OPERAND (stmt, 1);
1200 if (TREE_CODE (rhs) != PLUS_EXPR
1201 && TREE_CODE (rhs) != MINUS_EXPR)
1202 return false;
1204 preinc = TREE_OPERAND (rhs, 0);
1205 if (TREE_CODE (preinc) != SSA_NAME)
1206 return false;
1208 phi = SSA_NAME_DEF_STMT (preinc);
1209 if (TREE_CODE (phi) != PHI_NODE)
1210 return false;
1212 for (i = 0; i < (unsigned) PHI_NUM_ARGS (phi); i++)
1213 if (PHI_ARG_DEF (phi, i) == lhs)
1214 return true;
1216 return false;
1219 /* CONST_AND_COPIES is a table which maps an SSA_NAME to the current
1220 known value for that SSA_NAME (or NULL if no value is known).
1222 Propagate values from CONST_AND_COPIES into the PHI nodes of the
1223 successors of BB. */
1225 static void
1226 cprop_into_successor_phis (basic_block bb)
1228 edge e;
1229 edge_iterator ei;
1231 FOR_EACH_EDGE (e, ei, bb->succs)
1233 tree phi;
1234 int indx;
1236 /* If this is an abnormal edge, then we do not want to copy propagate
1237 into the PHI alternative associated with this edge. */
1238 if (e->flags & EDGE_ABNORMAL)
1239 continue;
1241 phi = phi_nodes (e->dest);
1242 if (! phi)
1243 continue;
1245 indx = e->dest_idx;
1246 for ( ; phi; phi = PHI_CHAIN (phi))
1248 tree new;
1249 use_operand_p orig_p;
1250 tree orig;
1252 /* The alternative may be associated with a constant, so verify
1253 it is an SSA_NAME before doing anything with it. */
1254 orig_p = PHI_ARG_DEF_PTR (phi, indx);
1255 orig = USE_FROM_PTR (orig_p);
1256 if (TREE_CODE (orig) != SSA_NAME)
1257 continue;
1259 /* If we have *ORIG_P in our constant/copy table, then replace
1260 ORIG_P with its value in our constant/copy table. */
1261 new = SSA_NAME_VALUE (orig);
1262 if (new
1263 && new != orig
1264 && (TREE_CODE (new) == SSA_NAME
1265 || is_gimple_min_invariant (new))
1266 && may_propagate_copy (orig, new))
1267 propagate_value (orig_p, new);
1272 /* We have finished optimizing BB, record any information implied by
1273 taking a specific outgoing edge from BB. */
1275 static void
1276 record_edge_info (basic_block bb)
1278 block_stmt_iterator bsi = bsi_last (bb);
1279 struct edge_info *edge_info;
1281 if (! bsi_end_p (bsi))
1283 tree stmt = bsi_stmt (bsi);
1285 if (stmt && TREE_CODE (stmt) == SWITCH_EXPR)
1287 tree cond = SWITCH_COND (stmt);
1289 if (TREE_CODE (cond) == SSA_NAME)
1291 tree labels = SWITCH_LABELS (stmt);
1292 int i, n_labels = TREE_VEC_LENGTH (labels);
1293 tree *info = XCNEWVEC (tree, last_basic_block);
1294 edge e;
1295 edge_iterator ei;
1297 for (i = 0; i < n_labels; i++)
1299 tree label = TREE_VEC_ELT (labels, i);
1300 basic_block target_bb = label_to_block (CASE_LABEL (label));
1302 if (CASE_HIGH (label)
1303 || !CASE_LOW (label)
1304 || info[target_bb->index])
1305 info[target_bb->index] = error_mark_node;
1306 else
1307 info[target_bb->index] = label;
1310 FOR_EACH_EDGE (e, ei, bb->succs)
1312 basic_block target_bb = e->dest;
1313 tree node = info[target_bb->index];
1315 if (node != NULL && node != error_mark_node)
1317 tree x = fold_convert (TREE_TYPE (cond), CASE_LOW (node));
1318 edge_info = allocate_edge_info (e);
1319 edge_info->lhs = cond;
1320 edge_info->rhs = x;
1323 free (info);
1327 /* A COND_EXPR may create equivalences too. */
1328 if (stmt && TREE_CODE (stmt) == COND_EXPR)
1330 tree cond = COND_EXPR_COND (stmt);
1331 edge true_edge;
1332 edge false_edge;
1334 extract_true_false_edges_from_block (bb, &true_edge, &false_edge);
1336 /* If the conditional is a single variable 'X', record 'X = 1'
1337 for the true edge and 'X = 0' on the false edge. */
1338 if (SSA_VAR_P (cond))
1340 struct edge_info *edge_info;
1342 edge_info = allocate_edge_info (true_edge);
1343 edge_info->lhs = cond;
1344 edge_info->rhs = constant_boolean_node (1, TREE_TYPE (cond));
1346 edge_info = allocate_edge_info (false_edge);
1347 edge_info->lhs = cond;
1348 edge_info->rhs = constant_boolean_node (0, TREE_TYPE (cond));
1350 /* Equality tests may create one or two equivalences. */
1351 else if (COMPARISON_CLASS_P (cond))
1353 tree op0 = TREE_OPERAND (cond, 0);
1354 tree op1 = TREE_OPERAND (cond, 1);
1356 /* Special case comparing booleans against a constant as we
1357 know the value of OP0 on both arms of the branch. i.e., we
1358 can record an equivalence for OP0 rather than COND. */
1359 if ((TREE_CODE (cond) == EQ_EXPR || TREE_CODE (cond) == NE_EXPR)
1360 && TREE_CODE (op0) == SSA_NAME
1361 && TREE_CODE (TREE_TYPE (op0)) == BOOLEAN_TYPE
1362 && is_gimple_min_invariant (op1))
1364 if (TREE_CODE (cond) == EQ_EXPR)
1366 edge_info = allocate_edge_info (true_edge);
1367 edge_info->lhs = op0;
1368 edge_info->rhs = (integer_zerop (op1)
1369 ? boolean_false_node
1370 : boolean_true_node);
1372 edge_info = allocate_edge_info (false_edge);
1373 edge_info->lhs = op0;
1374 edge_info->rhs = (integer_zerop (op1)
1375 ? boolean_true_node
1376 : boolean_false_node);
1378 else
1380 edge_info = allocate_edge_info (true_edge);
1381 edge_info->lhs = op0;
1382 edge_info->rhs = (integer_zerop (op1)
1383 ? boolean_true_node
1384 : boolean_false_node);
1386 edge_info = allocate_edge_info (false_edge);
1387 edge_info->lhs = op0;
1388 edge_info->rhs = (integer_zerop (op1)
1389 ? boolean_false_node
1390 : boolean_true_node);
1394 else if (is_gimple_min_invariant (op0)
1395 && (TREE_CODE (op1) == SSA_NAME
1396 || is_gimple_min_invariant (op1)))
1398 tree inverted = invert_truthvalue (cond);
1399 struct edge_info *edge_info;
1401 edge_info = allocate_edge_info (true_edge);
1402 record_conditions (edge_info, cond, inverted);
1404 if (TREE_CODE (cond) == EQ_EXPR)
1406 edge_info->lhs = op1;
1407 edge_info->rhs = op0;
1410 edge_info = allocate_edge_info (false_edge);
1411 record_conditions (edge_info, inverted, cond);
1413 if (TREE_CODE (cond) == NE_EXPR)
1415 edge_info->lhs = op1;
1416 edge_info->rhs = op0;
1420 else if (TREE_CODE (op0) == SSA_NAME
1421 && (is_gimple_min_invariant (op1)
1422 || TREE_CODE (op1) == SSA_NAME))
1424 tree inverted = invert_truthvalue (cond);
1425 struct edge_info *edge_info;
1427 edge_info = allocate_edge_info (true_edge);
1428 record_conditions (edge_info, cond, inverted);
1430 if (TREE_CODE (cond) == EQ_EXPR)
1432 edge_info->lhs = op0;
1433 edge_info->rhs = op1;
1436 edge_info = allocate_edge_info (false_edge);
1437 record_conditions (edge_info, inverted, cond);
1439 if (TREE_CODE (cond) == NE_EXPR)
1441 edge_info->lhs = op0;
1442 edge_info->rhs = op1;
1447 /* ??? TRUTH_NOT_EXPR can create an equivalence too. */
1452 /* Propagate information from BB to its outgoing edges.
1454 This can include equivalency information implied by control statements
1455 at the end of BB and const/copy propagation into PHIs in BB's
1456 successor blocks. */
1458 static void
1459 propagate_to_outgoing_edges (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
1460 basic_block bb)
1462 record_edge_info (bb);
1463 cprop_into_successor_phis (bb);
1466 /* Search for redundant computations in STMT. If any are found, then
1467 replace them with the variable holding the result of the computation.
1469 If safe, record this expression into the available expression hash
1470 table. */
1472 static bool
1473 eliminate_redundant_computations (tree stmt)
1475 tree *expr_p, def = NULL_TREE;
1476 bool insert = true;
1477 tree cached_lhs;
1478 bool retval = false;
1479 bool modify_expr_p = false;
1481 if (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT)
1482 def = GIMPLE_STMT_OPERAND (stmt, 0);
1484 /* Certain expressions on the RHS can be optimized away, but can not
1485 themselves be entered into the hash tables. */
1486 if (! def
1487 || TREE_CODE (def) != SSA_NAME
1488 || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (def)
1489 || !ZERO_SSA_OPERANDS (stmt, SSA_OP_VDEF)
1490 /* Do not record equivalences for increments of ivs. This would create
1491 overlapping live ranges for a very questionable gain. */
1492 || simple_iv_increment_p (stmt))
1493 insert = false;
1495 /* Check if the expression has been computed before. */
1496 cached_lhs = lookup_avail_expr (stmt, insert);
1498 opt_stats.num_exprs_considered++;
1500 /* Get a pointer to the expression we are trying to optimize. */
1501 if (TREE_CODE (stmt) == COND_EXPR)
1502 expr_p = &COND_EXPR_COND (stmt);
1503 else if (TREE_CODE (stmt) == SWITCH_EXPR)
1504 expr_p = &SWITCH_COND (stmt);
1505 else if (TREE_CODE (stmt) == RETURN_EXPR && TREE_OPERAND (stmt, 0))
1507 expr_p = &GIMPLE_STMT_OPERAND (TREE_OPERAND (stmt, 0), 1);
1508 modify_expr_p = true;
1510 else
1512 expr_p = &GENERIC_TREE_OPERAND (stmt, 1);
1513 modify_expr_p = true;
1516 /* It is safe to ignore types here since we have already done
1517 type checking in the hashing and equality routines. In fact
1518 type checking here merely gets in the way of constant
1519 propagation. Also, make sure that it is safe to propagate
1520 CACHED_LHS into *EXPR_P. */
1521 if (cached_lhs
1522 && ((TREE_CODE (cached_lhs) != SSA_NAME
1523 && (modify_expr_p
1524 || tree_ssa_useless_type_conversion_1 (TREE_TYPE (*expr_p),
1525 TREE_TYPE (cached_lhs))))
1526 || may_propagate_copy (*expr_p, cached_lhs)))
1528 if (dump_file && (dump_flags & TDF_DETAILS))
1530 fprintf (dump_file, " Replaced redundant expr '");
1531 print_generic_expr (dump_file, *expr_p, dump_flags);
1532 fprintf (dump_file, "' with '");
1533 print_generic_expr (dump_file, cached_lhs, dump_flags);
1534 fprintf (dump_file, "'\n");
1537 opt_stats.num_re++;
1539 #if defined ENABLE_CHECKING
1540 gcc_assert (TREE_CODE (cached_lhs) == SSA_NAME
1541 || is_gimple_min_invariant (cached_lhs));
1542 #endif
1544 if (TREE_CODE (cached_lhs) == ADDR_EXPR
1545 || (POINTER_TYPE_P (TREE_TYPE (*expr_p))
1546 && is_gimple_min_invariant (cached_lhs)))
1547 retval = true;
1549 if (modify_expr_p
1550 && !tree_ssa_useless_type_conversion_1 (TREE_TYPE (*expr_p),
1551 TREE_TYPE (cached_lhs)))
1552 cached_lhs = fold_convert (TREE_TYPE (*expr_p), cached_lhs);
1554 propagate_tree_value (expr_p, cached_lhs);
1555 mark_stmt_modified (stmt);
1557 return retval;
1560 /* STMT, a GIMPLE_MODIFY_STMT, may create certain equivalences, in either
1561 the available expressions table or the const_and_copies table.
1562 Detect and record those equivalences. */
1564 static void
1565 record_equivalences_from_stmt (tree stmt, int may_optimize_p, stmt_ann_t ann)
1567 tree lhs = GIMPLE_STMT_OPERAND (stmt, 0);
1568 enum tree_code lhs_code = TREE_CODE (lhs);
1570 if (lhs_code == SSA_NAME)
1572 tree rhs = GIMPLE_STMT_OPERAND (stmt, 1);
1574 /* Strip away any useless type conversions. */
1575 STRIP_USELESS_TYPE_CONVERSION (rhs);
1577 /* If the RHS of the assignment is a constant or another variable that
1578 may be propagated, register it in the CONST_AND_COPIES table. We
1579 do not need to record unwind data for this, since this is a true
1580 assignment and not an equivalence inferred from a comparison. All
1581 uses of this ssa name are dominated by this assignment, so unwinding
1582 just costs time and space. */
1583 if (may_optimize_p
1584 && (TREE_CODE (rhs) == SSA_NAME
1585 || is_gimple_min_invariant (rhs)))
1586 SSA_NAME_VALUE (lhs) = rhs;
1589 /* A memory store, even an aliased store, creates a useful
1590 equivalence. By exchanging the LHS and RHS, creating suitable
1591 vops and recording the result in the available expression table,
1592 we may be able to expose more redundant loads. */
1593 if (!ann->has_volatile_ops
1594 && stmt_references_memory_p (stmt)
1595 && (TREE_CODE (GIMPLE_STMT_OPERAND (stmt, 1)) == SSA_NAME
1596 || is_gimple_min_invariant (GIMPLE_STMT_OPERAND (stmt, 1)))
1597 && !is_gimple_reg (lhs))
1599 tree rhs = GIMPLE_STMT_OPERAND (stmt, 1);
1600 tree new;
1602 /* FIXME: If the LHS of the assignment is a bitfield and the RHS
1603 is a constant, we need to adjust the constant to fit into the
1604 type of the LHS. If the LHS is a bitfield and the RHS is not
1605 a constant, then we can not record any equivalences for this
1606 statement since we would need to represent the widening or
1607 narrowing of RHS. This fixes gcc.c-torture/execute/921016-1.c
1608 and should not be necessary if GCC represented bitfields
1609 properly. */
1610 if (lhs_code == COMPONENT_REF
1611 && DECL_BIT_FIELD (TREE_OPERAND (lhs, 1)))
1613 if (TREE_CONSTANT (rhs))
1614 rhs = widen_bitfield (rhs, TREE_OPERAND (lhs, 1), lhs);
1615 else
1616 rhs = NULL;
1618 /* If the value overflowed, then we can not use this equivalence. */
1619 if (rhs && ! is_gimple_min_invariant (rhs))
1620 rhs = NULL;
1623 if (rhs)
1625 /* Build a new statement with the RHS and LHS exchanged. */
1626 new = build2_gimple (GIMPLE_MODIFY_STMT, rhs, lhs);
1628 create_ssa_artificial_load_stmt (new, stmt);
1630 /* Finally enter the statement into the available expression
1631 table. */
1632 lookup_avail_expr (new, true);
1637 /* Replace *OP_P in STMT with any known equivalent value for *OP_P from
1638 CONST_AND_COPIES. */
1640 static bool
1641 cprop_operand (tree stmt, use_operand_p op_p)
1643 bool may_have_exposed_new_symbols = false;
1644 tree val;
1645 tree op = USE_FROM_PTR (op_p);
1647 /* If the operand has a known constant value or it is known to be a
1648 copy of some other variable, use the value or copy stored in
1649 CONST_AND_COPIES. */
1650 val = SSA_NAME_VALUE (op);
1651 if (val && val != op && TREE_CODE (val) != VALUE_HANDLE)
1653 tree op_type, val_type;
1655 /* Do not change the base variable in the virtual operand
1656 tables. That would make it impossible to reconstruct
1657 the renamed virtual operand if we later modify this
1658 statement. Also only allow the new value to be an SSA_NAME
1659 for propagation into virtual operands. */
1660 if (!is_gimple_reg (op)
1661 && (TREE_CODE (val) != SSA_NAME
1662 || is_gimple_reg (val)
1663 || get_virtual_var (val) != get_virtual_var (op)))
1664 return false;
1666 /* Do not replace hard register operands in asm statements. */
1667 if (TREE_CODE (stmt) == ASM_EXPR
1668 && !may_propagate_copy_into_asm (op))
1669 return false;
1671 /* Get the toplevel type of each operand. */
1672 op_type = TREE_TYPE (op);
1673 val_type = TREE_TYPE (val);
1675 /* While both types are pointers, get the type of the object
1676 pointed to. */
1677 while (POINTER_TYPE_P (op_type) && POINTER_TYPE_P (val_type))
1679 op_type = TREE_TYPE (op_type);
1680 val_type = TREE_TYPE (val_type);
1683 /* Make sure underlying types match before propagating a constant by
1684 converting the constant to the proper type. Note that convert may
1685 return a non-gimple expression, in which case we ignore this
1686 propagation opportunity. */
1687 if (TREE_CODE (val) != SSA_NAME)
1689 if (!lang_hooks.types_compatible_p (op_type, val_type))
1691 val = fold_convert (TREE_TYPE (op), val);
1692 if (!is_gimple_min_invariant (val))
1693 return false;
1697 /* Certain operands are not allowed to be copy propagated due
1698 to their interaction with exception handling and some GCC
1699 extensions. */
1700 else if (!may_propagate_copy (op, val))
1701 return false;
1703 /* Do not propagate copies if the propagated value is at a deeper loop
1704 depth than the propagatee. Otherwise, this may move loop variant
1705 variables outside of their loops and prevent coalescing
1706 opportunities. If the value was loop invariant, it will be hoisted
1707 by LICM and exposed for copy propagation. */
1708 if (loop_depth_of_name (val) > loop_depth_of_name (op))
1709 return false;
1711 /* Dump details. */
1712 if (dump_file && (dump_flags & TDF_DETAILS))
1714 fprintf (dump_file, " Replaced '");
1715 print_generic_expr (dump_file, op, dump_flags);
1716 fprintf (dump_file, "' with %s '",
1717 (TREE_CODE (val) != SSA_NAME ? "constant" : "variable"));
1718 print_generic_expr (dump_file, val, dump_flags);
1719 fprintf (dump_file, "'\n");
1722 /* If VAL is an ADDR_EXPR or a constant of pointer type, note
1723 that we may have exposed a new symbol for SSA renaming. */
1724 if (TREE_CODE (val) == ADDR_EXPR
1725 || (POINTER_TYPE_P (TREE_TYPE (op))
1726 && is_gimple_min_invariant (val)))
1727 may_have_exposed_new_symbols = true;
1729 if (TREE_CODE (val) != SSA_NAME)
1730 opt_stats.num_const_prop++;
1731 else
1732 opt_stats.num_copy_prop++;
1734 propagate_value (op_p, val);
1736 /* And note that we modified this statement. This is now
1737 safe, even if we changed virtual operands since we will
1738 rescan the statement and rewrite its operands again. */
1739 mark_stmt_modified (stmt);
1741 return may_have_exposed_new_symbols;
1744 /* CONST_AND_COPIES is a table which maps an SSA_NAME to the current
1745 known value for that SSA_NAME (or NULL if no value is known).
1747 Propagate values from CONST_AND_COPIES into the uses, vuses and
1748 vdef_ops of STMT. */
1750 static bool
1751 cprop_into_stmt (tree stmt)
1753 bool may_have_exposed_new_symbols = false;
1754 use_operand_p op_p;
1755 ssa_op_iter iter;
1757 FOR_EACH_SSA_USE_OPERAND (op_p, stmt, iter, SSA_OP_ALL_USES)
1759 if (TREE_CODE (USE_FROM_PTR (op_p)) == SSA_NAME)
1760 may_have_exposed_new_symbols |= cprop_operand (stmt, op_p);
1763 return may_have_exposed_new_symbols;
1767 /* Optimize the statement pointed to by iterator SI.
1769 We try to perform some simplistic global redundancy elimination and
1770 constant propagation:
1772 1- To detect global redundancy, we keep track of expressions that have
1773 been computed in this block and its dominators. If we find that the
1774 same expression is computed more than once, we eliminate repeated
1775 computations by using the target of the first one.
1777 2- Constant values and copy assignments. This is used to do very
1778 simplistic constant and copy propagation. When a constant or copy
1779 assignment is found, we map the value on the RHS of the assignment to
1780 the variable in the LHS in the CONST_AND_COPIES table. */
1782 static void
1783 optimize_stmt (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
1784 basic_block bb, block_stmt_iterator si)
1786 stmt_ann_t ann;
1787 tree stmt, old_stmt;
1788 bool may_optimize_p;
1789 bool may_have_exposed_new_symbols = false;
1791 old_stmt = stmt = bsi_stmt (si);
1793 if (TREE_CODE (stmt) == COND_EXPR)
1794 canonicalize_comparison (stmt);
1796 update_stmt_if_modified (stmt);
1797 ann = stmt_ann (stmt);
1798 opt_stats.num_stmts++;
1799 may_have_exposed_new_symbols = false;
1800 push_stmt_changes (bsi_stmt_ptr (si));
1802 if (dump_file && (dump_flags & TDF_DETAILS))
1804 fprintf (dump_file, "Optimizing statement ");
1805 print_generic_stmt (dump_file, stmt, TDF_SLIM);
1808 /* Const/copy propagate into USES, VUSES and the RHS of VDEFs. */
1809 may_have_exposed_new_symbols = cprop_into_stmt (stmt);
1811 /* If the statement has been modified with constant replacements,
1812 fold its RHS before checking for redundant computations. */
1813 if (ann->modified)
1815 tree rhs;
1817 /* Try to fold the statement making sure that STMT is kept
1818 up to date. */
1819 if (fold_stmt (bsi_stmt_ptr (si)))
1821 stmt = bsi_stmt (si);
1822 ann = stmt_ann (stmt);
1824 if (dump_file && (dump_flags & TDF_DETAILS))
1826 fprintf (dump_file, " Folded to: ");
1827 print_generic_stmt (dump_file, stmt, TDF_SLIM);
1831 rhs = get_rhs (stmt);
1832 if (rhs && TREE_CODE (rhs) == ADDR_EXPR)
1833 recompute_tree_invariant_for_addr_expr (rhs);
1835 /* Constant/copy propagation above may change the set of
1836 virtual operands associated with this statement. Folding
1837 may remove the need for some virtual operands.
1839 Indicate we will need to rescan and rewrite the statement. */
1840 may_have_exposed_new_symbols = true;
1843 /* Check for redundant computations. Do this optimization only
1844 for assignments that have no volatile ops and conditionals. */
1845 may_optimize_p = (!ann->has_volatile_ops
1846 && ((TREE_CODE (stmt) == RETURN_EXPR
1847 && TREE_OPERAND (stmt, 0)
1848 && TREE_CODE (TREE_OPERAND (stmt, 0))
1849 == GIMPLE_MODIFY_STMT
1850 && ! (TREE_SIDE_EFFECTS
1851 (GIMPLE_STMT_OPERAND
1852 (TREE_OPERAND (stmt, 0), 1))))
1853 || (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT
1854 && ! TREE_SIDE_EFFECTS (GIMPLE_STMT_OPERAND (stmt,
1855 1)))
1856 || TREE_CODE (stmt) == COND_EXPR
1857 || TREE_CODE (stmt) == SWITCH_EXPR));
1859 if (may_optimize_p)
1860 may_have_exposed_new_symbols |= eliminate_redundant_computations (stmt);
1862 /* Record any additional equivalences created by this statement. */
1863 if (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT)
1864 record_equivalences_from_stmt (stmt, may_optimize_p, ann);
1866 /* If STMT is a COND_EXPR and it was modified, then we may know
1867 where it goes. If that is the case, then mark the CFG as altered.
1869 This will cause us to later call remove_unreachable_blocks and
1870 cleanup_tree_cfg when it is safe to do so. It is not safe to
1871 clean things up here since removal of edges and such can trigger
1872 the removal of PHI nodes, which in turn can release SSA_NAMEs to
1873 the manager.
1875 That's all fine and good, except that once SSA_NAMEs are released
1876 to the manager, we must not call create_ssa_name until all references
1877 to released SSA_NAMEs have been eliminated.
1879 All references to the deleted SSA_NAMEs can not be eliminated until
1880 we remove unreachable blocks.
1882 We can not remove unreachable blocks until after we have completed
1883 any queued jump threading.
1885 We can not complete any queued jump threads until we have taken
1886 appropriate variables out of SSA form. Taking variables out of
1887 SSA form can call create_ssa_name and thus we lose.
1889 Ultimately I suspect we're going to need to change the interface
1890 into the SSA_NAME manager. */
1891 if (ann->modified)
1893 tree val = NULL;
1895 if (TREE_CODE (stmt) == COND_EXPR)
1896 val = COND_EXPR_COND (stmt);
1897 else if (TREE_CODE (stmt) == SWITCH_EXPR)
1898 val = SWITCH_COND (stmt);
1900 if (val && TREE_CODE (val) == INTEGER_CST && find_taken_edge (bb, val))
1901 cfg_altered = true;
1903 /* If we simplified a statement in such a way as to be shown that it
1904 cannot trap, update the eh information and the cfg to match. */
1905 if (maybe_clean_or_replace_eh_stmt (old_stmt, stmt))
1907 bitmap_set_bit (need_eh_cleanup, bb->index);
1908 if (dump_file && (dump_flags & TDF_DETAILS))
1909 fprintf (dump_file, " Flagged to clear EH edges.\n");
1913 if (may_have_exposed_new_symbols)
1915 /* Queue the statement to be re-scanned after all the
1916 AVAIL_EXPRS have been processed. The change buffer stack for
1917 all the pushed statements will be processed when this queue
1918 is emptied. */
1919 VEC_safe_push (tree_p, heap, stmts_to_rescan, bsi_stmt_ptr (si));
1921 else
1923 /* Otherwise, just discard the recently pushed change buffer. If
1924 not, the STMTS_TO_RESCAN queue will get out of synch with the
1925 change buffer stack. */
1926 discard_stmt_changes (bsi_stmt_ptr (si));
1930 /* Search for an existing instance of STMT in the AVAIL_EXPRS table. If
1931 found, return its LHS. Otherwise insert STMT in the table and return
1932 NULL_TREE.
1934 Also, when an expression is first inserted in the AVAIL_EXPRS table, it
1935 is also added to the stack pointed to by BLOCK_AVAIL_EXPRS_P, so that they
1936 can be removed when we finish processing this block and its children.
1938 NOTE: This function assumes that STMT is a GIMPLE_MODIFY_STMT node that
1939 contains no CALL_EXPR on its RHS and makes no volatile nor
1940 aliased references. */
1942 static tree
1943 lookup_avail_expr (tree stmt, bool insert)
1945 void **slot;
1946 tree lhs;
1947 tree temp;
1948 struct expr_hash_elt *element = XNEW (struct expr_hash_elt);
1950 lhs = TREE_CODE (stmt) == GIMPLE_MODIFY_STMT
1951 ? GIMPLE_STMT_OPERAND (stmt, 0) : NULL;
1953 initialize_hash_element (stmt, lhs, element);
1955 /* Don't bother remembering constant assignments and copy operations.
1956 Constants and copy operations are handled by the constant/copy propagator
1957 in optimize_stmt. */
1958 if (TREE_CODE (element->rhs) == SSA_NAME
1959 || is_gimple_min_invariant (element->rhs))
1961 free (element);
1962 return NULL_TREE;
1965 /* Finally try to find the expression in the main expression hash table. */
1966 slot = htab_find_slot_with_hash (avail_exprs, element, element->hash,
1967 (insert ? INSERT : NO_INSERT));
1968 if (slot == NULL)
1970 free (element);
1971 return NULL_TREE;
1974 if (*slot == NULL)
1976 *slot = (void *) element;
1977 VEC_safe_push (tree, heap, avail_exprs_stack,
1978 stmt ? stmt : element->rhs);
1979 return NULL_TREE;
1982 /* Extract the LHS of the assignment so that it can be used as the current
1983 definition of another variable. */
1984 lhs = ((struct expr_hash_elt *)*slot)->lhs;
1986 /* See if the LHS appears in the CONST_AND_COPIES table. If it does, then
1987 use the value from the const_and_copies table. */
1988 if (TREE_CODE (lhs) == SSA_NAME)
1990 temp = SSA_NAME_VALUE (lhs);
1991 if (temp && TREE_CODE (temp) != VALUE_HANDLE)
1992 lhs = temp;
1995 free (element);
1996 return lhs;
1999 /* Hashing and equality functions for AVAIL_EXPRS. The table stores
2000 GIMPLE_MODIFY_STMT statements. We compute a value number for expressions
2001 using the code of the expression and the SSA numbers of its operands. */
2003 static hashval_t
2004 avail_expr_hash (const void *p)
2006 tree stmt = ((struct expr_hash_elt *)p)->stmt;
2007 tree rhs = ((struct expr_hash_elt *)p)->rhs;
2008 tree vuse;
2009 ssa_op_iter iter;
2010 hashval_t val = 0;
2012 /* iterative_hash_expr knows how to deal with any expression and
2013 deals with commutative operators as well, so just use it instead
2014 of duplicating such complexities here. */
2015 val = iterative_hash_expr (rhs, val);
2017 /* If the hash table entry is not associated with a statement, then we
2018 can just hash the expression and not worry about virtual operands
2019 and such. */
2020 if (!stmt || !stmt_ann (stmt))
2021 return val;
2023 /* Add the SSA version numbers of every vuse operand. This is important
2024 because compound variables like arrays are not renamed in the
2025 operands. Rather, the rename is done on the virtual variable
2026 representing all the elements of the array. */
2027 FOR_EACH_SSA_TREE_OPERAND (vuse, stmt, iter, SSA_OP_VUSE)
2028 val = iterative_hash_expr (vuse, val);
2030 return val;
2033 static hashval_t
2034 real_avail_expr_hash (const void *p)
2036 return ((const struct expr_hash_elt *)p)->hash;
2039 static int
2040 avail_expr_eq (const void *p1, const void *p2)
2042 tree stmt1 = ((struct expr_hash_elt *)p1)->stmt;
2043 tree rhs1 = ((struct expr_hash_elt *)p1)->rhs;
2044 tree stmt2 = ((struct expr_hash_elt *)p2)->stmt;
2045 tree rhs2 = ((struct expr_hash_elt *)p2)->rhs;
2047 /* If they are the same physical expression, return true. */
2048 if (rhs1 == rhs2 && stmt1 == stmt2)
2049 return true;
2051 /* If their codes are not equal, then quit now. */
2052 if (TREE_CODE (rhs1) != TREE_CODE (rhs2))
2053 return false;
2055 /* In case of a collision, both RHS have to be identical and have the
2056 same VUSE operands. */
2057 if ((TREE_TYPE (rhs1) == TREE_TYPE (rhs2)
2058 || lang_hooks.types_compatible_p (TREE_TYPE (rhs1), TREE_TYPE (rhs2)))
2059 && operand_equal_p (rhs1, rhs2, OEP_PURE_SAME))
2061 bool ret = compare_ssa_operands_equal (stmt1, stmt2, SSA_OP_VUSE);
2062 gcc_assert (!ret || ((struct expr_hash_elt *)p1)->hash
2063 == ((struct expr_hash_elt *)p2)->hash);
2064 return ret;
2067 return false;
2070 /* PHI-ONLY copy and constant propagation. This pass is meant to clean
2071 up degenerate PHIs created by or exposed by jump threading. */
2073 /* Given PHI, return its RHS if the PHI is a degenerate, otherwise return
2074 NULL. */
2076 static tree
2077 degenerate_phi_result (tree phi)
2079 tree lhs = PHI_RESULT (phi);
2080 tree val = NULL;
2081 int i;
2083 /* Ignoring arguments which are the same as LHS, if all the remaining
2084 arguments are the same, then the PHI is a degenerate and has the
2085 value of that common argument. */
2086 for (i = 0; i < PHI_NUM_ARGS (phi); i++)
2088 tree arg = PHI_ARG_DEF (phi, i);
2090 if (arg == lhs)
2091 continue;
2092 else if (!val)
2093 val = arg;
2094 else if (!operand_equal_p (arg, val, 0))
2095 break;
2097 return (i == PHI_NUM_ARGS (phi) ? val : NULL);
2100 /* Given a tree node T, which is either a PHI_NODE or GIMPLE_MODIFY_STMT,
2101 remove it from the IL. */
2103 static void
2104 remove_stmt_or_phi (tree t)
2106 if (TREE_CODE (t) == PHI_NODE)
2107 remove_phi_node (t, NULL, true);
2108 else
2110 block_stmt_iterator bsi = bsi_for_stmt (t);
2111 bsi_remove (&bsi, true);
2115 /* Given a tree node T, which is either a PHI_NODE or GIMPLE_MODIFY_STMT,
2116 return the "rhs" of the node, in the case of a non-degenerate
2117 PHI, NULL is returned. */
2119 static tree
2120 get_rhs_or_phi_arg (tree t)
2122 if (TREE_CODE (t) == PHI_NODE)
2123 return degenerate_phi_result (t);
2124 else if (TREE_CODE (t) == GIMPLE_MODIFY_STMT)
2125 return GIMPLE_STMT_OPERAND (t, 1);
2126 gcc_unreachable ();
2130 /* Given a tree node T, which is either a PHI_NODE or a GIMPLE_MODIFY_STMT,
2131 return the "lhs" of the node. */
2133 static tree
2134 get_lhs_or_phi_result (tree t)
2136 if (TREE_CODE (t) == PHI_NODE)
2137 return PHI_RESULT (t);
2138 else if (TREE_CODE (t) == GIMPLE_MODIFY_STMT)
2139 return GIMPLE_STMT_OPERAND (t, 0);
2140 gcc_unreachable ();
2143 /* Propagate RHS into all uses of LHS (when possible).
2145 RHS and LHS are derived from STMT, which is passed in solely so
2146 that we can remove it if propagation is successful.
2148 When propagating into a PHI node or into a statement which turns
2149 into a trivial copy or constant initialization, set the
2150 appropriate bit in INTERESTING_NAMEs so that we will visit those
2151 nodes as well in an effort to pick up secondary optimization
2152 opportunities. */
2154 static void
2155 propagate_rhs_into_lhs (tree stmt, tree lhs, tree rhs, bitmap interesting_names)
2157 /* First verify that propagation is valid and isn't going to move a
2158 loop variant variable outside its loop. */
2159 if (! SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs)
2160 && (TREE_CODE (rhs) != SSA_NAME
2161 || ! SSA_NAME_OCCURS_IN_ABNORMAL_PHI (rhs))
2162 && may_propagate_copy (lhs, rhs)
2163 && loop_depth_of_name (lhs) >= loop_depth_of_name (rhs))
2165 use_operand_p use_p;
2166 imm_use_iterator iter;
2167 tree use_stmt;
2168 bool all = true;
2170 /* Dump details. */
2171 if (dump_file && (dump_flags & TDF_DETAILS))
2173 fprintf (dump_file, " Replacing '");
2174 print_generic_expr (dump_file, lhs, dump_flags);
2175 fprintf (dump_file, "' with %s '",
2176 (TREE_CODE (rhs) != SSA_NAME ? "constant" : "variable"));
2177 print_generic_expr (dump_file, rhs, dump_flags);
2178 fprintf (dump_file, "'\n");
2181 /* Walk over every use of LHS and try to replace the use with RHS.
2182 At this point the only reason why such a propagation would not
2183 be successful would be if the use occurs in an ASM_EXPR. */
2184 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
2187 /* It's not always safe to propagate into an ASM_EXPR. */
2188 if (TREE_CODE (use_stmt) == ASM_EXPR
2189 && ! may_propagate_copy_into_asm (lhs))
2191 all = false;
2192 continue;
2195 /* Dump details. */
2196 if (dump_file && (dump_flags & TDF_DETAILS))
2198 fprintf (dump_file, " Original statement:");
2199 print_generic_expr (dump_file, use_stmt, dump_flags);
2200 fprintf (dump_file, "\n");
2203 push_stmt_changes (&use_stmt);
2205 /* Propagate the RHS into this use of the LHS. */
2206 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
2207 propagate_value (use_p, rhs);
2209 /* Special cases to avoid useless calls into the folding
2210 routines, operand scanning, etc.
2212 First, propagation into a PHI may cause the PHI to become
2213 a degenerate, so mark the PHI as interesting. No other
2214 actions are necessary.
2216 Second, if we're propagating a virtual operand and the
2217 propagation does not change the underlying _DECL node for
2218 the virtual operand, then no further actions are necessary. */
2219 if (TREE_CODE (use_stmt) == PHI_NODE
2220 || (! is_gimple_reg (lhs)
2221 && TREE_CODE (rhs) == SSA_NAME
2222 && SSA_NAME_VAR (lhs) == SSA_NAME_VAR (rhs)))
2224 /* Dump details. */
2225 if (dump_file && (dump_flags & TDF_DETAILS))
2227 fprintf (dump_file, " Updated statement:");
2228 print_generic_expr (dump_file, use_stmt, dump_flags);
2229 fprintf (dump_file, "\n");
2232 /* Propagation into a PHI may expose new degenerate PHIs,
2233 so mark the result of the PHI as interesting. */
2234 if (TREE_CODE (use_stmt) == PHI_NODE)
2236 tree result = get_lhs_or_phi_result (use_stmt);
2237 bitmap_set_bit (interesting_names, SSA_NAME_VERSION (result));
2240 discard_stmt_changes (&use_stmt);
2241 continue;
2244 /* From this point onward we are propagating into a
2245 real statement. Folding may (or may not) be possible,
2246 we may expose new operands, expose dead EH edges,
2247 etc. */
2248 fold_stmt_inplace (use_stmt);
2250 /* Sometimes propagation can expose new operands to the
2251 renamer. Note this will call update_stmt at the
2252 appropriate time. */
2253 pop_stmt_changes (&use_stmt);
2255 /* Dump details. */
2256 if (dump_file && (dump_flags & TDF_DETAILS))
2258 fprintf (dump_file, " Updated statement:");
2259 print_generic_expr (dump_file, use_stmt, dump_flags);
2260 fprintf (dump_file, "\n");
2263 /* If we replaced a variable index with a constant, then
2264 we would need to update the invariant flag for ADDR_EXPRs. */
2265 if (TREE_CODE (use_stmt) == GIMPLE_MODIFY_STMT
2266 && TREE_CODE (GIMPLE_STMT_OPERAND (use_stmt, 1)) == ADDR_EXPR)
2267 recompute_tree_invariant_for_addr_expr
2268 (GIMPLE_STMT_OPERAND (use_stmt, 1));
2270 /* If we cleaned up EH information from the statement,
2271 mark its containing block as needing EH cleanups. */
2272 if (maybe_clean_or_replace_eh_stmt (use_stmt, use_stmt))
2274 bitmap_set_bit (need_eh_cleanup, bb_for_stmt (use_stmt)->index);
2275 if (dump_file && (dump_flags & TDF_DETAILS))
2276 fprintf (dump_file, " Flagged to clear EH edges.\n");
2279 /* Propagation may expose new trivial copy/constant propagation
2280 opportunities. */
2281 if (TREE_CODE (use_stmt) == GIMPLE_MODIFY_STMT
2282 && TREE_CODE (GIMPLE_STMT_OPERAND (use_stmt, 0)) == SSA_NAME
2283 && (TREE_CODE (GIMPLE_STMT_OPERAND (use_stmt, 1)) == SSA_NAME
2284 || is_gimple_min_invariant (GIMPLE_STMT_OPERAND (use_stmt,
2285 1))))
2287 tree result = get_lhs_or_phi_result (use_stmt);
2288 bitmap_set_bit (interesting_names, SSA_NAME_VERSION (result));
2291 /* Propagation into these nodes may make certain edges in
2292 the CFG unexecutable. We want to identify them as PHI nodes
2293 at the destination of those unexecutable edges may become
2294 degenerates. */
2295 else if (TREE_CODE (use_stmt) == COND_EXPR
2296 || TREE_CODE (use_stmt) == SWITCH_EXPR
2297 || TREE_CODE (use_stmt) == GOTO_EXPR)
2299 tree val;
2301 if (TREE_CODE (use_stmt) == COND_EXPR)
2302 val = COND_EXPR_COND (use_stmt);
2303 else if (TREE_CODE (use_stmt) == SWITCH_EXPR)
2304 val = SWITCH_COND (use_stmt);
2305 else
2306 val = GOTO_DESTINATION (use_stmt);
2308 if (is_gimple_min_invariant (val))
2310 basic_block bb = bb_for_stmt (use_stmt);
2311 edge te = find_taken_edge (bb, val);
2312 edge_iterator ei;
2313 edge e;
2314 block_stmt_iterator bsi;
2316 /* Remove all outgoing edges except TE. */
2317 for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei));)
2319 if (e != te)
2321 tree phi;
2323 /* Mark all the PHI nodes at the destination of
2324 the unexecutable edge as interesting. */
2325 for (phi = phi_nodes (e->dest);
2326 phi;
2327 phi = PHI_CHAIN (phi))
2329 tree result = PHI_RESULT (phi);
2330 int version = SSA_NAME_VERSION (result);
2332 bitmap_set_bit (interesting_names, version);
2335 te->probability += e->probability;
2337 te->count += e->count;
2338 remove_edge (e);
2339 cfg_altered = 1;
2341 else
2342 ei_next (&ei);
2345 bsi = bsi_last (bb_for_stmt (use_stmt));
2346 bsi_remove (&bsi, true);
2348 /* And fixup the flags on the single remaining edge. */
2349 te->flags &= ~(EDGE_TRUE_VALUE | EDGE_FALSE_VALUE);
2350 te->flags &= ~EDGE_ABNORMAL;
2351 te->flags |= EDGE_FALLTHRU;
2352 if (te->probability > REG_BR_PROB_BASE)
2353 te->probability = REG_BR_PROB_BASE;
2358 /* Ensure there is nothing else to do. */
2359 gcc_assert (!all || has_zero_uses (lhs));
2361 /* If we were able to propagate away all uses of LHS, then
2362 we can remove STMT. */
2363 if (all)
2364 remove_stmt_or_phi (stmt);
2368 /* T is either a PHI node (potentially a degenerate PHI node) or
2369 a statement that is a trivial copy or constant initialization.
2371 Attempt to eliminate T by propagating its RHS into all uses of
2372 its LHS. This may in turn set new bits in INTERESTING_NAMES
2373 for nodes we want to revisit later.
2375 All exit paths should clear INTERESTING_NAMES for the result
2376 of T. */
2378 static void
2379 eliminate_const_or_copy (tree t, bitmap interesting_names)
2381 tree lhs = get_lhs_or_phi_result (t);
2382 tree rhs;
2383 int version = SSA_NAME_VERSION (lhs);
2385 /* If the LHS of this statement or PHI has no uses, then we can
2386 just eliminate it. This can occur if, for example, the PHI
2387 was created by block duplication due to threading and its only
2388 use was in the conditional at the end of the block which was
2389 deleted. */
2390 if (has_zero_uses (lhs))
2392 bitmap_clear_bit (interesting_names, version);
2393 remove_stmt_or_phi (t);
2394 return;
2397 /* Get the RHS of the assignment or PHI node if the PHI is a
2398 degenerate. */
2399 rhs = get_rhs_or_phi_arg (t);
2400 if (!rhs)
2402 bitmap_clear_bit (interesting_names, version);
2403 return;
2406 propagate_rhs_into_lhs (t, lhs, rhs, interesting_names);
2408 /* Note that T may well have been deleted by now, so do
2409 not access it, instead use the saved version # to clear
2410 T's entry in the worklist. */
2411 bitmap_clear_bit (interesting_names, version);
2414 /* The first phase in degenerate PHI elimination.
2416 Eliminate the degenerate PHIs in BB, then recurse on the
2417 dominator children of BB. */
2419 static void
2420 eliminate_degenerate_phis_1 (basic_block bb, bitmap interesting_names)
2422 tree phi, next;
2423 basic_block son;
2425 for (phi = phi_nodes (bb); phi; phi = next)
2427 next = PHI_CHAIN (phi);
2428 eliminate_const_or_copy (phi, interesting_names);
2431 /* Recurse into the dominator children of BB. */
2432 for (son = first_dom_son (CDI_DOMINATORS, bb);
2433 son;
2434 son = next_dom_son (CDI_DOMINATORS, son))
2435 eliminate_degenerate_phis_1 (son, interesting_names);
2439 /* A very simple pass to eliminate degenerate PHI nodes from the
2440 IL. This is meant to be fast enough to be able to be run several
2441 times in the optimization pipeline.
2443 Certain optimizations, particularly those which duplicate blocks
2444 or remove edges from the CFG can create or expose PHIs which are
2445 trivial copies or constant initializations.
2447 While we could pick up these optimizations in DOM or with the
2448 combination of copy-prop and CCP, those solutions are far too
2449 heavy-weight for our needs.
2451 This implementation has two phases so that we can efficiently
2452 eliminate the first order degenerate PHIs and second order
2453 degenerate PHIs.
2455 The first phase performs a dominator walk to identify and eliminate
2456 the vast majority of the degenerate PHIs. When a degenerate PHI
2457 is identified and eliminated any affected statements or PHIs
2458 are put on a worklist.
2460 The second phase eliminates degenerate PHIs and trivial copies
2461 or constant initializations using the worklist. This is how we
2462 pick up the secondary optimization opportunities with minimal
2463 cost. */
2465 static unsigned int
2466 eliminate_degenerate_phis (void)
2468 bitmap interesting_names;
2469 bitmap interesting_names1;
2471 /* Bitmap of blocks which need EH information updated. We can not
2472 update it on-the-fly as doing so invalidates the dominator tree. */
2473 need_eh_cleanup = BITMAP_ALLOC (NULL);
2475 /* INTERESTING_NAMES is effectively our worklist, indexed by
2476 SSA_NAME_VERSION.
2478 A set bit indicates that the statement or PHI node which
2479 defines the SSA_NAME should be (re)examined to determine if
2480 it has become a degenerate PHI or trivial const/copy propagation
2481 opportunity.
2483 Experiments have show we generally get better compilation
2484 time behavior with bitmaps rather than sbitmaps. */
2485 interesting_names = BITMAP_ALLOC (NULL);
2486 interesting_names1 = BITMAP_ALLOC (NULL);
2488 /* First phase. Eliminate degenerate PHIs via a dominator
2489 walk of the CFG.
2491 Experiments have indicated that we generally get better
2492 compile-time behavior by visiting blocks in the first
2493 phase in dominator order. Presumably this is because walking
2494 in dominator order leaves fewer PHIs for later examination
2495 by the worklist phase. */
2496 calculate_dominance_info (CDI_DOMINATORS);
2497 eliminate_degenerate_phis_1 (ENTRY_BLOCK_PTR, interesting_names);
2499 /* Second phase. Eliminate second order degenerate PHIs as well
2500 as trivial copies or constant initializations identified by
2501 the first phase or this phase. Basically we keep iterating
2502 until our set of INTERESTING_NAMEs is empty. */
2503 while (!bitmap_empty_p (interesting_names))
2505 unsigned int i;
2506 bitmap_iterator bi;
2508 /* EXECUTE_IF_SET_IN_BITMAP does not like its bitmap
2509 changed during the loop. Copy it to another bitmap and
2510 use that. */
2511 bitmap_copy (interesting_names1, interesting_names);
2513 EXECUTE_IF_SET_IN_BITMAP (interesting_names1, 0, i, bi)
2515 tree name = ssa_name (i);
2517 /* Ignore SSA_NAMEs that have been released because
2518 their defining statement was deleted (unreachable). */
2519 if (name)
2520 eliminate_const_or_copy (SSA_NAME_DEF_STMT (ssa_name (i)),
2521 interesting_names);
2525 /* Propagation of const and copies may make some EH edges dead. Purge
2526 such edges from the CFG as needed. */
2527 if (!bitmap_empty_p (need_eh_cleanup))
2529 cfg_altered |= tree_purge_all_dead_eh_edges (need_eh_cleanup);
2530 BITMAP_FREE (need_eh_cleanup);
2533 BITMAP_FREE (interesting_names);
2534 BITMAP_FREE (interesting_names1);
2535 if (cfg_altered)
2536 free_dominance_info (CDI_DOMINATORS);
2537 return 0;
2540 struct tree_opt_pass pass_phi_only_cprop =
2542 "phicprop", /* name */
2543 gate_dominator, /* gate */
2544 eliminate_degenerate_phis, /* execute */
2545 NULL, /* sub */
2546 NULL, /* next */
2547 0, /* static_pass_number */
2548 TV_TREE_PHI_CPROP, /* tv_id */
2549 PROP_cfg | PROP_ssa | PROP_alias, /* properties_required */
2550 0, /* properties_provided */
2551 0, /* properties_destroyed */
2552 0, /* todo_flags_start */
2553 TODO_cleanup_cfg | TODO_dump_func
2554 | TODO_ggc_collect | TODO_verify_ssa
2555 | TODO_verify_stmts | TODO_update_smt_usage
2556 | TODO_update_ssa, /* todo_flags_finish */
2557 0 /* letter */