2005-08-31 J"orn Rennecke <joern.rennecke@st.com>
[official-gcc.git] / gcc / tree-ssa-dom.c
blob6d99e54364008e158c83fb22e3fa173650c1e3eb
1 /* SSA Dominator optimizations for trees
2 Copyright (C) 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
3 Contributed by Diego Novillo <dnovillo@redhat.com>
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, 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301, 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 "cfgloop.h"
33 #include "output.h"
34 #include "expr.h"
35 #include "function.h"
36 #include "diagnostic.h"
37 #include "timevar.h"
38 #include "tree-dump.h"
39 #include "tree-flow.h"
40 #include "domwalk.h"
41 #include "real.h"
42 #include "tree-pass.h"
43 #include "tree-ssa-propagate.h"
44 #include "langhooks.h"
46 /* This file implements optimizations on the dominator tree. */
49 /* Structure for recording edge equivalences as well as any pending
50 edge redirections during the dominator optimizer.
52 Computing and storing the edge equivalences instead of creating
53 them on-demand can save significant amounts of time, particularly
54 for pathological cases involving switch statements.
56 These structures live for a single iteration of the dominator
57 optimizer in the edge's AUX field. At the end of an iteration we
58 free each of these structures and update the AUX field to point
59 to any requested redirection target (the code for updating the
60 CFG and SSA graph for edge redirection expects redirection edge
61 targets to be in the AUX field for each edge. */
63 struct edge_info
65 /* If this edge creates a simple equivalence, the LHS and RHS of
66 the equivalence will be stored here. */
67 tree lhs;
68 tree rhs;
70 /* Traversing an edge may also indicate one or more particular conditions
71 are true or false. The number of recorded conditions can vary, but
72 can be determined by the condition's code. So we have an array
73 and its maximum index rather than use a varray. */
74 tree *cond_equivalences;
75 unsigned int max_cond_equivalences;
77 /* If we can thread this edge this field records the new target. */
78 edge redirection_target;
82 /* Hash table with expressions made available during the renaming process.
83 When an assignment of the form X_i = EXPR is found, the statement is
84 stored in this table. If the same expression EXPR is later found on the
85 RHS of another statement, it is replaced with X_i (thus performing
86 global redundancy elimination). Similarly as we pass through conditionals
87 we record the conditional itself as having either a true or false value
88 in this table. */
89 static htab_t avail_exprs;
91 /* Stack of available expressions in AVAIL_EXPRs. Each block pushes any
92 expressions it enters into the hash table along with a marker entry
93 (null). When we finish processing the block, we pop off entries and
94 remove the expressions from the global hash table until we hit the
95 marker. */
96 static VEC(tree,heap) *avail_exprs_stack;
98 /* Stack of statements we need to rescan during finalization for newly
99 exposed variables.
101 Statement rescanning must occur after the current block's available
102 expressions are removed from AVAIL_EXPRS. Else we may change the
103 hash code for an expression and be unable to find/remove it from
104 AVAIL_EXPRS. */
105 static VEC(tree,heap) *stmts_to_rescan;
107 /* Structure for entries in the expression hash table.
109 This requires more memory for the hash table entries, but allows us
110 to avoid creating silly tree nodes and annotations for conditionals,
111 eliminates 2 global hash tables and two block local varrays.
113 It also allows us to reduce the number of hash table lookups we
114 have to perform in lookup_avail_expr and finally it allows us to
115 significantly reduce the number of calls into the hashing routine
116 itself. */
118 struct expr_hash_elt
120 /* The value (lhs) of this expression. */
121 tree lhs;
123 /* The expression (rhs) we want to record. */
124 tree rhs;
126 /* The stmt pointer if this element corresponds to a statement. */
127 tree stmt;
129 /* The hash value for RHS/ann. */
130 hashval_t hash;
133 /* Stack of dest,src pairs that need to be restored during finalization.
135 A NULL entry is used to mark the end of pairs which need to be
136 restored during finalization of this block. */
137 static VEC(tree,heap) *const_and_copies_stack;
139 /* Bitmap of SSA_NAMEs known to have a nonzero value, even if we do not
140 know their exact value. */
141 static bitmap nonzero_vars;
143 /* Bitmap of blocks that are scheduled to be threaded through. This
144 is used to communicate with thread_through_blocks. */
145 static bitmap threaded_blocks;
147 /* Stack of SSA_NAMEs which need their NONZERO_VARS property cleared
148 when the current block is finalized.
150 A NULL entry is used to mark the end of names needing their
151 entry in NONZERO_VARS cleared during finalization of this block. */
152 static VEC(tree,heap) *nonzero_vars_stack;
154 /* Track whether or not we have changed the control flow graph. */
155 static bool cfg_altered;
157 /* Bitmap of blocks that have had EH statements cleaned. We should
158 remove their dead edges eventually. */
159 static bitmap need_eh_cleanup;
161 /* Statistics for dominator optimizations. */
162 struct opt_stats_d
164 long num_stmts;
165 long num_exprs_considered;
166 long num_re;
167 long num_const_prop;
168 long num_copy_prop;
169 long num_iterations;
172 static struct opt_stats_d opt_stats;
174 /* Value range propagation record. Each time we encounter a conditional
175 of the form SSA_NAME COND CONST we create a new vrp_element to record
176 how the condition affects the possible values SSA_NAME may have.
178 Each record contains the condition tested (COND), and the range of
179 values the variable may legitimately have if COND is true. Note the
180 range of values may be a smaller range than COND specifies if we have
181 recorded other ranges for this variable. Each record also contains the
182 block in which the range was recorded for invalidation purposes.
184 Note that the current known range is computed lazily. This allows us
185 to avoid the overhead of computing ranges which are never queried.
187 When we encounter a conditional, we look for records which constrain
188 the SSA_NAME used in the condition. In some cases those records allow
189 us to determine the condition's result at compile time. In other cases
190 they may allow us to simplify the condition.
192 We also use value ranges to do things like transform signed div/mod
193 operations into unsigned div/mod or to simplify ABS_EXPRs.
195 Simple experiments have shown these optimizations to not be all that
196 useful on switch statements (much to my surprise). So switch statement
197 optimizations are not performed.
199 Note carefully we do not propagate information through each statement
200 in the block. i.e., if we know variable X has a value defined of
201 [0, 25] and we encounter Y = X + 1, we do not track a value range
202 for Y (which would be [1, 26] if we cared). Similarly we do not
203 constrain values as we encounter narrowing typecasts, etc. */
205 struct vrp_element
207 /* The highest and lowest values the variable in COND may contain when
208 COND is true. Note this may not necessarily be the same values
209 tested by COND if the same variable was used in earlier conditionals.
211 Note this is computed lazily and thus can be NULL indicating that
212 the values have not been computed yet. */
213 tree low;
214 tree high;
216 /* The actual conditional we recorded. This is needed since we compute
217 ranges lazily. */
218 tree cond;
220 /* The basic block where this record was created. We use this to determine
221 when to remove records. */
222 basic_block bb;
225 /* A hash table holding value range records (VRP_ELEMENTs) for a given
226 SSA_NAME. We used to use a varray indexed by SSA_NAME_VERSION, but
227 that gets awful wasteful, particularly since the density objects
228 with useful information is very low. */
229 static htab_t vrp_data;
231 typedef struct vrp_element *vrp_element_p;
233 DEF_VEC_P(vrp_element_p);
234 DEF_VEC_ALLOC_P(vrp_element_p,heap);
236 /* An entry in the VRP_DATA hash table. We record the variable and a
237 varray of VRP_ELEMENT records associated with that variable. */
238 struct vrp_hash_elt
240 tree var;
241 VEC(vrp_element_p,heap) *records;
244 /* Array of variables which have their values constrained by operations
245 in this basic block. We use this during finalization to know
246 which variables need their VRP data updated. */
248 /* Stack of SSA_NAMEs which had their values constrained by operations
249 in this basic block. During finalization of this block we use this
250 list to determine which variables need their VRP data updated.
252 A NULL entry marks the end of the SSA_NAMEs associated with this block. */
253 static VEC(tree,heap) *vrp_variables_stack;
255 struct eq_expr_value
257 tree src;
258 tree dst;
261 /* Local functions. */
262 static void optimize_stmt (struct dom_walk_data *,
263 basic_block bb,
264 block_stmt_iterator);
265 static tree lookup_avail_expr (tree, bool);
266 static hashval_t vrp_hash (const void *);
267 static int vrp_eq (const void *, const void *);
268 static hashval_t avail_expr_hash (const void *);
269 static hashval_t real_avail_expr_hash (const void *);
270 static int avail_expr_eq (const void *, const void *);
271 static void htab_statistics (FILE *, htab_t);
272 static void record_cond (tree, tree);
273 static void record_const_or_copy (tree, tree);
274 static void record_equality (tree, tree);
275 static tree update_rhs_and_lookup_avail_expr (tree, tree, bool);
276 static tree simplify_rhs_and_lookup_avail_expr (tree, int);
277 static tree simplify_cond_and_lookup_avail_expr (tree, stmt_ann_t, int);
278 static tree simplify_switch_and_lookup_avail_expr (tree, int);
279 static tree find_equivalent_equality_comparison (tree);
280 static void record_range (tree, basic_block);
281 static bool extract_range_from_cond (tree, tree *, tree *, int *);
282 static void record_equivalences_from_phis (basic_block);
283 static void record_equivalences_from_incoming_edge (basic_block);
284 static bool eliminate_redundant_computations (tree, stmt_ann_t);
285 static void record_equivalences_from_stmt (tree, int, stmt_ann_t);
286 static void thread_across_edge (struct dom_walk_data *, edge);
287 static void dom_opt_finalize_block (struct dom_walk_data *, basic_block);
288 static void dom_opt_initialize_block (struct dom_walk_data *, basic_block);
289 static void propagate_to_outgoing_edges (struct dom_walk_data *, basic_block);
290 static void remove_local_expressions_from_table (void);
291 static void restore_vars_to_original_value (void);
292 static edge single_incoming_edge_ignoring_loop_edges (basic_block);
293 static void restore_nonzero_vars_to_original_value (void);
294 static inline bool unsafe_associative_fp_binop (tree);
297 /* Local version of fold that doesn't introduce cruft. */
299 static tree
300 local_fold (tree t)
302 t = fold (t);
304 /* Strip away useless type conversions. Both the NON_LVALUE_EXPR that
305 may have been added by fold, and "useless" type conversions that might
306 now be apparent due to propagation. */
307 STRIP_USELESS_TYPE_CONVERSION (t);
309 return t;
312 /* Allocate an EDGE_INFO for edge E and attach it to E.
313 Return the new EDGE_INFO structure. */
315 static struct edge_info *
316 allocate_edge_info (edge e)
318 struct edge_info *edge_info;
320 edge_info = xcalloc (1, sizeof (struct edge_info));
322 e->aux = edge_info;
323 return edge_info;
326 /* Free all EDGE_INFO structures associated with edges in the CFG.
327 If a particular edge can be threaded, copy the redirection
328 target from the EDGE_INFO structure into the edge's AUX field
329 as required by code to update the CFG and SSA graph for
330 jump threading. */
332 static void
333 free_all_edge_infos (void)
335 basic_block bb;
336 edge_iterator ei;
337 edge e;
339 FOR_EACH_BB (bb)
341 FOR_EACH_EDGE (e, ei, bb->preds)
343 struct edge_info *edge_info = e->aux;
345 if (edge_info)
347 e->aux = edge_info->redirection_target;
348 if (edge_info->cond_equivalences)
349 free (edge_info->cond_equivalences);
350 free (edge_info);
356 /* Free an instance of vrp_hash_elt. */
358 static void
359 vrp_free (void *data)
361 struct vrp_hash_elt *elt = data;
362 struct VEC(vrp_element_p,heap) **vrp_elt = &elt->records;
364 VEC_free (vrp_element_p, heap, *vrp_elt);
365 free (elt);
368 /* Jump threading, redundancy elimination and const/copy propagation.
370 This pass may expose new symbols that need to be renamed into SSA. For
371 every new symbol exposed, its corresponding bit will be set in
372 VARS_TO_RENAME. */
374 static void
375 tree_ssa_dominator_optimize (void)
377 struct dom_walk_data walk_data;
378 unsigned int i;
379 struct loops loops_info;
381 memset (&opt_stats, 0, sizeof (opt_stats));
383 /* Create our hash tables. */
384 avail_exprs = htab_create (1024, real_avail_expr_hash, avail_expr_eq, free);
385 vrp_data = htab_create (ceil_log2 (num_ssa_names), vrp_hash, vrp_eq,
386 vrp_free);
387 avail_exprs_stack = VEC_alloc (tree, heap, 20);
388 const_and_copies_stack = VEC_alloc (tree, heap, 20);
389 nonzero_vars_stack = VEC_alloc (tree, heap, 20);
390 vrp_variables_stack = VEC_alloc (tree, heap, 20);
391 stmts_to_rescan = VEC_alloc (tree, heap, 20);
392 nonzero_vars = BITMAP_ALLOC (NULL);
393 threaded_blocks = BITMAP_ALLOC (NULL);
394 need_eh_cleanup = BITMAP_ALLOC (NULL);
396 /* Setup callbacks for the generic dominator tree walker. */
397 walk_data.walk_stmts_backward = false;
398 walk_data.dom_direction = CDI_DOMINATORS;
399 walk_data.initialize_block_local_data = NULL;
400 walk_data.before_dom_children_before_stmts = dom_opt_initialize_block;
401 walk_data.before_dom_children_walk_stmts = optimize_stmt;
402 walk_data.before_dom_children_after_stmts = propagate_to_outgoing_edges;
403 walk_data.after_dom_children_before_stmts = NULL;
404 walk_data.after_dom_children_walk_stmts = NULL;
405 walk_data.after_dom_children_after_stmts = dom_opt_finalize_block;
406 /* Right now we only attach a dummy COND_EXPR to the global data pointer.
407 When we attach more stuff we'll need to fill this out with a real
408 structure. */
409 walk_data.global_data = NULL;
410 walk_data.block_local_data_size = 0;
411 walk_data.interesting_blocks = NULL;
413 /* Now initialize the dominator walker. */
414 init_walk_dominator_tree (&walk_data);
416 calculate_dominance_info (CDI_DOMINATORS);
418 /* We need to know which edges exit loops so that we can
419 aggressively thread through loop headers to an exit
420 edge. */
421 flow_loops_find (&loops_info);
422 mark_loop_exit_edges (&loops_info);
423 flow_loops_free (&loops_info);
425 /* Clean up the CFG so that any forwarder blocks created by loop
426 canonicalization are removed. */
427 cleanup_tree_cfg ();
428 calculate_dominance_info (CDI_DOMINATORS);
430 /* If we prove certain blocks are unreachable, then we want to
431 repeat the dominator optimization process as PHI nodes may
432 have turned into copies which allows better propagation of
433 values. So we repeat until we do not identify any new unreachable
434 blocks. */
437 /* Optimize the dominator tree. */
438 cfg_altered = false;
440 /* We need accurate information regarding back edges in the CFG
441 for jump threading. */
442 mark_dfs_back_edges ();
444 /* Recursively walk the dominator tree optimizing statements. */
445 walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);
448 block_stmt_iterator bsi;
449 basic_block bb;
450 FOR_EACH_BB (bb)
452 for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
454 update_stmt_if_modified (bsi_stmt (bsi));
459 /* If we exposed any new variables, go ahead and put them into
460 SSA form now, before we handle jump threading. This simplifies
461 interactions between rewriting of _DECL nodes into SSA form
462 and rewriting SSA_NAME nodes into SSA form after block
463 duplication and CFG manipulation. */
464 update_ssa (TODO_update_ssa);
466 free_all_edge_infos ();
468 /* Thread jumps, creating duplicate blocks as needed. */
469 cfg_altered |= thread_through_all_blocks (threaded_blocks);
471 /* Removal of statements may make some EH edges dead. Purge
472 such edges from the CFG as needed. */
473 if (!bitmap_empty_p (need_eh_cleanup))
475 cfg_altered |= tree_purge_all_dead_eh_edges (need_eh_cleanup);
476 bitmap_zero (need_eh_cleanup);
479 if (cfg_altered)
480 free_dominance_info (CDI_DOMINATORS);
482 cfg_altered = cleanup_tree_cfg ();
484 if (rediscover_loops_after_threading)
486 /* Rerun basic loop analysis to discover any newly
487 created loops and update the set of exit edges. */
488 rediscover_loops_after_threading = false;
489 flow_loops_find (&loops_info);
490 mark_loop_exit_edges (&loops_info);
491 flow_loops_free (&loops_info);
493 /* Remove any forwarder blocks inserted by loop
494 header canonicalization. */
495 cleanup_tree_cfg ();
498 calculate_dominance_info (CDI_DOMINATORS);
500 update_ssa (TODO_update_ssa);
502 /* Reinitialize the various tables. */
503 bitmap_clear (nonzero_vars);
504 bitmap_clear (threaded_blocks);
505 htab_empty (avail_exprs);
506 htab_empty (vrp_data);
508 /* Finally, remove everything except invariants in SSA_NAME_VALUE.
510 This must be done before we iterate as we might have a
511 reference to an SSA_NAME which was removed by the call to
512 update_ssa.
514 Long term we will be able to let everything in SSA_NAME_VALUE
515 persist. However, for now, we know this is the safe thing to do. */
516 for (i = 0; i < num_ssa_names; i++)
518 tree name = ssa_name (i);
519 tree value;
521 if (!name)
522 continue;
524 value = SSA_NAME_VALUE (name);
525 if (value && !is_gimple_min_invariant (value))
526 SSA_NAME_VALUE (name) = NULL;
529 opt_stats.num_iterations++;
531 while (optimize > 1 && cfg_altered);
533 /* Debugging dumps. */
534 if (dump_file && (dump_flags & TDF_STATS))
535 dump_dominator_optimization_stats (dump_file);
537 /* We emptied the hash table earlier, now delete it completely. */
538 htab_delete (avail_exprs);
539 htab_delete (vrp_data);
541 /* It is not necessary to clear CURRDEFS, REDIRECTION_EDGES, VRP_DATA,
542 CONST_AND_COPIES, and NONZERO_VARS as they all get cleared at the bottom
543 of the do-while loop above. */
545 /* And finalize the dominator walker. */
546 fini_walk_dominator_tree (&walk_data);
548 /* Free nonzero_vars. */
549 BITMAP_FREE (nonzero_vars);
550 BITMAP_FREE (threaded_blocks);
551 BITMAP_FREE (need_eh_cleanup);
553 VEC_free (tree, heap, avail_exprs_stack);
554 VEC_free (tree, heap, const_and_copies_stack);
555 VEC_free (tree, heap, nonzero_vars_stack);
556 VEC_free (tree, heap, vrp_variables_stack);
557 VEC_free (tree, heap, stmts_to_rescan);
560 static bool
561 gate_dominator (void)
563 return flag_tree_dom != 0;
566 struct tree_opt_pass pass_dominator =
568 "dom", /* name */
569 gate_dominator, /* gate */
570 tree_ssa_dominator_optimize, /* execute */
571 NULL, /* sub */
572 NULL, /* next */
573 0, /* static_pass_number */
574 TV_TREE_SSA_DOMINATOR_OPTS, /* tv_id */
575 PROP_cfg | PROP_ssa | PROP_alias, /* properties_required */
576 0, /* properties_provided */
577 0, /* properties_destroyed */
578 0, /* todo_flags_start */
579 TODO_dump_func
580 | TODO_update_ssa
581 | TODO_verify_ssa, /* todo_flags_finish */
582 0 /* letter */
586 /* We are exiting E->src, see if E->dest ends with a conditional
587 jump which has a known value when reached via E.
589 Special care is necessary if E is a back edge in the CFG as we
590 will have already recorded equivalences for E->dest into our
591 various tables, including the result of the conditional at
592 the end of E->dest. Threading opportunities are severely
593 limited in that case to avoid short-circuiting the loop
594 incorrectly.
596 Note it is quite common for the first block inside a loop to
597 end with a conditional which is either always true or always
598 false when reached via the loop backedge. Thus we do not want
599 to blindly disable threading across a loop backedge. */
601 static void
602 thread_across_edge (struct dom_walk_data *walk_data, edge e)
604 block_stmt_iterator bsi;
605 tree stmt = NULL;
606 tree phi;
608 /* If E->dest does not end with a conditional, then there is
609 nothing to do. */
610 bsi = bsi_last (e->dest);
611 if (bsi_end_p (bsi)
612 || ! bsi_stmt (bsi)
613 || (TREE_CODE (bsi_stmt (bsi)) != COND_EXPR
614 && TREE_CODE (bsi_stmt (bsi)) != GOTO_EXPR
615 && TREE_CODE (bsi_stmt (bsi)) != SWITCH_EXPR))
616 return;
618 /* The basic idea here is to use whatever knowledge we have
619 from our dominator walk to simplify statements in E->dest,
620 with the ultimate goal being to simplify the conditional
621 at the end of E->dest.
623 Note that we must undo any changes we make to the underlying
624 statements as the simplifications we are making are control
625 flow sensitive (ie, the simplifications are valid when we
626 traverse E, but may not be valid on other paths to E->dest. */
628 /* Each PHI creates a temporary equivalence, record them. Again
629 these are context sensitive equivalences and will be removed
630 by our caller. */
631 for (phi = phi_nodes (e->dest); phi; phi = PHI_CHAIN (phi))
633 tree src = PHI_ARG_DEF_FROM_EDGE (phi, e);
634 tree dst = PHI_RESULT (phi);
636 /* If the desired argument is not the same as this PHI's result
637 and it is set by a PHI in E->dest, then we can not thread
638 through E->dest. */
639 if (src != dst
640 && TREE_CODE (src) == SSA_NAME
641 && TREE_CODE (SSA_NAME_DEF_STMT (src)) == PHI_NODE
642 && bb_for_stmt (SSA_NAME_DEF_STMT (src)) == e->dest)
643 return;
645 record_const_or_copy (dst, src);
648 /* Try to simplify each statement in E->dest, ultimately leading to
649 a simplification of the COND_EXPR at the end of E->dest.
651 We might consider marking just those statements which ultimately
652 feed the COND_EXPR. It's not clear if the overhead of bookkeeping
653 would be recovered by trying to simplify fewer statements.
655 If we are able to simplify a statement into the form
656 SSA_NAME = (SSA_NAME | gimple invariant), then we can record
657 a context sensitive equivalency which may help us simplify
658 later statements in E->dest.
660 Failure to simplify into the form above merely means that the
661 statement provides no equivalences to help simplify later
662 statements. This does not prevent threading through E->dest. */
663 for (bsi = bsi_start (e->dest); ! bsi_end_p (bsi); bsi_next (&bsi))
665 tree cached_lhs;
667 stmt = bsi_stmt (bsi);
669 /* Ignore empty statements and labels. */
670 if (IS_EMPTY_STMT (stmt) || TREE_CODE (stmt) == LABEL_EXPR)
671 continue;
673 /* Safely handle threading across loop backedges. This is
674 over conservative, but still allows us to capture the
675 majority of the cases where we can thread across a loop
676 backedge. */
677 if ((e->flags & EDGE_DFS_BACK) != 0
678 && TREE_CODE (stmt) != COND_EXPR
679 && TREE_CODE (stmt) != SWITCH_EXPR)
680 return;
682 /* If the statement has volatile operands, then we assume we
683 can not thread through this block. This is overly
684 conservative in some ways. */
685 if (TREE_CODE (stmt) == ASM_EXPR && ASM_VOLATILE_P (stmt))
686 return;
688 /* If this is not a MODIFY_EXPR which sets an SSA_NAME to a new
689 value, then do not try to simplify this statement as it will
690 not simplify in any way that is helpful for jump threading. */
691 if (TREE_CODE (stmt) != MODIFY_EXPR
692 || TREE_CODE (TREE_OPERAND (stmt, 0)) != SSA_NAME)
693 continue;
695 /* At this point we have a statement which assigns an RHS to an
696 SSA_VAR on the LHS. We want to try and simplify this statement
697 to expose more context sensitive equivalences which in turn may
698 allow us to simplify the condition at the end of the loop. */
699 if (TREE_CODE (TREE_OPERAND (stmt, 1)) == SSA_NAME)
700 cached_lhs = TREE_OPERAND (stmt, 1);
701 else
703 /* Copy the operands. */
704 tree *copy;
705 ssa_op_iter iter;
706 use_operand_p use_p;
707 unsigned int num, i = 0;
709 num = NUM_SSA_OPERANDS (stmt, (SSA_OP_USE | SSA_OP_VUSE));
710 copy = xcalloc (num, sizeof (tree));
712 /* Make a copy of the uses & vuses into USES_COPY, then cprop into
713 the operands. */
714 FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_USE | SSA_OP_VUSE)
716 tree tmp = NULL;
717 tree use = USE_FROM_PTR (use_p);
719 copy[i++] = use;
720 if (TREE_CODE (use) == SSA_NAME)
721 tmp = SSA_NAME_VALUE (use);
722 if (tmp && TREE_CODE (tmp) != VALUE_HANDLE)
723 SET_USE (use_p, tmp);
726 /* Try to fold/lookup the new expression. Inserting the
727 expression into the hash table is unlikely to help
728 simplify anything later, so just query the hashtable. */
729 cached_lhs = fold (TREE_OPERAND (stmt, 1));
730 if (TREE_CODE (cached_lhs) != SSA_NAME
731 && !is_gimple_min_invariant (cached_lhs))
732 cached_lhs = lookup_avail_expr (stmt, false);
735 /* Restore the statement's original uses/defs. */
736 i = 0;
737 FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_USE | SSA_OP_VUSE)
738 SET_USE (use_p, copy[i++]);
740 free (copy);
743 /* Record the context sensitive equivalence if we were able
744 to simplify this statement. */
745 if (cached_lhs
746 && (TREE_CODE (cached_lhs) == SSA_NAME
747 || is_gimple_min_invariant (cached_lhs)))
748 record_const_or_copy (TREE_OPERAND (stmt, 0), cached_lhs);
751 /* If we stopped at a COND_EXPR or SWITCH_EXPR, see if we know which arm
752 will be taken. */
753 if (stmt
754 && (TREE_CODE (stmt) == COND_EXPR
755 || TREE_CODE (stmt) == GOTO_EXPR
756 || TREE_CODE (stmt) == SWITCH_EXPR))
758 tree cond, cached_lhs;
760 /* Now temporarily cprop the operands and try to find the resulting
761 expression in the hash tables. */
762 if (TREE_CODE (stmt) == COND_EXPR)
763 cond = COND_EXPR_COND (stmt);
764 else if (TREE_CODE (stmt) == GOTO_EXPR)
765 cond = GOTO_DESTINATION (stmt);
766 else
767 cond = SWITCH_COND (stmt);
769 if (COMPARISON_CLASS_P (cond))
771 tree dummy_cond, op0, op1;
772 enum tree_code cond_code;
774 op0 = TREE_OPERAND (cond, 0);
775 op1 = TREE_OPERAND (cond, 1);
776 cond_code = TREE_CODE (cond);
778 /* Get the current value of both operands. */
779 if (TREE_CODE (op0) == SSA_NAME)
781 tree tmp = SSA_NAME_VALUE (op0);
782 if (tmp && TREE_CODE (tmp) != VALUE_HANDLE)
783 op0 = tmp;
786 if (TREE_CODE (op1) == SSA_NAME)
788 tree tmp = SSA_NAME_VALUE (op1);
789 if (tmp && TREE_CODE (tmp) != VALUE_HANDLE)
790 op1 = tmp;
793 /* Stuff the operator and operands into our dummy conditional
794 expression, creating the dummy conditional if necessary. */
795 dummy_cond = walk_data->global_data;
796 if (! dummy_cond)
798 dummy_cond = build (cond_code, boolean_type_node, op0, op1);
799 dummy_cond = build (COND_EXPR, void_type_node,
800 dummy_cond, NULL, NULL);
801 walk_data->global_data = dummy_cond;
803 else
805 TREE_SET_CODE (COND_EXPR_COND (dummy_cond), cond_code);
806 TREE_OPERAND (COND_EXPR_COND (dummy_cond), 0) = op0;
807 TREE_OPERAND (COND_EXPR_COND (dummy_cond), 1) = op1;
810 /* If the conditional folds to an invariant, then we are done,
811 otherwise look it up in the hash tables. */
812 cached_lhs = local_fold (COND_EXPR_COND (dummy_cond));
813 if (! is_gimple_min_invariant (cached_lhs))
815 cached_lhs = lookup_avail_expr (dummy_cond, false);
816 if (!cached_lhs || ! is_gimple_min_invariant (cached_lhs))
817 cached_lhs = simplify_cond_and_lookup_avail_expr (dummy_cond,
818 NULL,
819 false);
822 /* We can have conditionals which just test the state of a
823 variable rather than use a relational operator. These are
824 simpler to handle. */
825 else if (TREE_CODE (cond) == SSA_NAME)
827 cached_lhs = cond;
828 cached_lhs = SSA_NAME_VALUE (cached_lhs);
829 if (cached_lhs && ! is_gimple_min_invariant (cached_lhs))
830 cached_lhs = NULL;
832 else
833 cached_lhs = lookup_avail_expr (stmt, false);
835 if (cached_lhs)
837 edge taken_edge = find_taken_edge (e->dest, cached_lhs);
838 basic_block dest = (taken_edge ? taken_edge->dest : NULL);
840 if (dest == e->dest)
841 return;
843 /* If we have a known destination for the conditional, then
844 we can perform this optimization, which saves at least one
845 conditional jump each time it applies since we get to
846 bypass the conditional at our original destination. */
847 if (dest)
849 struct edge_info *edge_info;
851 if (e->aux)
852 edge_info = e->aux;
853 else
854 edge_info = allocate_edge_info (e);
855 edge_info->redirection_target = taken_edge;
856 bitmap_set_bit (threaded_blocks, e->dest->index);
863 /* Initialize local stacks for this optimizer and record equivalences
864 upon entry to BB. Equivalences can come from the edge traversed to
865 reach BB or they may come from PHI nodes at the start of BB. */
867 static void
868 dom_opt_initialize_block (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
869 basic_block bb)
871 if (dump_file && (dump_flags & TDF_DETAILS))
872 fprintf (dump_file, "\n\nOptimizing block #%d\n\n", bb->index);
874 /* Push a marker on the stacks of local information so that we know how
875 far to unwind when we finalize this block. */
876 VEC_safe_push (tree, heap, avail_exprs_stack, NULL_TREE);
877 VEC_safe_push (tree, heap, const_and_copies_stack, NULL_TREE);
878 VEC_safe_push (tree, heap, nonzero_vars_stack, NULL_TREE);
879 VEC_safe_push (tree, heap, vrp_variables_stack, NULL_TREE);
881 record_equivalences_from_incoming_edge (bb);
883 /* PHI nodes can create equivalences too. */
884 record_equivalences_from_phis (bb);
887 /* Given an expression EXPR (a relational expression or a statement),
888 initialize the hash table element pointed to by ELEMENT. */
890 static void
891 initialize_hash_element (tree expr, tree lhs, struct expr_hash_elt *element)
893 /* Hash table elements may be based on conditional expressions or statements.
895 For the former case, we have no annotation and we want to hash the
896 conditional expression. In the latter case we have an annotation and
897 we want to record the expression the statement evaluates. */
898 if (COMPARISON_CLASS_P (expr) || TREE_CODE (expr) == TRUTH_NOT_EXPR)
900 element->stmt = NULL;
901 element->rhs = expr;
903 else if (TREE_CODE (expr) == COND_EXPR)
905 element->stmt = expr;
906 element->rhs = COND_EXPR_COND (expr);
908 else if (TREE_CODE (expr) == SWITCH_EXPR)
910 element->stmt = expr;
911 element->rhs = SWITCH_COND (expr);
913 else if (TREE_CODE (expr) == RETURN_EXPR && TREE_OPERAND (expr, 0))
915 element->stmt = expr;
916 element->rhs = TREE_OPERAND (TREE_OPERAND (expr, 0), 1);
918 else if (TREE_CODE (expr) == GOTO_EXPR)
920 element->stmt = expr;
921 element->rhs = GOTO_DESTINATION (expr);
923 else
925 element->stmt = expr;
926 element->rhs = TREE_OPERAND (expr, 1);
929 element->lhs = lhs;
930 element->hash = avail_expr_hash (element);
933 /* Remove all the expressions in LOCALS from TABLE, stopping when there are
934 LIMIT entries left in LOCALs. */
936 static void
937 remove_local_expressions_from_table (void)
939 /* Remove all the expressions made available in this block. */
940 while (VEC_length (tree, avail_exprs_stack) > 0)
942 struct expr_hash_elt element;
943 tree expr = VEC_pop (tree, avail_exprs_stack);
945 if (expr == NULL_TREE)
946 break;
948 initialize_hash_element (expr, NULL, &element);
949 htab_remove_elt_with_hash (avail_exprs, &element, element.hash);
953 /* Use the SSA_NAMES in LOCALS to restore TABLE to its original
954 state, stopping when there are LIMIT entries left in LOCALs. */
956 static void
957 restore_nonzero_vars_to_original_value (void)
959 while (VEC_length (tree, nonzero_vars_stack) > 0)
961 tree name = VEC_pop (tree, nonzero_vars_stack);
963 if (name == NULL)
964 break;
966 bitmap_clear_bit (nonzero_vars, SSA_NAME_VERSION (name));
970 /* Use the source/dest pairs in CONST_AND_COPIES_STACK to restore
971 CONST_AND_COPIES to its original state, stopping when we hit a
972 NULL marker. */
974 static void
975 restore_vars_to_original_value (void)
977 while (VEC_length (tree, const_and_copies_stack) > 0)
979 tree prev_value, dest;
981 dest = VEC_pop (tree, const_and_copies_stack);
983 if (dest == NULL)
984 break;
986 prev_value = VEC_pop (tree, const_and_copies_stack);
987 SSA_NAME_VALUE (dest) = prev_value;
991 /* We have finished processing the dominator children of BB, perform
992 any finalization actions in preparation for leaving this node in
993 the dominator tree. */
995 static void
996 dom_opt_finalize_block (struct dom_walk_data *walk_data, basic_block bb)
998 tree last;
1000 /* If we are at a leaf node in the dominator tree, see if we can thread
1001 the edge from BB through its successor.
1003 Do this before we remove entries from our equivalence tables. */
1004 if (single_succ_p (bb)
1005 && (single_succ_edge (bb)->flags & EDGE_ABNORMAL) == 0
1006 && (get_immediate_dominator (CDI_DOMINATORS, single_succ (bb)) != bb
1007 || phi_nodes (single_succ (bb))))
1010 thread_across_edge (walk_data, single_succ_edge (bb));
1012 else if ((last = last_stmt (bb))
1013 && TREE_CODE (last) == COND_EXPR
1014 && (COMPARISON_CLASS_P (COND_EXPR_COND (last))
1015 || TREE_CODE (COND_EXPR_COND (last)) == SSA_NAME)
1016 && EDGE_COUNT (bb->succs) == 2
1017 && (EDGE_SUCC (bb, 0)->flags & EDGE_ABNORMAL) == 0
1018 && (EDGE_SUCC (bb, 1)->flags & EDGE_ABNORMAL) == 0)
1020 edge true_edge, false_edge;
1022 extract_true_false_edges_from_block (bb, &true_edge, &false_edge);
1024 /* If the THEN arm is the end of a dominator tree or has PHI nodes,
1025 then try to thread through its edge. */
1026 if (get_immediate_dominator (CDI_DOMINATORS, true_edge->dest) != bb
1027 || phi_nodes (true_edge->dest))
1029 struct edge_info *edge_info;
1030 unsigned int i;
1032 /* Push a marker onto the available expression stack so that we
1033 unwind any expressions related to the TRUE arm before processing
1034 the false arm below. */
1035 VEC_safe_push (tree, heap, avail_exprs_stack, NULL_TREE);
1036 VEC_safe_push (tree, heap, const_and_copies_stack, NULL_TREE);
1038 edge_info = true_edge->aux;
1040 /* If we have info associated with this edge, record it into
1041 our equivalency tables. */
1042 if (edge_info)
1044 tree *cond_equivalences = edge_info->cond_equivalences;
1045 tree lhs = edge_info->lhs;
1046 tree rhs = edge_info->rhs;
1048 /* If we have a simple NAME = VALUE equivalency record it. */
1049 if (lhs && TREE_CODE (lhs) == SSA_NAME)
1050 record_const_or_copy (lhs, rhs);
1052 /* If we have 0 = COND or 1 = COND equivalences, record them
1053 into our expression hash tables. */
1054 if (cond_equivalences)
1055 for (i = 0; i < edge_info->max_cond_equivalences; i += 2)
1057 tree expr = cond_equivalences[i];
1058 tree value = cond_equivalences[i + 1];
1060 record_cond (expr, value);
1064 /* Now thread the edge. */
1065 thread_across_edge (walk_data, true_edge);
1067 /* And restore the various tables to their state before
1068 we threaded this edge. */
1069 remove_local_expressions_from_table ();
1070 restore_vars_to_original_value ();
1073 /* Similarly for the ELSE arm. */
1074 if (get_immediate_dominator (CDI_DOMINATORS, false_edge->dest) != bb
1075 || phi_nodes (false_edge->dest))
1077 struct edge_info *edge_info;
1078 unsigned int i;
1080 edge_info = false_edge->aux;
1082 /* If we have info associated with this edge, record it into
1083 our equivalency tables. */
1084 if (edge_info)
1086 tree *cond_equivalences = edge_info->cond_equivalences;
1087 tree lhs = edge_info->lhs;
1088 tree rhs = edge_info->rhs;
1090 /* If we have a simple NAME = VALUE equivalency record it. */
1091 if (lhs && TREE_CODE (lhs) == SSA_NAME)
1092 record_const_or_copy (lhs, rhs);
1094 /* If we have 0 = COND or 1 = COND equivalences, record them
1095 into our expression hash tables. */
1096 if (cond_equivalences)
1097 for (i = 0; i < edge_info->max_cond_equivalences; i += 2)
1099 tree expr = cond_equivalences[i];
1100 tree value = cond_equivalences[i + 1];
1102 record_cond (expr, value);
1106 thread_across_edge (walk_data, false_edge);
1108 /* No need to remove local expressions from our tables
1109 or restore vars to their original value as that will
1110 be done immediately below. */
1114 remove_local_expressions_from_table ();
1115 restore_nonzero_vars_to_original_value ();
1116 restore_vars_to_original_value ();
1118 /* Remove VRP records associated with this basic block. They are no
1119 longer valid.
1121 To be efficient, we note which variables have had their values
1122 constrained in this block. So walk over each variable in the
1123 VRP_VARIABLEs array. */
1124 while (VEC_length (tree, vrp_variables_stack) > 0)
1126 tree var = VEC_pop (tree, vrp_variables_stack);
1127 struct vrp_hash_elt vrp_hash_elt, *vrp_hash_elt_p;
1128 void **slot;
1130 /* Each variable has a stack of value range records. We want to
1131 invalidate those associated with our basic block. So we walk
1132 the array backwards popping off records associated with our
1133 block. Once we hit a record not associated with our block
1134 we are done. */
1135 VEC(vrp_element_p,heap) **var_vrp_records;
1137 if (var == NULL)
1138 break;
1140 vrp_hash_elt.var = var;
1141 vrp_hash_elt.records = NULL;
1143 slot = htab_find_slot (vrp_data, &vrp_hash_elt, NO_INSERT);
1145 vrp_hash_elt_p = (struct vrp_hash_elt *) *slot;
1146 var_vrp_records = &vrp_hash_elt_p->records;
1148 while (VEC_length (vrp_element_p, *var_vrp_records) > 0)
1150 struct vrp_element *element
1151 = VEC_last (vrp_element_p, *var_vrp_records);
1153 if (element->bb != bb)
1154 break;
1156 VEC_pop (vrp_element_p, *var_vrp_records);
1160 /* If we queued any statements to rescan in this block, then
1161 go ahead and rescan them now. */
1162 while (VEC_length (tree, stmts_to_rescan) > 0)
1164 tree stmt = VEC_last (tree, stmts_to_rescan);
1165 basic_block stmt_bb = bb_for_stmt (stmt);
1167 if (stmt_bb != bb)
1168 break;
1170 VEC_pop (tree, stmts_to_rescan);
1171 mark_new_vars_to_rename (stmt);
1175 /* PHI nodes can create equivalences too.
1177 Ignoring any alternatives which are the same as the result, if
1178 all the alternatives are equal, then the PHI node creates an
1179 equivalence.
1181 Additionally, if all the PHI alternatives are known to have a nonzero
1182 value, then the result of this PHI is known to have a nonzero value,
1183 even if we do not know its exact value. */
1185 static void
1186 record_equivalences_from_phis (basic_block bb)
1188 tree phi;
1190 for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
1192 tree lhs = PHI_RESULT (phi);
1193 tree rhs = NULL;
1194 int i;
1196 for (i = 0; i < PHI_NUM_ARGS (phi); i++)
1198 tree t = PHI_ARG_DEF (phi, i);
1200 /* Ignore alternatives which are the same as our LHS. Since
1201 LHS is a PHI_RESULT, it is known to be a SSA_NAME, so we
1202 can simply compare pointers. */
1203 if (lhs == t)
1204 continue;
1206 /* If we have not processed an alternative yet, then set
1207 RHS to this alternative. */
1208 if (rhs == NULL)
1209 rhs = t;
1210 /* If we have processed an alternative (stored in RHS), then
1211 see if it is equal to this one. If it isn't, then stop
1212 the search. */
1213 else if (! operand_equal_for_phi_arg_p (rhs, t))
1214 break;
1217 /* If we had no interesting alternatives, then all the RHS alternatives
1218 must have been the same as LHS. */
1219 if (!rhs)
1220 rhs = lhs;
1222 /* If we managed to iterate through each PHI alternative without
1223 breaking out of the loop, then we have a PHI which may create
1224 a useful equivalence. We do not need to record unwind data for
1225 this, since this is a true assignment and not an equivalence
1226 inferred from a comparison. All uses of this ssa name are dominated
1227 by this assignment, so unwinding just costs time and space. */
1228 if (i == PHI_NUM_ARGS (phi)
1229 && may_propagate_copy (lhs, rhs))
1230 SSA_NAME_VALUE (lhs) = rhs;
1232 /* Now see if we know anything about the nonzero property for the
1233 result of this PHI. */
1234 for (i = 0; i < PHI_NUM_ARGS (phi); i++)
1236 if (!PHI_ARG_NONZERO (phi, i))
1237 break;
1240 if (i == PHI_NUM_ARGS (phi))
1241 bitmap_set_bit (nonzero_vars, SSA_NAME_VERSION (PHI_RESULT (phi)));
1245 /* Ignoring loop backedges, if BB has precisely one incoming edge then
1246 return that edge. Otherwise return NULL. */
1247 static edge
1248 single_incoming_edge_ignoring_loop_edges (basic_block bb)
1250 edge retval = NULL;
1251 edge e;
1252 edge_iterator ei;
1254 FOR_EACH_EDGE (e, ei, bb->preds)
1256 /* A loop back edge can be identified by the destination of
1257 the edge dominating the source of the edge. */
1258 if (dominated_by_p (CDI_DOMINATORS, e->src, e->dest))
1259 continue;
1261 /* If we have already seen a non-loop edge, then we must have
1262 multiple incoming non-loop edges and thus we return NULL. */
1263 if (retval)
1264 return NULL;
1266 /* This is the first non-loop incoming edge we have found. Record
1267 it. */
1268 retval = e;
1271 return retval;
1274 /* Record any equivalences created by the incoming edge to BB. If BB
1275 has more than one incoming edge, then no equivalence is created. */
1277 static void
1278 record_equivalences_from_incoming_edge (basic_block bb)
1280 edge e;
1281 basic_block parent;
1282 struct edge_info *edge_info;
1284 /* If our parent block ended with a control statement, then we may be
1285 able to record some equivalences based on which outgoing edge from
1286 the parent was followed. */
1287 parent = get_immediate_dominator (CDI_DOMINATORS, bb);
1289 e = single_incoming_edge_ignoring_loop_edges (bb);
1291 /* If we had a single incoming edge from our parent block, then enter
1292 any data associated with the edge into our tables. */
1293 if (e && e->src == parent)
1295 unsigned int i;
1297 edge_info = e->aux;
1299 if (edge_info)
1301 tree lhs = edge_info->lhs;
1302 tree rhs = edge_info->rhs;
1303 tree *cond_equivalences = edge_info->cond_equivalences;
1305 if (lhs)
1306 record_equality (lhs, rhs);
1308 if (cond_equivalences)
1310 bool recorded_range = false;
1311 for (i = 0; i < edge_info->max_cond_equivalences; i += 2)
1313 tree expr = cond_equivalences[i];
1314 tree value = cond_equivalences[i + 1];
1316 record_cond (expr, value);
1318 /* For the first true equivalence, record range
1319 information. We only do this for the first
1320 true equivalence as it should dominate any
1321 later true equivalences. */
1322 if (! recorded_range
1323 && COMPARISON_CLASS_P (expr)
1324 && value == boolean_true_node
1325 && TREE_CONSTANT (TREE_OPERAND (expr, 1)))
1327 record_range (expr, bb);
1328 recorded_range = true;
1336 /* Dump SSA statistics on FILE. */
1338 void
1339 dump_dominator_optimization_stats (FILE *file)
1341 long n_exprs;
1343 fprintf (file, "Total number of statements: %6ld\n\n",
1344 opt_stats.num_stmts);
1345 fprintf (file, "Exprs considered for dominator optimizations: %6ld\n",
1346 opt_stats.num_exprs_considered);
1348 n_exprs = opt_stats.num_exprs_considered;
1349 if (n_exprs == 0)
1350 n_exprs = 1;
1352 fprintf (file, " Redundant expressions eliminated: %6ld (%.0f%%)\n",
1353 opt_stats.num_re, PERCENT (opt_stats.num_re,
1354 n_exprs));
1355 fprintf (file, " Constants propagated: %6ld\n",
1356 opt_stats.num_const_prop);
1357 fprintf (file, " Copies propagated: %6ld\n",
1358 opt_stats.num_copy_prop);
1360 fprintf (file, "\nTotal number of DOM iterations: %6ld\n",
1361 opt_stats.num_iterations);
1363 fprintf (file, "\nHash table statistics:\n");
1365 fprintf (file, " avail_exprs: ");
1366 htab_statistics (file, avail_exprs);
1370 /* Dump SSA statistics on stderr. */
1372 void
1373 debug_dominator_optimization_stats (void)
1375 dump_dominator_optimization_stats (stderr);
1379 /* Dump statistics for the hash table HTAB. */
1381 static void
1382 htab_statistics (FILE *file, htab_t htab)
1384 fprintf (file, "size %ld, %ld elements, %f collision/search ratio\n",
1385 (long) htab_size (htab),
1386 (long) htab_elements (htab),
1387 htab_collisions (htab));
1390 /* Record the fact that VAR has a nonzero value, though we may not know
1391 its exact value. Note that if VAR is already known to have a nonzero
1392 value, then we do nothing. */
1394 static void
1395 record_var_is_nonzero (tree var)
1397 int indx = SSA_NAME_VERSION (var);
1399 if (bitmap_bit_p (nonzero_vars, indx))
1400 return;
1402 /* Mark it in the global table. */
1403 bitmap_set_bit (nonzero_vars, indx);
1405 /* Record this SSA_NAME so that we can reset the global table
1406 when we leave this block. */
1407 VEC_safe_push (tree, heap, nonzero_vars_stack, var);
1410 /* Enter a statement into the true/false expression hash table indicating
1411 that the condition COND has the value VALUE. */
1413 static void
1414 record_cond (tree cond, tree value)
1416 struct expr_hash_elt *element = xmalloc (sizeof (struct expr_hash_elt));
1417 void **slot;
1419 initialize_hash_element (cond, value, element);
1421 slot = htab_find_slot_with_hash (avail_exprs, (void *)element,
1422 element->hash, INSERT);
1423 if (*slot == NULL)
1425 *slot = (void *) element;
1426 VEC_safe_push (tree, heap, avail_exprs_stack, cond);
1428 else
1429 free (element);
1432 /* Build a new conditional using NEW_CODE, OP0 and OP1 and store
1433 the new conditional into *p, then store a boolean_true_node
1434 into *(p + 1). */
1436 static void
1437 build_and_record_new_cond (enum tree_code new_code, tree op0, tree op1, tree *p)
1439 *p = build2 (new_code, boolean_type_node, op0, op1);
1440 p++;
1441 *p = boolean_true_node;
1444 /* Record that COND is true and INVERTED is false into the edge information
1445 structure. Also record that any conditions dominated by COND are true
1446 as well.
1448 For example, if a < b is true, then a <= b must also be true. */
1450 static void
1451 record_conditions (struct edge_info *edge_info, tree cond, tree inverted)
1453 tree op0, op1;
1455 if (!COMPARISON_CLASS_P (cond))
1456 return;
1458 op0 = TREE_OPERAND (cond, 0);
1459 op1 = TREE_OPERAND (cond, 1);
1461 switch (TREE_CODE (cond))
1463 case LT_EXPR:
1464 case GT_EXPR:
1465 edge_info->max_cond_equivalences = 12;
1466 edge_info->cond_equivalences = xmalloc (12 * sizeof (tree));
1467 build_and_record_new_cond ((TREE_CODE (cond) == LT_EXPR
1468 ? LE_EXPR : GE_EXPR),
1469 op0, op1, &edge_info->cond_equivalences[4]);
1470 build_and_record_new_cond (ORDERED_EXPR, op0, op1,
1471 &edge_info->cond_equivalences[6]);
1472 build_and_record_new_cond (NE_EXPR, op0, op1,
1473 &edge_info->cond_equivalences[8]);
1474 build_and_record_new_cond (LTGT_EXPR, op0, op1,
1475 &edge_info->cond_equivalences[10]);
1476 break;
1478 case GE_EXPR:
1479 case LE_EXPR:
1480 edge_info->max_cond_equivalences = 6;
1481 edge_info->cond_equivalences = xmalloc (6 * sizeof (tree));
1482 build_and_record_new_cond (ORDERED_EXPR, op0, op1,
1483 &edge_info->cond_equivalences[4]);
1484 break;
1486 case EQ_EXPR:
1487 edge_info->max_cond_equivalences = 10;
1488 edge_info->cond_equivalences = xmalloc (10 * sizeof (tree));
1489 build_and_record_new_cond (ORDERED_EXPR, op0, op1,
1490 &edge_info->cond_equivalences[4]);
1491 build_and_record_new_cond (LE_EXPR, op0, op1,
1492 &edge_info->cond_equivalences[6]);
1493 build_and_record_new_cond (GE_EXPR, op0, op1,
1494 &edge_info->cond_equivalences[8]);
1495 break;
1497 case UNORDERED_EXPR:
1498 edge_info->max_cond_equivalences = 16;
1499 edge_info->cond_equivalences = xmalloc (16 * sizeof (tree));
1500 build_and_record_new_cond (NE_EXPR, op0, op1,
1501 &edge_info->cond_equivalences[4]);
1502 build_and_record_new_cond (UNLE_EXPR, op0, op1,
1503 &edge_info->cond_equivalences[6]);
1504 build_and_record_new_cond (UNGE_EXPR, op0, op1,
1505 &edge_info->cond_equivalences[8]);
1506 build_and_record_new_cond (UNEQ_EXPR, op0, op1,
1507 &edge_info->cond_equivalences[10]);
1508 build_and_record_new_cond (UNLT_EXPR, op0, op1,
1509 &edge_info->cond_equivalences[12]);
1510 build_and_record_new_cond (UNGT_EXPR, op0, op1,
1511 &edge_info->cond_equivalences[14]);
1512 break;
1514 case UNLT_EXPR:
1515 case UNGT_EXPR:
1516 edge_info->max_cond_equivalences = 8;
1517 edge_info->cond_equivalences = xmalloc (8 * sizeof (tree));
1518 build_and_record_new_cond ((TREE_CODE (cond) == UNLT_EXPR
1519 ? UNLE_EXPR : UNGE_EXPR),
1520 op0, op1, &edge_info->cond_equivalences[4]);
1521 build_and_record_new_cond (NE_EXPR, op0, op1,
1522 &edge_info->cond_equivalences[6]);
1523 break;
1525 case UNEQ_EXPR:
1526 edge_info->max_cond_equivalences = 8;
1527 edge_info->cond_equivalences = xmalloc (8 * sizeof (tree));
1528 build_and_record_new_cond (UNLE_EXPR, op0, op1,
1529 &edge_info->cond_equivalences[4]);
1530 build_and_record_new_cond (UNGE_EXPR, op0, op1,
1531 &edge_info->cond_equivalences[6]);
1532 break;
1534 case LTGT_EXPR:
1535 edge_info->max_cond_equivalences = 8;
1536 edge_info->cond_equivalences = xmalloc (8 * sizeof (tree));
1537 build_and_record_new_cond (NE_EXPR, op0, op1,
1538 &edge_info->cond_equivalences[4]);
1539 build_and_record_new_cond (ORDERED_EXPR, op0, op1,
1540 &edge_info->cond_equivalences[6]);
1541 break;
1543 default:
1544 edge_info->max_cond_equivalences = 4;
1545 edge_info->cond_equivalences = xmalloc (4 * sizeof (tree));
1546 break;
1549 /* Now store the original true and false conditions into the first
1550 two slots. */
1551 edge_info->cond_equivalences[0] = cond;
1552 edge_info->cond_equivalences[1] = boolean_true_node;
1553 edge_info->cond_equivalences[2] = inverted;
1554 edge_info->cond_equivalences[3] = boolean_false_node;
1557 /* A helper function for record_const_or_copy and record_equality.
1558 Do the work of recording the value and undo info. */
1560 static void
1561 record_const_or_copy_1 (tree x, tree y, tree prev_x)
1563 SSA_NAME_VALUE (x) = y;
1565 VEC_reserve (tree, heap, const_and_copies_stack, 2);
1566 VEC_quick_push (tree, const_and_copies_stack, prev_x);
1567 VEC_quick_push (tree, const_and_copies_stack, x);
1571 /* Return the loop depth of the basic block of the defining statement of X.
1572 This number should not be treated as absolutely correct because the loop
1573 information may not be completely up-to-date when dom runs. However, it
1574 will be relatively correct, and as more passes are taught to keep loop info
1575 up to date, the result will become more and more accurate. */
1578 loop_depth_of_name (tree x)
1580 tree defstmt;
1581 basic_block defbb;
1583 /* If it's not an SSA_NAME, we have no clue where the definition is. */
1584 if (TREE_CODE (x) != SSA_NAME)
1585 return 0;
1587 /* Otherwise return the loop depth of the defining statement's bb.
1588 Note that there may not actually be a bb for this statement, if the
1589 ssa_name is live on entry. */
1590 defstmt = SSA_NAME_DEF_STMT (x);
1591 defbb = bb_for_stmt (defstmt);
1592 if (!defbb)
1593 return 0;
1595 return defbb->loop_depth;
1599 /* Record that X is equal to Y in const_and_copies. Record undo
1600 information in the block-local vector. */
1602 static void
1603 record_const_or_copy (tree x, tree y)
1605 tree prev_x = SSA_NAME_VALUE (x);
1607 if (TREE_CODE (y) == SSA_NAME)
1609 tree tmp = SSA_NAME_VALUE (y);
1610 if (tmp)
1611 y = tmp;
1614 record_const_or_copy_1 (x, y, prev_x);
1617 /* Similarly, but assume that X and Y are the two operands of an EQ_EXPR.
1618 This constrains the cases in which we may treat this as assignment. */
1620 static void
1621 record_equality (tree x, tree y)
1623 tree prev_x = NULL, prev_y = NULL;
1625 if (TREE_CODE (x) == SSA_NAME)
1626 prev_x = SSA_NAME_VALUE (x);
1627 if (TREE_CODE (y) == SSA_NAME)
1628 prev_y = SSA_NAME_VALUE (y);
1630 /* If one of the previous values is invariant, or invariant in more loops
1631 (by depth), then use that.
1632 Otherwise it doesn't matter which value we choose, just so
1633 long as we canonicalize on one value. */
1634 if (TREE_INVARIANT (y))
1636 else if (TREE_INVARIANT (x) || (loop_depth_of_name (x) <= loop_depth_of_name (y)))
1637 prev_x = x, x = y, y = prev_x, prev_x = prev_y;
1638 else if (prev_x && TREE_INVARIANT (prev_x))
1639 x = y, y = prev_x, prev_x = prev_y;
1640 else if (prev_y && TREE_CODE (prev_y) != VALUE_HANDLE)
1641 y = prev_y;
1643 /* After the swapping, we must have one SSA_NAME. */
1644 if (TREE_CODE (x) != SSA_NAME)
1645 return;
1647 /* For IEEE, -0.0 == 0.0, so we don't necessarily know the sign of a
1648 variable compared against zero. If we're honoring signed zeros,
1649 then we cannot record this value unless we know that the value is
1650 nonzero. */
1651 if (HONOR_SIGNED_ZEROS (TYPE_MODE (TREE_TYPE (x)))
1652 && (TREE_CODE (y) != REAL_CST
1653 || REAL_VALUES_EQUAL (dconst0, TREE_REAL_CST (y))))
1654 return;
1656 record_const_or_copy_1 (x, y, prev_x);
1659 /* Return true, if it is ok to do folding of an associative expression.
1660 EXP is the tree for the associative expression. */
1662 static inline bool
1663 unsafe_associative_fp_binop (tree exp)
1665 enum tree_code code = TREE_CODE (exp);
1666 return !(!flag_unsafe_math_optimizations
1667 && (code == MULT_EXPR || code == PLUS_EXPR
1668 || code == MINUS_EXPR)
1669 && FLOAT_TYPE_P (TREE_TYPE (exp)));
1672 /* Returns true when STMT is a simple iv increment. It detects the
1673 following situation:
1675 i_1 = phi (..., i_2)
1676 i_2 = i_1 +/- ... */
1678 static bool
1679 simple_iv_increment_p (tree stmt)
1681 tree lhs, rhs, preinc, phi;
1682 unsigned i;
1684 if (TREE_CODE (stmt) != MODIFY_EXPR)
1685 return false;
1687 lhs = TREE_OPERAND (stmt, 0);
1688 if (TREE_CODE (lhs) != SSA_NAME)
1689 return false;
1691 rhs = TREE_OPERAND (stmt, 1);
1693 if (TREE_CODE (rhs) != PLUS_EXPR
1694 && TREE_CODE (rhs) != MINUS_EXPR)
1695 return false;
1697 preinc = TREE_OPERAND (rhs, 0);
1698 if (TREE_CODE (preinc) != SSA_NAME)
1699 return false;
1701 phi = SSA_NAME_DEF_STMT (preinc);
1702 if (TREE_CODE (phi) != PHI_NODE)
1703 return false;
1705 for (i = 0; i < (unsigned) PHI_NUM_ARGS (phi); i++)
1706 if (PHI_ARG_DEF (phi, i) == lhs)
1707 return true;
1709 return false;
1712 /* STMT is a MODIFY_EXPR for which we were unable to find RHS in the
1713 hash tables. Try to simplify the RHS using whatever equivalences
1714 we may have recorded.
1716 If we are able to simplify the RHS, then lookup the simplified form in
1717 the hash table and return the result. Otherwise return NULL. */
1719 static tree
1720 simplify_rhs_and_lookup_avail_expr (tree stmt, int insert)
1722 tree rhs = TREE_OPERAND (stmt, 1);
1723 enum tree_code rhs_code = TREE_CODE (rhs);
1724 tree result = NULL;
1726 /* If we have lhs = ~x, look and see if we earlier had x = ~y.
1727 In which case we can change this statement to be lhs = y.
1728 Which can then be copy propagated.
1730 Similarly for negation. */
1731 if ((rhs_code == BIT_NOT_EXPR || rhs_code == NEGATE_EXPR)
1732 && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME)
1734 /* Get the definition statement for our RHS. */
1735 tree rhs_def_stmt = SSA_NAME_DEF_STMT (TREE_OPERAND (rhs, 0));
1737 /* See if the RHS_DEF_STMT has the same form as our statement. */
1738 if (TREE_CODE (rhs_def_stmt) == MODIFY_EXPR
1739 && TREE_CODE (TREE_OPERAND (rhs_def_stmt, 1)) == rhs_code)
1741 tree rhs_def_operand;
1743 rhs_def_operand = TREE_OPERAND (TREE_OPERAND (rhs_def_stmt, 1), 0);
1745 /* Verify that RHS_DEF_OPERAND is a suitable SSA variable. */
1746 if (TREE_CODE (rhs_def_operand) == SSA_NAME
1747 && ! SSA_NAME_OCCURS_IN_ABNORMAL_PHI (rhs_def_operand))
1748 result = update_rhs_and_lookup_avail_expr (stmt,
1749 rhs_def_operand,
1750 insert);
1754 /* If we have z = (x OP C1), see if we earlier had x = y OP C2.
1755 If OP is associative, create and fold (y OP C2) OP C1 which
1756 should result in (y OP C3), use that as the RHS for the
1757 assignment. Add minus to this, as we handle it specially below. */
1758 if ((associative_tree_code (rhs_code) || rhs_code == MINUS_EXPR)
1759 && TREE_CODE (TREE_OPERAND (rhs, 0)) == SSA_NAME
1760 && is_gimple_min_invariant (TREE_OPERAND (rhs, 1)))
1762 tree rhs_def_stmt = SSA_NAME_DEF_STMT (TREE_OPERAND (rhs, 0));
1764 /* If the statement defines an induction variable, do not propagate
1765 its value, so that we do not create overlapping life ranges. */
1766 if (simple_iv_increment_p (rhs_def_stmt))
1767 goto dont_fold_assoc;
1769 /* See if the RHS_DEF_STMT has the same form as our statement. */
1770 if (TREE_CODE (rhs_def_stmt) == MODIFY_EXPR)
1772 tree rhs_def_rhs = TREE_OPERAND (rhs_def_stmt, 1);
1773 enum tree_code rhs_def_code = TREE_CODE (rhs_def_rhs);
1775 if ((rhs_code == rhs_def_code && unsafe_associative_fp_binop (rhs))
1776 || (rhs_code == PLUS_EXPR && rhs_def_code == MINUS_EXPR)
1777 || (rhs_code == MINUS_EXPR && rhs_def_code == PLUS_EXPR))
1779 tree def_stmt_op0 = TREE_OPERAND (rhs_def_rhs, 0);
1780 tree def_stmt_op1 = TREE_OPERAND (rhs_def_rhs, 1);
1782 if (TREE_CODE (def_stmt_op0) == SSA_NAME
1783 && ! SSA_NAME_OCCURS_IN_ABNORMAL_PHI (def_stmt_op0)
1784 && is_gimple_min_invariant (def_stmt_op1))
1786 tree outer_const = TREE_OPERAND (rhs, 1);
1787 tree type = TREE_TYPE (TREE_OPERAND (stmt, 0));
1788 tree t;
1790 /* If we care about correct floating point results, then
1791 don't fold x + c1 - c2. Note that we need to take both
1792 the codes and the signs to figure this out. */
1793 if (FLOAT_TYPE_P (type)
1794 && !flag_unsafe_math_optimizations
1795 && (rhs_def_code == PLUS_EXPR
1796 || rhs_def_code == MINUS_EXPR))
1798 bool neg = false;
1800 neg ^= (rhs_code == MINUS_EXPR);
1801 neg ^= (rhs_def_code == MINUS_EXPR);
1802 neg ^= real_isneg (TREE_REAL_CST_PTR (outer_const));
1803 neg ^= real_isneg (TREE_REAL_CST_PTR (def_stmt_op1));
1805 if (neg)
1806 goto dont_fold_assoc;
1809 /* Ho hum. So fold will only operate on the outermost
1810 thingy that we give it, so we have to build the new
1811 expression in two pieces. This requires that we handle
1812 combinations of plus and minus. */
1813 if (rhs_def_code != rhs_code)
1815 if (rhs_def_code == MINUS_EXPR)
1816 t = build (MINUS_EXPR, type, outer_const, def_stmt_op1);
1817 else
1818 t = build (MINUS_EXPR, type, def_stmt_op1, outer_const);
1819 rhs_code = PLUS_EXPR;
1821 else if (rhs_def_code == MINUS_EXPR)
1822 t = build (PLUS_EXPR, type, def_stmt_op1, outer_const);
1823 else
1824 t = build (rhs_def_code, type, def_stmt_op1, outer_const);
1825 t = local_fold (t);
1826 t = build (rhs_code, type, def_stmt_op0, t);
1827 t = local_fold (t);
1829 /* If the result is a suitable looking gimple expression,
1830 then use it instead of the original for STMT. */
1831 if (TREE_CODE (t) == SSA_NAME
1832 || (UNARY_CLASS_P (t)
1833 && TREE_CODE (TREE_OPERAND (t, 0)) == SSA_NAME)
1834 || ((BINARY_CLASS_P (t) || COMPARISON_CLASS_P (t))
1835 && TREE_CODE (TREE_OPERAND (t, 0)) == SSA_NAME
1836 && is_gimple_val (TREE_OPERAND (t, 1))))
1837 result = update_rhs_and_lookup_avail_expr (stmt, t, insert);
1841 dont_fold_assoc:;
1844 /* Optimize *"foo" into 'f'. This is done here rather than
1845 in fold to avoid problems with stuff like &*"foo". */
1846 if (TREE_CODE (rhs) == INDIRECT_REF || TREE_CODE (rhs) == ARRAY_REF)
1848 tree t = fold_read_from_constant_string (rhs);
1850 if (t)
1851 result = update_rhs_and_lookup_avail_expr (stmt, t, insert);
1854 return result;
1857 /* COND is a condition of the form:
1859 x == const or x != const
1861 Look back to x's defining statement and see if x is defined as
1863 x = (type) y;
1865 If const is unchanged if we convert it to type, then we can build
1866 the equivalent expression:
1869 y == const or y != const
1871 Which may allow further optimizations.
1873 Return the equivalent comparison or NULL if no such equivalent comparison
1874 was found. */
1876 static tree
1877 find_equivalent_equality_comparison (tree cond)
1879 tree op0 = TREE_OPERAND (cond, 0);
1880 tree op1 = TREE_OPERAND (cond, 1);
1881 tree def_stmt = SSA_NAME_DEF_STMT (op0);
1883 /* OP0 might have been a parameter, so first make sure it
1884 was defined by a MODIFY_EXPR. */
1885 if (def_stmt && TREE_CODE (def_stmt) == MODIFY_EXPR)
1887 tree def_rhs = TREE_OPERAND (def_stmt, 1);
1890 /* If either operand to the comparison is a pointer to
1891 a function, then we can not apply this optimization
1892 as some targets require function pointers to be
1893 canonicalized and in this case this optimization would
1894 eliminate a necessary canonicalization. */
1895 if ((POINTER_TYPE_P (TREE_TYPE (op0))
1896 && TREE_CODE (TREE_TYPE (TREE_TYPE (op0))) == FUNCTION_TYPE)
1897 || (POINTER_TYPE_P (TREE_TYPE (op1))
1898 && TREE_CODE (TREE_TYPE (TREE_TYPE (op1))) == FUNCTION_TYPE))
1899 return NULL;
1901 /* Now make sure the RHS of the MODIFY_EXPR is a typecast. */
1902 if ((TREE_CODE (def_rhs) == NOP_EXPR
1903 || TREE_CODE (def_rhs) == CONVERT_EXPR)
1904 && TREE_CODE (TREE_OPERAND (def_rhs, 0)) == SSA_NAME)
1906 tree def_rhs_inner = TREE_OPERAND (def_rhs, 0);
1907 tree def_rhs_inner_type = TREE_TYPE (def_rhs_inner);
1908 tree new;
1910 if (TYPE_PRECISION (def_rhs_inner_type)
1911 > TYPE_PRECISION (TREE_TYPE (def_rhs)))
1912 return NULL;
1914 /* If the inner type of the conversion is a pointer to
1915 a function, then we can not apply this optimization
1916 as some targets require function pointers to be
1917 canonicalized. This optimization would result in
1918 canonicalization of the pointer when it was not originally
1919 needed/intended. */
1920 if (POINTER_TYPE_P (def_rhs_inner_type)
1921 && TREE_CODE (TREE_TYPE (def_rhs_inner_type)) == FUNCTION_TYPE)
1922 return NULL;
1924 /* What we want to prove is that if we convert OP1 to
1925 the type of the object inside the NOP_EXPR that the
1926 result is still equivalent to SRC.
1928 If that is true, the build and return new equivalent
1929 condition which uses the source of the typecast and the
1930 new constant (which has only changed its type). */
1931 new = build1 (TREE_CODE (def_rhs), def_rhs_inner_type, op1);
1932 new = local_fold (new);
1933 if (is_gimple_val (new) && tree_int_cst_equal (new, op1))
1934 return build (TREE_CODE (cond), TREE_TYPE (cond),
1935 def_rhs_inner, new);
1938 return NULL;
1941 /* STMT is a COND_EXPR for which we could not trivially determine its
1942 result. This routine attempts to find equivalent forms of the
1943 condition which we may be able to optimize better. It also
1944 uses simple value range propagation to optimize conditionals. */
1946 static tree
1947 simplify_cond_and_lookup_avail_expr (tree stmt,
1948 stmt_ann_t ann,
1949 int insert)
1951 tree cond = COND_EXPR_COND (stmt);
1953 if (COMPARISON_CLASS_P (cond))
1955 tree op0 = TREE_OPERAND (cond, 0);
1956 tree op1 = TREE_OPERAND (cond, 1);
1958 if (TREE_CODE (op0) == SSA_NAME && is_gimple_min_invariant (op1))
1960 int limit;
1961 tree low, high, cond_low, cond_high;
1962 int lowequal, highequal, swapped, no_overlap, subset, cond_inverted;
1963 VEC(vrp_element_p,heap) **vrp_records;
1964 struct vrp_element *element;
1965 struct vrp_hash_elt vrp_hash_elt, *vrp_hash_elt_p;
1966 void **slot;
1968 /* First see if we have test of an SSA_NAME against a constant
1969 where the SSA_NAME is defined by an earlier typecast which
1970 is irrelevant when performing tests against the given
1971 constant. */
1972 if (TREE_CODE (cond) == EQ_EXPR || TREE_CODE (cond) == NE_EXPR)
1974 tree new_cond = find_equivalent_equality_comparison (cond);
1976 if (new_cond)
1978 /* Update the statement to use the new equivalent
1979 condition. */
1980 COND_EXPR_COND (stmt) = new_cond;
1982 /* If this is not a real stmt, ann will be NULL and we
1983 avoid processing the operands. */
1984 if (ann)
1985 mark_stmt_modified (stmt);
1987 /* Lookup the condition and return its known value if it
1988 exists. */
1989 new_cond = lookup_avail_expr (stmt, insert);
1990 if (new_cond)
1991 return new_cond;
1993 /* The operands have changed, so update op0 and op1. */
1994 op0 = TREE_OPERAND (cond, 0);
1995 op1 = TREE_OPERAND (cond, 1);
1999 /* Consult the value range records for this variable (if they exist)
2000 to see if we can eliminate or simplify this conditional.
2002 Note two tests are necessary to determine no records exist.
2003 First we have to see if the virtual array exists, if it
2004 exists, then we have to check its active size.
2006 Also note the vast majority of conditionals are not testing
2007 a variable which has had its range constrained by an earlier
2008 conditional. So this filter avoids a lot of unnecessary work. */
2009 vrp_hash_elt.var = op0;
2010 vrp_hash_elt.records = NULL;
2011 slot = htab_find_slot (vrp_data, &vrp_hash_elt, NO_INSERT);
2012 if (slot == NULL)
2013 return NULL;
2015 vrp_hash_elt_p = (struct vrp_hash_elt *) *slot;
2016 vrp_records = &vrp_hash_elt_p->records;
2018 limit = VEC_length (vrp_element_p, *vrp_records);
2020 /* If we have no value range records for this variable, or we are
2021 unable to extract a range for this condition, then there is
2022 nothing to do. */
2023 if (limit == 0
2024 || ! extract_range_from_cond (cond, &cond_high,
2025 &cond_low, &cond_inverted))
2026 return NULL;
2028 /* We really want to avoid unnecessary computations of range
2029 info. So all ranges are computed lazily; this avoids a
2030 lot of unnecessary work. i.e., we record the conditional,
2031 but do not process how it constrains the variable's
2032 potential values until we know that processing the condition
2033 could be helpful.
2035 However, we do not want to have to walk a potentially long
2036 list of ranges, nor do we want to compute a variable's
2037 range more than once for a given path.
2039 Luckily, each time we encounter a conditional that can not
2040 be otherwise optimized we will end up here and we will
2041 compute the necessary range information for the variable
2042 used in this condition.
2044 Thus you can conclude that there will never be more than one
2045 conditional associated with a variable which has not been
2046 processed. So we never need to merge more than one new
2047 conditional into the current range.
2049 These properties also help us avoid unnecessary work. */
2050 element = VEC_last (vrp_element_p, *vrp_records);
2052 if (element->high && element->low)
2054 /* The last element has been processed, so there is no range
2055 merging to do, we can simply use the high/low values
2056 recorded in the last element. */
2057 low = element->low;
2058 high = element->high;
2060 else
2062 tree tmp_high, tmp_low;
2063 int dummy;
2065 /* The last element has not been processed. Process it now.
2066 record_range should ensure for cond inverted is not set.
2067 This call can only fail if cond is x < min or x > max,
2068 which fold should have optimized into false.
2069 If that doesn't happen, just pretend all values are
2070 in the range. */
2071 if (! extract_range_from_cond (element->cond, &tmp_high,
2072 &tmp_low, &dummy))
2073 gcc_unreachable ();
2074 else
2075 gcc_assert (dummy == 0);
2077 /* If this is the only element, then no merging is necessary,
2078 the high/low values from extract_range_from_cond are all
2079 we need. */
2080 if (limit == 1)
2082 low = tmp_low;
2083 high = tmp_high;
2085 else
2087 /* Get the high/low value from the previous element. */
2088 struct vrp_element *prev
2089 = VEC_index (vrp_element_p, *vrp_records, limit - 2);
2090 low = prev->low;
2091 high = prev->high;
2093 /* Merge in this element's range with the range from the
2094 previous element.
2096 The low value for the merged range is the maximum of
2097 the previous low value and the low value of this record.
2099 Similarly the high value for the merged range is the
2100 minimum of the previous high value and the high value of
2101 this record. */
2102 low = (low && tree_int_cst_compare (low, tmp_low) == 1
2103 ? low : tmp_low);
2104 high = (high && tree_int_cst_compare (high, tmp_high) == -1
2105 ? high : tmp_high);
2108 /* And record the computed range. */
2109 element->low = low;
2110 element->high = high;
2114 /* After we have constrained this variable's potential values,
2115 we try to determine the result of the given conditional.
2117 To simplify later tests, first determine if the current
2118 low value is the same low value as the conditional.
2119 Similarly for the current high value and the high value
2120 for the conditional. */
2121 lowequal = tree_int_cst_equal (low, cond_low);
2122 highequal = tree_int_cst_equal (high, cond_high);
2124 if (lowequal && highequal)
2125 return (cond_inverted ? boolean_false_node : boolean_true_node);
2127 /* To simplify the overlap/subset tests below we may want
2128 to swap the two ranges so that the larger of the two
2129 ranges occurs "first". */
2130 swapped = 0;
2131 if (tree_int_cst_compare (low, cond_low) == 1
2132 || (lowequal
2133 && tree_int_cst_compare (cond_high, high) == 1))
2135 tree temp;
2137 swapped = 1;
2138 temp = low;
2139 low = cond_low;
2140 cond_low = temp;
2141 temp = high;
2142 high = cond_high;
2143 cond_high = temp;
2146 /* Now determine if there is no overlap in the ranges
2147 or if the second range is a subset of the first range. */
2148 no_overlap = tree_int_cst_lt (high, cond_low);
2149 subset = tree_int_cst_compare (cond_high, high) != 1;
2151 /* If there was no overlap in the ranges, then this conditional
2152 always has a false value (unless we had to invert this
2153 conditional, in which case it always has a true value). */
2154 if (no_overlap)
2155 return (cond_inverted ? boolean_true_node : boolean_false_node);
2157 /* If the current range is a subset of the condition's range,
2158 then this conditional always has a true value (unless we
2159 had to invert this conditional, in which case it always
2160 has a true value). */
2161 if (subset && swapped)
2162 return (cond_inverted ? boolean_false_node : boolean_true_node);
2164 /* We were unable to determine the result of the conditional.
2165 However, we may be able to simplify the conditional. First
2166 merge the ranges in the same manner as range merging above. */
2167 low = tree_int_cst_compare (low, cond_low) == 1 ? low : cond_low;
2168 high = tree_int_cst_compare (high, cond_high) == -1 ? high : cond_high;
2170 /* If the range has converged to a single point, then turn this
2171 into an equality comparison. */
2172 if (TREE_CODE (cond) != EQ_EXPR
2173 && TREE_CODE (cond) != NE_EXPR
2174 && tree_int_cst_equal (low, high))
2176 TREE_SET_CODE (cond, EQ_EXPR);
2177 TREE_OPERAND (cond, 1) = high;
2181 return 0;
2184 /* STMT is a SWITCH_EXPR for which we could not trivially determine its
2185 result. This routine attempts to find equivalent forms of the
2186 condition which we may be able to optimize better. */
2188 static tree
2189 simplify_switch_and_lookup_avail_expr (tree stmt, int insert)
2191 tree cond = SWITCH_COND (stmt);
2192 tree def, to, ti;
2194 /* The optimization that we really care about is removing unnecessary
2195 casts. That will let us do much better in propagating the inferred
2196 constant at the switch target. */
2197 if (TREE_CODE (cond) == SSA_NAME)
2199 def = SSA_NAME_DEF_STMT (cond);
2200 if (TREE_CODE (def) == MODIFY_EXPR)
2202 def = TREE_OPERAND (def, 1);
2203 if (TREE_CODE (def) == NOP_EXPR)
2205 int need_precision;
2206 bool fail;
2208 def = TREE_OPERAND (def, 0);
2210 #ifdef ENABLE_CHECKING
2211 /* ??? Why was Jeff testing this? We are gimple... */
2212 gcc_assert (is_gimple_val (def));
2213 #endif
2215 to = TREE_TYPE (cond);
2216 ti = TREE_TYPE (def);
2218 /* If we have an extension that preserves value, then we
2219 can copy the source value into the switch. */
2221 need_precision = TYPE_PRECISION (ti);
2222 fail = false;
2223 if (TYPE_UNSIGNED (to) && !TYPE_UNSIGNED (ti))
2224 fail = true;
2225 else if (!TYPE_UNSIGNED (to) && TYPE_UNSIGNED (ti))
2226 need_precision += 1;
2227 if (TYPE_PRECISION (to) < need_precision)
2228 fail = true;
2230 if (!fail)
2232 SWITCH_COND (stmt) = def;
2233 mark_stmt_modified (stmt);
2235 return lookup_avail_expr (stmt, insert);
2241 return 0;
2245 /* CONST_AND_COPIES is a table which maps an SSA_NAME to the current
2246 known value for that SSA_NAME (or NULL if no value is known).
2248 NONZERO_VARS is the set SSA_NAMES known to have a nonzero value,
2249 even if we don't know their precise value.
2251 Propagate values from CONST_AND_COPIES and NONZERO_VARS into the PHI
2252 nodes of the successors of BB. */
2254 static void
2255 cprop_into_successor_phis (basic_block bb, bitmap nonzero_vars)
2257 edge e;
2258 edge_iterator ei;
2260 FOR_EACH_EDGE (e, ei, bb->succs)
2262 tree phi;
2263 int indx;
2265 /* If this is an abnormal edge, then we do not want to copy propagate
2266 into the PHI alternative associated with this edge. */
2267 if (e->flags & EDGE_ABNORMAL)
2268 continue;
2270 phi = phi_nodes (e->dest);
2271 if (! phi)
2272 continue;
2274 indx = e->dest_idx;
2275 for ( ; phi; phi = PHI_CHAIN (phi))
2277 tree new;
2278 use_operand_p orig_p;
2279 tree orig;
2281 /* The alternative may be associated with a constant, so verify
2282 it is an SSA_NAME before doing anything with it. */
2283 orig_p = PHI_ARG_DEF_PTR (phi, indx);
2284 orig = USE_FROM_PTR (orig_p);
2285 if (TREE_CODE (orig) != SSA_NAME)
2286 continue;
2288 /* If the alternative is known to have a nonzero value, record
2289 that fact in the PHI node itself for future use. */
2290 if (bitmap_bit_p (nonzero_vars, SSA_NAME_VERSION (orig)))
2291 PHI_ARG_NONZERO (phi, indx) = true;
2293 /* If we have *ORIG_P in our constant/copy table, then replace
2294 ORIG_P with its value in our constant/copy table. */
2295 new = SSA_NAME_VALUE (orig);
2296 if (new
2297 && new != orig
2298 && (TREE_CODE (new) == SSA_NAME
2299 || is_gimple_min_invariant (new))
2300 && may_propagate_copy (orig, new))
2301 propagate_value (orig_p, new);
2306 /* We have finished optimizing BB, record any information implied by
2307 taking a specific outgoing edge from BB. */
2309 static void
2310 record_edge_info (basic_block bb)
2312 block_stmt_iterator bsi = bsi_last (bb);
2313 struct edge_info *edge_info;
2315 if (! bsi_end_p (bsi))
2317 tree stmt = bsi_stmt (bsi);
2319 if (stmt && TREE_CODE (stmt) == SWITCH_EXPR)
2321 tree cond = SWITCH_COND (stmt);
2323 if (TREE_CODE (cond) == SSA_NAME)
2325 tree labels = SWITCH_LABELS (stmt);
2326 int i, n_labels = TREE_VEC_LENGTH (labels);
2327 tree *info = xcalloc (last_basic_block, sizeof (tree));
2328 edge e;
2329 edge_iterator ei;
2331 for (i = 0; i < n_labels; i++)
2333 tree label = TREE_VEC_ELT (labels, i);
2334 basic_block target_bb = label_to_block (CASE_LABEL (label));
2336 if (CASE_HIGH (label)
2337 || !CASE_LOW (label)
2338 || info[target_bb->index])
2339 info[target_bb->index] = error_mark_node;
2340 else
2341 info[target_bb->index] = label;
2344 FOR_EACH_EDGE (e, ei, bb->succs)
2346 basic_block target_bb = e->dest;
2347 tree node = info[target_bb->index];
2349 if (node != NULL && node != error_mark_node)
2351 tree x = fold_convert (TREE_TYPE (cond), CASE_LOW (node));
2352 edge_info = allocate_edge_info (e);
2353 edge_info->lhs = cond;
2354 edge_info->rhs = x;
2357 free (info);
2361 /* A COND_EXPR may create equivalences too. */
2362 if (stmt && TREE_CODE (stmt) == COND_EXPR)
2364 tree cond = COND_EXPR_COND (stmt);
2365 edge true_edge;
2366 edge false_edge;
2368 extract_true_false_edges_from_block (bb, &true_edge, &false_edge);
2370 /* If the conditional is a single variable 'X', record 'X = 1'
2371 for the true edge and 'X = 0' on the false edge. */
2372 if (SSA_VAR_P (cond))
2374 struct edge_info *edge_info;
2376 edge_info = allocate_edge_info (true_edge);
2377 edge_info->lhs = cond;
2378 edge_info->rhs = constant_boolean_node (1, TREE_TYPE (cond));
2380 edge_info = allocate_edge_info (false_edge);
2381 edge_info->lhs = cond;
2382 edge_info->rhs = constant_boolean_node (0, TREE_TYPE (cond));
2384 /* Equality tests may create one or two equivalences. */
2385 else if (COMPARISON_CLASS_P (cond))
2387 tree op0 = TREE_OPERAND (cond, 0);
2388 tree op1 = TREE_OPERAND (cond, 1);
2390 /* Special case comparing booleans against a constant as we
2391 know the value of OP0 on both arms of the branch. i.e., we
2392 can record an equivalence for OP0 rather than COND. */
2393 if ((TREE_CODE (cond) == EQ_EXPR || TREE_CODE (cond) == NE_EXPR)
2394 && TREE_CODE (op0) == SSA_NAME
2395 && TREE_CODE (TREE_TYPE (op0)) == BOOLEAN_TYPE
2396 && is_gimple_min_invariant (op1))
2398 if (TREE_CODE (cond) == EQ_EXPR)
2400 edge_info = allocate_edge_info (true_edge);
2401 edge_info->lhs = op0;
2402 edge_info->rhs = (integer_zerop (op1)
2403 ? boolean_false_node
2404 : boolean_true_node);
2406 edge_info = allocate_edge_info (false_edge);
2407 edge_info->lhs = op0;
2408 edge_info->rhs = (integer_zerop (op1)
2409 ? boolean_true_node
2410 : boolean_false_node);
2412 else
2414 edge_info = allocate_edge_info (true_edge);
2415 edge_info->lhs = op0;
2416 edge_info->rhs = (integer_zerop (op1)
2417 ? boolean_true_node
2418 : boolean_false_node);
2420 edge_info = allocate_edge_info (false_edge);
2421 edge_info->lhs = op0;
2422 edge_info->rhs = (integer_zerop (op1)
2423 ? boolean_false_node
2424 : boolean_true_node);
2428 else if (is_gimple_min_invariant (op0)
2429 && (TREE_CODE (op1) == SSA_NAME
2430 || is_gimple_min_invariant (op1)))
2432 tree inverted = invert_truthvalue (cond);
2433 struct edge_info *edge_info;
2435 edge_info = allocate_edge_info (true_edge);
2436 record_conditions (edge_info, cond, inverted);
2438 if (TREE_CODE (cond) == EQ_EXPR)
2440 edge_info->lhs = op1;
2441 edge_info->rhs = op0;
2444 edge_info = allocate_edge_info (false_edge);
2445 record_conditions (edge_info, inverted, cond);
2447 if (TREE_CODE (cond) == NE_EXPR)
2449 edge_info->lhs = op1;
2450 edge_info->rhs = op0;
2454 else if (TREE_CODE (op0) == SSA_NAME
2455 && (is_gimple_min_invariant (op1)
2456 || TREE_CODE (op1) == SSA_NAME))
2458 tree inverted = invert_truthvalue (cond);
2459 struct edge_info *edge_info;
2461 edge_info = allocate_edge_info (true_edge);
2462 record_conditions (edge_info, cond, inverted);
2464 if (TREE_CODE (cond) == EQ_EXPR)
2466 edge_info->lhs = op0;
2467 edge_info->rhs = op1;
2470 edge_info = allocate_edge_info (false_edge);
2471 record_conditions (edge_info, inverted, cond);
2473 if (TREE_CODE (cond) == NE_EXPR)
2475 edge_info->lhs = op0;
2476 edge_info->rhs = op1;
2481 /* ??? TRUTH_NOT_EXPR can create an equivalence too. */
2486 /* Propagate information from BB to its outgoing edges.
2488 This can include equivalency information implied by control statements
2489 at the end of BB and const/copy propagation into PHIs in BB's
2490 successor blocks. */
2492 static void
2493 propagate_to_outgoing_edges (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
2494 basic_block bb)
2496 record_edge_info (bb);
2497 cprop_into_successor_phis (bb, nonzero_vars);
2500 /* Search for redundant computations in STMT. If any are found, then
2501 replace them with the variable holding the result of the computation.
2503 If safe, record this expression into the available expression hash
2504 table. */
2506 static bool
2507 eliminate_redundant_computations (tree stmt, stmt_ann_t ann)
2509 tree *expr_p, def = NULL_TREE;
2510 bool insert = true;
2511 tree cached_lhs;
2512 bool retval = false;
2513 bool modify_expr_p = false;
2515 if (TREE_CODE (stmt) == MODIFY_EXPR)
2516 def = TREE_OPERAND (stmt, 0);
2518 /* Certain expressions on the RHS can be optimized away, but can not
2519 themselves be entered into the hash tables. */
2520 if (ann->makes_aliased_stores
2521 || ! def
2522 || TREE_CODE (def) != SSA_NAME
2523 || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (def)
2524 || !ZERO_SSA_OPERANDS (stmt, SSA_OP_VMAYDEF)
2525 /* Do not record equivalences for increments of ivs. This would create
2526 overlapping live ranges for a very questionable gain. */
2527 || simple_iv_increment_p (stmt))
2528 insert = false;
2530 /* Check if the expression has been computed before. */
2531 cached_lhs = lookup_avail_expr (stmt, insert);
2533 /* If this is an assignment and the RHS was not in the hash table,
2534 then try to simplify the RHS and lookup the new RHS in the
2535 hash table. */
2536 if (! cached_lhs && TREE_CODE (stmt) == MODIFY_EXPR)
2537 cached_lhs = simplify_rhs_and_lookup_avail_expr (stmt, insert);
2538 /* Similarly if this is a COND_EXPR and we did not find its
2539 expression in the hash table, simplify the condition and
2540 try again. */
2541 else if (! cached_lhs && TREE_CODE (stmt) == COND_EXPR)
2542 cached_lhs = simplify_cond_and_lookup_avail_expr (stmt, ann, insert);
2543 /* Similarly for a SWITCH_EXPR. */
2544 else if (!cached_lhs && TREE_CODE (stmt) == SWITCH_EXPR)
2545 cached_lhs = simplify_switch_and_lookup_avail_expr (stmt, insert);
2547 opt_stats.num_exprs_considered++;
2549 /* Get a pointer to the expression we are trying to optimize. */
2550 if (TREE_CODE (stmt) == COND_EXPR)
2551 expr_p = &COND_EXPR_COND (stmt);
2552 else if (TREE_CODE (stmt) == SWITCH_EXPR)
2553 expr_p = &SWITCH_COND (stmt);
2554 else if (TREE_CODE (stmt) == RETURN_EXPR && TREE_OPERAND (stmt, 0))
2556 expr_p = &TREE_OPERAND (TREE_OPERAND (stmt, 0), 1);
2557 modify_expr_p = true;
2559 else
2561 expr_p = &TREE_OPERAND (stmt, 1);
2562 modify_expr_p = true;
2565 /* It is safe to ignore types here since we have already done
2566 type checking in the hashing and equality routines. In fact
2567 type checking here merely gets in the way of constant
2568 propagation. Also, make sure that it is safe to propagate
2569 CACHED_LHS into *EXPR_P. */
2570 if (cached_lhs
2571 && ((TREE_CODE (cached_lhs) != SSA_NAME
2572 && (modify_expr_p
2573 || tree_ssa_useless_type_conversion_1 (TREE_TYPE (*expr_p),
2574 TREE_TYPE (cached_lhs))))
2575 || may_propagate_copy (*expr_p, cached_lhs)))
2577 if (dump_file && (dump_flags & TDF_DETAILS))
2579 fprintf (dump_file, " Replaced redundant expr '");
2580 print_generic_expr (dump_file, *expr_p, dump_flags);
2581 fprintf (dump_file, "' with '");
2582 print_generic_expr (dump_file, cached_lhs, dump_flags);
2583 fprintf (dump_file, "'\n");
2586 opt_stats.num_re++;
2588 #if defined ENABLE_CHECKING
2589 gcc_assert (TREE_CODE (cached_lhs) == SSA_NAME
2590 || is_gimple_min_invariant (cached_lhs));
2591 #endif
2593 if (TREE_CODE (cached_lhs) == ADDR_EXPR
2594 || (POINTER_TYPE_P (TREE_TYPE (*expr_p))
2595 && is_gimple_min_invariant (cached_lhs)))
2596 retval = true;
2598 if (modify_expr_p
2599 && !tree_ssa_useless_type_conversion_1 (TREE_TYPE (*expr_p),
2600 TREE_TYPE (cached_lhs)))
2601 cached_lhs = fold_convert (TREE_TYPE (*expr_p), cached_lhs);
2603 propagate_tree_value (expr_p, cached_lhs);
2604 mark_stmt_modified (stmt);
2606 return retval;
2609 /* STMT, a MODIFY_EXPR, may create certain equivalences, in either
2610 the available expressions table or the const_and_copies table.
2611 Detect and record those equivalences. */
2613 static void
2614 record_equivalences_from_stmt (tree stmt,
2615 int may_optimize_p,
2616 stmt_ann_t ann)
2618 tree lhs = TREE_OPERAND (stmt, 0);
2619 enum tree_code lhs_code = TREE_CODE (lhs);
2620 int i;
2622 if (lhs_code == SSA_NAME)
2624 tree rhs = TREE_OPERAND (stmt, 1);
2626 /* Strip away any useless type conversions. */
2627 STRIP_USELESS_TYPE_CONVERSION (rhs);
2629 /* If the RHS of the assignment is a constant or another variable that
2630 may be propagated, register it in the CONST_AND_COPIES table. We
2631 do not need to record unwind data for this, since this is a true
2632 assignment and not an equivalence inferred from a comparison. All
2633 uses of this ssa name are dominated by this assignment, so unwinding
2634 just costs time and space. */
2635 if (may_optimize_p
2636 && (TREE_CODE (rhs) == SSA_NAME
2637 || is_gimple_min_invariant (rhs)))
2638 SSA_NAME_VALUE (lhs) = rhs;
2640 if (tree_expr_nonzero_p (rhs))
2641 record_var_is_nonzero (lhs);
2644 /* Look at both sides for pointer dereferences. If we find one, then
2645 the pointer must be nonnull and we can enter that equivalence into
2646 the hash tables. */
2647 if (flag_delete_null_pointer_checks)
2648 for (i = 0; i < 2; i++)
2650 tree t = TREE_OPERAND (stmt, i);
2652 /* Strip away any COMPONENT_REFs. */
2653 while (TREE_CODE (t) == COMPONENT_REF)
2654 t = TREE_OPERAND (t, 0);
2656 /* Now see if this is a pointer dereference. */
2657 if (INDIRECT_REF_P (t))
2659 tree op = TREE_OPERAND (t, 0);
2661 /* If the pointer is a SSA variable, then enter new
2662 equivalences into the hash table. */
2663 while (TREE_CODE (op) == SSA_NAME)
2665 tree def = SSA_NAME_DEF_STMT (op);
2667 record_var_is_nonzero (op);
2669 /* And walk up the USE-DEF chains noting other SSA_NAMEs
2670 which are known to have a nonzero value. */
2671 if (def
2672 && TREE_CODE (def) == MODIFY_EXPR
2673 && TREE_CODE (TREE_OPERAND (def, 1)) == NOP_EXPR)
2674 op = TREE_OPERAND (TREE_OPERAND (def, 1), 0);
2675 else
2676 break;
2681 /* A memory store, even an aliased store, creates a useful
2682 equivalence. By exchanging the LHS and RHS, creating suitable
2683 vops and recording the result in the available expression table,
2684 we may be able to expose more redundant loads. */
2685 if (!ann->has_volatile_ops
2686 && (TREE_CODE (TREE_OPERAND (stmt, 1)) == SSA_NAME
2687 || is_gimple_min_invariant (TREE_OPERAND (stmt, 1)))
2688 && !is_gimple_reg (lhs))
2690 tree rhs = TREE_OPERAND (stmt, 1);
2691 tree new;
2693 /* FIXME: If the LHS of the assignment is a bitfield and the RHS
2694 is a constant, we need to adjust the constant to fit into the
2695 type of the LHS. If the LHS is a bitfield and the RHS is not
2696 a constant, then we can not record any equivalences for this
2697 statement since we would need to represent the widening or
2698 narrowing of RHS. This fixes gcc.c-torture/execute/921016-1.c
2699 and should not be necessary if GCC represented bitfields
2700 properly. */
2701 if (lhs_code == COMPONENT_REF
2702 && DECL_BIT_FIELD (TREE_OPERAND (lhs, 1)))
2704 if (TREE_CONSTANT (rhs))
2705 rhs = widen_bitfield (rhs, TREE_OPERAND (lhs, 1), lhs);
2706 else
2707 rhs = NULL;
2709 /* If the value overflowed, then we can not use this equivalence. */
2710 if (rhs && ! is_gimple_min_invariant (rhs))
2711 rhs = NULL;
2714 if (rhs)
2716 /* Build a new statement with the RHS and LHS exchanged. */
2717 new = build (MODIFY_EXPR, TREE_TYPE (stmt), rhs, lhs);
2719 create_ssa_artficial_load_stmt (new, stmt);
2721 /* Finally enter the statement into the available expression
2722 table. */
2723 lookup_avail_expr (new, true);
2728 /* Replace *OP_P in STMT with any known equivalent value for *OP_P from
2729 CONST_AND_COPIES. */
2731 static bool
2732 cprop_operand (tree stmt, use_operand_p op_p)
2734 bool may_have_exposed_new_symbols = false;
2735 tree val;
2736 tree op = USE_FROM_PTR (op_p);
2738 /* If the operand has a known constant value or it is known to be a
2739 copy of some other variable, use the value or copy stored in
2740 CONST_AND_COPIES. */
2741 val = SSA_NAME_VALUE (op);
2742 if (val && val != op && TREE_CODE (val) != VALUE_HANDLE)
2744 tree op_type, val_type;
2746 /* Do not change the base variable in the virtual operand
2747 tables. That would make it impossible to reconstruct
2748 the renamed virtual operand if we later modify this
2749 statement. Also only allow the new value to be an SSA_NAME
2750 for propagation into virtual operands. */
2751 if (!is_gimple_reg (op)
2752 && (TREE_CODE (val) != SSA_NAME
2753 || is_gimple_reg (val)
2754 || get_virtual_var (val) != get_virtual_var (op)))
2755 return false;
2757 /* Do not replace hard register operands in asm statements. */
2758 if (TREE_CODE (stmt) == ASM_EXPR
2759 && !may_propagate_copy_into_asm (op))
2760 return false;
2762 /* Get the toplevel type of each operand. */
2763 op_type = TREE_TYPE (op);
2764 val_type = TREE_TYPE (val);
2766 /* While both types are pointers, get the type of the object
2767 pointed to. */
2768 while (POINTER_TYPE_P (op_type) && POINTER_TYPE_P (val_type))
2770 op_type = TREE_TYPE (op_type);
2771 val_type = TREE_TYPE (val_type);
2774 /* Make sure underlying types match before propagating a constant by
2775 converting the constant to the proper type. Note that convert may
2776 return a non-gimple expression, in which case we ignore this
2777 propagation opportunity. */
2778 if (TREE_CODE (val) != SSA_NAME)
2780 if (!lang_hooks.types_compatible_p (op_type, val_type))
2782 val = fold_convert (TREE_TYPE (op), val);
2783 if (!is_gimple_min_invariant (val))
2784 return false;
2788 /* Certain operands are not allowed to be copy propagated due
2789 to their interaction with exception handling and some GCC
2790 extensions. */
2791 else if (!may_propagate_copy (op, val))
2792 return false;
2794 /* Do not propagate copies if the propagated value is at a deeper loop
2795 depth than the propagatee. Otherwise, this may move loop variant
2796 variables outside of their loops and prevent coalescing
2797 opportunities. If the value was loop invariant, it will be hoisted
2798 by LICM and exposed for copy propagation. */
2799 if (loop_depth_of_name (val) > loop_depth_of_name (op))
2800 return false;
2802 /* Dump details. */
2803 if (dump_file && (dump_flags & TDF_DETAILS))
2805 fprintf (dump_file, " Replaced '");
2806 print_generic_expr (dump_file, op, dump_flags);
2807 fprintf (dump_file, "' with %s '",
2808 (TREE_CODE (val) != SSA_NAME ? "constant" : "variable"));
2809 print_generic_expr (dump_file, val, dump_flags);
2810 fprintf (dump_file, "'\n");
2813 /* If VAL is an ADDR_EXPR or a constant of pointer type, note
2814 that we may have exposed a new symbol for SSA renaming. */
2815 if (TREE_CODE (val) == ADDR_EXPR
2816 || (POINTER_TYPE_P (TREE_TYPE (op))
2817 && is_gimple_min_invariant (val)))
2818 may_have_exposed_new_symbols = true;
2820 if (TREE_CODE (val) != SSA_NAME)
2821 opt_stats.num_const_prop++;
2822 else
2823 opt_stats.num_copy_prop++;
2825 propagate_value (op_p, val);
2827 /* And note that we modified this statement. This is now
2828 safe, even if we changed virtual operands since we will
2829 rescan the statement and rewrite its operands again. */
2830 mark_stmt_modified (stmt);
2832 return may_have_exposed_new_symbols;
2835 /* CONST_AND_COPIES is a table which maps an SSA_NAME to the current
2836 known value for that SSA_NAME (or NULL if no value is known).
2838 Propagate values from CONST_AND_COPIES into the uses, vuses and
2839 v_may_def_ops of STMT. */
2841 static bool
2842 cprop_into_stmt (tree stmt)
2844 bool may_have_exposed_new_symbols = false;
2845 use_operand_p op_p;
2846 ssa_op_iter iter;
2848 FOR_EACH_SSA_USE_OPERAND (op_p, stmt, iter, SSA_OP_ALL_USES)
2850 if (TREE_CODE (USE_FROM_PTR (op_p)) == SSA_NAME)
2851 may_have_exposed_new_symbols |= cprop_operand (stmt, op_p);
2854 return may_have_exposed_new_symbols;
2858 /* Optimize the statement pointed to by iterator SI.
2860 We try to perform some simplistic global redundancy elimination and
2861 constant propagation:
2863 1- To detect global redundancy, we keep track of expressions that have
2864 been computed in this block and its dominators. If we find that the
2865 same expression is computed more than once, we eliminate repeated
2866 computations by using the target of the first one.
2868 2- Constant values and copy assignments. This is used to do very
2869 simplistic constant and copy propagation. When a constant or copy
2870 assignment is found, we map the value on the RHS of the assignment to
2871 the variable in the LHS in the CONST_AND_COPIES table. */
2873 static void
2874 optimize_stmt (struct dom_walk_data *walk_data ATTRIBUTE_UNUSED,
2875 basic_block bb, block_stmt_iterator si)
2877 stmt_ann_t ann;
2878 tree stmt, old_stmt;
2879 bool may_optimize_p;
2880 bool may_have_exposed_new_symbols = false;
2882 old_stmt = stmt = bsi_stmt (si);
2884 update_stmt_if_modified (stmt);
2885 ann = stmt_ann (stmt);
2886 opt_stats.num_stmts++;
2887 may_have_exposed_new_symbols = false;
2889 if (dump_file && (dump_flags & TDF_DETAILS))
2891 fprintf (dump_file, "Optimizing statement ");
2892 print_generic_stmt (dump_file, stmt, TDF_SLIM);
2895 /* Const/copy propagate into USES, VUSES and the RHS of V_MAY_DEFs. */
2896 may_have_exposed_new_symbols = cprop_into_stmt (stmt);
2898 /* If the statement has been modified with constant replacements,
2899 fold its RHS before checking for redundant computations. */
2900 if (ann->modified)
2902 tree rhs;
2904 /* Try to fold the statement making sure that STMT is kept
2905 up to date. */
2906 if (fold_stmt (bsi_stmt_ptr (si)))
2908 stmt = bsi_stmt (si);
2909 ann = stmt_ann (stmt);
2911 if (dump_file && (dump_flags & TDF_DETAILS))
2913 fprintf (dump_file, " Folded to: ");
2914 print_generic_stmt (dump_file, stmt, TDF_SLIM);
2918 rhs = get_rhs (stmt);
2919 if (rhs && TREE_CODE (rhs) == ADDR_EXPR)
2920 recompute_tree_invarant_for_addr_expr (rhs);
2922 /* Constant/copy propagation above may change the set of
2923 virtual operands associated with this statement. Folding
2924 may remove the need for some virtual operands.
2926 Indicate we will need to rescan and rewrite the statement. */
2927 may_have_exposed_new_symbols = true;
2930 /* Check for redundant computations. Do this optimization only
2931 for assignments that have no volatile ops and conditionals. */
2932 may_optimize_p = (!ann->has_volatile_ops
2933 && ((TREE_CODE (stmt) == RETURN_EXPR
2934 && TREE_OPERAND (stmt, 0)
2935 && TREE_CODE (TREE_OPERAND (stmt, 0)) == MODIFY_EXPR
2936 && ! (TREE_SIDE_EFFECTS
2937 (TREE_OPERAND (TREE_OPERAND (stmt, 0), 1))))
2938 || (TREE_CODE (stmt) == MODIFY_EXPR
2939 && ! TREE_SIDE_EFFECTS (TREE_OPERAND (stmt, 1)))
2940 || TREE_CODE (stmt) == COND_EXPR
2941 || TREE_CODE (stmt) == SWITCH_EXPR));
2943 if (may_optimize_p)
2944 may_have_exposed_new_symbols
2945 |= eliminate_redundant_computations (stmt, ann);
2947 /* Record any additional equivalences created by this statement. */
2948 if (TREE_CODE (stmt) == MODIFY_EXPR)
2949 record_equivalences_from_stmt (stmt,
2950 may_optimize_p,
2951 ann);
2953 /* If STMT is a COND_EXPR and it was modified, then we may know
2954 where it goes. If that is the case, then mark the CFG as altered.
2956 This will cause us to later call remove_unreachable_blocks and
2957 cleanup_tree_cfg when it is safe to do so. It is not safe to
2958 clean things up here since removal of edges and such can trigger
2959 the removal of PHI nodes, which in turn can release SSA_NAMEs to
2960 the manager.
2962 That's all fine and good, except that once SSA_NAMEs are released
2963 to the manager, we must not call create_ssa_name until all references
2964 to released SSA_NAMEs have been eliminated.
2966 All references to the deleted SSA_NAMEs can not be eliminated until
2967 we remove unreachable blocks.
2969 We can not remove unreachable blocks until after we have completed
2970 any queued jump threading.
2972 We can not complete any queued jump threads until we have taken
2973 appropriate variables out of SSA form. Taking variables out of
2974 SSA form can call create_ssa_name and thus we lose.
2976 Ultimately I suspect we're going to need to change the interface
2977 into the SSA_NAME manager. */
2979 if (ann->modified)
2981 tree val = NULL;
2983 if (TREE_CODE (stmt) == COND_EXPR)
2984 val = COND_EXPR_COND (stmt);
2985 else if (TREE_CODE (stmt) == SWITCH_EXPR)
2986 val = SWITCH_COND (stmt);
2988 if (val && TREE_CODE (val) == INTEGER_CST && find_taken_edge (bb, val))
2989 cfg_altered = true;
2991 /* If we simplified a statement in such a way as to be shown that it
2992 cannot trap, update the eh information and the cfg to match. */
2993 if (maybe_clean_or_replace_eh_stmt (old_stmt, stmt))
2995 bitmap_set_bit (need_eh_cleanup, bb->index);
2996 if (dump_file && (dump_flags & TDF_DETAILS))
2997 fprintf (dump_file, " Flagged to clear EH edges.\n");
3001 if (may_have_exposed_new_symbols)
3002 VEC_safe_push (tree, heap, stmts_to_rescan, bsi_stmt (si));
3005 /* Replace the RHS of STMT with NEW_RHS. If RHS can be found in the
3006 available expression hashtable, then return the LHS from the hash
3007 table.
3009 If INSERT is true, then we also update the available expression
3010 hash table to account for the changes made to STMT. */
3012 static tree
3013 update_rhs_and_lookup_avail_expr (tree stmt, tree new_rhs, bool insert)
3015 tree cached_lhs = NULL;
3017 /* Remove the old entry from the hash table. */
3018 if (insert)
3020 struct expr_hash_elt element;
3022 initialize_hash_element (stmt, NULL, &element);
3023 htab_remove_elt_with_hash (avail_exprs, &element, element.hash);
3026 /* Now update the RHS of the assignment. */
3027 TREE_OPERAND (stmt, 1) = new_rhs;
3029 /* Now lookup the updated statement in the hash table. */
3030 cached_lhs = lookup_avail_expr (stmt, insert);
3032 /* We have now called lookup_avail_expr twice with two different
3033 versions of this same statement, once in optimize_stmt, once here.
3035 We know the call in optimize_stmt did not find an existing entry
3036 in the hash table, so a new entry was created. At the same time
3037 this statement was pushed onto the AVAIL_EXPRS_STACK vector.
3039 If this call failed to find an existing entry on the hash table,
3040 then the new version of this statement was entered into the
3041 hash table. And this statement was pushed onto BLOCK_AVAIL_EXPR
3042 for the second time. So there are two copies on BLOCK_AVAIL_EXPRs
3044 If this call succeeded, we still have one copy of this statement
3045 on the BLOCK_AVAIL_EXPRs vector.
3047 For both cases, we need to pop the most recent entry off the
3048 BLOCK_AVAIL_EXPRs vector. For the case where we never found this
3049 statement in the hash tables, that will leave precisely one
3050 copy of this statement on BLOCK_AVAIL_EXPRs. For the case where
3051 we found a copy of this statement in the second hash table lookup
3052 we want _no_ copies of this statement in BLOCK_AVAIL_EXPRs. */
3053 if (insert)
3054 VEC_pop (tree, avail_exprs_stack);
3056 /* And make sure we record the fact that we modified this
3057 statement. */
3058 mark_stmt_modified (stmt);
3060 return cached_lhs;
3063 /* Search for an existing instance of STMT in the AVAIL_EXPRS table. If
3064 found, return its LHS. Otherwise insert STMT in the table and return
3065 NULL_TREE.
3067 Also, when an expression is first inserted in the AVAIL_EXPRS table, it
3068 is also added to the stack pointed to by BLOCK_AVAIL_EXPRS_P, so that they
3069 can be removed when we finish processing this block and its children.
3071 NOTE: This function assumes that STMT is a MODIFY_EXPR node that
3072 contains no CALL_EXPR on its RHS and makes no volatile nor
3073 aliased references. */
3075 static tree
3076 lookup_avail_expr (tree stmt, bool insert)
3078 void **slot;
3079 tree lhs;
3080 tree temp;
3081 struct expr_hash_elt *element = xmalloc (sizeof (struct expr_hash_elt));
3083 lhs = TREE_CODE (stmt) == MODIFY_EXPR ? TREE_OPERAND (stmt, 0) : NULL;
3085 initialize_hash_element (stmt, lhs, element);
3087 /* Don't bother remembering constant assignments and copy operations.
3088 Constants and copy operations are handled by the constant/copy propagator
3089 in optimize_stmt. */
3090 if (TREE_CODE (element->rhs) == SSA_NAME
3091 || is_gimple_min_invariant (element->rhs))
3093 free (element);
3094 return NULL_TREE;
3097 /* If this is an equality test against zero, see if we have recorded a
3098 nonzero value for the variable in question. */
3099 if ((TREE_CODE (element->rhs) == EQ_EXPR
3100 || TREE_CODE (element->rhs) == NE_EXPR)
3101 && TREE_CODE (TREE_OPERAND (element->rhs, 0)) == SSA_NAME
3102 && integer_zerop (TREE_OPERAND (element->rhs, 1)))
3104 int indx = SSA_NAME_VERSION (TREE_OPERAND (element->rhs, 0));
3106 if (bitmap_bit_p (nonzero_vars, indx))
3108 tree t = element->rhs;
3109 free (element);
3110 return constant_boolean_node (TREE_CODE (t) != EQ_EXPR,
3111 TREE_TYPE (t));
3115 /* Finally try to find the expression in the main expression hash table. */
3116 slot = htab_find_slot_with_hash (avail_exprs, element, element->hash,
3117 (insert ? INSERT : NO_INSERT));
3118 if (slot == NULL)
3120 free (element);
3121 return NULL_TREE;
3124 if (*slot == NULL)
3126 *slot = (void *) element;
3127 VEC_safe_push (tree, heap, avail_exprs_stack,
3128 stmt ? stmt : element->rhs);
3129 return NULL_TREE;
3132 /* Extract the LHS of the assignment so that it can be used as the current
3133 definition of another variable. */
3134 lhs = ((struct expr_hash_elt *)*slot)->lhs;
3136 /* See if the LHS appears in the CONST_AND_COPIES table. If it does, then
3137 use the value from the const_and_copies table. */
3138 if (TREE_CODE (lhs) == SSA_NAME)
3140 temp = SSA_NAME_VALUE (lhs);
3141 if (temp && TREE_CODE (temp) != VALUE_HANDLE)
3142 lhs = temp;
3145 free (element);
3146 return lhs;
3149 /* Given a condition COND, record into HI_P, LO_P and INVERTED_P the
3150 range of values that result in the conditional having a true value.
3152 Return true if we are successful in extracting a range from COND and
3153 false if we are unsuccessful. */
3155 static bool
3156 extract_range_from_cond (tree cond, tree *hi_p, tree *lo_p, int *inverted_p)
3158 tree op1 = TREE_OPERAND (cond, 1);
3159 tree high, low, type;
3160 int inverted;
3162 type = TREE_TYPE (op1);
3164 /* Experiments have shown that it's rarely, if ever useful to
3165 record ranges for enumerations. Presumably this is due to
3166 the fact that they're rarely used directly. They are typically
3167 cast into an integer type and used that way. */
3168 if (TREE_CODE (type) != INTEGER_TYPE
3169 /* We don't know how to deal with types with variable bounds. */
3170 || TREE_CODE (TYPE_MIN_VALUE (type)) != INTEGER_CST
3171 || TREE_CODE (TYPE_MAX_VALUE (type)) != INTEGER_CST)
3172 return 0;
3174 switch (TREE_CODE (cond))
3176 case EQ_EXPR:
3177 high = low = op1;
3178 inverted = 0;
3179 break;
3181 case NE_EXPR:
3182 high = low = op1;
3183 inverted = 1;
3184 break;
3186 case GE_EXPR:
3187 low = op1;
3188 high = TYPE_MAX_VALUE (type);
3189 inverted = 0;
3190 break;
3192 case GT_EXPR:
3193 high = TYPE_MAX_VALUE (type);
3194 if (!tree_int_cst_lt (op1, high))
3195 return 0;
3196 low = int_const_binop (PLUS_EXPR, op1, integer_one_node, 1);
3197 inverted = 0;
3198 break;
3200 case LE_EXPR:
3201 high = op1;
3202 low = TYPE_MIN_VALUE (type);
3203 inverted = 0;
3204 break;
3206 case LT_EXPR:
3207 low = TYPE_MIN_VALUE (type);
3208 if (!tree_int_cst_lt (low, op1))
3209 return 0;
3210 high = int_const_binop (MINUS_EXPR, op1, integer_one_node, 1);
3211 inverted = 0;
3212 break;
3214 default:
3215 return 0;
3218 *hi_p = high;
3219 *lo_p = low;
3220 *inverted_p = inverted;
3221 return 1;
3224 /* Record a range created by COND for basic block BB. */
3226 static void
3227 record_range (tree cond, basic_block bb)
3229 enum tree_code code = TREE_CODE (cond);
3231 /* We explicitly ignore NE_EXPRs and all the unordered comparisons.
3232 They rarely allow for meaningful range optimizations and significantly
3233 complicate the implementation. */
3234 if ((code == LT_EXPR || code == LE_EXPR || code == GT_EXPR
3235 || code == GE_EXPR || code == EQ_EXPR)
3236 && TREE_CODE (TREE_TYPE (TREE_OPERAND (cond, 1))) == INTEGER_TYPE)
3238 struct vrp_hash_elt *vrp_hash_elt;
3239 struct vrp_element *element;
3240 VEC(vrp_element_p,heap) **vrp_records_p;
3241 void **slot;
3244 vrp_hash_elt = xmalloc (sizeof (struct vrp_hash_elt));
3245 vrp_hash_elt->var = TREE_OPERAND (cond, 0);
3246 vrp_hash_elt->records = NULL;
3247 slot = htab_find_slot (vrp_data, vrp_hash_elt, INSERT);
3249 if (*slot == NULL)
3250 *slot = (void *) vrp_hash_elt;
3251 else
3252 vrp_free (vrp_hash_elt);
3254 vrp_hash_elt = (struct vrp_hash_elt *) *slot;
3255 vrp_records_p = &vrp_hash_elt->records;
3257 element = ggc_alloc (sizeof (struct vrp_element));
3258 element->low = NULL;
3259 element->high = NULL;
3260 element->cond = cond;
3261 element->bb = bb;
3263 VEC_safe_push (vrp_element_p, heap, *vrp_records_p, element);
3264 VEC_safe_push (tree, heap, vrp_variables_stack, TREE_OPERAND (cond, 0));
3268 /* Hashing and equality functions for VRP_DATA.
3270 Since this hash table is addressed by SSA_NAMEs, we can hash on
3271 their version number and equality can be determined with a
3272 pointer comparison. */
3274 static hashval_t
3275 vrp_hash (const void *p)
3277 tree var = ((struct vrp_hash_elt *)p)->var;
3279 return SSA_NAME_VERSION (var);
3282 static int
3283 vrp_eq (const void *p1, const void *p2)
3285 tree var1 = ((struct vrp_hash_elt *)p1)->var;
3286 tree var2 = ((struct vrp_hash_elt *)p2)->var;
3288 return var1 == var2;
3291 /* Hashing and equality functions for AVAIL_EXPRS. The table stores
3292 MODIFY_EXPR statements. We compute a value number for expressions using
3293 the code of the expression and the SSA numbers of its operands. */
3295 static hashval_t
3296 avail_expr_hash (const void *p)
3298 tree stmt = ((struct expr_hash_elt *)p)->stmt;
3299 tree rhs = ((struct expr_hash_elt *)p)->rhs;
3300 tree vuse;
3301 ssa_op_iter iter;
3302 hashval_t val = 0;
3304 /* iterative_hash_expr knows how to deal with any expression and
3305 deals with commutative operators as well, so just use it instead
3306 of duplicating such complexities here. */
3307 val = iterative_hash_expr (rhs, val);
3309 /* If the hash table entry is not associated with a statement, then we
3310 can just hash the expression and not worry about virtual operands
3311 and such. */
3312 if (!stmt || !stmt_ann (stmt))
3313 return val;
3315 /* Add the SSA version numbers of every vuse operand. This is important
3316 because compound variables like arrays are not renamed in the
3317 operands. Rather, the rename is done on the virtual variable
3318 representing all the elements of the array. */
3319 FOR_EACH_SSA_TREE_OPERAND (vuse, stmt, iter, SSA_OP_VUSE)
3320 val = iterative_hash_expr (vuse, val);
3322 return val;
3325 static hashval_t
3326 real_avail_expr_hash (const void *p)
3328 return ((const struct expr_hash_elt *)p)->hash;
3331 static int
3332 avail_expr_eq (const void *p1, const void *p2)
3334 tree stmt1 = ((struct expr_hash_elt *)p1)->stmt;
3335 tree rhs1 = ((struct expr_hash_elt *)p1)->rhs;
3336 tree stmt2 = ((struct expr_hash_elt *)p2)->stmt;
3337 tree rhs2 = ((struct expr_hash_elt *)p2)->rhs;
3339 /* If they are the same physical expression, return true. */
3340 if (rhs1 == rhs2 && stmt1 == stmt2)
3341 return true;
3343 /* If their codes are not equal, then quit now. */
3344 if (TREE_CODE (rhs1) != TREE_CODE (rhs2))
3345 return false;
3347 /* In case of a collision, both RHS have to be identical and have the
3348 same VUSE operands. */
3349 if ((TREE_TYPE (rhs1) == TREE_TYPE (rhs2)
3350 || lang_hooks.types_compatible_p (TREE_TYPE (rhs1), TREE_TYPE (rhs2)))
3351 && operand_equal_p (rhs1, rhs2, OEP_PURE_SAME))
3353 bool ret = compare_ssa_operands_equal (stmt1, stmt2, SSA_OP_VUSE);
3354 gcc_assert (!ret || ((struct expr_hash_elt *)p1)->hash
3355 == ((struct expr_hash_elt *)p2)->hash);
3356 return ret;
3359 return false;