c-family/
[official-gcc.git] / gcc / tree-ssa-pre.c
blobbc3381bd85e7c0f50cb4b10bcec819acd919ce75
1 /* SSA-PRE for trees.
2 Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
3 Free Software Foundation, Inc.
4 Contributed by Daniel Berlin <dan@dberlin.org> and Steven Bosscher
5 <stevenb@suse.de>
7 This file is part of GCC.
9 GCC is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3, or (at your option)
12 any later version.
14 GCC is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3. If not see
21 <http://www.gnu.org/licenses/>. */
23 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "tm.h"
27 #include "tree.h"
28 #include "basic-block.h"
29 #include "gimple-pretty-print.h"
30 #include "tree-inline.h"
31 #include "tree-flow.h"
32 #include "gimple.h"
33 #include "hash-table.h"
34 #include "tree-iterator.h"
35 #include "alloc-pool.h"
36 #include "obstack.h"
37 #include "tree-pass.h"
38 #include "flags.h"
39 #include "bitmap.h"
40 #include "langhooks.h"
41 #include "cfgloop.h"
42 #include "tree-ssa-sccvn.h"
43 #include "tree-scalar-evolution.h"
44 #include "params.h"
45 #include "dbgcnt.h"
46 #include "domwalk.h"
48 /* TODO:
50 1. Avail sets can be shared by making an avail_find_leader that
51 walks up the dominator tree and looks in those avail sets.
52 This might affect code optimality, it's unclear right now.
53 2. Strength reduction can be performed by anticipating expressions
54 we can repair later on.
55 3. We can do back-substitution or smarter value numbering to catch
56 commutative expressions split up over multiple statements.
59 /* For ease of terminology, "expression node" in the below refers to
60 every expression node but GIMPLE_ASSIGN, because GIMPLE_ASSIGNs
61 represent the actual statement containing the expressions we care about,
62 and we cache the value number by putting it in the expression. */
64 /* Basic algorithm
66 First we walk the statements to generate the AVAIL sets, the
67 EXP_GEN sets, and the tmp_gen sets. EXP_GEN sets represent the
68 generation of values/expressions by a given block. We use them
69 when computing the ANTIC sets. The AVAIL sets consist of
70 SSA_NAME's that represent values, so we know what values are
71 available in what blocks. AVAIL is a forward dataflow problem. In
72 SSA, values are never killed, so we don't need a kill set, or a
73 fixpoint iteration, in order to calculate the AVAIL sets. In
74 traditional parlance, AVAIL sets tell us the downsafety of the
75 expressions/values.
77 Next, we generate the ANTIC sets. These sets represent the
78 anticipatable expressions. ANTIC is a backwards dataflow
79 problem. An expression is anticipatable in a given block if it could
80 be generated in that block. This means that if we had to perform
81 an insertion in that block, of the value of that expression, we
82 could. Calculating the ANTIC sets requires phi translation of
83 expressions, because the flow goes backwards through phis. We must
84 iterate to a fixpoint of the ANTIC sets, because we have a kill
85 set. Even in SSA form, values are not live over the entire
86 function, only from their definition point onwards. So we have to
87 remove values from the ANTIC set once we go past the definition
88 point of the leaders that make them up.
89 compute_antic/compute_antic_aux performs this computation.
91 Third, we perform insertions to make partially redundant
92 expressions fully redundant.
94 An expression is partially redundant (excluding partial
95 anticipation) if:
97 1. It is AVAIL in some, but not all, of the predecessors of a
98 given block.
99 2. It is ANTIC in all the predecessors.
101 In order to make it fully redundant, we insert the expression into
102 the predecessors where it is not available, but is ANTIC.
104 For the partial anticipation case, we only perform insertion if it
105 is partially anticipated in some block, and fully available in all
106 of the predecessors.
108 insert/insert_aux/do_regular_insertion/do_partial_partial_insertion
109 performs these steps.
111 Fourth, we eliminate fully redundant expressions.
112 This is a simple statement walk that replaces redundant
113 calculations with the now available values. */
115 /* Representations of value numbers:
117 Value numbers are represented by a representative SSA_NAME. We
118 will create fake SSA_NAME's in situations where we need a
119 representative but do not have one (because it is a complex
120 expression). In order to facilitate storing the value numbers in
121 bitmaps, and keep the number of wasted SSA_NAME's down, we also
122 associate a value_id with each value number, and create full blown
123 ssa_name's only where we actually need them (IE in operands of
124 existing expressions).
126 Theoretically you could replace all the value_id's with
127 SSA_NAME_VERSION, but this would allocate a large number of
128 SSA_NAME's (which are each > 30 bytes) just to get a 4 byte number.
129 It would also require an additional indirection at each point we
130 use the value id. */
132 /* Representation of expressions on value numbers:
134 Expressions consisting of value numbers are represented the same
135 way as our VN internally represents them, with an additional
136 "pre_expr" wrapping around them in order to facilitate storing all
137 of the expressions in the same sets. */
139 /* Representation of sets:
141 The dataflow sets do not need to be sorted in any particular order
142 for the majority of their lifetime, are simply represented as two
143 bitmaps, one that keeps track of values present in the set, and one
144 that keeps track of expressions present in the set.
146 When we need them in topological order, we produce it on demand by
147 transforming the bitmap into an array and sorting it into topo
148 order. */
150 /* Type of expression, used to know which member of the PRE_EXPR union
151 is valid. */
153 enum pre_expr_kind
155 NAME,
156 NARY,
157 REFERENCE,
158 CONSTANT
161 typedef union pre_expr_union_d
163 tree name;
164 tree constant;
165 vn_nary_op_t nary;
166 vn_reference_t reference;
167 } pre_expr_union;
169 typedef struct pre_expr_d : typed_noop_remove <pre_expr_d>
171 enum pre_expr_kind kind;
172 unsigned int id;
173 pre_expr_union u;
175 /* hash_table support. */
176 typedef pre_expr_d T;
177 static inline hashval_t hash (const pre_expr_d *);
178 static inline int equal (const pre_expr_d *, const pre_expr_d *);
179 } *pre_expr;
181 #define PRE_EXPR_NAME(e) (e)->u.name
182 #define PRE_EXPR_NARY(e) (e)->u.nary
183 #define PRE_EXPR_REFERENCE(e) (e)->u.reference
184 #define PRE_EXPR_CONSTANT(e) (e)->u.constant
186 /* Compare E1 and E1 for equality. */
188 inline int
189 pre_expr_d::equal (const struct pre_expr_d *e1, const struct pre_expr_d *e2)
191 if (e1->kind != e2->kind)
192 return false;
194 switch (e1->kind)
196 case CONSTANT:
197 return vn_constant_eq_with_type (PRE_EXPR_CONSTANT (e1),
198 PRE_EXPR_CONSTANT (e2));
199 case NAME:
200 return PRE_EXPR_NAME (e1) == PRE_EXPR_NAME (e2);
201 case NARY:
202 return vn_nary_op_eq (PRE_EXPR_NARY (e1), PRE_EXPR_NARY (e2));
203 case REFERENCE:
204 return vn_reference_eq (PRE_EXPR_REFERENCE (e1),
205 PRE_EXPR_REFERENCE (e2));
206 default:
207 gcc_unreachable ();
211 /* Hash E. */
213 inline hashval_t
214 pre_expr_d::hash (const struct pre_expr_d *e)
216 switch (e->kind)
218 case CONSTANT:
219 return vn_hash_constant_with_type (PRE_EXPR_CONSTANT (e));
220 case NAME:
221 return SSA_NAME_VERSION (PRE_EXPR_NAME (e));
222 case NARY:
223 return PRE_EXPR_NARY (e)->hashcode;
224 case REFERENCE:
225 return PRE_EXPR_REFERENCE (e)->hashcode;
226 default:
227 gcc_unreachable ();
231 /* Next global expression id number. */
232 static unsigned int next_expression_id;
234 /* Mapping from expression to id number we can use in bitmap sets. */
235 DEF_VEC_P (pre_expr);
236 DEF_VEC_ALLOC_P (pre_expr, heap);
237 static VEC(pre_expr, heap) *expressions;
238 static hash_table <pre_expr_d> expression_to_id;
239 static VEC(unsigned, heap) *name_to_id;
241 /* Allocate an expression id for EXPR. */
243 static inline unsigned int
244 alloc_expression_id (pre_expr expr)
246 struct pre_expr_d **slot;
247 /* Make sure we won't overflow. */
248 gcc_assert (next_expression_id + 1 > next_expression_id);
249 expr->id = next_expression_id++;
250 VEC_safe_push (pre_expr, heap, expressions, expr);
251 if (expr->kind == NAME)
253 unsigned version = SSA_NAME_VERSION (PRE_EXPR_NAME (expr));
254 /* VEC_safe_grow_cleared allocates no headroom. Avoid frequent
255 re-allocations by using VEC_reserve upfront. There is no
256 VEC_quick_grow_cleared unfortunately. */
257 unsigned old_len = VEC_length (unsigned, name_to_id);
258 VEC_reserve (unsigned, heap, name_to_id, num_ssa_names - old_len);
259 VEC_safe_grow_cleared (unsigned, heap, name_to_id, num_ssa_names);
260 gcc_assert (VEC_index (unsigned, name_to_id, version) == 0);
261 VEC_replace (unsigned, name_to_id, version, expr->id);
263 else
265 slot = expression_to_id.find_slot (expr, INSERT);
266 gcc_assert (!*slot);
267 *slot = expr;
269 return next_expression_id - 1;
272 /* Return the expression id for tree EXPR. */
274 static inline unsigned int
275 get_expression_id (const pre_expr expr)
277 return expr->id;
280 static inline unsigned int
281 lookup_expression_id (const pre_expr expr)
283 struct pre_expr_d **slot;
285 if (expr->kind == NAME)
287 unsigned version = SSA_NAME_VERSION (PRE_EXPR_NAME (expr));
288 if (VEC_length (unsigned, name_to_id) <= version)
289 return 0;
290 return VEC_index (unsigned, name_to_id, version);
292 else
294 slot = expression_to_id.find_slot (expr, NO_INSERT);
295 if (!slot)
296 return 0;
297 return ((pre_expr)*slot)->id;
301 /* Return the existing expression id for EXPR, or create one if one
302 does not exist yet. */
304 static inline unsigned int
305 get_or_alloc_expression_id (pre_expr expr)
307 unsigned int id = lookup_expression_id (expr);
308 if (id == 0)
309 return alloc_expression_id (expr);
310 return expr->id = id;
313 /* Return the expression that has expression id ID */
315 static inline pre_expr
316 expression_for_id (unsigned int id)
318 return VEC_index (pre_expr, expressions, id);
321 /* Free the expression id field in all of our expressions,
322 and then destroy the expressions array. */
324 static void
325 clear_expression_ids (void)
327 VEC_free (pre_expr, heap, expressions);
330 static alloc_pool pre_expr_pool;
332 /* Given an SSA_NAME NAME, get or create a pre_expr to represent it. */
334 static pre_expr
335 get_or_alloc_expr_for_name (tree name)
337 struct pre_expr_d expr;
338 pre_expr result;
339 unsigned int result_id;
341 expr.kind = NAME;
342 expr.id = 0;
343 PRE_EXPR_NAME (&expr) = name;
344 result_id = lookup_expression_id (&expr);
345 if (result_id != 0)
346 return expression_for_id (result_id);
348 result = (pre_expr) pool_alloc (pre_expr_pool);
349 result->kind = NAME;
350 PRE_EXPR_NAME (result) = name;
351 alloc_expression_id (result);
352 return result;
355 /* An unordered bitmap set. One bitmap tracks values, the other,
356 expressions. */
357 typedef struct bitmap_set
359 bitmap_head expressions;
360 bitmap_head values;
361 } *bitmap_set_t;
363 #define FOR_EACH_EXPR_ID_IN_SET(set, id, bi) \
364 EXECUTE_IF_SET_IN_BITMAP(&(set)->expressions, 0, (id), (bi))
366 #define FOR_EACH_VALUE_ID_IN_SET(set, id, bi) \
367 EXECUTE_IF_SET_IN_BITMAP(&(set)->values, 0, (id), (bi))
369 /* Mapping from value id to expressions with that value_id. */
370 static VEC(bitmap, heap) *value_expressions;
372 /* Sets that we need to keep track of. */
373 typedef struct bb_bitmap_sets
375 /* The EXP_GEN set, which represents expressions/values generated in
376 a basic block. */
377 bitmap_set_t exp_gen;
379 /* The PHI_GEN set, which represents PHI results generated in a
380 basic block. */
381 bitmap_set_t phi_gen;
383 /* The TMP_GEN set, which represents results/temporaries generated
384 in a basic block. IE the LHS of an expression. */
385 bitmap_set_t tmp_gen;
387 /* The AVAIL_OUT set, which represents which values are available in
388 a given basic block. */
389 bitmap_set_t avail_out;
391 /* The ANTIC_IN set, which represents which values are anticipatable
392 in a given basic block. */
393 bitmap_set_t antic_in;
395 /* The PA_IN set, which represents which values are
396 partially anticipatable in a given basic block. */
397 bitmap_set_t pa_in;
399 /* The NEW_SETS set, which is used during insertion to augment the
400 AVAIL_OUT set of blocks with the new insertions performed during
401 the current iteration. */
402 bitmap_set_t new_sets;
404 /* A cache for value_dies_in_block_x. */
405 bitmap expr_dies;
407 /* True if we have visited this block during ANTIC calculation. */
408 unsigned int visited : 1;
410 /* True we have deferred processing this block during ANTIC
411 calculation until its successor is processed. */
412 unsigned int deferred : 1;
414 /* True when the block contains a call that might not return. */
415 unsigned int contains_may_not_return_call : 1;
416 } *bb_value_sets_t;
418 #define EXP_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->exp_gen
419 #define PHI_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->phi_gen
420 #define TMP_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->tmp_gen
421 #define AVAIL_OUT(BB) ((bb_value_sets_t) ((BB)->aux))->avail_out
422 #define ANTIC_IN(BB) ((bb_value_sets_t) ((BB)->aux))->antic_in
423 #define PA_IN(BB) ((bb_value_sets_t) ((BB)->aux))->pa_in
424 #define NEW_SETS(BB) ((bb_value_sets_t) ((BB)->aux))->new_sets
425 #define EXPR_DIES(BB) ((bb_value_sets_t) ((BB)->aux))->expr_dies
426 #define BB_VISITED(BB) ((bb_value_sets_t) ((BB)->aux))->visited
427 #define BB_DEFERRED(BB) ((bb_value_sets_t) ((BB)->aux))->deferred
428 #define BB_MAY_NOTRETURN(BB) ((bb_value_sets_t) ((BB)->aux))->contains_may_not_return_call
431 /* Basic block list in postorder. */
432 static int *postorder;
433 static int postorder_num;
435 /* This structure is used to keep track of statistics on what
436 optimization PRE was able to perform. */
437 static struct
439 /* The number of RHS computations eliminated by PRE. */
440 int eliminations;
442 /* The number of new expressions/temporaries generated by PRE. */
443 int insertions;
445 /* The number of inserts found due to partial anticipation */
446 int pa_insert;
448 /* The number of new PHI nodes added by PRE. */
449 int phis;
451 /* The number of values found constant. */
452 int constified;
454 } pre_stats;
456 static bool do_partial_partial;
457 static pre_expr bitmap_find_leader (bitmap_set_t, unsigned int);
458 static void bitmap_value_insert_into_set (bitmap_set_t, pre_expr);
459 static void bitmap_value_replace_in_set (bitmap_set_t, pre_expr);
460 static void bitmap_set_copy (bitmap_set_t, bitmap_set_t);
461 static bool bitmap_set_contains_value (bitmap_set_t, unsigned int);
462 static void bitmap_insert_into_set (bitmap_set_t, pre_expr);
463 static void bitmap_insert_into_set_1 (bitmap_set_t, pre_expr,
464 unsigned int, bool);
465 static bitmap_set_t bitmap_set_new (void);
466 static tree create_expression_by_pieces (basic_block, pre_expr, gimple_seq *,
467 tree);
468 static tree find_or_generate_expression (basic_block, tree, gimple_seq *);
469 static unsigned int get_expr_value_id (pre_expr);
471 /* We can add and remove elements and entries to and from sets
472 and hash tables, so we use alloc pools for them. */
474 static alloc_pool bitmap_set_pool;
475 static bitmap_obstack grand_bitmap_obstack;
477 /* Set of blocks with statements that have had their EH properties changed. */
478 static bitmap need_eh_cleanup;
480 /* Set of blocks with statements that have had their AB properties changed. */
481 static bitmap need_ab_cleanup;
483 /* A three tuple {e, pred, v} used to cache phi translations in the
484 phi_translate_table. */
486 typedef struct expr_pred_trans_d : typed_free_remove<expr_pred_trans_d>
488 /* The expression. */
489 pre_expr e;
491 /* The predecessor block along which we translated the expression. */
492 basic_block pred;
494 /* The value that resulted from the translation. */
495 pre_expr v;
497 /* The hashcode for the expression, pred pair. This is cached for
498 speed reasons. */
499 hashval_t hashcode;
501 /* hash_table support. */
502 typedef expr_pred_trans_d T;
503 static inline hashval_t hash (const expr_pred_trans_d *);
504 static inline int equal (const expr_pred_trans_d *, const expr_pred_trans_d *);
505 } *expr_pred_trans_t;
506 typedef const struct expr_pred_trans_d *const_expr_pred_trans_t;
508 inline hashval_t
509 expr_pred_trans_d::hash (const expr_pred_trans_d *e)
511 return e->hashcode;
514 inline int
515 expr_pred_trans_d::equal (const expr_pred_trans_d *ve1,
516 const expr_pred_trans_d *ve2)
518 basic_block b1 = ve1->pred;
519 basic_block b2 = ve2->pred;
521 /* If they are not translations for the same basic block, they can't
522 be equal. */
523 if (b1 != b2)
524 return false;
525 return pre_expr_d::equal (ve1->e, ve2->e);
528 /* The phi_translate_table caches phi translations for a given
529 expression and predecessor. */
530 static hash_table <expr_pred_trans_d> phi_translate_table;
532 /* Search in the phi translation table for the translation of
533 expression E in basic block PRED.
534 Return the translated value, if found, NULL otherwise. */
536 static inline pre_expr
537 phi_trans_lookup (pre_expr e, basic_block pred)
539 expr_pred_trans_t *slot;
540 struct expr_pred_trans_d ept;
542 ept.e = e;
543 ept.pred = pred;
544 ept.hashcode = iterative_hash_hashval_t (pre_expr_d::hash (e), pred->index);
545 slot = phi_translate_table.find_slot_with_hash (&ept, ept.hashcode,
546 NO_INSERT);
547 if (!slot)
548 return NULL;
549 else
550 return (*slot)->v;
554 /* Add the tuple mapping from {expression E, basic block PRED} to
555 value V, to the phi translation table. */
557 static inline void
558 phi_trans_add (pre_expr e, pre_expr v, basic_block pred)
560 expr_pred_trans_t *slot;
561 expr_pred_trans_t new_pair = XNEW (struct expr_pred_trans_d);
562 new_pair->e = e;
563 new_pair->pred = pred;
564 new_pair->v = v;
565 new_pair->hashcode = iterative_hash_hashval_t (pre_expr_d::hash (e),
566 pred->index);
568 slot = phi_translate_table.find_slot_with_hash (new_pair,
569 new_pair->hashcode, INSERT);
570 free (*slot);
571 *slot = new_pair;
575 /* Add expression E to the expression set of value id V. */
577 static void
578 add_to_value (unsigned int v, pre_expr e)
580 bitmap set;
582 gcc_checking_assert (get_expr_value_id (e) == v);
584 if (v >= VEC_length (bitmap, value_expressions))
586 VEC_safe_grow_cleared (bitmap, heap, value_expressions, v + 1);
589 set = VEC_index (bitmap, value_expressions, v);
590 if (!set)
592 set = BITMAP_ALLOC (&grand_bitmap_obstack);
593 VEC_replace (bitmap, value_expressions, v, set);
596 bitmap_set_bit (set, get_or_alloc_expression_id (e));
599 /* Create a new bitmap set and return it. */
601 static bitmap_set_t
602 bitmap_set_new (void)
604 bitmap_set_t ret = (bitmap_set_t) pool_alloc (bitmap_set_pool);
605 bitmap_initialize (&ret->expressions, &grand_bitmap_obstack);
606 bitmap_initialize (&ret->values, &grand_bitmap_obstack);
607 return ret;
610 /* Return the value id for a PRE expression EXPR. */
612 static unsigned int
613 get_expr_value_id (pre_expr expr)
615 switch (expr->kind)
617 case CONSTANT:
619 unsigned int id;
620 id = get_constant_value_id (PRE_EXPR_CONSTANT (expr));
621 if (id == 0)
623 id = get_or_alloc_constant_value_id (PRE_EXPR_CONSTANT (expr));
624 add_to_value (id, expr);
626 return id;
628 case NAME:
629 return VN_INFO (PRE_EXPR_NAME (expr))->value_id;
630 case NARY:
631 return PRE_EXPR_NARY (expr)->value_id;
632 case REFERENCE:
633 return PRE_EXPR_REFERENCE (expr)->value_id;
634 default:
635 gcc_unreachable ();
639 /* Return a SCCVN valnum (SSA name or constant) for the PRE value-id VAL. */
641 static tree
642 sccvn_valnum_from_value_id (unsigned int val)
644 bitmap_iterator bi;
645 unsigned int i;
646 bitmap exprset = VEC_index (bitmap, value_expressions, val);
647 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
649 pre_expr vexpr = expression_for_id (i);
650 if (vexpr->kind == NAME)
651 return VN_INFO (PRE_EXPR_NAME (vexpr))->valnum;
652 else if (vexpr->kind == CONSTANT)
653 return PRE_EXPR_CONSTANT (vexpr);
655 return NULL_TREE;
658 /* Remove an expression EXPR from a bitmapped set. */
660 static void
661 bitmap_remove_from_set (bitmap_set_t set, pre_expr expr)
663 unsigned int val = get_expr_value_id (expr);
664 if (!value_id_constant_p (val))
666 bitmap_clear_bit (&set->values, val);
667 bitmap_clear_bit (&set->expressions, get_expression_id (expr));
671 static void
672 bitmap_insert_into_set_1 (bitmap_set_t set, pre_expr expr,
673 unsigned int val, bool allow_constants)
675 if (allow_constants || !value_id_constant_p (val))
677 /* We specifically expect this and only this function to be able to
678 insert constants into a set. */
679 bitmap_set_bit (&set->values, val);
680 bitmap_set_bit (&set->expressions, get_or_alloc_expression_id (expr));
684 /* Insert an expression EXPR into a bitmapped set. */
686 static void
687 bitmap_insert_into_set (bitmap_set_t set, pre_expr expr)
689 bitmap_insert_into_set_1 (set, expr, get_expr_value_id (expr), false);
692 /* Copy a bitmapped set ORIG, into bitmapped set DEST. */
694 static void
695 bitmap_set_copy (bitmap_set_t dest, bitmap_set_t orig)
697 bitmap_copy (&dest->expressions, &orig->expressions);
698 bitmap_copy (&dest->values, &orig->values);
702 /* Free memory used up by SET. */
703 static void
704 bitmap_set_free (bitmap_set_t set)
706 bitmap_clear (&set->expressions);
707 bitmap_clear (&set->values);
711 /* Generate an topological-ordered array of bitmap set SET. */
713 static VEC(pre_expr, heap) *
714 sorted_array_from_bitmap_set (bitmap_set_t set)
716 unsigned int i, j;
717 bitmap_iterator bi, bj;
718 VEC(pre_expr, heap) *result;
720 /* Pre-allocate roughly enough space for the array. */
721 result = VEC_alloc (pre_expr, heap, bitmap_count_bits (&set->values));
723 FOR_EACH_VALUE_ID_IN_SET (set, i, bi)
725 /* The number of expressions having a given value is usually
726 relatively small. Thus, rather than making a vector of all
727 the expressions and sorting it by value-id, we walk the values
728 and check in the reverse mapping that tells us what expressions
729 have a given value, to filter those in our set. As a result,
730 the expressions are inserted in value-id order, which means
731 topological order.
733 If this is somehow a significant lose for some cases, we can
734 choose which set to walk based on the set size. */
735 bitmap exprset = VEC_index (bitmap, value_expressions, i);
736 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, j, bj)
738 if (bitmap_bit_p (&set->expressions, j))
739 VEC_safe_push (pre_expr, heap, result, expression_for_id (j));
743 return result;
746 /* Perform bitmapped set operation DEST &= ORIG. */
748 static void
749 bitmap_set_and (bitmap_set_t dest, bitmap_set_t orig)
751 bitmap_iterator bi;
752 unsigned int i;
754 if (dest != orig)
756 bitmap_head temp;
757 bitmap_initialize (&temp, &grand_bitmap_obstack);
759 bitmap_and_into (&dest->values, &orig->values);
760 bitmap_copy (&temp, &dest->expressions);
761 EXECUTE_IF_SET_IN_BITMAP (&temp, 0, i, bi)
763 pre_expr expr = expression_for_id (i);
764 unsigned int value_id = get_expr_value_id (expr);
765 if (!bitmap_bit_p (&dest->values, value_id))
766 bitmap_clear_bit (&dest->expressions, i);
768 bitmap_clear (&temp);
772 /* Subtract all values and expressions contained in ORIG from DEST. */
774 static bitmap_set_t
775 bitmap_set_subtract (bitmap_set_t dest, bitmap_set_t orig)
777 bitmap_set_t result = bitmap_set_new ();
778 bitmap_iterator bi;
779 unsigned int i;
781 bitmap_and_compl (&result->expressions, &dest->expressions,
782 &orig->expressions);
784 FOR_EACH_EXPR_ID_IN_SET (result, i, bi)
786 pre_expr expr = expression_for_id (i);
787 unsigned int value_id = get_expr_value_id (expr);
788 bitmap_set_bit (&result->values, value_id);
791 return result;
794 /* Subtract all the values in bitmap set B from bitmap set A. */
796 static void
797 bitmap_set_subtract_values (bitmap_set_t a, bitmap_set_t b)
799 unsigned int i;
800 bitmap_iterator bi;
801 bitmap_head temp;
803 bitmap_initialize (&temp, &grand_bitmap_obstack);
805 bitmap_copy (&temp, &a->expressions);
806 EXECUTE_IF_SET_IN_BITMAP (&temp, 0, i, bi)
808 pre_expr expr = expression_for_id (i);
809 if (bitmap_set_contains_value (b, get_expr_value_id (expr)))
810 bitmap_remove_from_set (a, expr);
812 bitmap_clear (&temp);
816 /* Return true if bitmapped set SET contains the value VALUE_ID. */
818 static bool
819 bitmap_set_contains_value (bitmap_set_t set, unsigned int value_id)
821 if (value_id_constant_p (value_id))
822 return true;
824 if (!set || bitmap_empty_p (&set->expressions))
825 return false;
827 return bitmap_bit_p (&set->values, value_id);
830 static inline bool
831 bitmap_set_contains_expr (bitmap_set_t set, const pre_expr expr)
833 return bitmap_bit_p (&set->expressions, get_expression_id (expr));
836 /* Replace an instance of value LOOKFOR with expression EXPR in SET. */
838 static void
839 bitmap_set_replace_value (bitmap_set_t set, unsigned int lookfor,
840 const pre_expr expr)
842 bitmap exprset;
843 unsigned int i;
844 bitmap_iterator bi;
846 if (value_id_constant_p (lookfor))
847 return;
849 if (!bitmap_set_contains_value (set, lookfor))
850 return;
852 /* The number of expressions having a given value is usually
853 significantly less than the total number of expressions in SET.
854 Thus, rather than check, for each expression in SET, whether it
855 has the value LOOKFOR, we walk the reverse mapping that tells us
856 what expressions have a given value, and see if any of those
857 expressions are in our set. For large testcases, this is about
858 5-10x faster than walking the bitmap. If this is somehow a
859 significant lose for some cases, we can choose which set to walk
860 based on the set size. */
861 exprset = VEC_index (bitmap, value_expressions, lookfor);
862 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
864 if (bitmap_clear_bit (&set->expressions, i))
866 bitmap_set_bit (&set->expressions, get_expression_id (expr));
867 return;
872 /* Return true if two bitmap sets are equal. */
874 static bool
875 bitmap_set_equal (bitmap_set_t a, bitmap_set_t b)
877 return bitmap_equal_p (&a->values, &b->values);
880 /* Replace an instance of EXPR's VALUE with EXPR in SET if it exists,
881 and add it otherwise. */
883 static void
884 bitmap_value_replace_in_set (bitmap_set_t set, pre_expr expr)
886 unsigned int val = get_expr_value_id (expr);
888 if (bitmap_set_contains_value (set, val))
889 bitmap_set_replace_value (set, val, expr);
890 else
891 bitmap_insert_into_set (set, expr);
894 /* Insert EXPR into SET if EXPR's value is not already present in
895 SET. */
897 static void
898 bitmap_value_insert_into_set (bitmap_set_t set, pre_expr expr)
900 unsigned int val = get_expr_value_id (expr);
902 gcc_checking_assert (expr->id == get_or_alloc_expression_id (expr));
904 /* Constant values are always considered to be part of the set. */
905 if (value_id_constant_p (val))
906 return;
908 /* If the value membership changed, add the expression. */
909 if (bitmap_set_bit (&set->values, val))
910 bitmap_set_bit (&set->expressions, expr->id);
913 /* Print out EXPR to outfile. */
915 static void
916 print_pre_expr (FILE *outfile, const pre_expr expr)
918 switch (expr->kind)
920 case CONSTANT:
921 print_generic_expr (outfile, PRE_EXPR_CONSTANT (expr), 0);
922 break;
923 case NAME:
924 print_generic_expr (outfile, PRE_EXPR_NAME (expr), 0);
925 break;
926 case NARY:
928 unsigned int i;
929 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
930 fprintf (outfile, "{%s,", tree_code_name [nary->opcode]);
931 for (i = 0; i < nary->length; i++)
933 print_generic_expr (outfile, nary->op[i], 0);
934 if (i != (unsigned) nary->length - 1)
935 fprintf (outfile, ",");
937 fprintf (outfile, "}");
939 break;
941 case REFERENCE:
943 vn_reference_op_t vro;
944 unsigned int i;
945 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
946 fprintf (outfile, "{");
947 for (i = 0;
948 VEC_iterate (vn_reference_op_s, ref->operands, i, vro);
949 i++)
951 bool closebrace = false;
952 if (vro->opcode != SSA_NAME
953 && TREE_CODE_CLASS (vro->opcode) != tcc_declaration)
955 fprintf (outfile, "%s", tree_code_name [vro->opcode]);
956 if (vro->op0)
958 fprintf (outfile, "<");
959 closebrace = true;
962 if (vro->op0)
964 print_generic_expr (outfile, vro->op0, 0);
965 if (vro->op1)
967 fprintf (outfile, ",");
968 print_generic_expr (outfile, vro->op1, 0);
970 if (vro->op2)
972 fprintf (outfile, ",");
973 print_generic_expr (outfile, vro->op2, 0);
976 if (closebrace)
977 fprintf (outfile, ">");
978 if (i != VEC_length (vn_reference_op_s, ref->operands) - 1)
979 fprintf (outfile, ",");
981 fprintf (outfile, "}");
982 if (ref->vuse)
984 fprintf (outfile, "@");
985 print_generic_expr (outfile, ref->vuse, 0);
988 break;
991 void debug_pre_expr (pre_expr);
993 /* Like print_pre_expr but always prints to stderr. */
994 DEBUG_FUNCTION void
995 debug_pre_expr (pre_expr e)
997 print_pre_expr (stderr, e);
998 fprintf (stderr, "\n");
1001 /* Print out SET to OUTFILE. */
1003 static void
1004 print_bitmap_set (FILE *outfile, bitmap_set_t set,
1005 const char *setname, int blockindex)
1007 fprintf (outfile, "%s[%d] := { ", setname, blockindex);
1008 if (set)
1010 bool first = true;
1011 unsigned i;
1012 bitmap_iterator bi;
1014 FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
1016 const pre_expr expr = expression_for_id (i);
1018 if (!first)
1019 fprintf (outfile, ", ");
1020 first = false;
1021 print_pre_expr (outfile, expr);
1023 fprintf (outfile, " (%04d)", get_expr_value_id (expr));
1026 fprintf (outfile, " }\n");
1029 void debug_bitmap_set (bitmap_set_t);
1031 DEBUG_FUNCTION void
1032 debug_bitmap_set (bitmap_set_t set)
1034 print_bitmap_set (stderr, set, "debug", 0);
1037 void debug_bitmap_sets_for (basic_block);
1039 DEBUG_FUNCTION void
1040 debug_bitmap_sets_for (basic_block bb)
1042 print_bitmap_set (stderr, AVAIL_OUT (bb), "avail_out", bb->index);
1043 print_bitmap_set (stderr, EXP_GEN (bb), "exp_gen", bb->index);
1044 print_bitmap_set (stderr, PHI_GEN (bb), "phi_gen", bb->index);
1045 print_bitmap_set (stderr, TMP_GEN (bb), "tmp_gen", bb->index);
1046 print_bitmap_set (stderr, ANTIC_IN (bb), "antic_in", bb->index);
1047 if (do_partial_partial)
1048 print_bitmap_set (stderr, PA_IN (bb), "pa_in", bb->index);
1049 print_bitmap_set (stderr, NEW_SETS (bb), "new_sets", bb->index);
1052 /* Print out the expressions that have VAL to OUTFILE. */
1054 static void
1055 print_value_expressions (FILE *outfile, unsigned int val)
1057 bitmap set = VEC_index (bitmap, value_expressions, val);
1058 if (set)
1060 bitmap_set x;
1061 char s[10];
1062 sprintf (s, "%04d", val);
1063 x.expressions = *set;
1064 print_bitmap_set (outfile, &x, s, 0);
1069 DEBUG_FUNCTION void
1070 debug_value_expressions (unsigned int val)
1072 print_value_expressions (stderr, val);
1075 /* Given a CONSTANT, allocate a new CONSTANT type PRE_EXPR to
1076 represent it. */
1078 static pre_expr
1079 get_or_alloc_expr_for_constant (tree constant)
1081 unsigned int result_id;
1082 unsigned int value_id;
1083 struct pre_expr_d expr;
1084 pre_expr newexpr;
1086 expr.kind = CONSTANT;
1087 PRE_EXPR_CONSTANT (&expr) = constant;
1088 result_id = lookup_expression_id (&expr);
1089 if (result_id != 0)
1090 return expression_for_id (result_id);
1092 newexpr = (pre_expr) pool_alloc (pre_expr_pool);
1093 newexpr->kind = CONSTANT;
1094 PRE_EXPR_CONSTANT (newexpr) = constant;
1095 alloc_expression_id (newexpr);
1096 value_id = get_or_alloc_constant_value_id (constant);
1097 add_to_value (value_id, newexpr);
1098 return newexpr;
1101 /* Given a value id V, find the actual tree representing the constant
1102 value if there is one, and return it. Return NULL if we can't find
1103 a constant. */
1105 static tree
1106 get_constant_for_value_id (unsigned int v)
1108 if (value_id_constant_p (v))
1110 unsigned int i;
1111 bitmap_iterator bi;
1112 bitmap exprset = VEC_index (bitmap, value_expressions, v);
1114 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
1116 pre_expr expr = expression_for_id (i);
1117 if (expr->kind == CONSTANT)
1118 return PRE_EXPR_CONSTANT (expr);
1121 return NULL;
1124 /* Get or allocate a pre_expr for a piece of GIMPLE, and return it.
1125 Currently only supports constants and SSA_NAMES. */
1126 static pre_expr
1127 get_or_alloc_expr_for (tree t)
1129 if (TREE_CODE (t) == SSA_NAME)
1130 return get_or_alloc_expr_for_name (t);
1131 else if (is_gimple_min_invariant (t))
1132 return get_or_alloc_expr_for_constant (t);
1133 else
1135 /* More complex expressions can result from SCCVN expression
1136 simplification that inserts values for them. As they all
1137 do not have VOPs the get handled by the nary ops struct. */
1138 vn_nary_op_t result;
1139 unsigned int result_id;
1140 vn_nary_op_lookup (t, &result);
1141 if (result != NULL)
1143 pre_expr e = (pre_expr) pool_alloc (pre_expr_pool);
1144 e->kind = NARY;
1145 PRE_EXPR_NARY (e) = result;
1146 result_id = lookup_expression_id (e);
1147 if (result_id != 0)
1149 pool_free (pre_expr_pool, e);
1150 e = expression_for_id (result_id);
1151 return e;
1153 alloc_expression_id (e);
1154 return e;
1157 return NULL;
1160 /* Return the folded version of T if T, when folded, is a gimple
1161 min_invariant. Otherwise, return T. */
1163 static pre_expr
1164 fully_constant_expression (pre_expr e)
1166 switch (e->kind)
1168 case CONSTANT:
1169 return e;
1170 case NARY:
1172 vn_nary_op_t nary = PRE_EXPR_NARY (e);
1173 switch (TREE_CODE_CLASS (nary->opcode))
1175 case tcc_binary:
1176 case tcc_comparison:
1178 /* We have to go from trees to pre exprs to value ids to
1179 constants. */
1180 tree naryop0 = nary->op[0];
1181 tree naryop1 = nary->op[1];
1182 tree result;
1183 if (!is_gimple_min_invariant (naryop0))
1185 pre_expr rep0 = get_or_alloc_expr_for (naryop0);
1186 unsigned int vrep0 = get_expr_value_id (rep0);
1187 tree const0 = get_constant_for_value_id (vrep0);
1188 if (const0)
1189 naryop0 = fold_convert (TREE_TYPE (naryop0), const0);
1191 if (!is_gimple_min_invariant (naryop1))
1193 pre_expr rep1 = get_or_alloc_expr_for (naryop1);
1194 unsigned int vrep1 = get_expr_value_id (rep1);
1195 tree const1 = get_constant_for_value_id (vrep1);
1196 if (const1)
1197 naryop1 = fold_convert (TREE_TYPE (naryop1), const1);
1199 result = fold_binary (nary->opcode, nary->type,
1200 naryop0, naryop1);
1201 if (result && is_gimple_min_invariant (result))
1202 return get_or_alloc_expr_for_constant (result);
1203 /* We might have simplified the expression to a
1204 SSA_NAME for example from x_1 * 1. But we cannot
1205 insert a PHI for x_1 unconditionally as x_1 might
1206 not be available readily. */
1207 return e;
1209 case tcc_reference:
1210 if (nary->opcode != REALPART_EXPR
1211 && nary->opcode != IMAGPART_EXPR
1212 && nary->opcode != VIEW_CONVERT_EXPR)
1213 return e;
1214 /* Fallthrough. */
1215 case tcc_unary:
1217 /* We have to go from trees to pre exprs to value ids to
1218 constants. */
1219 tree naryop0 = nary->op[0];
1220 tree const0, result;
1221 if (is_gimple_min_invariant (naryop0))
1222 const0 = naryop0;
1223 else
1225 pre_expr rep0 = get_or_alloc_expr_for (naryop0);
1226 unsigned int vrep0 = get_expr_value_id (rep0);
1227 const0 = get_constant_for_value_id (vrep0);
1229 result = NULL;
1230 if (const0)
1232 tree type1 = TREE_TYPE (nary->op[0]);
1233 const0 = fold_convert (type1, const0);
1234 result = fold_unary (nary->opcode, nary->type, const0);
1236 if (result && is_gimple_min_invariant (result))
1237 return get_or_alloc_expr_for_constant (result);
1238 return e;
1240 default:
1241 return e;
1244 case REFERENCE:
1246 vn_reference_t ref = PRE_EXPR_REFERENCE (e);
1247 tree folded;
1248 if ((folded = fully_constant_vn_reference_p (ref)))
1249 return get_or_alloc_expr_for_constant (folded);
1250 return e;
1252 default:
1253 return e;
1255 return e;
1258 /* Translate the VUSE backwards through phi nodes in PHIBLOCK, so that
1259 it has the value it would have in BLOCK. Set *SAME_VALID to true
1260 in case the new vuse doesn't change the value id of the OPERANDS. */
1262 static tree
1263 translate_vuse_through_block (VEC (vn_reference_op_s, heap) *operands,
1264 alias_set_type set, tree type, tree vuse,
1265 basic_block phiblock,
1266 basic_block block, bool *same_valid)
1268 gimple phi = SSA_NAME_DEF_STMT (vuse);
1269 ao_ref ref;
1270 edge e = NULL;
1271 bool use_oracle;
1273 *same_valid = true;
1275 if (gimple_bb (phi) != phiblock)
1276 return vuse;
1278 use_oracle = ao_ref_init_from_vn_reference (&ref, set, type, operands);
1280 /* Use the alias-oracle to find either the PHI node in this block,
1281 the first VUSE used in this block that is equivalent to vuse or
1282 the first VUSE which definition in this block kills the value. */
1283 if (gimple_code (phi) == GIMPLE_PHI)
1284 e = find_edge (block, phiblock);
1285 else if (use_oracle)
1286 while (!stmt_may_clobber_ref_p_1 (phi, &ref))
1288 vuse = gimple_vuse (phi);
1289 phi = SSA_NAME_DEF_STMT (vuse);
1290 if (gimple_bb (phi) != phiblock)
1291 return vuse;
1292 if (gimple_code (phi) == GIMPLE_PHI)
1294 e = find_edge (block, phiblock);
1295 break;
1298 else
1299 return NULL_TREE;
1301 if (e)
1303 if (use_oracle)
1305 bitmap visited = NULL;
1306 unsigned int cnt;
1307 /* Try to find a vuse that dominates this phi node by skipping
1308 non-clobbering statements. */
1309 vuse = get_continuation_for_phi (phi, &ref, &cnt, &visited, false);
1310 if (visited)
1311 BITMAP_FREE (visited);
1313 else
1314 vuse = NULL_TREE;
1315 if (!vuse)
1317 /* If we didn't find any, the value ID can't stay the same,
1318 but return the translated vuse. */
1319 *same_valid = false;
1320 vuse = PHI_ARG_DEF (phi, e->dest_idx);
1322 /* ??? We would like to return vuse here as this is the canonical
1323 upmost vdef that this reference is associated with. But during
1324 insertion of the references into the hash tables we only ever
1325 directly insert with their direct gimple_vuse, hence returning
1326 something else would make us not find the other expression. */
1327 return PHI_ARG_DEF (phi, e->dest_idx);
1330 return NULL_TREE;
1333 /* Like bitmap_find_leader, but checks for the value existing in SET1 *or*
1334 SET2. This is used to avoid making a set consisting of the union
1335 of PA_IN and ANTIC_IN during insert. */
1337 static inline pre_expr
1338 find_leader_in_sets (unsigned int val, bitmap_set_t set1, bitmap_set_t set2)
1340 pre_expr result;
1342 result = bitmap_find_leader (set1, val);
1343 if (!result && set2)
1344 result = bitmap_find_leader (set2, val);
1345 return result;
1348 /* Get the tree type for our PRE expression e. */
1350 static tree
1351 get_expr_type (const pre_expr e)
1353 switch (e->kind)
1355 case NAME:
1356 return TREE_TYPE (PRE_EXPR_NAME (e));
1357 case CONSTANT:
1358 return TREE_TYPE (PRE_EXPR_CONSTANT (e));
1359 case REFERENCE:
1360 return PRE_EXPR_REFERENCE (e)->type;
1361 case NARY:
1362 return PRE_EXPR_NARY (e)->type;
1364 gcc_unreachable();
1367 /* Get a representative SSA_NAME for a given expression.
1368 Since all of our sub-expressions are treated as values, we require
1369 them to be SSA_NAME's for simplicity.
1370 Prior versions of GVNPRE used to use "value handles" here, so that
1371 an expression would be VH.11 + VH.10 instead of d_3 + e_6. In
1372 either case, the operands are really values (IE we do not expect
1373 them to be usable without finding leaders). */
1375 static tree
1376 get_representative_for (const pre_expr e)
1378 tree name;
1379 unsigned int value_id = get_expr_value_id (e);
1381 switch (e->kind)
1383 case NAME:
1384 return PRE_EXPR_NAME (e);
1385 case CONSTANT:
1386 return PRE_EXPR_CONSTANT (e);
1387 case NARY:
1388 case REFERENCE:
1390 /* Go through all of the expressions representing this value
1391 and pick out an SSA_NAME. */
1392 unsigned int i;
1393 bitmap_iterator bi;
1394 bitmap exprs = VEC_index (bitmap, value_expressions, value_id);
1395 EXECUTE_IF_SET_IN_BITMAP (exprs, 0, i, bi)
1397 pre_expr rep = expression_for_id (i);
1398 if (rep->kind == NAME)
1399 return PRE_EXPR_NAME (rep);
1402 break;
1404 /* If we reached here we couldn't find an SSA_NAME. This can
1405 happen when we've discovered a value that has never appeared in
1406 the program as set to an SSA_NAME, most likely as the result of
1407 phi translation. */
1408 if (dump_file)
1410 fprintf (dump_file,
1411 "Could not find SSA_NAME representative for expression:");
1412 print_pre_expr (dump_file, e);
1413 fprintf (dump_file, "\n");
1416 /* Build and insert the assignment of the end result to the temporary
1417 that we will return. */
1418 name = make_temp_ssa_name (get_expr_type (e), gimple_build_nop (), "pretmp");
1419 VN_INFO_GET (name)->value_id = value_id;
1420 VN_INFO (name)->valnum = sccvn_valnum_from_value_id (value_id);
1421 if (VN_INFO (name)->valnum == NULL_TREE)
1422 VN_INFO (name)->valnum = name;
1423 add_to_value (value_id, get_or_alloc_expr_for_name (name));
1424 if (dump_file)
1426 fprintf (dump_file, "Created SSA_NAME representative ");
1427 print_generic_expr (dump_file, name, 0);
1428 fprintf (dump_file, " for expression:");
1429 print_pre_expr (dump_file, e);
1430 fprintf (dump_file, "\n");
1433 return name;
1438 static pre_expr
1439 phi_translate (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1440 basic_block pred, basic_block phiblock);
1442 /* Translate EXPR using phis in PHIBLOCK, so that it has the values of
1443 the phis in PRED. Return NULL if we can't find a leader for each part
1444 of the translated expression. */
1446 static pre_expr
1447 phi_translate_1 (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1448 basic_block pred, basic_block phiblock)
1450 switch (expr->kind)
1452 case NARY:
1454 unsigned int i;
1455 bool changed = false;
1456 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1457 vn_nary_op_t newnary = XALLOCAVAR (struct vn_nary_op_s,
1458 sizeof_vn_nary_op (nary->length));
1459 memcpy (newnary, nary, sizeof_vn_nary_op (nary->length));
1461 for (i = 0; i < newnary->length; i++)
1463 if (TREE_CODE (newnary->op[i]) != SSA_NAME)
1464 continue;
1465 else
1467 pre_expr leader, result;
1468 unsigned int op_val_id = VN_INFO (newnary->op[i])->value_id;
1469 leader = find_leader_in_sets (op_val_id, set1, set2);
1470 result = phi_translate (leader, set1, set2, pred, phiblock);
1471 if (result && result != leader)
1473 tree name = get_representative_for (result);
1474 if (!name)
1475 return NULL;
1476 newnary->op[i] = name;
1478 else if (!result)
1479 return NULL;
1481 changed |= newnary->op[i] != nary->op[i];
1484 if (changed)
1486 pre_expr constant;
1487 unsigned int new_val_id;
1489 tree result = vn_nary_op_lookup_pieces (newnary->length,
1490 newnary->opcode,
1491 newnary->type,
1492 &newnary->op[0],
1493 &nary);
1494 if (result && is_gimple_min_invariant (result))
1495 return get_or_alloc_expr_for_constant (result);
1497 expr = (pre_expr) pool_alloc (pre_expr_pool);
1498 expr->kind = NARY;
1499 expr->id = 0;
1500 if (nary)
1502 PRE_EXPR_NARY (expr) = nary;
1503 constant = fully_constant_expression (expr);
1504 if (constant != expr)
1505 return constant;
1507 new_val_id = nary->value_id;
1508 get_or_alloc_expression_id (expr);
1510 else
1512 new_val_id = get_next_value_id ();
1513 VEC_safe_grow_cleared (bitmap, heap,
1514 value_expressions,
1515 get_max_value_id() + 1);
1516 nary = vn_nary_op_insert_pieces (newnary->length,
1517 newnary->opcode,
1518 newnary->type,
1519 &newnary->op[0],
1520 result, new_val_id);
1521 PRE_EXPR_NARY (expr) = nary;
1522 constant = fully_constant_expression (expr);
1523 if (constant != expr)
1524 return constant;
1525 get_or_alloc_expression_id (expr);
1527 add_to_value (new_val_id, expr);
1529 return expr;
1531 break;
1533 case REFERENCE:
1535 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1536 VEC (vn_reference_op_s, heap) *operands = ref->operands;
1537 tree vuse = ref->vuse;
1538 tree newvuse = vuse;
1539 VEC (vn_reference_op_s, heap) *newoperands = NULL;
1540 bool changed = false, same_valid = true;
1541 unsigned int i, j, n;
1542 vn_reference_op_t operand;
1543 vn_reference_t newref;
1545 for (i = 0, j = 0;
1546 VEC_iterate (vn_reference_op_s, operands, i, operand); i++, j++)
1548 pre_expr opresult;
1549 pre_expr leader;
1550 tree op[3];
1551 tree type = operand->type;
1552 vn_reference_op_s newop = *operand;
1553 op[0] = operand->op0;
1554 op[1] = operand->op1;
1555 op[2] = operand->op2;
1556 for (n = 0; n < 3; ++n)
1558 unsigned int op_val_id;
1559 if (!op[n])
1560 continue;
1561 if (TREE_CODE (op[n]) != SSA_NAME)
1563 /* We can't possibly insert these. */
1564 if (n != 0
1565 && !is_gimple_min_invariant (op[n]))
1566 break;
1567 continue;
1569 op_val_id = VN_INFO (op[n])->value_id;
1570 leader = find_leader_in_sets (op_val_id, set1, set2);
1571 if (!leader)
1572 break;
1573 /* Make sure we do not recursively translate ourselves
1574 like for translating a[n_1] with the leader for
1575 n_1 being a[n_1]. */
1576 if (get_expression_id (leader) != get_expression_id (expr))
1578 opresult = phi_translate (leader, set1, set2,
1579 pred, phiblock);
1580 if (!opresult)
1581 break;
1582 if (opresult != leader)
1584 tree name = get_representative_for (opresult);
1585 if (!name)
1586 break;
1587 changed |= name != op[n];
1588 op[n] = name;
1592 if (n != 3)
1594 if (newoperands)
1595 VEC_free (vn_reference_op_s, heap, newoperands);
1596 return NULL;
1598 if (!newoperands)
1599 newoperands = VEC_copy (vn_reference_op_s, heap, operands);
1600 /* We may have changed from an SSA_NAME to a constant */
1601 if (newop.opcode == SSA_NAME && TREE_CODE (op[0]) != SSA_NAME)
1602 newop.opcode = TREE_CODE (op[0]);
1603 newop.type = type;
1604 newop.op0 = op[0];
1605 newop.op1 = op[1];
1606 newop.op2 = op[2];
1607 /* If it transforms a non-constant ARRAY_REF into a constant
1608 one, adjust the constant offset. */
1609 if (newop.opcode == ARRAY_REF
1610 && newop.off == -1
1611 && TREE_CODE (op[0]) == INTEGER_CST
1612 && TREE_CODE (op[1]) == INTEGER_CST
1613 && TREE_CODE (op[2]) == INTEGER_CST)
1615 double_int off = tree_to_double_int (op[0]);
1616 off += -tree_to_double_int (op[1]);
1617 off *= tree_to_double_int (op[2]);
1618 if (off.fits_shwi ())
1619 newop.off = off.low;
1621 VEC_replace (vn_reference_op_s, newoperands, j, newop);
1622 /* If it transforms from an SSA_NAME to an address, fold with
1623 a preceding indirect reference. */
1624 if (j > 0 && op[0] && TREE_CODE (op[0]) == ADDR_EXPR
1625 && VEC_index (vn_reference_op_s,
1626 newoperands, j - 1).opcode == MEM_REF)
1627 vn_reference_fold_indirect (&newoperands, &j);
1629 if (i != VEC_length (vn_reference_op_s, operands))
1631 if (newoperands)
1632 VEC_free (vn_reference_op_s, heap, newoperands);
1633 return NULL;
1636 if (vuse)
1638 newvuse = translate_vuse_through_block (newoperands,
1639 ref->set, ref->type,
1640 vuse, phiblock, pred,
1641 &same_valid);
1642 if (newvuse == NULL_TREE)
1644 VEC_free (vn_reference_op_s, heap, newoperands);
1645 return NULL;
1649 if (changed || newvuse != vuse)
1651 unsigned int new_val_id;
1652 pre_expr constant;
1654 tree result = vn_reference_lookup_pieces (newvuse, ref->set,
1655 ref->type,
1656 newoperands,
1657 &newref, VN_WALK);
1658 if (result)
1659 VEC_free (vn_reference_op_s, heap, newoperands);
1661 /* We can always insert constants, so if we have a partial
1662 redundant constant load of another type try to translate it
1663 to a constant of appropriate type. */
1664 if (result && is_gimple_min_invariant (result))
1666 tree tem = result;
1667 if (!useless_type_conversion_p (ref->type, TREE_TYPE (result)))
1669 tem = fold_unary (VIEW_CONVERT_EXPR, ref->type, result);
1670 if (tem && !is_gimple_min_invariant (tem))
1671 tem = NULL_TREE;
1673 if (tem)
1674 return get_or_alloc_expr_for_constant (tem);
1677 /* If we'd have to convert things we would need to validate
1678 if we can insert the translated expression. So fail
1679 here for now - we cannot insert an alias with a different
1680 type in the VN tables either, as that would assert. */
1681 if (result
1682 && !useless_type_conversion_p (ref->type, TREE_TYPE (result)))
1683 return NULL;
1684 else if (!result && newref
1685 && !useless_type_conversion_p (ref->type, newref->type))
1687 VEC_free (vn_reference_op_s, heap, newoperands);
1688 return NULL;
1691 expr = (pre_expr) pool_alloc (pre_expr_pool);
1692 expr->kind = REFERENCE;
1693 expr->id = 0;
1695 if (newref)
1697 PRE_EXPR_REFERENCE (expr) = newref;
1698 constant = fully_constant_expression (expr);
1699 if (constant != expr)
1700 return constant;
1702 new_val_id = newref->value_id;
1703 get_or_alloc_expression_id (expr);
1705 else
1707 if (changed || !same_valid)
1709 new_val_id = get_next_value_id ();
1710 VEC_safe_grow_cleared (bitmap, heap,
1711 value_expressions,
1712 get_max_value_id() + 1);
1714 else
1715 new_val_id = ref->value_id;
1716 newref = vn_reference_insert_pieces (newvuse, ref->set,
1717 ref->type,
1718 newoperands,
1719 result, new_val_id);
1720 newoperands = NULL;
1721 PRE_EXPR_REFERENCE (expr) = newref;
1722 constant = fully_constant_expression (expr);
1723 if (constant != expr)
1724 return constant;
1725 get_or_alloc_expression_id (expr);
1727 add_to_value (new_val_id, expr);
1729 VEC_free (vn_reference_op_s, heap, newoperands);
1730 return expr;
1732 break;
1734 case NAME:
1736 tree name = PRE_EXPR_NAME (expr);
1737 gimple def_stmt = SSA_NAME_DEF_STMT (name);
1738 /* If the SSA name is defined by a PHI node in this block,
1739 translate it. */
1740 if (gimple_code (def_stmt) == GIMPLE_PHI
1741 && gimple_bb (def_stmt) == phiblock)
1743 edge e = find_edge (pred, gimple_bb (def_stmt));
1744 tree def = PHI_ARG_DEF (def_stmt, e->dest_idx);
1746 /* Handle constant. */
1747 if (is_gimple_min_invariant (def))
1748 return get_or_alloc_expr_for_constant (def);
1750 return get_or_alloc_expr_for_name (def);
1752 /* Otherwise return it unchanged - it will get cleaned if its
1753 value is not available in PREDs AVAIL_OUT set of expressions. */
1754 return expr;
1757 default:
1758 gcc_unreachable ();
1762 /* Wrapper around phi_translate_1 providing caching functionality. */
1764 static pre_expr
1765 phi_translate (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1766 basic_block pred, basic_block phiblock)
1768 pre_expr phitrans;
1770 if (!expr)
1771 return NULL;
1773 /* Constants contain no values that need translation. */
1774 if (expr->kind == CONSTANT)
1775 return expr;
1777 if (value_id_constant_p (get_expr_value_id (expr)))
1778 return expr;
1780 if (expr->kind != NAME)
1782 phitrans = phi_trans_lookup (expr, pred);
1783 if (phitrans)
1784 return phitrans;
1787 /* Translate. */
1788 phitrans = phi_translate_1 (expr, set1, set2, pred, phiblock);
1790 /* Don't add empty translations to the cache. Neither add
1791 translations of NAMEs as those are cheap to translate. */
1792 if (phitrans
1793 && expr->kind != NAME)
1794 phi_trans_add (expr, phitrans, pred);
1796 return phitrans;
1800 /* For each expression in SET, translate the values through phi nodes
1801 in PHIBLOCK using edge PHIBLOCK->PRED, and store the resulting
1802 expressions in DEST. */
1804 static void
1805 phi_translate_set (bitmap_set_t dest, bitmap_set_t set, basic_block pred,
1806 basic_block phiblock)
1808 VEC (pre_expr, heap) *exprs;
1809 pre_expr expr;
1810 int i;
1812 if (gimple_seq_empty_p (phi_nodes (phiblock)))
1814 bitmap_set_copy (dest, set);
1815 return;
1818 exprs = sorted_array_from_bitmap_set (set);
1819 FOR_EACH_VEC_ELT (pre_expr, exprs, i, expr)
1821 pre_expr translated;
1822 translated = phi_translate (expr, set, NULL, pred, phiblock);
1823 if (!translated)
1824 continue;
1826 /* We might end up with multiple expressions from SET being
1827 translated to the same value. In this case we do not want
1828 to retain the NARY or REFERENCE expression but prefer a NAME
1829 which would be the leader. */
1830 if (translated->kind == NAME)
1831 bitmap_value_replace_in_set (dest, translated);
1832 else
1833 bitmap_value_insert_into_set (dest, translated);
1835 VEC_free (pre_expr, heap, exprs);
1838 /* Find the leader for a value (i.e., the name representing that
1839 value) in a given set, and return it. If STMT is non-NULL it
1840 makes sure the defining statement for the leader dominates it.
1841 Return NULL if no leader is found. */
1843 static pre_expr
1844 bitmap_find_leader (bitmap_set_t set, unsigned int val)
1846 if (value_id_constant_p (val))
1848 unsigned int i;
1849 bitmap_iterator bi;
1850 bitmap exprset = VEC_index (bitmap, value_expressions, val);
1852 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
1854 pre_expr expr = expression_for_id (i);
1855 if (expr->kind == CONSTANT)
1856 return expr;
1859 if (bitmap_set_contains_value (set, val))
1861 /* Rather than walk the entire bitmap of expressions, and see
1862 whether any of them has the value we are looking for, we look
1863 at the reverse mapping, which tells us the set of expressions
1864 that have a given value (IE value->expressions with that
1865 value) and see if any of those expressions are in our set.
1866 The number of expressions per value is usually significantly
1867 less than the number of expressions in the set. In fact, for
1868 large testcases, doing it this way is roughly 5-10x faster
1869 than walking the bitmap.
1870 If this is somehow a significant lose for some cases, we can
1871 choose which set to walk based on which set is smaller. */
1872 unsigned int i;
1873 bitmap_iterator bi;
1874 bitmap exprset = VEC_index (bitmap, value_expressions, val);
1876 EXECUTE_IF_AND_IN_BITMAP (exprset, &set->expressions, 0, i, bi)
1877 return expression_for_id (i);
1879 return NULL;
1882 /* Determine if EXPR, a memory expression, is ANTIC_IN at the top of
1883 BLOCK by seeing if it is not killed in the block. Note that we are
1884 only determining whether there is a store that kills it. Because
1885 of the order in which clean iterates over values, we are guaranteed
1886 that altered operands will have caused us to be eliminated from the
1887 ANTIC_IN set already. */
1889 static bool
1890 value_dies_in_block_x (pre_expr expr, basic_block block)
1892 tree vuse = PRE_EXPR_REFERENCE (expr)->vuse;
1893 vn_reference_t refx = PRE_EXPR_REFERENCE (expr);
1894 gimple def;
1895 gimple_stmt_iterator gsi;
1896 unsigned id = get_expression_id (expr);
1897 bool res = false;
1898 ao_ref ref;
1900 if (!vuse)
1901 return false;
1903 /* Lookup a previously calculated result. */
1904 if (EXPR_DIES (block)
1905 && bitmap_bit_p (EXPR_DIES (block), id * 2))
1906 return bitmap_bit_p (EXPR_DIES (block), id * 2 + 1);
1908 /* A memory expression {e, VUSE} dies in the block if there is a
1909 statement that may clobber e. If, starting statement walk from the
1910 top of the basic block, a statement uses VUSE there can be no kill
1911 inbetween that use and the original statement that loaded {e, VUSE},
1912 so we can stop walking. */
1913 ref.base = NULL_TREE;
1914 for (gsi = gsi_start_bb (block); !gsi_end_p (gsi); gsi_next (&gsi))
1916 tree def_vuse, def_vdef;
1917 def = gsi_stmt (gsi);
1918 def_vuse = gimple_vuse (def);
1919 def_vdef = gimple_vdef (def);
1921 /* Not a memory statement. */
1922 if (!def_vuse)
1923 continue;
1925 /* Not a may-def. */
1926 if (!def_vdef)
1928 /* A load with the same VUSE, we're done. */
1929 if (def_vuse == vuse)
1930 break;
1932 continue;
1935 /* Init ref only if we really need it. */
1936 if (ref.base == NULL_TREE
1937 && !ao_ref_init_from_vn_reference (&ref, refx->set, refx->type,
1938 refx->operands))
1940 res = true;
1941 break;
1943 /* If the statement may clobber expr, it dies. */
1944 if (stmt_may_clobber_ref_p_1 (def, &ref))
1946 res = true;
1947 break;
1951 /* Remember the result. */
1952 if (!EXPR_DIES (block))
1953 EXPR_DIES (block) = BITMAP_ALLOC (&grand_bitmap_obstack);
1954 bitmap_set_bit (EXPR_DIES (block), id * 2);
1955 if (res)
1956 bitmap_set_bit (EXPR_DIES (block), id * 2 + 1);
1958 return res;
1962 /* Determine if OP is valid in SET1 U SET2, which it is when the union
1963 contains its value-id. */
1965 static bool
1966 op_valid_in_sets (bitmap_set_t set1, bitmap_set_t set2, tree op)
1968 if (op && TREE_CODE (op) == SSA_NAME)
1970 unsigned int value_id = VN_INFO (op)->value_id;
1971 if (!(bitmap_set_contains_value (set1, value_id)
1972 || (set2 && bitmap_set_contains_value (set2, value_id))))
1973 return false;
1975 return true;
1978 /* Determine if the expression EXPR is valid in SET1 U SET2.
1979 ONLY SET2 CAN BE NULL.
1980 This means that we have a leader for each part of the expression
1981 (if it consists of values), or the expression is an SSA_NAME.
1982 For loads/calls, we also see if the vuse is killed in this block. */
1984 static bool
1985 valid_in_sets (bitmap_set_t set1, bitmap_set_t set2, pre_expr expr,
1986 basic_block block)
1988 switch (expr->kind)
1990 case NAME:
1991 return bitmap_set_contains_expr (AVAIL_OUT (block), expr);
1992 case NARY:
1994 unsigned int i;
1995 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1996 for (i = 0; i < nary->length; i++)
1997 if (!op_valid_in_sets (set1, set2, nary->op[i]))
1998 return false;
1999 return true;
2001 break;
2002 case REFERENCE:
2004 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
2005 vn_reference_op_t vro;
2006 unsigned int i;
2008 FOR_EACH_VEC_ELT (vn_reference_op_s, ref->operands, i, vro)
2010 if (!op_valid_in_sets (set1, set2, vro->op0)
2011 || !op_valid_in_sets (set1, set2, vro->op1)
2012 || !op_valid_in_sets (set1, set2, vro->op2))
2013 return false;
2015 return true;
2017 default:
2018 gcc_unreachable ();
2022 /* Clean the set of expressions that are no longer valid in SET1 or
2023 SET2. This means expressions that are made up of values we have no
2024 leaders for in SET1 or SET2. This version is used for partial
2025 anticipation, which means it is not valid in either ANTIC_IN or
2026 PA_IN. */
2028 static void
2029 dependent_clean (bitmap_set_t set1, bitmap_set_t set2, basic_block block)
2031 VEC (pre_expr, heap) *exprs = sorted_array_from_bitmap_set (set1);
2032 pre_expr expr;
2033 int i;
2035 FOR_EACH_VEC_ELT (pre_expr, exprs, i, expr)
2037 if (!valid_in_sets (set1, set2, expr, block))
2038 bitmap_remove_from_set (set1, expr);
2040 VEC_free (pre_expr, heap, exprs);
2043 /* Clean the set of expressions that are no longer valid in SET. This
2044 means expressions that are made up of values we have no leaders for
2045 in SET. */
2047 static void
2048 clean (bitmap_set_t set, basic_block block)
2050 VEC (pre_expr, heap) *exprs = sorted_array_from_bitmap_set (set);
2051 pre_expr expr;
2052 int i;
2054 FOR_EACH_VEC_ELT (pre_expr, exprs, i, expr)
2056 if (!valid_in_sets (set, NULL, expr, block))
2057 bitmap_remove_from_set (set, expr);
2059 VEC_free (pre_expr, heap, exprs);
2062 /* Clean the set of expressions that are no longer valid in SET because
2063 they are clobbered in BLOCK or because they trap and may not be executed. */
2065 static void
2066 prune_clobbered_mems (bitmap_set_t set, basic_block block)
2068 bitmap_iterator bi;
2069 unsigned i;
2071 FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
2073 pre_expr expr = expression_for_id (i);
2074 if (expr->kind == REFERENCE)
2076 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
2077 if (ref->vuse)
2079 gimple def_stmt = SSA_NAME_DEF_STMT (ref->vuse);
2080 if (!gimple_nop_p (def_stmt)
2081 && ((gimple_bb (def_stmt) != block
2082 && !dominated_by_p (CDI_DOMINATORS,
2083 block, gimple_bb (def_stmt)))
2084 || (gimple_bb (def_stmt) == block
2085 && value_dies_in_block_x (expr, block))))
2086 bitmap_remove_from_set (set, expr);
2089 else if (expr->kind == NARY)
2091 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
2092 /* If the NARY may trap make sure the block does not contain
2093 a possible exit point.
2094 ??? This is overly conservative if we translate AVAIL_OUT
2095 as the available expression might be after the exit point. */
2096 if (BB_MAY_NOTRETURN (block)
2097 && vn_nary_may_trap (nary))
2098 bitmap_remove_from_set (set, expr);
2103 static sbitmap has_abnormal_preds;
2105 /* List of blocks that may have changed during ANTIC computation and
2106 thus need to be iterated over. */
2108 static sbitmap changed_blocks;
2110 /* Decide whether to defer a block for a later iteration, or PHI
2111 translate SOURCE to DEST using phis in PHIBLOCK. Return false if we
2112 should defer the block, and true if we processed it. */
2114 static bool
2115 defer_or_phi_translate_block (bitmap_set_t dest, bitmap_set_t source,
2116 basic_block block, basic_block phiblock)
2118 if (!BB_VISITED (phiblock))
2120 SET_BIT (changed_blocks, block->index);
2121 BB_VISITED (block) = 0;
2122 BB_DEFERRED (block) = 1;
2123 return false;
2125 else
2126 phi_translate_set (dest, source, block, phiblock);
2127 return true;
2130 /* Compute the ANTIC set for BLOCK.
2132 If succs(BLOCK) > 1 then
2133 ANTIC_OUT[BLOCK] = intersection of ANTIC_IN[b] for all succ(BLOCK)
2134 else if succs(BLOCK) == 1 then
2135 ANTIC_OUT[BLOCK] = phi_translate (ANTIC_IN[succ(BLOCK)])
2137 ANTIC_IN[BLOCK] = clean(ANTIC_OUT[BLOCK] U EXP_GEN[BLOCK] - TMP_GEN[BLOCK])
2140 static bool
2141 compute_antic_aux (basic_block block, bool block_has_abnormal_pred_edge)
2143 bool changed = false;
2144 bitmap_set_t S, old, ANTIC_OUT;
2145 bitmap_iterator bi;
2146 unsigned int bii;
2147 edge e;
2148 edge_iterator ei;
2150 old = ANTIC_OUT = S = NULL;
2151 BB_VISITED (block) = 1;
2153 /* If any edges from predecessors are abnormal, antic_in is empty,
2154 so do nothing. */
2155 if (block_has_abnormal_pred_edge)
2156 goto maybe_dump_sets;
2158 old = ANTIC_IN (block);
2159 ANTIC_OUT = bitmap_set_new ();
2161 /* If the block has no successors, ANTIC_OUT is empty. */
2162 if (EDGE_COUNT (block->succs) == 0)
2164 /* If we have one successor, we could have some phi nodes to
2165 translate through. */
2166 else if (single_succ_p (block))
2168 basic_block succ_bb = single_succ (block);
2170 /* We trade iterations of the dataflow equations for having to
2171 phi translate the maximal set, which is incredibly slow
2172 (since the maximal set often has 300+ members, even when you
2173 have a small number of blocks).
2174 Basically, we defer the computation of ANTIC for this block
2175 until we have processed it's successor, which will inevitably
2176 have a *much* smaller set of values to phi translate once
2177 clean has been run on it.
2178 The cost of doing this is that we technically perform more
2179 iterations, however, they are lower cost iterations.
2181 Timings for PRE on tramp3d-v4:
2182 without maximal set fix: 11 seconds
2183 with maximal set fix/without deferring: 26 seconds
2184 with maximal set fix/with deferring: 11 seconds
2187 if (!defer_or_phi_translate_block (ANTIC_OUT, ANTIC_IN (succ_bb),
2188 block, succ_bb))
2190 changed = true;
2191 goto maybe_dump_sets;
2194 /* If we have multiple successors, we take the intersection of all of
2195 them. Note that in the case of loop exit phi nodes, we may have
2196 phis to translate through. */
2197 else
2199 VEC(basic_block, heap) * worklist;
2200 size_t i;
2201 basic_block bprime, first = NULL;
2203 worklist = VEC_alloc (basic_block, heap, EDGE_COUNT (block->succs));
2204 FOR_EACH_EDGE (e, ei, block->succs)
2206 if (!first
2207 && BB_VISITED (e->dest))
2208 first = e->dest;
2209 else if (BB_VISITED (e->dest))
2210 VEC_quick_push (basic_block, worklist, e->dest);
2213 /* Of multiple successors we have to have visited one already. */
2214 if (!first)
2216 SET_BIT (changed_blocks, block->index);
2217 BB_VISITED (block) = 0;
2218 BB_DEFERRED (block) = 1;
2219 changed = true;
2220 VEC_free (basic_block, heap, worklist);
2221 goto maybe_dump_sets;
2224 if (!gimple_seq_empty_p (phi_nodes (first)))
2225 phi_translate_set (ANTIC_OUT, ANTIC_IN (first), block, first);
2226 else
2227 bitmap_set_copy (ANTIC_OUT, ANTIC_IN (first));
2229 FOR_EACH_VEC_ELT (basic_block, worklist, i, bprime)
2231 if (!gimple_seq_empty_p (phi_nodes (bprime)))
2233 bitmap_set_t tmp = bitmap_set_new ();
2234 phi_translate_set (tmp, ANTIC_IN (bprime), block, bprime);
2235 bitmap_set_and (ANTIC_OUT, tmp);
2236 bitmap_set_free (tmp);
2238 else
2239 bitmap_set_and (ANTIC_OUT, ANTIC_IN (bprime));
2241 VEC_free (basic_block, heap, worklist);
2244 /* Prune expressions that are clobbered in block and thus become
2245 invalid if translated from ANTIC_OUT to ANTIC_IN. */
2246 prune_clobbered_mems (ANTIC_OUT, block);
2248 /* Generate ANTIC_OUT - TMP_GEN. */
2249 S = bitmap_set_subtract (ANTIC_OUT, TMP_GEN (block));
2251 /* Start ANTIC_IN with EXP_GEN - TMP_GEN. */
2252 ANTIC_IN (block) = bitmap_set_subtract (EXP_GEN (block),
2253 TMP_GEN (block));
2255 /* Then union in the ANTIC_OUT - TMP_GEN values,
2256 to get ANTIC_OUT U EXP_GEN - TMP_GEN */
2257 FOR_EACH_EXPR_ID_IN_SET (S, bii, bi)
2258 bitmap_value_insert_into_set (ANTIC_IN (block),
2259 expression_for_id (bii));
2261 clean (ANTIC_IN (block), block);
2263 if (!bitmap_set_equal (old, ANTIC_IN (block)))
2265 changed = true;
2266 SET_BIT (changed_blocks, block->index);
2267 FOR_EACH_EDGE (e, ei, block->preds)
2268 SET_BIT (changed_blocks, e->src->index);
2270 else
2271 RESET_BIT (changed_blocks, block->index);
2273 maybe_dump_sets:
2274 if (dump_file && (dump_flags & TDF_DETAILS))
2276 if (!BB_DEFERRED (block) || BB_VISITED (block))
2278 if (ANTIC_OUT)
2279 print_bitmap_set (dump_file, ANTIC_OUT, "ANTIC_OUT", block->index);
2281 print_bitmap_set (dump_file, ANTIC_IN (block), "ANTIC_IN",
2282 block->index);
2284 if (S)
2285 print_bitmap_set (dump_file, S, "S", block->index);
2287 else
2289 fprintf (dump_file,
2290 "Block %d was deferred for a future iteration.\n",
2291 block->index);
2294 if (old)
2295 bitmap_set_free (old);
2296 if (S)
2297 bitmap_set_free (S);
2298 if (ANTIC_OUT)
2299 bitmap_set_free (ANTIC_OUT);
2300 return changed;
2303 /* Compute PARTIAL_ANTIC for BLOCK.
2305 If succs(BLOCK) > 1 then
2306 PA_OUT[BLOCK] = value wise union of PA_IN[b] + all ANTIC_IN not
2307 in ANTIC_OUT for all succ(BLOCK)
2308 else if succs(BLOCK) == 1 then
2309 PA_OUT[BLOCK] = phi_translate (PA_IN[succ(BLOCK)])
2311 PA_IN[BLOCK] = dependent_clean(PA_OUT[BLOCK] - TMP_GEN[BLOCK]
2312 - ANTIC_IN[BLOCK])
2315 static bool
2316 compute_partial_antic_aux (basic_block block,
2317 bool block_has_abnormal_pred_edge)
2319 bool changed = false;
2320 bitmap_set_t old_PA_IN;
2321 bitmap_set_t PA_OUT;
2322 edge e;
2323 edge_iterator ei;
2324 unsigned long max_pa = PARAM_VALUE (PARAM_MAX_PARTIAL_ANTIC_LENGTH);
2326 old_PA_IN = PA_OUT = NULL;
2328 /* If any edges from predecessors are abnormal, antic_in is empty,
2329 so do nothing. */
2330 if (block_has_abnormal_pred_edge)
2331 goto maybe_dump_sets;
2333 /* If there are too many partially anticipatable values in the
2334 block, phi_translate_set can take an exponential time: stop
2335 before the translation starts. */
2336 if (max_pa
2337 && single_succ_p (block)
2338 && bitmap_count_bits (&PA_IN (single_succ (block))->values) > max_pa)
2339 goto maybe_dump_sets;
2341 old_PA_IN = PA_IN (block);
2342 PA_OUT = bitmap_set_new ();
2344 /* If the block has no successors, ANTIC_OUT is empty. */
2345 if (EDGE_COUNT (block->succs) == 0)
2347 /* If we have one successor, we could have some phi nodes to
2348 translate through. Note that we can't phi translate across DFS
2349 back edges in partial antic, because it uses a union operation on
2350 the successors. For recurrences like IV's, we will end up
2351 generating a new value in the set on each go around (i + 3 (VH.1)
2352 VH.1 + 1 (VH.2), VH.2 + 1 (VH.3), etc), forever. */
2353 else if (single_succ_p (block))
2355 basic_block succ = single_succ (block);
2356 if (!(single_succ_edge (block)->flags & EDGE_DFS_BACK))
2357 phi_translate_set (PA_OUT, PA_IN (succ), block, succ);
2359 /* If we have multiple successors, we take the union of all of
2360 them. */
2361 else
2363 VEC(basic_block, heap) * worklist;
2364 size_t i;
2365 basic_block bprime;
2367 worklist = VEC_alloc (basic_block, heap, EDGE_COUNT (block->succs));
2368 FOR_EACH_EDGE (e, ei, block->succs)
2370 if (e->flags & EDGE_DFS_BACK)
2371 continue;
2372 VEC_quick_push (basic_block, worklist, e->dest);
2374 if (VEC_length (basic_block, worklist) > 0)
2376 FOR_EACH_VEC_ELT (basic_block, worklist, i, bprime)
2378 unsigned int i;
2379 bitmap_iterator bi;
2381 FOR_EACH_EXPR_ID_IN_SET (ANTIC_IN (bprime), i, bi)
2382 bitmap_value_insert_into_set (PA_OUT,
2383 expression_for_id (i));
2384 if (!gimple_seq_empty_p (phi_nodes (bprime)))
2386 bitmap_set_t pa_in = bitmap_set_new ();
2387 phi_translate_set (pa_in, PA_IN (bprime), block, bprime);
2388 FOR_EACH_EXPR_ID_IN_SET (pa_in, i, bi)
2389 bitmap_value_insert_into_set (PA_OUT,
2390 expression_for_id (i));
2391 bitmap_set_free (pa_in);
2393 else
2394 FOR_EACH_EXPR_ID_IN_SET (PA_IN (bprime), i, bi)
2395 bitmap_value_insert_into_set (PA_OUT,
2396 expression_for_id (i));
2399 VEC_free (basic_block, heap, worklist);
2402 /* Prune expressions that are clobbered in block and thus become
2403 invalid if translated from PA_OUT to PA_IN. */
2404 prune_clobbered_mems (PA_OUT, block);
2406 /* PA_IN starts with PA_OUT - TMP_GEN.
2407 Then we subtract things from ANTIC_IN. */
2408 PA_IN (block) = bitmap_set_subtract (PA_OUT, TMP_GEN (block));
2410 /* For partial antic, we want to put back in the phi results, since
2411 we will properly avoid making them partially antic over backedges. */
2412 bitmap_ior_into (&PA_IN (block)->values, &PHI_GEN (block)->values);
2413 bitmap_ior_into (&PA_IN (block)->expressions, &PHI_GEN (block)->expressions);
2415 /* PA_IN[block] = PA_IN[block] - ANTIC_IN[block] */
2416 bitmap_set_subtract_values (PA_IN (block), ANTIC_IN (block));
2418 dependent_clean (PA_IN (block), ANTIC_IN (block), block);
2420 if (!bitmap_set_equal (old_PA_IN, PA_IN (block)))
2422 changed = true;
2423 SET_BIT (changed_blocks, block->index);
2424 FOR_EACH_EDGE (e, ei, block->preds)
2425 SET_BIT (changed_blocks, e->src->index);
2427 else
2428 RESET_BIT (changed_blocks, block->index);
2430 maybe_dump_sets:
2431 if (dump_file && (dump_flags & TDF_DETAILS))
2433 if (PA_OUT)
2434 print_bitmap_set (dump_file, PA_OUT, "PA_OUT", block->index);
2436 print_bitmap_set (dump_file, PA_IN (block), "PA_IN", block->index);
2438 if (old_PA_IN)
2439 bitmap_set_free (old_PA_IN);
2440 if (PA_OUT)
2441 bitmap_set_free (PA_OUT);
2442 return changed;
2445 /* Compute ANTIC and partial ANTIC sets. */
2447 static void
2448 compute_antic (void)
2450 bool changed = true;
2451 int num_iterations = 0;
2452 basic_block block;
2453 int i;
2455 /* If any predecessor edges are abnormal, we punt, so antic_in is empty.
2456 We pre-build the map of blocks with incoming abnormal edges here. */
2457 has_abnormal_preds = sbitmap_alloc (last_basic_block);
2458 sbitmap_zero (has_abnormal_preds);
2460 FOR_ALL_BB (block)
2462 edge_iterator ei;
2463 edge e;
2465 FOR_EACH_EDGE (e, ei, block->preds)
2467 e->flags &= ~EDGE_DFS_BACK;
2468 if (e->flags & EDGE_ABNORMAL)
2470 SET_BIT (has_abnormal_preds, block->index);
2471 break;
2475 BB_VISITED (block) = 0;
2476 BB_DEFERRED (block) = 0;
2478 /* While we are here, give empty ANTIC_IN sets to each block. */
2479 ANTIC_IN (block) = bitmap_set_new ();
2480 PA_IN (block) = bitmap_set_new ();
2483 /* At the exit block we anticipate nothing. */
2484 BB_VISITED (EXIT_BLOCK_PTR) = 1;
2486 changed_blocks = sbitmap_alloc (last_basic_block + 1);
2487 sbitmap_ones (changed_blocks);
2488 while (changed)
2490 if (dump_file && (dump_flags & TDF_DETAILS))
2491 fprintf (dump_file, "Starting iteration %d\n", num_iterations);
2492 /* ??? We need to clear our PHI translation cache here as the
2493 ANTIC sets shrink and we restrict valid translations to
2494 those having operands with leaders in ANTIC. Same below
2495 for PA ANTIC computation. */
2496 num_iterations++;
2497 changed = false;
2498 for (i = postorder_num - 1; i >= 0; i--)
2500 if (TEST_BIT (changed_blocks, postorder[i]))
2502 basic_block block = BASIC_BLOCK (postorder[i]);
2503 changed |= compute_antic_aux (block,
2504 TEST_BIT (has_abnormal_preds,
2505 block->index));
2508 /* Theoretically possible, but *highly* unlikely. */
2509 gcc_checking_assert (num_iterations < 500);
2512 statistics_histogram_event (cfun, "compute_antic iterations",
2513 num_iterations);
2515 if (do_partial_partial)
2517 sbitmap_ones (changed_blocks);
2518 mark_dfs_back_edges ();
2519 num_iterations = 0;
2520 changed = true;
2521 while (changed)
2523 if (dump_file && (dump_flags & TDF_DETAILS))
2524 fprintf (dump_file, "Starting iteration %d\n", num_iterations);
2525 num_iterations++;
2526 changed = false;
2527 for (i = postorder_num - 1 ; i >= 0; i--)
2529 if (TEST_BIT (changed_blocks, postorder[i]))
2531 basic_block block = BASIC_BLOCK (postorder[i]);
2532 changed
2533 |= compute_partial_antic_aux (block,
2534 TEST_BIT (has_abnormal_preds,
2535 block->index));
2538 /* Theoretically possible, but *highly* unlikely. */
2539 gcc_checking_assert (num_iterations < 500);
2541 statistics_histogram_event (cfun, "compute_partial_antic iterations",
2542 num_iterations);
2544 sbitmap_free (has_abnormal_preds);
2545 sbitmap_free (changed_blocks);
2549 /* Inserted expressions are placed onto this worklist, which is used
2550 for performing quick dead code elimination of insertions we made
2551 that didn't turn out to be necessary. */
2552 static bitmap inserted_exprs;
2554 /* The actual worker for create_component_ref_by_pieces. */
2556 static tree
2557 create_component_ref_by_pieces_1 (basic_block block, vn_reference_t ref,
2558 unsigned int *operand, gimple_seq *stmts)
2560 vn_reference_op_t currop = &VEC_index (vn_reference_op_s, ref->operands,
2561 *operand);
2562 tree genop;
2563 ++*operand;
2564 switch (currop->opcode)
2566 case CALL_EXPR:
2568 tree folded, sc = NULL_TREE;
2569 unsigned int nargs = 0;
2570 tree fn, *args;
2571 if (TREE_CODE (currop->op0) == FUNCTION_DECL)
2572 fn = currop->op0;
2573 else
2574 fn = find_or_generate_expression (block, currop->op0, stmts);
2575 if (currop->op1)
2576 sc = find_or_generate_expression (block, currop->op1, stmts);
2577 args = XNEWVEC (tree, VEC_length (vn_reference_op_s,
2578 ref->operands) - 1);
2579 while (*operand < VEC_length (vn_reference_op_s, ref->operands))
2581 args[nargs] = create_component_ref_by_pieces_1 (block, ref,
2582 operand, stmts);
2583 nargs++;
2585 folded = build_call_array (currop->type,
2586 (TREE_CODE (fn) == FUNCTION_DECL
2587 ? build_fold_addr_expr (fn) : fn),
2588 nargs, args);
2589 free (args);
2590 if (sc)
2591 CALL_EXPR_STATIC_CHAIN (folded) = sc;
2592 return folded;
2595 case MEM_REF:
2597 tree baseop = create_component_ref_by_pieces_1 (block, ref, operand,
2598 stmts);
2599 tree offset = currop->op0;
2600 if (TREE_CODE (baseop) == ADDR_EXPR
2601 && handled_component_p (TREE_OPERAND (baseop, 0)))
2603 HOST_WIDE_INT off;
2604 tree base;
2605 base = get_addr_base_and_unit_offset (TREE_OPERAND (baseop, 0),
2606 &off);
2607 gcc_assert (base);
2608 offset = int_const_binop (PLUS_EXPR, offset,
2609 build_int_cst (TREE_TYPE (offset),
2610 off));
2611 baseop = build_fold_addr_expr (base);
2613 return fold_build2 (MEM_REF, currop->type, baseop, offset);
2616 case TARGET_MEM_REF:
2618 tree genop0 = NULL_TREE, genop1 = NULL_TREE;
2619 vn_reference_op_t nextop = &VEC_index (vn_reference_op_s, ref->operands,
2620 ++*operand);
2621 tree baseop = create_component_ref_by_pieces_1 (block, ref, operand,
2622 stmts);
2623 if (currop->op0)
2624 genop0 = find_or_generate_expression (block, currop->op0, stmts);
2625 if (nextop->op0)
2626 genop1 = find_or_generate_expression (block, nextop->op0, stmts);
2627 return build5 (TARGET_MEM_REF, currop->type,
2628 baseop, currop->op2, genop0, currop->op1, genop1);
2631 case ADDR_EXPR:
2632 if (currop->op0)
2634 gcc_assert (is_gimple_min_invariant (currop->op0));
2635 return currop->op0;
2637 /* Fallthrough. */
2638 case REALPART_EXPR:
2639 case IMAGPART_EXPR:
2640 case VIEW_CONVERT_EXPR:
2642 tree genop0 = create_component_ref_by_pieces_1 (block, ref,
2643 operand, stmts);
2644 return fold_build1 (currop->opcode, currop->type, genop0);
2647 case WITH_SIZE_EXPR:
2649 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2650 stmts);
2651 tree genop1 = find_or_generate_expression (block, currop->op0, stmts);
2652 return fold_build2 (currop->opcode, currop->type, genop0, genop1);
2655 case BIT_FIELD_REF:
2657 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2658 stmts);
2659 tree op1 = currop->op0;
2660 tree op2 = currop->op1;
2661 return fold_build3 (BIT_FIELD_REF, currop->type, genop0, op1, op2);
2664 /* For array ref vn_reference_op's, operand 1 of the array ref
2665 is op0 of the reference op and operand 3 of the array ref is
2666 op1. */
2667 case ARRAY_RANGE_REF:
2668 case ARRAY_REF:
2670 tree genop0;
2671 tree genop1 = currop->op0;
2672 tree genop2 = currop->op1;
2673 tree genop3 = currop->op2;
2674 genop0 = create_component_ref_by_pieces_1 (block, ref, operand, stmts);
2675 genop1 = find_or_generate_expression (block, genop1, stmts);
2676 if (genop2)
2678 tree domain_type = TYPE_DOMAIN (TREE_TYPE (genop0));
2679 /* Drop zero minimum index if redundant. */
2680 if (integer_zerop (genop2)
2681 && (!domain_type
2682 || integer_zerop (TYPE_MIN_VALUE (domain_type))))
2683 genop2 = NULL_TREE;
2684 else
2685 genop2 = find_or_generate_expression (block, genop2, stmts);
2687 if (genop3)
2689 tree elmt_type = TREE_TYPE (TREE_TYPE (genop0));
2690 /* We can't always put a size in units of the element alignment
2691 here as the element alignment may be not visible. See
2692 PR43783. Simply drop the element size for constant
2693 sizes. */
2694 if (tree_int_cst_equal (genop3, TYPE_SIZE_UNIT (elmt_type)))
2695 genop3 = NULL_TREE;
2696 else
2698 genop3 = size_binop (EXACT_DIV_EXPR, genop3,
2699 size_int (TYPE_ALIGN_UNIT (elmt_type)));
2700 genop3 = find_or_generate_expression (block, genop3, stmts);
2703 return build4 (currop->opcode, currop->type, genop0, genop1,
2704 genop2, genop3);
2706 case COMPONENT_REF:
2708 tree op0;
2709 tree op1;
2710 tree genop2 = currop->op1;
2711 op0 = create_component_ref_by_pieces_1 (block, ref, operand, stmts);
2712 /* op1 should be a FIELD_DECL, which are represented by themselves. */
2713 op1 = currop->op0;
2714 if (genop2)
2715 genop2 = find_or_generate_expression (block, genop2, stmts);
2716 return fold_build3 (COMPONENT_REF, TREE_TYPE (op1), op0, op1, genop2);
2719 case SSA_NAME:
2721 genop = find_or_generate_expression (block, currop->op0, stmts);
2722 return genop;
2724 case STRING_CST:
2725 case INTEGER_CST:
2726 case COMPLEX_CST:
2727 case VECTOR_CST:
2728 case REAL_CST:
2729 case CONSTRUCTOR:
2730 case VAR_DECL:
2731 case PARM_DECL:
2732 case CONST_DECL:
2733 case RESULT_DECL:
2734 case FUNCTION_DECL:
2735 return currop->op0;
2737 default:
2738 gcc_unreachable ();
2742 /* For COMPONENT_REF's and ARRAY_REF's, we can't have any intermediates for the
2743 COMPONENT_REF or MEM_REF or ARRAY_REF portion, because we'd end up with
2744 trying to rename aggregates into ssa form directly, which is a no no.
2746 Thus, this routine doesn't create temporaries, it just builds a
2747 single access expression for the array, calling
2748 find_or_generate_expression to build the innermost pieces.
2750 This function is a subroutine of create_expression_by_pieces, and
2751 should not be called on it's own unless you really know what you
2752 are doing. */
2754 static tree
2755 create_component_ref_by_pieces (basic_block block, vn_reference_t ref,
2756 gimple_seq *stmts)
2758 unsigned int op = 0;
2759 return create_component_ref_by_pieces_1 (block, ref, &op, stmts);
2762 /* Find a leader for an expression, or generate one using
2763 create_expression_by_pieces if it's ANTIC but
2764 complex.
2765 BLOCK is the basic_block we are looking for leaders in.
2766 OP is the tree expression to find a leader for or generate.
2767 STMTS is the statement list to put the inserted expressions on.
2768 Returns the SSA_NAME of the LHS of the generated expression or the
2769 leader.
2770 DOMSTMT if non-NULL is a statement that should be dominated by
2771 all uses in the generated expression. If DOMSTMT is non-NULL this
2772 routine can fail and return NULL_TREE. Otherwise it will assert
2773 on failure. */
2775 static tree
2776 find_or_generate_expression (basic_block block, tree op, gimple_seq *stmts)
2778 pre_expr expr = get_or_alloc_expr_for (op);
2779 unsigned int lookfor = get_expr_value_id (expr);
2780 pre_expr leader = bitmap_find_leader (AVAIL_OUT (block), lookfor);
2781 if (leader)
2783 if (leader->kind == NAME)
2784 return PRE_EXPR_NAME (leader);
2785 else if (leader->kind == CONSTANT)
2786 return PRE_EXPR_CONSTANT (leader);
2789 /* It must be a complex expression, so generate it recursively. */
2790 bitmap exprset = VEC_index (bitmap, value_expressions, lookfor);
2791 bitmap_iterator bi;
2792 unsigned int i;
2793 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
2795 pre_expr temp = expression_for_id (i);
2796 if (temp->kind != NAME)
2797 return create_expression_by_pieces (block, temp, stmts,
2798 get_expr_type (expr));
2801 gcc_unreachable ();
2804 #define NECESSARY GF_PLF_1
2806 /* Create an expression in pieces, so that we can handle very complex
2807 expressions that may be ANTIC, but not necessary GIMPLE.
2808 BLOCK is the basic block the expression will be inserted into,
2809 EXPR is the expression to insert (in value form)
2810 STMTS is a statement list to append the necessary insertions into.
2812 This function will die if we hit some value that shouldn't be
2813 ANTIC but is (IE there is no leader for it, or its components).
2814 This function may also generate expressions that are themselves
2815 partially or fully redundant. Those that are will be either made
2816 fully redundant during the next iteration of insert (for partially
2817 redundant ones), or eliminated by eliminate (for fully redundant
2818 ones).
2820 If DOMSTMT is non-NULL then we make sure that all uses in the
2821 expressions dominate that statement. In this case the function
2822 can return NULL_TREE to signal failure. */
2824 static tree
2825 create_expression_by_pieces (basic_block block, pre_expr expr,
2826 gimple_seq *stmts, tree type)
2828 tree name;
2829 tree folded;
2830 gimple_seq forced_stmts = NULL;
2831 unsigned int value_id;
2832 gimple_stmt_iterator gsi;
2833 tree exprtype = type ? type : get_expr_type (expr);
2834 pre_expr nameexpr;
2835 gimple newstmt;
2837 switch (expr->kind)
2839 /* We may hit the NAME/CONSTANT case if we have to convert types
2840 that value numbering saw through. */
2841 case NAME:
2842 folded = PRE_EXPR_NAME (expr);
2843 break;
2844 case CONSTANT:
2845 folded = PRE_EXPR_CONSTANT (expr);
2846 break;
2847 case REFERENCE:
2849 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
2850 folded = create_component_ref_by_pieces (block, ref, stmts);
2852 break;
2853 case NARY:
2855 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
2856 tree *genop = XALLOCAVEC (tree, nary->length);
2857 unsigned i;
2858 for (i = 0; i < nary->length; ++i)
2860 genop[i] = find_or_generate_expression (block, nary->op[i], stmts);
2861 /* Ensure genop[] is properly typed for POINTER_PLUS_EXPR. It
2862 may have conversions stripped. */
2863 if (nary->opcode == POINTER_PLUS_EXPR)
2865 if (i == 0)
2866 genop[i] = fold_convert (nary->type, genop[i]);
2867 else if (i == 1)
2868 genop[i] = convert_to_ptrofftype (genop[i]);
2870 else
2871 genop[i] = fold_convert (TREE_TYPE (nary->op[i]), genop[i]);
2873 if (nary->opcode == CONSTRUCTOR)
2875 VEC(constructor_elt,gc) *elts = NULL;
2876 for (i = 0; i < nary->length; ++i)
2877 CONSTRUCTOR_APPEND_ELT (elts, NULL_TREE, genop[i]);
2878 folded = build_constructor (nary->type, elts);
2880 else
2882 switch (nary->length)
2884 case 1:
2885 folded = fold_build1 (nary->opcode, nary->type,
2886 genop[0]);
2887 break;
2888 case 2:
2889 folded = fold_build2 (nary->opcode, nary->type,
2890 genop[0], genop[1]);
2891 break;
2892 case 3:
2893 folded = fold_build3 (nary->opcode, nary->type,
2894 genop[0], genop[1], genop[3]);
2895 break;
2896 default:
2897 gcc_unreachable ();
2901 break;
2902 default:
2903 gcc_unreachable ();
2906 if (!useless_type_conversion_p (exprtype, TREE_TYPE (folded)))
2907 folded = fold_convert (exprtype, folded);
2909 /* Force the generated expression to be a sequence of GIMPLE
2910 statements.
2911 We have to call unshare_expr because force_gimple_operand may
2912 modify the tree we pass to it. */
2913 folded = force_gimple_operand (unshare_expr (folded), &forced_stmts,
2914 false, NULL);
2916 /* If we have any intermediate expressions to the value sets, add them
2917 to the value sets and chain them in the instruction stream. */
2918 if (forced_stmts)
2920 gsi = gsi_start (forced_stmts);
2921 for (; !gsi_end_p (gsi); gsi_next (&gsi))
2923 gimple stmt = gsi_stmt (gsi);
2924 tree forcedname = gimple_get_lhs (stmt);
2925 pre_expr nameexpr;
2927 if (TREE_CODE (forcedname) == SSA_NAME)
2929 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (forcedname));
2930 VN_INFO_GET (forcedname)->valnum = forcedname;
2931 VN_INFO (forcedname)->value_id = get_next_value_id ();
2932 nameexpr = get_or_alloc_expr_for_name (forcedname);
2933 add_to_value (VN_INFO (forcedname)->value_id, nameexpr);
2934 bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
2935 bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
2938 gimple_seq_add_seq (stmts, forced_stmts);
2941 name = make_temp_ssa_name (exprtype, NULL, "pretmp");
2942 newstmt = gimple_build_assign (name, folded);
2943 gimple_set_plf (newstmt, NECESSARY, false);
2945 gimple_seq_add_stmt (stmts, newstmt);
2946 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (name));
2948 /* Fold the last statement. */
2949 gsi = gsi_last (*stmts);
2950 if (fold_stmt_inplace (&gsi))
2951 update_stmt (gsi_stmt (gsi));
2953 /* Add a value number to the temporary.
2954 The value may already exist in either NEW_SETS, or AVAIL_OUT, because
2955 we are creating the expression by pieces, and this particular piece of
2956 the expression may have been represented. There is no harm in replacing
2957 here. */
2958 value_id = get_expr_value_id (expr);
2959 VN_INFO_GET (name)->value_id = value_id;
2960 VN_INFO (name)->valnum = sccvn_valnum_from_value_id (value_id);
2961 if (VN_INFO (name)->valnum == NULL_TREE)
2962 VN_INFO (name)->valnum = name;
2963 gcc_assert (VN_INFO (name)->valnum != NULL_TREE);
2964 nameexpr = get_or_alloc_expr_for_name (name);
2965 add_to_value (value_id, nameexpr);
2966 if (NEW_SETS (block))
2967 bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
2968 bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
2970 pre_stats.insertions++;
2971 if (dump_file && (dump_flags & TDF_DETAILS))
2973 fprintf (dump_file, "Inserted ");
2974 print_gimple_stmt (dump_file, newstmt, 0, 0);
2975 fprintf (dump_file, " in predecessor %d\n", block->index);
2978 return name;
2982 /* Returns true if we want to inhibit the insertions of PHI nodes
2983 for the given EXPR for basic block BB (a member of a loop).
2984 We want to do this, when we fear that the induction variable we
2985 create might inhibit vectorization. */
2987 static bool
2988 inhibit_phi_insertion (basic_block bb, pre_expr expr)
2990 vn_reference_t vr = PRE_EXPR_REFERENCE (expr);
2991 VEC (vn_reference_op_s, heap) *ops = vr->operands;
2992 vn_reference_op_t op;
2993 unsigned i;
2995 /* If we aren't going to vectorize we don't inhibit anything. */
2996 if (!flag_tree_vectorize)
2997 return false;
2999 /* Otherwise we inhibit the insertion when the address of the
3000 memory reference is a simple induction variable. In other
3001 cases the vectorizer won't do anything anyway (either it's
3002 loop invariant or a complicated expression). */
3003 FOR_EACH_VEC_ELT (vn_reference_op_s, ops, i, op)
3005 switch (op->opcode)
3007 case CALL_EXPR:
3008 /* Calls are not a problem. */
3009 return false;
3011 case ARRAY_REF:
3012 case ARRAY_RANGE_REF:
3013 if (TREE_CODE (op->op0) != SSA_NAME)
3014 break;
3015 /* Fallthru. */
3016 case SSA_NAME:
3018 basic_block defbb = gimple_bb (SSA_NAME_DEF_STMT (op->op0));
3019 affine_iv iv;
3020 /* Default defs are loop invariant. */
3021 if (!defbb)
3022 break;
3023 /* Defined outside this loop, also loop invariant. */
3024 if (!flow_bb_inside_loop_p (bb->loop_father, defbb))
3025 break;
3026 /* If it's a simple induction variable inhibit insertion,
3027 the vectorizer might be interested in this one. */
3028 if (simple_iv (bb->loop_father, bb->loop_father,
3029 op->op0, &iv, true))
3030 return true;
3031 /* No simple IV, vectorizer can't do anything, hence no
3032 reason to inhibit the transformation for this operand. */
3033 break;
3035 default:
3036 break;
3039 return false;
3042 /* Insert the to-be-made-available values of expression EXPRNUM for each
3043 predecessor, stored in AVAIL, into the predecessors of BLOCK, and
3044 merge the result with a phi node, given the same value number as
3045 NODE. Return true if we have inserted new stuff. */
3047 static bool
3048 insert_into_preds_of_block (basic_block block, unsigned int exprnum,
3049 VEC(pre_expr, heap) *avail)
3051 pre_expr expr = expression_for_id (exprnum);
3052 pre_expr newphi;
3053 unsigned int val = get_expr_value_id (expr);
3054 edge pred;
3055 bool insertions = false;
3056 bool nophi = false;
3057 basic_block bprime;
3058 pre_expr eprime;
3059 edge_iterator ei;
3060 tree type = get_expr_type (expr);
3061 tree temp;
3062 gimple phi;
3064 /* Make sure we aren't creating an induction variable. */
3065 if (bb_loop_depth (block) > 0 && EDGE_COUNT (block->preds) == 2)
3067 bool firstinsideloop = false;
3068 bool secondinsideloop = false;
3069 firstinsideloop = flow_bb_inside_loop_p (block->loop_father,
3070 EDGE_PRED (block, 0)->src);
3071 secondinsideloop = flow_bb_inside_loop_p (block->loop_father,
3072 EDGE_PRED (block, 1)->src);
3073 /* Induction variables only have one edge inside the loop. */
3074 if ((firstinsideloop ^ secondinsideloop)
3075 && (expr->kind != REFERENCE
3076 || inhibit_phi_insertion (block, expr)))
3078 if (dump_file && (dump_flags & TDF_DETAILS))
3079 fprintf (dump_file, "Skipping insertion of phi for partial redundancy: Looks like an induction variable\n");
3080 nophi = true;
3084 /* Make the necessary insertions. */
3085 FOR_EACH_EDGE (pred, ei, block->preds)
3087 gimple_seq stmts = NULL;
3088 tree builtexpr;
3089 bprime = pred->src;
3090 eprime = VEC_index (pre_expr, avail, pred->dest_idx);
3092 if (eprime->kind != NAME && eprime->kind != CONSTANT)
3094 builtexpr = create_expression_by_pieces (bprime, eprime,
3095 &stmts, type);
3096 gcc_assert (!(pred->flags & EDGE_ABNORMAL));
3097 gsi_insert_seq_on_edge (pred, stmts);
3098 VEC_replace (pre_expr, avail, pred->dest_idx,
3099 get_or_alloc_expr_for_name (builtexpr));
3100 insertions = true;
3102 else if (eprime->kind == CONSTANT)
3104 /* Constants may not have the right type, fold_convert
3105 should give us back a constant with the right type. */
3106 tree constant = PRE_EXPR_CONSTANT (eprime);
3107 if (!useless_type_conversion_p (type, TREE_TYPE (constant)))
3109 tree builtexpr = fold_convert (type, constant);
3110 if (!is_gimple_min_invariant (builtexpr))
3112 tree forcedexpr = force_gimple_operand (builtexpr,
3113 &stmts, true,
3114 NULL);
3115 if (!is_gimple_min_invariant (forcedexpr))
3117 if (forcedexpr != builtexpr)
3119 VN_INFO_GET (forcedexpr)->valnum = PRE_EXPR_CONSTANT (eprime);
3120 VN_INFO (forcedexpr)->value_id = get_expr_value_id (eprime);
3122 if (stmts)
3124 gimple_stmt_iterator gsi;
3125 gsi = gsi_start (stmts);
3126 for (; !gsi_end_p (gsi); gsi_next (&gsi))
3128 gimple stmt = gsi_stmt (gsi);
3129 tree lhs = gimple_get_lhs (stmt);
3130 if (TREE_CODE (lhs) == SSA_NAME)
3131 bitmap_set_bit (inserted_exprs,
3132 SSA_NAME_VERSION (lhs));
3133 gimple_set_plf (stmt, NECESSARY, false);
3135 gsi_insert_seq_on_edge (pred, stmts);
3137 VEC_replace (pre_expr, avail, pred->dest_idx,
3138 get_or_alloc_expr_for_name (forcedexpr));
3141 else
3142 VEC_replace (pre_expr, avail, pred->dest_idx,
3143 get_or_alloc_expr_for_constant (builtexpr));
3146 else if (eprime->kind == NAME)
3148 /* We may have to do a conversion because our value
3149 numbering can look through types in certain cases, but
3150 our IL requires all operands of a phi node have the same
3151 type. */
3152 tree name = PRE_EXPR_NAME (eprime);
3153 if (!useless_type_conversion_p (type, TREE_TYPE (name)))
3155 tree builtexpr;
3156 tree forcedexpr;
3157 builtexpr = fold_convert (type, name);
3158 forcedexpr = force_gimple_operand (builtexpr,
3159 &stmts, true,
3160 NULL);
3162 if (forcedexpr != name)
3164 VN_INFO_GET (forcedexpr)->valnum = VN_INFO (name)->valnum;
3165 VN_INFO (forcedexpr)->value_id = VN_INFO (name)->value_id;
3168 if (stmts)
3170 gimple_stmt_iterator gsi;
3171 gsi = gsi_start (stmts);
3172 for (; !gsi_end_p (gsi); gsi_next (&gsi))
3174 gimple stmt = gsi_stmt (gsi);
3175 tree lhs = gimple_get_lhs (stmt);
3176 if (TREE_CODE (lhs) == SSA_NAME)
3177 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (lhs));
3178 gimple_set_plf (stmt, NECESSARY, false);
3180 gsi_insert_seq_on_edge (pred, stmts);
3182 VEC_replace (pre_expr, avail, pred->dest_idx,
3183 get_or_alloc_expr_for_name (forcedexpr));
3187 /* If we didn't want a phi node, and we made insertions, we still have
3188 inserted new stuff, and thus return true. If we didn't want a phi node,
3189 and didn't make insertions, we haven't added anything new, so return
3190 false. */
3191 if (nophi && insertions)
3192 return true;
3193 else if (nophi && !insertions)
3194 return false;
3196 /* Now build a phi for the new variable. */
3197 temp = make_temp_ssa_name (type, NULL, "prephitmp");
3198 phi = create_phi_node (temp, block);
3200 gimple_set_plf (phi, NECESSARY, false);
3201 VN_INFO_GET (temp)->value_id = val;
3202 VN_INFO (temp)->valnum = sccvn_valnum_from_value_id (val);
3203 if (VN_INFO (temp)->valnum == NULL_TREE)
3204 VN_INFO (temp)->valnum = temp;
3205 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (temp));
3206 FOR_EACH_EDGE (pred, ei, block->preds)
3208 pre_expr ae = VEC_index (pre_expr, avail, pred->dest_idx);
3209 gcc_assert (get_expr_type (ae) == type
3210 || useless_type_conversion_p (type, get_expr_type (ae)));
3211 if (ae->kind == CONSTANT)
3212 add_phi_arg (phi, PRE_EXPR_CONSTANT (ae), pred, UNKNOWN_LOCATION);
3213 else
3214 add_phi_arg (phi, PRE_EXPR_NAME (ae), pred, UNKNOWN_LOCATION);
3217 newphi = get_or_alloc_expr_for_name (temp);
3218 add_to_value (val, newphi);
3220 /* The value should *not* exist in PHI_GEN, or else we wouldn't be doing
3221 this insertion, since we test for the existence of this value in PHI_GEN
3222 before proceeding with the partial redundancy checks in insert_aux.
3224 The value may exist in AVAIL_OUT, in particular, it could be represented
3225 by the expression we are trying to eliminate, in which case we want the
3226 replacement to occur. If it's not existing in AVAIL_OUT, we want it
3227 inserted there.
3229 Similarly, to the PHI_GEN case, the value should not exist in NEW_SETS of
3230 this block, because if it did, it would have existed in our dominator's
3231 AVAIL_OUT, and would have been skipped due to the full redundancy check.
3234 bitmap_insert_into_set (PHI_GEN (block), newphi);
3235 bitmap_value_replace_in_set (AVAIL_OUT (block),
3236 newphi);
3237 bitmap_insert_into_set (NEW_SETS (block),
3238 newphi);
3240 if (dump_file && (dump_flags & TDF_DETAILS))
3242 fprintf (dump_file, "Created phi ");
3243 print_gimple_stmt (dump_file, phi, 0, 0);
3244 fprintf (dump_file, " in block %d\n", block->index);
3246 pre_stats.phis++;
3247 return true;
3252 /* Perform insertion of partially redundant values.
3253 For BLOCK, do the following:
3254 1. Propagate the NEW_SETS of the dominator into the current block.
3255 If the block has multiple predecessors,
3256 2a. Iterate over the ANTIC expressions for the block to see if
3257 any of them are partially redundant.
3258 2b. If so, insert them into the necessary predecessors to make
3259 the expression fully redundant.
3260 2c. Insert a new PHI merging the values of the predecessors.
3261 2d. Insert the new PHI, and the new expressions, into the
3262 NEW_SETS set.
3263 3. Recursively call ourselves on the dominator children of BLOCK.
3265 Steps 1, 2a, and 3 are done by insert_aux. 2b, 2c and 2d are done by
3266 do_regular_insertion and do_partial_insertion.
3270 static bool
3271 do_regular_insertion (basic_block block, basic_block dom)
3273 bool new_stuff = false;
3274 VEC (pre_expr, heap) *exprs;
3275 pre_expr expr;
3276 VEC (pre_expr, heap) *avail = NULL;
3277 int i;
3279 exprs = sorted_array_from_bitmap_set (ANTIC_IN (block));
3280 VEC_safe_grow (pre_expr, heap, avail, EDGE_COUNT (block->preds));
3282 FOR_EACH_VEC_ELT (pre_expr, exprs, i, expr)
3284 if (expr->kind != NAME)
3286 unsigned int val;
3287 bool by_some = false;
3288 bool cant_insert = false;
3289 bool all_same = true;
3290 pre_expr first_s = NULL;
3291 edge pred;
3292 basic_block bprime;
3293 pre_expr eprime = NULL;
3294 edge_iterator ei;
3295 pre_expr edoubleprime = NULL;
3296 bool do_insertion = false;
3298 val = get_expr_value_id (expr);
3299 if (bitmap_set_contains_value (PHI_GEN (block), val))
3300 continue;
3301 if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3303 if (dump_file && (dump_flags & TDF_DETAILS))
3304 fprintf (dump_file, "Found fully redundant value\n");
3305 continue;
3308 FOR_EACH_EDGE (pred, ei, block->preds)
3310 unsigned int vprime;
3312 /* We should never run insertion for the exit block
3313 and so not come across fake pred edges. */
3314 gcc_assert (!(pred->flags & EDGE_FAKE));
3315 bprime = pred->src;
3316 eprime = phi_translate (expr, ANTIC_IN (block), NULL,
3317 bprime, block);
3319 /* eprime will generally only be NULL if the
3320 value of the expression, translated
3321 through the PHI for this predecessor, is
3322 undefined. If that is the case, we can't
3323 make the expression fully redundant,
3324 because its value is undefined along a
3325 predecessor path. We can thus break out
3326 early because it doesn't matter what the
3327 rest of the results are. */
3328 if (eprime == NULL)
3330 VEC_replace (pre_expr, avail, pred->dest_idx, NULL);
3331 cant_insert = true;
3332 break;
3335 eprime = fully_constant_expression (eprime);
3336 vprime = get_expr_value_id (eprime);
3337 edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime),
3338 vprime);
3339 if (edoubleprime == NULL)
3341 VEC_replace (pre_expr, avail, pred->dest_idx, eprime);
3342 all_same = false;
3344 else
3346 VEC_replace (pre_expr, avail, pred->dest_idx, edoubleprime);
3347 by_some = true;
3348 /* We want to perform insertions to remove a redundancy on
3349 a path in the CFG we want to optimize for speed. */
3350 if (optimize_edge_for_speed_p (pred))
3351 do_insertion = true;
3352 if (first_s == NULL)
3353 first_s = edoubleprime;
3354 else if (!pre_expr_d::equal (first_s, edoubleprime))
3355 all_same = false;
3358 /* If we can insert it, it's not the same value
3359 already existing along every predecessor, and
3360 it's defined by some predecessor, it is
3361 partially redundant. */
3362 if (!cant_insert && !all_same && by_some)
3364 if (!do_insertion)
3366 if (dump_file && (dump_flags & TDF_DETAILS))
3368 fprintf (dump_file, "Skipping partial redundancy for "
3369 "expression ");
3370 print_pre_expr (dump_file, expr);
3371 fprintf (dump_file, " (%04d), no redundancy on to be "
3372 "optimized for speed edge\n", val);
3375 else if (dbg_cnt (treepre_insert))
3377 if (dump_file && (dump_flags & TDF_DETAILS))
3379 fprintf (dump_file, "Found partial redundancy for "
3380 "expression ");
3381 print_pre_expr (dump_file, expr);
3382 fprintf (dump_file, " (%04d)\n",
3383 get_expr_value_id (expr));
3385 if (insert_into_preds_of_block (block,
3386 get_expression_id (expr),
3387 avail))
3388 new_stuff = true;
3391 /* If all edges produce the same value and that value is
3392 an invariant, then the PHI has the same value on all
3393 edges. Note this. */
3394 else if (!cant_insert && all_same && eprime
3395 && (edoubleprime->kind == CONSTANT
3396 || edoubleprime->kind == NAME)
3397 && !value_id_constant_p (val))
3399 unsigned int j;
3400 bitmap_iterator bi;
3401 bitmap exprset = VEC_index (bitmap, value_expressions, val);
3403 unsigned int new_val = get_expr_value_id (edoubleprime);
3404 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, j, bi)
3406 pre_expr expr = expression_for_id (j);
3408 if (expr->kind == NAME)
3410 vn_ssa_aux_t info = VN_INFO (PRE_EXPR_NAME (expr));
3411 /* Just reset the value id and valnum so it is
3412 the same as the constant we have discovered. */
3413 if (edoubleprime->kind == CONSTANT)
3415 info->valnum = PRE_EXPR_CONSTANT (edoubleprime);
3416 pre_stats.constified++;
3418 else
3419 info->valnum = VN_INFO (PRE_EXPR_NAME (edoubleprime))->valnum;
3420 info->value_id = new_val;
3427 VEC_free (pre_expr, heap, exprs);
3428 VEC_free (pre_expr, heap, avail);
3429 return new_stuff;
3433 /* Perform insertion for partially anticipatable expressions. There
3434 is only one case we will perform insertion for these. This case is
3435 if the expression is partially anticipatable, and fully available.
3436 In this case, we know that putting it earlier will enable us to
3437 remove the later computation. */
3440 static bool
3441 do_partial_partial_insertion (basic_block block, basic_block dom)
3443 bool new_stuff = false;
3444 VEC (pre_expr, heap) *exprs;
3445 pre_expr expr;
3446 VEC (pre_expr, heap) *avail = NULL;
3447 int i;
3449 exprs = sorted_array_from_bitmap_set (PA_IN (block));
3450 VEC_safe_grow (pre_expr, heap, avail, EDGE_COUNT (block->preds));
3452 FOR_EACH_VEC_ELT (pre_expr, exprs, i, expr)
3454 if (expr->kind != NAME)
3456 unsigned int val;
3457 bool by_all = true;
3458 bool cant_insert = false;
3459 edge pred;
3460 basic_block bprime;
3461 pre_expr eprime = NULL;
3462 edge_iterator ei;
3464 val = get_expr_value_id (expr);
3465 if (bitmap_set_contains_value (PHI_GEN (block), val))
3466 continue;
3467 if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3468 continue;
3470 FOR_EACH_EDGE (pred, ei, block->preds)
3472 unsigned int vprime;
3473 pre_expr edoubleprime;
3475 /* We should never run insertion for the exit block
3476 and so not come across fake pred edges. */
3477 gcc_assert (!(pred->flags & EDGE_FAKE));
3478 bprime = pred->src;
3479 eprime = phi_translate (expr, ANTIC_IN (block),
3480 PA_IN (block),
3481 bprime, block);
3483 /* eprime will generally only be NULL if the
3484 value of the expression, translated
3485 through the PHI for this predecessor, is
3486 undefined. If that is the case, we can't
3487 make the expression fully redundant,
3488 because its value is undefined along a
3489 predecessor path. We can thus break out
3490 early because it doesn't matter what the
3491 rest of the results are. */
3492 if (eprime == NULL)
3494 VEC_replace (pre_expr, avail, pred->dest_idx, NULL);
3495 cant_insert = true;
3496 break;
3499 eprime = fully_constant_expression (eprime);
3500 vprime = get_expr_value_id (eprime);
3501 edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime), vprime);
3502 VEC_replace (pre_expr, avail, pred->dest_idx, edoubleprime);
3503 if (edoubleprime == NULL)
3505 by_all = false;
3506 break;
3510 /* If we can insert it, it's not the same value
3511 already existing along every predecessor, and
3512 it's defined by some predecessor, it is
3513 partially redundant. */
3514 if (!cant_insert && by_all)
3516 edge succ;
3517 bool do_insertion = false;
3519 /* Insert only if we can remove a later expression on a path
3520 that we want to optimize for speed.
3521 The phi node that we will be inserting in BLOCK is not free,
3522 and inserting it for the sake of !optimize_for_speed successor
3523 may cause regressions on the speed path. */
3524 FOR_EACH_EDGE (succ, ei, block->succs)
3526 if (bitmap_set_contains_value (PA_IN (succ->dest), val))
3528 if (optimize_edge_for_speed_p (succ))
3529 do_insertion = true;
3533 if (!do_insertion)
3535 if (dump_file && (dump_flags & TDF_DETAILS))
3537 fprintf (dump_file, "Skipping partial partial redundancy "
3538 "for expression ");
3539 print_pre_expr (dump_file, expr);
3540 fprintf (dump_file, " (%04d), not partially anticipated "
3541 "on any to be optimized for speed edges\n", val);
3544 else if (dbg_cnt (treepre_insert))
3546 pre_stats.pa_insert++;
3547 if (dump_file && (dump_flags & TDF_DETAILS))
3549 fprintf (dump_file, "Found partial partial redundancy "
3550 "for expression ");
3551 print_pre_expr (dump_file, expr);
3552 fprintf (dump_file, " (%04d)\n",
3553 get_expr_value_id (expr));
3555 if (insert_into_preds_of_block (block,
3556 get_expression_id (expr),
3557 avail))
3558 new_stuff = true;
3564 VEC_free (pre_expr, heap, exprs);
3565 VEC_free (pre_expr, heap, avail);
3566 return new_stuff;
3569 static bool
3570 insert_aux (basic_block block)
3572 basic_block son;
3573 bool new_stuff = false;
3575 if (block)
3577 basic_block dom;
3578 dom = get_immediate_dominator (CDI_DOMINATORS, block);
3579 if (dom)
3581 unsigned i;
3582 bitmap_iterator bi;
3583 bitmap_set_t newset = NEW_SETS (dom);
3584 if (newset)
3586 /* Note that we need to value_replace both NEW_SETS, and
3587 AVAIL_OUT. For both the case of NEW_SETS, the value may be
3588 represented by some non-simple expression here that we want
3589 to replace it with. */
3590 FOR_EACH_EXPR_ID_IN_SET (newset, i, bi)
3592 pre_expr expr = expression_for_id (i);
3593 bitmap_value_replace_in_set (NEW_SETS (block), expr);
3594 bitmap_value_replace_in_set (AVAIL_OUT (block), expr);
3597 if (!single_pred_p (block))
3599 new_stuff |= do_regular_insertion (block, dom);
3600 if (do_partial_partial)
3601 new_stuff |= do_partial_partial_insertion (block, dom);
3605 for (son = first_dom_son (CDI_DOMINATORS, block);
3606 son;
3607 son = next_dom_son (CDI_DOMINATORS, son))
3609 new_stuff |= insert_aux (son);
3612 return new_stuff;
3615 /* Perform insertion of partially redundant values. */
3617 static void
3618 insert (void)
3620 bool new_stuff = true;
3621 basic_block bb;
3622 int num_iterations = 0;
3624 FOR_ALL_BB (bb)
3625 NEW_SETS (bb) = bitmap_set_new ();
3627 while (new_stuff)
3629 num_iterations++;
3630 if (dump_file && dump_flags & TDF_DETAILS)
3631 fprintf (dump_file, "Starting insert iteration %d\n", num_iterations);
3632 new_stuff = insert_aux (ENTRY_BLOCK_PTR);
3634 statistics_histogram_event (cfun, "insert iterations", num_iterations);
3638 /* Add OP to EXP_GEN (block), and possibly to the maximal set. */
3640 static void
3641 add_to_exp_gen (basic_block block, tree op)
3643 pre_expr result;
3645 if (TREE_CODE (op) == SSA_NAME && ssa_undefined_value_p (op))
3646 return;
3648 result = get_or_alloc_expr_for_name (op);
3649 bitmap_value_insert_into_set (EXP_GEN (block), result);
3652 /* Create value ids for PHI in BLOCK. */
3654 static void
3655 make_values_for_phi (gimple phi, basic_block block)
3657 tree result = gimple_phi_result (phi);
3658 unsigned i;
3660 /* We have no need for virtual phis, as they don't represent
3661 actual computations. */
3662 if (virtual_operand_p (result))
3663 return;
3665 pre_expr e = get_or_alloc_expr_for_name (result);
3666 add_to_value (get_expr_value_id (e), e);
3667 bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3668 bitmap_insert_into_set (PHI_GEN (block), e);
3669 for (i = 0; i < gimple_phi_num_args (phi); ++i)
3671 tree arg = gimple_phi_arg_def (phi, i);
3672 if (TREE_CODE (arg) == SSA_NAME)
3674 e = get_or_alloc_expr_for_name (arg);
3675 add_to_value (get_expr_value_id (e), e);
3680 /* Compute the AVAIL set for all basic blocks.
3682 This function performs value numbering of the statements in each basic
3683 block. The AVAIL sets are built from information we glean while doing
3684 this value numbering, since the AVAIL sets contain only one entry per
3685 value.
3687 AVAIL_IN[BLOCK] = AVAIL_OUT[dom(BLOCK)].
3688 AVAIL_OUT[BLOCK] = AVAIL_IN[BLOCK] U PHI_GEN[BLOCK] U TMP_GEN[BLOCK]. */
3690 static void
3691 compute_avail (void)
3694 basic_block block, son;
3695 basic_block *worklist;
3696 size_t sp = 0;
3697 unsigned i;
3699 /* We pretend that default definitions are defined in the entry block.
3700 This includes function arguments and the static chain decl. */
3701 for (i = 1; i < num_ssa_names; ++i)
3703 tree name = ssa_name (i);
3704 pre_expr e;
3705 if (!name
3706 || !SSA_NAME_IS_DEFAULT_DEF (name)
3707 || has_zero_uses (name)
3708 || virtual_operand_p (name))
3709 continue;
3711 e = get_or_alloc_expr_for_name (name);
3712 add_to_value (get_expr_value_id (e), e);
3713 bitmap_insert_into_set (TMP_GEN (ENTRY_BLOCK_PTR), e);
3714 bitmap_value_insert_into_set (AVAIL_OUT (ENTRY_BLOCK_PTR), e);
3717 /* Allocate the worklist. */
3718 worklist = XNEWVEC (basic_block, n_basic_blocks);
3720 /* Seed the algorithm by putting the dominator children of the entry
3721 block on the worklist. */
3722 for (son = first_dom_son (CDI_DOMINATORS, ENTRY_BLOCK_PTR);
3723 son;
3724 son = next_dom_son (CDI_DOMINATORS, son))
3725 worklist[sp++] = son;
3727 /* Loop until the worklist is empty. */
3728 while (sp)
3730 gimple_stmt_iterator gsi;
3731 gimple stmt;
3732 basic_block dom;
3734 /* Pick a block from the worklist. */
3735 block = worklist[--sp];
3737 /* Initially, the set of available values in BLOCK is that of
3738 its immediate dominator. */
3739 dom = get_immediate_dominator (CDI_DOMINATORS, block);
3740 if (dom)
3741 bitmap_set_copy (AVAIL_OUT (block), AVAIL_OUT (dom));
3743 /* Generate values for PHI nodes. */
3744 for (gsi = gsi_start_phis (block); !gsi_end_p (gsi); gsi_next (&gsi))
3745 make_values_for_phi (gsi_stmt (gsi), block);
3747 BB_MAY_NOTRETURN (block) = 0;
3749 /* Now compute value numbers and populate value sets with all
3750 the expressions computed in BLOCK. */
3751 for (gsi = gsi_start_bb (block); !gsi_end_p (gsi); gsi_next (&gsi))
3753 ssa_op_iter iter;
3754 tree op;
3756 stmt = gsi_stmt (gsi);
3758 /* Cache whether the basic-block has any non-visible side-effect
3759 or control flow.
3760 If this isn't a call or it is the last stmt in the
3761 basic-block then the CFG represents things correctly. */
3762 if (is_gimple_call (stmt) && !stmt_ends_bb_p (stmt))
3764 /* Non-looping const functions always return normally.
3765 Otherwise the call might not return or have side-effects
3766 that forbids hoisting possibly trapping expressions
3767 before it. */
3768 int flags = gimple_call_flags (stmt);
3769 if (!(flags & ECF_CONST)
3770 || (flags & ECF_LOOPING_CONST_OR_PURE))
3771 BB_MAY_NOTRETURN (block) = 1;
3774 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_DEF)
3776 pre_expr e = get_or_alloc_expr_for_name (op);
3778 add_to_value (get_expr_value_id (e), e);
3779 bitmap_insert_into_set (TMP_GEN (block), e);
3780 bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3783 if (gimple_has_side_effects (stmt)
3784 || stmt_could_throw_p (stmt)
3785 || is_gimple_debug (stmt))
3786 continue;
3788 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
3789 add_to_exp_gen (block, op);
3791 switch (gimple_code (stmt))
3793 case GIMPLE_RETURN:
3794 continue;
3796 case GIMPLE_CALL:
3798 vn_reference_t ref;
3799 pre_expr result = NULL;
3800 VEC(vn_reference_op_s, heap) *ops = NULL;
3802 /* We can value number only calls to real functions. */
3803 if (gimple_call_internal_p (stmt))
3804 continue;
3806 copy_reference_ops_from_call (stmt, &ops);
3807 vn_reference_lookup_pieces (gimple_vuse (stmt), 0,
3808 gimple_expr_type (stmt),
3809 ops, &ref, VN_NOWALK);
3810 VEC_free (vn_reference_op_s, heap, ops);
3811 if (!ref)
3812 continue;
3814 /* If the value of the call is not invalidated in
3815 this block until it is computed, add the expression
3816 to EXP_GEN. */
3817 if (!gimple_vuse (stmt)
3818 || gimple_code
3819 (SSA_NAME_DEF_STMT (gimple_vuse (stmt))) == GIMPLE_PHI
3820 || gimple_bb (SSA_NAME_DEF_STMT
3821 (gimple_vuse (stmt))) != block)
3823 result = (pre_expr) pool_alloc (pre_expr_pool);
3824 result->kind = REFERENCE;
3825 result->id = 0;
3826 PRE_EXPR_REFERENCE (result) = ref;
3828 get_or_alloc_expression_id (result);
3829 add_to_value (get_expr_value_id (result), result);
3830 bitmap_value_insert_into_set (EXP_GEN (block), result);
3832 continue;
3835 case GIMPLE_ASSIGN:
3837 pre_expr result = NULL;
3838 switch (vn_get_stmt_kind (stmt))
3840 case VN_NARY:
3842 enum tree_code code = gimple_assign_rhs_code (stmt);
3843 vn_nary_op_t nary;
3845 /* COND_EXPR and VEC_COND_EXPR are awkward in
3846 that they contain an embedded complex expression.
3847 Don't even try to shove those through PRE. */
3848 if (code == COND_EXPR
3849 || code == VEC_COND_EXPR)
3850 continue;
3852 vn_nary_op_lookup_stmt (stmt, &nary);
3853 if (!nary)
3854 continue;
3856 /* If the NARY traps and there was a preceding
3857 point in the block that might not return avoid
3858 adding the nary to EXP_GEN. */
3859 if (BB_MAY_NOTRETURN (block)
3860 && vn_nary_may_trap (nary))
3861 continue;
3863 result = (pre_expr) pool_alloc (pre_expr_pool);
3864 result->kind = NARY;
3865 result->id = 0;
3866 PRE_EXPR_NARY (result) = nary;
3867 break;
3870 case VN_REFERENCE:
3872 vn_reference_t ref;
3873 vn_reference_lookup (gimple_assign_rhs1 (stmt),
3874 gimple_vuse (stmt),
3875 VN_WALK, &ref);
3876 if (!ref)
3877 continue;
3879 /* If the value of the reference is not invalidated in
3880 this block until it is computed, add the expression
3881 to EXP_GEN. */
3882 if (gimple_vuse (stmt))
3884 gimple def_stmt;
3885 bool ok = true;
3886 def_stmt = SSA_NAME_DEF_STMT (gimple_vuse (stmt));
3887 while (!gimple_nop_p (def_stmt)
3888 && gimple_code (def_stmt) != GIMPLE_PHI
3889 && gimple_bb (def_stmt) == block)
3891 if (stmt_may_clobber_ref_p
3892 (def_stmt, gimple_assign_rhs1 (stmt)))
3894 ok = false;
3895 break;
3897 def_stmt
3898 = SSA_NAME_DEF_STMT (gimple_vuse (def_stmt));
3900 if (!ok)
3901 continue;
3904 result = (pre_expr) pool_alloc (pre_expr_pool);
3905 result->kind = REFERENCE;
3906 result->id = 0;
3907 PRE_EXPR_REFERENCE (result) = ref;
3908 break;
3911 default:
3912 continue;
3915 get_or_alloc_expression_id (result);
3916 add_to_value (get_expr_value_id (result), result);
3917 bitmap_value_insert_into_set (EXP_GEN (block), result);
3918 continue;
3920 default:
3921 break;
3925 /* Put the dominator children of BLOCK on the worklist of blocks
3926 to compute available sets for. */
3927 for (son = first_dom_son (CDI_DOMINATORS, block);
3928 son;
3929 son = next_dom_son (CDI_DOMINATORS, son))
3930 worklist[sp++] = son;
3933 free (worklist);
3937 /* Local state for the eliminate domwalk. */
3938 static VEC (gimple, heap) *el_to_remove;
3939 static VEC (gimple, heap) *el_to_update;
3940 static unsigned int el_todo;
3941 static VEC (tree, heap) *el_avail;
3942 static VEC (tree, heap) *el_avail_stack;
3944 /* Return a leader for OP that is available at the current point of the
3945 eliminate domwalk. */
3947 static tree
3948 eliminate_avail (tree op)
3950 tree valnum = VN_INFO (op)->valnum;
3951 if (TREE_CODE (valnum) == SSA_NAME)
3953 if (SSA_NAME_IS_DEFAULT_DEF (valnum))
3954 return valnum;
3955 if (VEC_length (tree, el_avail) > SSA_NAME_VERSION (valnum))
3956 return VEC_index (tree, el_avail, SSA_NAME_VERSION (valnum));
3958 else if (is_gimple_min_invariant (valnum))
3959 return valnum;
3960 return NULL_TREE;
3963 /* At the current point of the eliminate domwalk make OP available. */
3965 static void
3966 eliminate_push_avail (tree op)
3968 tree valnum = VN_INFO (op)->valnum;
3969 if (TREE_CODE (valnum) == SSA_NAME)
3971 if (VEC_length (tree, el_avail) <= SSA_NAME_VERSION (valnum))
3972 VEC_safe_grow_cleared (tree, heap,
3973 el_avail, SSA_NAME_VERSION (valnum) + 1);
3974 VEC_replace (tree, el_avail, SSA_NAME_VERSION (valnum), op);
3975 VEC_safe_push (tree, heap, el_avail_stack, op);
3979 /* Insert the expression recorded by SCCVN for VAL at *GSI. Returns
3980 the leader for the expression if insertion was successful. */
3982 static tree
3983 eliminate_insert (gimple_stmt_iterator *gsi, tree val)
3985 tree expr = vn_get_expr_for (val);
3986 if (!CONVERT_EXPR_P (expr)
3987 && TREE_CODE (expr) != VIEW_CONVERT_EXPR)
3988 return NULL_TREE;
3990 tree op = TREE_OPERAND (expr, 0);
3991 tree leader = TREE_CODE (op) == SSA_NAME ? eliminate_avail (op) : op;
3992 if (!leader)
3993 return NULL_TREE;
3995 tree res = make_temp_ssa_name (TREE_TYPE (val), NULL, "pretmp");
3996 gimple tem = gimple_build_assign (res,
3997 build1 (TREE_CODE (expr),
3998 TREE_TYPE (expr), leader));
3999 gsi_insert_before (gsi, tem, GSI_SAME_STMT);
4000 VN_INFO_GET (res)->valnum = val;
4002 if (TREE_CODE (leader) == SSA_NAME)
4003 gimple_set_plf (SSA_NAME_DEF_STMT (leader), NECESSARY, true);
4005 pre_stats.insertions++;
4006 if (dump_file && (dump_flags & TDF_DETAILS))
4008 fprintf (dump_file, "Inserted ");
4009 print_gimple_stmt (dump_file, tem, 0, 0);
4012 return res;
4015 /* Perform elimination for the basic-block B during the domwalk. */
4017 static void
4018 eliminate_bb (dom_walk_data *, basic_block b)
4020 gimple_stmt_iterator gsi;
4021 gimple stmt;
4023 /* Mark new bb. */
4024 VEC_safe_push (tree, heap, el_avail_stack, NULL_TREE);
4026 for (gsi = gsi_start_phis (b); !gsi_end_p (gsi);)
4028 gimple stmt, phi = gsi_stmt (gsi);
4029 tree sprime = NULL_TREE, res = PHI_RESULT (phi);
4030 gimple_stmt_iterator gsi2;
4032 /* We want to perform redundant PHI elimination. Do so by
4033 replacing the PHI with a single copy if possible.
4034 Do not touch inserted, single-argument or virtual PHIs. */
4035 if (gimple_phi_num_args (phi) == 1
4036 || virtual_operand_p (res))
4038 gsi_next (&gsi);
4039 continue;
4042 sprime = eliminate_avail (res);
4043 if (!sprime
4044 || sprime == res)
4046 eliminate_push_avail (res);
4047 gsi_next (&gsi);
4048 continue;
4050 else if (is_gimple_min_invariant (sprime))
4052 if (!useless_type_conversion_p (TREE_TYPE (res),
4053 TREE_TYPE (sprime)))
4054 sprime = fold_convert (TREE_TYPE (res), sprime);
4057 if (dump_file && (dump_flags & TDF_DETAILS))
4059 fprintf (dump_file, "Replaced redundant PHI node defining ");
4060 print_generic_expr (dump_file, res, 0);
4061 fprintf (dump_file, " with ");
4062 print_generic_expr (dump_file, sprime, 0);
4063 fprintf (dump_file, "\n");
4066 remove_phi_node (&gsi, false);
4068 if (inserted_exprs
4069 && !bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (res))
4070 && TREE_CODE (sprime) == SSA_NAME)
4071 gimple_set_plf (SSA_NAME_DEF_STMT (sprime), NECESSARY, true);
4073 if (!useless_type_conversion_p (TREE_TYPE (res), TREE_TYPE (sprime)))
4074 sprime = fold_convert (TREE_TYPE (res), sprime);
4075 stmt = gimple_build_assign (res, sprime);
4076 SSA_NAME_DEF_STMT (res) = stmt;
4077 gimple_set_plf (stmt, NECESSARY, gimple_plf (phi, NECESSARY));
4079 gsi2 = gsi_after_labels (b);
4080 gsi_insert_before (&gsi2, stmt, GSI_NEW_STMT);
4081 /* Queue the copy for eventual removal. */
4082 VEC_safe_push (gimple, heap, el_to_remove, stmt);
4083 /* If we inserted this PHI node ourself, it's not an elimination. */
4084 if (inserted_exprs
4085 && bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (res)))
4086 pre_stats.phis--;
4087 else
4088 pre_stats.eliminations++;
4091 for (gsi = gsi_start_bb (b); !gsi_end_p (gsi); gsi_next (&gsi))
4093 tree lhs = NULL_TREE;
4094 tree rhs = NULL_TREE;
4096 stmt = gsi_stmt (gsi);
4098 if (gimple_has_lhs (stmt))
4099 lhs = gimple_get_lhs (stmt);
4101 if (gimple_assign_single_p (stmt))
4102 rhs = gimple_assign_rhs1 (stmt);
4104 /* Lookup the RHS of the expression, see if we have an
4105 available computation for it. If so, replace the RHS with
4106 the available computation.
4108 See PR43491.
4109 We don't replace global register variable when it is a the RHS of
4110 a single assign. We do replace local register variable since gcc
4111 does not guarantee local variable will be allocated in register. */
4112 if (gimple_has_lhs (stmt)
4113 && TREE_CODE (lhs) == SSA_NAME
4114 && !gimple_assign_ssa_name_copy_p (stmt)
4115 && (!gimple_assign_single_p (stmt)
4116 || (!is_gimple_min_invariant (rhs)
4117 && (gimple_assign_rhs_code (stmt) != VAR_DECL
4118 || !is_global_var (rhs)
4119 || !DECL_HARD_REGISTER (rhs))))
4120 && !gimple_has_volatile_ops (stmt))
4122 tree sprime;
4123 gimple orig_stmt = stmt;
4125 sprime = eliminate_avail (lhs);
4126 if (!sprime)
4128 /* If there is no existing usable leader but SCCVN thinks
4129 it has an expression it wants to use as replacement,
4130 insert that. */
4131 tree val = VN_INFO (lhs)->valnum;
4132 if (val != VN_TOP
4133 && TREE_CODE (val) == SSA_NAME
4134 && VN_INFO (val)->needs_insertion
4135 && (sprime = eliminate_insert (&gsi, val)) != NULL_TREE)
4136 eliminate_push_avail (sprime);
4138 else if (is_gimple_min_invariant (sprime))
4140 /* If there is no existing leader but SCCVN knows this
4141 value is constant, use that constant. */
4142 if (!useless_type_conversion_p (TREE_TYPE (lhs),
4143 TREE_TYPE (sprime)))
4144 sprime = fold_convert (TREE_TYPE (lhs), sprime);
4146 if (dump_file && (dump_flags & TDF_DETAILS))
4148 fprintf (dump_file, "Replaced ");
4149 print_gimple_expr (dump_file, stmt, 0, 0);
4150 fprintf (dump_file, " with ");
4151 print_generic_expr (dump_file, sprime, 0);
4152 fprintf (dump_file, " in ");
4153 print_gimple_stmt (dump_file, stmt, 0, 0);
4155 pre_stats.eliminations++;
4156 propagate_tree_value_into_stmt (&gsi, sprime);
4157 stmt = gsi_stmt (gsi);
4158 update_stmt (stmt);
4160 /* If we removed EH side-effects from the statement, clean
4161 its EH information. */
4162 if (maybe_clean_or_replace_eh_stmt (orig_stmt, stmt))
4164 bitmap_set_bit (need_eh_cleanup,
4165 gimple_bb (stmt)->index);
4166 if (dump_file && (dump_flags & TDF_DETAILS))
4167 fprintf (dump_file, " Removed EH side-effects.\n");
4169 continue;
4172 /* If there is no usable leader mark lhs as leader for its value. */
4173 if (!sprime)
4174 eliminate_push_avail (lhs);
4176 if (sprime
4177 && sprime != lhs
4178 && (rhs == NULL_TREE
4179 || TREE_CODE (rhs) != SSA_NAME
4180 || may_propagate_copy (rhs, sprime)))
4182 bool can_make_abnormal_goto
4183 = is_gimple_call (stmt)
4184 && stmt_can_make_abnormal_goto (stmt);
4186 gcc_assert (sprime != rhs);
4188 if (dump_file && (dump_flags & TDF_DETAILS))
4190 fprintf (dump_file, "Replaced ");
4191 print_gimple_expr (dump_file, stmt, 0, 0);
4192 fprintf (dump_file, " with ");
4193 print_generic_expr (dump_file, sprime, 0);
4194 fprintf (dump_file, " in ");
4195 print_gimple_stmt (dump_file, stmt, 0, 0);
4198 if (TREE_CODE (sprime) == SSA_NAME)
4199 gimple_set_plf (SSA_NAME_DEF_STMT (sprime),
4200 NECESSARY, true);
4201 /* We need to make sure the new and old types actually match,
4202 which may require adding a simple cast, which fold_convert
4203 will do for us. */
4204 if ((!rhs || TREE_CODE (rhs) != SSA_NAME)
4205 && !useless_type_conversion_p (gimple_expr_type (stmt),
4206 TREE_TYPE (sprime)))
4207 sprime = fold_convert (gimple_expr_type (stmt), sprime);
4209 pre_stats.eliminations++;
4210 propagate_tree_value_into_stmt (&gsi, sprime);
4211 stmt = gsi_stmt (gsi);
4212 update_stmt (stmt);
4214 /* If we removed EH side-effects from the statement, clean
4215 its EH information. */
4216 if (maybe_clean_or_replace_eh_stmt (orig_stmt, stmt))
4218 bitmap_set_bit (need_eh_cleanup,
4219 gimple_bb (stmt)->index);
4220 if (dump_file && (dump_flags & TDF_DETAILS))
4221 fprintf (dump_file, " Removed EH side-effects.\n");
4224 /* Likewise for AB side-effects. */
4225 if (can_make_abnormal_goto
4226 && !stmt_can_make_abnormal_goto (stmt))
4228 bitmap_set_bit (need_ab_cleanup,
4229 gimple_bb (stmt)->index);
4230 if (dump_file && (dump_flags & TDF_DETAILS))
4231 fprintf (dump_file, " Removed AB side-effects.\n");
4235 /* If the statement is a scalar store, see if the expression
4236 has the same value number as its rhs. If so, the store is
4237 dead. */
4238 else if (gimple_assign_single_p (stmt)
4239 && !gimple_has_volatile_ops (stmt)
4240 && !is_gimple_reg (gimple_assign_lhs (stmt))
4241 && (TREE_CODE (rhs) == SSA_NAME
4242 || is_gimple_min_invariant (rhs)))
4244 tree val;
4245 val = vn_reference_lookup (gimple_assign_lhs (stmt),
4246 gimple_vuse (stmt), VN_WALK, NULL);
4247 if (TREE_CODE (rhs) == SSA_NAME)
4248 rhs = VN_INFO (rhs)->valnum;
4249 if (val
4250 && operand_equal_p (val, rhs, 0))
4252 if (dump_file && (dump_flags & TDF_DETAILS))
4254 fprintf (dump_file, "Deleted redundant store ");
4255 print_gimple_stmt (dump_file, stmt, 0, 0);
4258 /* Queue stmt for removal. */
4259 VEC_safe_push (gimple, heap, el_to_remove, stmt);
4262 /* Visit COND_EXPRs and fold the comparison with the
4263 available value-numbers. */
4264 else if (gimple_code (stmt) == GIMPLE_COND)
4266 tree op0 = gimple_cond_lhs (stmt);
4267 tree op1 = gimple_cond_rhs (stmt);
4268 tree result;
4270 if (TREE_CODE (op0) == SSA_NAME)
4271 op0 = VN_INFO (op0)->valnum;
4272 if (TREE_CODE (op1) == SSA_NAME)
4273 op1 = VN_INFO (op1)->valnum;
4274 result = fold_binary (gimple_cond_code (stmt), boolean_type_node,
4275 op0, op1);
4276 if (result && TREE_CODE (result) == INTEGER_CST)
4278 if (integer_zerop (result))
4279 gimple_cond_make_false (stmt);
4280 else
4281 gimple_cond_make_true (stmt);
4282 update_stmt (stmt);
4283 el_todo = TODO_cleanup_cfg;
4286 /* Visit indirect calls and turn them into direct calls if
4287 possible. */
4288 if (is_gimple_call (stmt))
4290 tree orig_fn = gimple_call_fn (stmt);
4291 tree fn;
4292 if (!orig_fn)
4293 continue;
4294 if (TREE_CODE (orig_fn) == SSA_NAME)
4295 fn = VN_INFO (orig_fn)->valnum;
4296 else if (TREE_CODE (orig_fn) == OBJ_TYPE_REF
4297 && TREE_CODE (OBJ_TYPE_REF_EXPR (orig_fn)) == SSA_NAME)
4298 fn = VN_INFO (OBJ_TYPE_REF_EXPR (orig_fn))->valnum;
4299 else
4300 continue;
4301 if (gimple_call_addr_fndecl (fn) != NULL_TREE
4302 && useless_type_conversion_p (TREE_TYPE (orig_fn),
4303 TREE_TYPE (fn)))
4305 bool can_make_abnormal_goto
4306 = stmt_can_make_abnormal_goto (stmt);
4307 bool was_noreturn = gimple_call_noreturn_p (stmt);
4309 if (dump_file && (dump_flags & TDF_DETAILS))
4311 fprintf (dump_file, "Replacing call target with ");
4312 print_generic_expr (dump_file, fn, 0);
4313 fprintf (dump_file, " in ");
4314 print_gimple_stmt (dump_file, stmt, 0, 0);
4317 gimple_call_set_fn (stmt, fn);
4318 VEC_safe_push (gimple, heap, el_to_update, stmt);
4320 /* When changing a call into a noreturn call, cfg cleanup
4321 is needed to fix up the noreturn call. */
4322 if (!was_noreturn && gimple_call_noreturn_p (stmt))
4323 el_todo |= TODO_cleanup_cfg;
4325 /* If we removed EH side-effects from the statement, clean
4326 its EH information. */
4327 if (maybe_clean_or_replace_eh_stmt (stmt, stmt))
4329 bitmap_set_bit (need_eh_cleanup,
4330 gimple_bb (stmt)->index);
4331 if (dump_file && (dump_flags & TDF_DETAILS))
4332 fprintf (dump_file, " Removed EH side-effects.\n");
4335 /* Likewise for AB side-effects. */
4336 if (can_make_abnormal_goto
4337 && !stmt_can_make_abnormal_goto (stmt))
4339 bitmap_set_bit (need_ab_cleanup,
4340 gimple_bb (stmt)->index);
4341 if (dump_file && (dump_flags & TDF_DETAILS))
4342 fprintf (dump_file, " Removed AB side-effects.\n");
4345 /* Changing an indirect call to a direct call may
4346 have exposed different semantics. This may
4347 require an SSA update. */
4348 el_todo |= TODO_update_ssa_only_virtuals;
4354 /* Make no longer available leaders no longer available. */
4356 static void
4357 eliminate_leave_block (dom_walk_data *, basic_block)
4359 tree entry;
4360 while ((entry = VEC_pop (tree, el_avail_stack)) != NULL_TREE)
4361 VEC_replace (tree, el_avail,
4362 SSA_NAME_VERSION (VN_INFO (entry)->valnum), NULL_TREE);
4365 /* Eliminate fully redundant computations. */
4367 static unsigned int
4368 eliminate (void)
4370 struct dom_walk_data walk_data;
4371 gimple_stmt_iterator gsi;
4372 gimple stmt;
4373 unsigned i;
4375 need_eh_cleanup = BITMAP_ALLOC (NULL);
4376 need_ab_cleanup = BITMAP_ALLOC (NULL);
4378 el_to_remove = NULL;
4379 el_to_update = NULL;
4380 el_todo = 0;
4381 el_avail = NULL;
4382 el_avail_stack = NULL;
4384 walk_data.dom_direction = CDI_DOMINATORS;
4385 walk_data.initialize_block_local_data = NULL;
4386 walk_data.before_dom_children = eliminate_bb;
4387 walk_data.after_dom_children = eliminate_leave_block;
4388 walk_data.global_data = NULL;
4389 walk_data.block_local_data_size = 0;
4390 init_walk_dominator_tree (&walk_data);
4391 walk_dominator_tree (&walk_data, ENTRY_BLOCK_PTR);
4392 fini_walk_dominator_tree (&walk_data);
4394 VEC_free (tree, heap, el_avail);
4395 VEC_free (tree, heap, el_avail_stack);
4397 /* We cannot remove stmts during BB walk, especially not release SSA
4398 names there as this confuses the VN machinery. The stmts ending
4399 up in el_to_remove are either stores or simple copies. */
4400 FOR_EACH_VEC_ELT (gimple, el_to_remove, i, stmt)
4402 tree lhs = gimple_assign_lhs (stmt);
4403 tree rhs = gimple_assign_rhs1 (stmt);
4404 use_operand_p use_p;
4405 gimple use_stmt;
4407 /* If there is a single use only, propagate the equivalency
4408 instead of keeping the copy. */
4409 if (TREE_CODE (lhs) == SSA_NAME
4410 && TREE_CODE (rhs) == SSA_NAME
4411 && single_imm_use (lhs, &use_p, &use_stmt)
4412 && may_propagate_copy (USE_FROM_PTR (use_p), rhs))
4414 SET_USE (use_p, rhs);
4415 update_stmt (use_stmt);
4416 if (inserted_exprs
4417 && bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (lhs))
4418 && TREE_CODE (rhs) == SSA_NAME)
4419 gimple_set_plf (SSA_NAME_DEF_STMT (rhs), NECESSARY, true);
4422 /* If this is a store or a now unused copy, remove it. */
4423 if (TREE_CODE (lhs) != SSA_NAME
4424 || has_zero_uses (lhs))
4426 basic_block bb = gimple_bb (stmt);
4427 gsi = gsi_for_stmt (stmt);
4428 unlink_stmt_vdef (stmt);
4429 if (gsi_remove (&gsi, true))
4430 bitmap_set_bit (need_eh_cleanup, bb->index);
4431 if (inserted_exprs
4432 && TREE_CODE (lhs) == SSA_NAME)
4433 bitmap_clear_bit (inserted_exprs, SSA_NAME_VERSION (lhs));
4434 release_defs (stmt);
4437 VEC_free (gimple, heap, el_to_remove);
4439 /* We cannot update call statements with virtual operands during
4440 SSA walk. This might remove them which in turn makes our
4441 VN lattice invalid. */
4442 FOR_EACH_VEC_ELT (gimple, el_to_update, i, stmt)
4443 update_stmt (stmt);
4444 VEC_free (gimple, heap, el_to_update);
4446 return el_todo;
4449 /* Perform CFG cleanups made necessary by elimination. */
4451 static unsigned
4452 fini_eliminate (void)
4454 bool do_eh_cleanup = !bitmap_empty_p (need_eh_cleanup);
4455 bool do_ab_cleanup = !bitmap_empty_p (need_ab_cleanup);
4457 if (do_eh_cleanup)
4458 gimple_purge_all_dead_eh_edges (need_eh_cleanup);
4460 if (do_ab_cleanup)
4461 gimple_purge_all_dead_abnormal_call_edges (need_ab_cleanup);
4463 BITMAP_FREE (need_eh_cleanup);
4464 BITMAP_FREE (need_ab_cleanup);
4466 if (do_eh_cleanup || do_ab_cleanup)
4467 return TODO_cleanup_cfg;
4468 return 0;
4471 /* Borrow a bit of tree-ssa-dce.c for the moment.
4472 XXX: In 4.1, we should be able to just run a DCE pass after PRE, though
4473 this may be a bit faster, and we may want critical edges kept split. */
4475 /* If OP's defining statement has not already been determined to be necessary,
4476 mark that statement necessary. Return the stmt, if it is newly
4477 necessary. */
4479 static inline gimple
4480 mark_operand_necessary (tree op)
4482 gimple stmt;
4484 gcc_assert (op);
4486 if (TREE_CODE (op) != SSA_NAME)
4487 return NULL;
4489 stmt = SSA_NAME_DEF_STMT (op);
4490 gcc_assert (stmt);
4492 if (gimple_plf (stmt, NECESSARY)
4493 || gimple_nop_p (stmt))
4494 return NULL;
4496 gimple_set_plf (stmt, NECESSARY, true);
4497 return stmt;
4500 /* Because we don't follow exactly the standard PRE algorithm, and decide not
4501 to insert PHI nodes sometimes, and because value numbering of casts isn't
4502 perfect, we sometimes end up inserting dead code. This simple DCE-like
4503 pass removes any insertions we made that weren't actually used. */
4505 static void
4506 remove_dead_inserted_code (void)
4508 bitmap worklist;
4509 unsigned i;
4510 bitmap_iterator bi;
4511 gimple t;
4513 worklist = BITMAP_ALLOC (NULL);
4514 EXECUTE_IF_SET_IN_BITMAP (inserted_exprs, 0, i, bi)
4516 t = SSA_NAME_DEF_STMT (ssa_name (i));
4517 if (gimple_plf (t, NECESSARY))
4518 bitmap_set_bit (worklist, i);
4520 while (!bitmap_empty_p (worklist))
4522 i = bitmap_first_set_bit (worklist);
4523 bitmap_clear_bit (worklist, i);
4524 t = SSA_NAME_DEF_STMT (ssa_name (i));
4526 /* PHI nodes are somewhat special in that each PHI alternative has
4527 data and control dependencies. All the statements feeding the
4528 PHI node's arguments are always necessary. */
4529 if (gimple_code (t) == GIMPLE_PHI)
4531 unsigned k;
4533 for (k = 0; k < gimple_phi_num_args (t); k++)
4535 tree arg = PHI_ARG_DEF (t, k);
4536 if (TREE_CODE (arg) == SSA_NAME)
4538 gimple n = mark_operand_necessary (arg);
4539 if (n)
4540 bitmap_set_bit (worklist, SSA_NAME_VERSION (arg));
4544 else
4546 /* Propagate through the operands. Examine all the USE, VUSE and
4547 VDEF operands in this statement. Mark all the statements
4548 which feed this statement's uses as necessary. */
4549 ssa_op_iter iter;
4550 tree use;
4552 /* The operands of VDEF expressions are also needed as they
4553 represent potential definitions that may reach this
4554 statement (VDEF operands allow us to follow def-def
4555 links). */
4557 FOR_EACH_SSA_TREE_OPERAND (use, t, iter, SSA_OP_ALL_USES)
4559 gimple n = mark_operand_necessary (use);
4560 if (n)
4561 bitmap_set_bit (worklist, SSA_NAME_VERSION (use));
4566 EXECUTE_IF_SET_IN_BITMAP (inserted_exprs, 0, i, bi)
4568 t = SSA_NAME_DEF_STMT (ssa_name (i));
4569 if (!gimple_plf (t, NECESSARY))
4571 gimple_stmt_iterator gsi;
4573 if (dump_file && (dump_flags & TDF_DETAILS))
4575 fprintf (dump_file, "Removing unnecessary insertion:");
4576 print_gimple_stmt (dump_file, t, 0, 0);
4579 gsi = gsi_for_stmt (t);
4580 if (gimple_code (t) == GIMPLE_PHI)
4581 remove_phi_node (&gsi, true);
4582 else
4584 gsi_remove (&gsi, true);
4585 release_defs (t);
4589 BITMAP_FREE (worklist);
4593 /* Initialize data structures used by PRE. */
4595 static void
4596 init_pre (void)
4598 basic_block bb;
4600 next_expression_id = 1;
4601 expressions = NULL;
4602 VEC_safe_push (pre_expr, heap, expressions, NULL);
4603 value_expressions = VEC_alloc (bitmap, heap, get_max_value_id () + 1);
4604 VEC_safe_grow_cleared (bitmap, heap, value_expressions,
4605 get_max_value_id() + 1);
4606 name_to_id = NULL;
4608 inserted_exprs = BITMAP_ALLOC (NULL);
4610 connect_infinite_loops_to_exit ();
4611 memset (&pre_stats, 0, sizeof (pre_stats));
4613 postorder = XNEWVEC (int, n_basic_blocks);
4614 postorder_num = inverted_post_order_compute (postorder);
4616 alloc_aux_for_blocks (sizeof (struct bb_bitmap_sets));
4618 calculate_dominance_info (CDI_POST_DOMINATORS);
4619 calculate_dominance_info (CDI_DOMINATORS);
4621 bitmap_obstack_initialize (&grand_bitmap_obstack);
4622 phi_translate_table.create (5110);
4623 expression_to_id.create (num_ssa_names * 3);
4624 bitmap_set_pool = create_alloc_pool ("Bitmap sets",
4625 sizeof (struct bitmap_set), 30);
4626 pre_expr_pool = create_alloc_pool ("pre_expr nodes",
4627 sizeof (struct pre_expr_d), 30);
4628 FOR_ALL_BB (bb)
4630 EXP_GEN (bb) = bitmap_set_new ();
4631 PHI_GEN (bb) = bitmap_set_new ();
4632 TMP_GEN (bb) = bitmap_set_new ();
4633 AVAIL_OUT (bb) = bitmap_set_new ();
4638 /* Deallocate data structures used by PRE. */
4640 static void
4641 fini_pre ()
4643 free (postorder);
4644 VEC_free (bitmap, heap, value_expressions);
4645 BITMAP_FREE (inserted_exprs);
4646 bitmap_obstack_release (&grand_bitmap_obstack);
4647 free_alloc_pool (bitmap_set_pool);
4648 free_alloc_pool (pre_expr_pool);
4649 phi_translate_table.dispose ();
4650 expression_to_id.dispose ();
4651 VEC_free (unsigned, heap, name_to_id);
4653 free_aux_for_blocks ();
4655 free_dominance_info (CDI_POST_DOMINATORS);
4658 /* Gate and execute functions for PRE. */
4660 static unsigned int
4661 do_pre (void)
4663 unsigned int todo = 0;
4665 do_partial_partial =
4666 flag_tree_partial_pre && optimize_function_for_speed_p (cfun);
4668 /* This has to happen before SCCVN runs because
4669 loop_optimizer_init may create new phis, etc. */
4670 loop_optimizer_init (LOOPS_NORMAL);
4672 if (!run_scc_vn (VN_WALK))
4674 loop_optimizer_finalize ();
4675 return 0;
4678 init_pre ();
4679 scev_initialize ();
4681 /* Collect and value number expressions computed in each basic block. */
4682 compute_avail ();
4684 if (dump_file && (dump_flags & TDF_DETAILS))
4686 basic_block bb;
4687 FOR_ALL_BB (bb)
4689 print_bitmap_set (dump_file, EXP_GEN (bb),
4690 "exp_gen", bb->index);
4691 print_bitmap_set (dump_file, PHI_GEN (bb),
4692 "phi_gen", bb->index);
4693 print_bitmap_set (dump_file, TMP_GEN (bb),
4694 "tmp_gen", bb->index);
4695 print_bitmap_set (dump_file, AVAIL_OUT (bb),
4696 "avail_out", bb->index);
4700 /* Insert can get quite slow on an incredibly large number of basic
4701 blocks due to some quadratic behavior. Until this behavior is
4702 fixed, don't run it when he have an incredibly large number of
4703 bb's. If we aren't going to run insert, there is no point in
4704 computing ANTIC, either, even though it's plenty fast. */
4705 if (n_basic_blocks < 4000)
4707 compute_antic ();
4708 insert ();
4711 /* Make sure to remove fake edges before committing our inserts.
4712 This makes sure we don't end up with extra critical edges that
4713 we would need to split. */
4714 remove_fake_exit_edges ();
4715 gsi_commit_edge_inserts ();
4717 /* Remove all the redundant expressions. */
4718 todo |= eliminate ();
4720 statistics_counter_event (cfun, "Insertions", pre_stats.insertions);
4721 statistics_counter_event (cfun, "PA inserted", pre_stats.pa_insert);
4722 statistics_counter_event (cfun, "New PHIs", pre_stats.phis);
4723 statistics_counter_event (cfun, "Eliminated", pre_stats.eliminations);
4724 statistics_counter_event (cfun, "Constified", pre_stats.constified);
4726 clear_expression_ids ();
4727 remove_dead_inserted_code ();
4728 todo |= TODO_verify_flow;
4730 scev_finalize ();
4731 fini_pre ();
4732 todo |= fini_eliminate ();
4733 loop_optimizer_finalize ();
4735 /* TODO: tail_merge_optimize may merge all predecessors of a block, in which
4736 case we can merge the block with the remaining predecessor of the block.
4737 It should either:
4738 - call merge_blocks after each tail merge iteration
4739 - call merge_blocks after all tail merge iterations
4740 - mark TODO_cleanup_cfg when necessary
4741 - share the cfg cleanup with fini_pre. */
4742 todo |= tail_merge_optimize (todo);
4744 free_scc_vn ();
4746 /* Tail merging invalidates the virtual SSA web, together with
4747 cfg-cleanup opportunities exposed by PRE this will wreck the
4748 SSA updating machinery. So make sure to run update-ssa
4749 manually, before eventually scheduling cfg-cleanup as part of
4750 the todo. */
4751 update_ssa (TODO_update_ssa_only_virtuals);
4753 return todo;
4756 static bool
4757 gate_pre (void)
4759 return flag_tree_pre != 0;
4762 struct gimple_opt_pass pass_pre =
4765 GIMPLE_PASS,
4766 "pre", /* name */
4767 gate_pre, /* gate */
4768 do_pre, /* execute */
4769 NULL, /* sub */
4770 NULL, /* next */
4771 0, /* static_pass_number */
4772 TV_TREE_PRE, /* tv_id */
4773 PROP_no_crit_edges | PROP_cfg
4774 | PROP_ssa, /* properties_required */
4775 0, /* properties_provided */
4776 0, /* properties_destroyed */
4777 TODO_rebuild_alias, /* todo_flags_start */
4778 TODO_ggc_collect | TODO_verify_ssa /* todo_flags_finish */
4783 /* Gate and execute functions for FRE. */
4785 static unsigned int
4786 execute_fre (void)
4788 unsigned int todo = 0;
4790 if (!run_scc_vn (VN_WALKREWRITE))
4791 return 0;
4793 memset (&pre_stats, 0, sizeof (pre_stats));
4795 /* Remove all the redundant expressions. */
4796 todo |= eliminate ();
4798 todo |= fini_eliminate ();
4800 free_scc_vn ();
4802 statistics_counter_event (cfun, "Insertions", pre_stats.insertions);
4803 statistics_counter_event (cfun, "Eliminated", pre_stats.eliminations);
4804 statistics_counter_event (cfun, "Constified", pre_stats.constified);
4806 return todo;
4809 static bool
4810 gate_fre (void)
4812 return flag_tree_fre != 0;
4815 struct gimple_opt_pass pass_fre =
4818 GIMPLE_PASS,
4819 "fre", /* name */
4820 gate_fre, /* gate */
4821 execute_fre, /* execute */
4822 NULL, /* sub */
4823 NULL, /* next */
4824 0, /* static_pass_number */
4825 TV_TREE_FRE, /* tv_id */
4826 PROP_cfg | PROP_ssa, /* properties_required */
4827 0, /* properties_provided */
4828 0, /* properties_destroyed */
4829 0, /* todo_flags_start */
4830 TODO_ggc_collect | TODO_verify_ssa /* todo_flags_finish */