Make vect_model_store_cost take a vec_load_store_type
[official-gcc.git] / gcc / tree-ssa-pre.c
blob63c2a6a209bf5edadabf419def69cd2cd5ed0a72
1 /* Full and partial redundancy elimination and code hoisting on SSA GIMPLE.
2 Copyright (C) 2001-2018 Free Software Foundation, Inc.
3 Contributed by Daniel Berlin <dan@dberlin.org> and Steven Bosscher
4 <stevenb@suse.de>
6 This file is part of GCC.
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "backend.h"
26 #include "rtl.h"
27 #include "tree.h"
28 #include "gimple.h"
29 #include "predict.h"
30 #include "alloc-pool.h"
31 #include "tree-pass.h"
32 #include "ssa.h"
33 #include "cgraph.h"
34 #include "gimple-pretty-print.h"
35 #include "fold-const.h"
36 #include "cfganal.h"
37 #include "gimple-fold.h"
38 #include "tree-eh.h"
39 #include "gimplify.h"
40 #include "gimple-iterator.h"
41 #include "tree-cfg.h"
42 #include "tree-into-ssa.h"
43 #include "tree-dfa.h"
44 #include "tree-ssa.h"
45 #include "cfgloop.h"
46 #include "tree-ssa-sccvn.h"
47 #include "tree-scalar-evolution.h"
48 #include "params.h"
49 #include "dbgcnt.h"
50 #include "domwalk.h"
51 #include "tree-ssa-propagate.h"
52 #include "tree-ssa-dce.h"
53 #include "tree-cfgcleanup.h"
54 #include "alias.h"
56 /* Even though this file is called tree-ssa-pre.c, we actually
57 implement a bit more than just PRE here. All of them piggy-back
58 on GVN which is implemented in tree-ssa-sccvn.c.
60 1. Full Redundancy Elimination (FRE)
61 This is the elimination phase of GVN.
63 2. Partial Redundancy Elimination (PRE)
64 This is adds computation of AVAIL_OUT and ANTIC_IN and
65 doing expression insertion to form GVN-PRE.
67 3. Code hoisting
68 This optimization uses the ANTIC_IN sets computed for PRE
69 to move expressions further up than PRE would do, to make
70 multiple computations of the same value fully redundant.
71 This pass is explained below (after the explanation of the
72 basic algorithm for PRE).
75 /* TODO:
77 1. Avail sets can be shared by making an avail_find_leader that
78 walks up the dominator tree and looks in those avail sets.
79 This might affect code optimality, it's unclear right now.
80 Currently the AVAIL_OUT sets are the remaining quadraticness in
81 memory of GVN-PRE.
82 2. Strength reduction can be performed by anticipating expressions
83 we can repair later on.
84 3. We can do back-substitution or smarter value numbering to catch
85 commutative expressions split up over multiple statements.
88 /* For ease of terminology, "expression node" in the below refers to
89 every expression node but GIMPLE_ASSIGN, because GIMPLE_ASSIGNs
90 represent the actual statement containing the expressions we care about,
91 and we cache the value number by putting it in the expression. */
93 /* Basic algorithm for Partial Redundancy Elimination:
95 First we walk the statements to generate the AVAIL sets, the
96 EXP_GEN sets, and the tmp_gen sets. EXP_GEN sets represent the
97 generation of values/expressions by a given block. We use them
98 when computing the ANTIC sets. The AVAIL sets consist of
99 SSA_NAME's that represent values, so we know what values are
100 available in what blocks. AVAIL is a forward dataflow problem. In
101 SSA, values are never killed, so we don't need a kill set, or a
102 fixpoint iteration, in order to calculate the AVAIL sets. In
103 traditional parlance, AVAIL sets tell us the downsafety of the
104 expressions/values.
106 Next, we generate the ANTIC sets. These sets represent the
107 anticipatable expressions. ANTIC is a backwards dataflow
108 problem. An expression is anticipatable in a given block if it could
109 be generated in that block. This means that if we had to perform
110 an insertion in that block, of the value of that expression, we
111 could. Calculating the ANTIC sets requires phi translation of
112 expressions, because the flow goes backwards through phis. We must
113 iterate to a fixpoint of the ANTIC sets, because we have a kill
114 set. Even in SSA form, values are not live over the entire
115 function, only from their definition point onwards. So we have to
116 remove values from the ANTIC set once we go past the definition
117 point of the leaders that make them up.
118 compute_antic/compute_antic_aux performs this computation.
120 Third, we perform insertions to make partially redundant
121 expressions fully redundant.
123 An expression is partially redundant (excluding partial
124 anticipation) if:
126 1. It is AVAIL in some, but not all, of the predecessors of a
127 given block.
128 2. It is ANTIC in all the predecessors.
130 In order to make it fully redundant, we insert the expression into
131 the predecessors where it is not available, but is ANTIC.
133 When optimizing for size, we only eliminate the partial redundancy
134 if we need to insert in only one predecessor. This avoids almost
135 completely the code size increase that PRE usually causes.
137 For the partial anticipation case, we only perform insertion if it
138 is partially anticipated in some block, and fully available in all
139 of the predecessors.
141 do_pre_regular_insertion/do_pre_partial_partial_insertion
142 performs these steps, driven by insert/insert_aux.
144 Fourth, we eliminate fully redundant expressions.
145 This is a simple statement walk that replaces redundant
146 calculations with the now available values. */
148 /* Basic algorithm for Code Hoisting:
150 Code hoisting is: Moving value computations up in the control flow
151 graph to make multiple copies redundant. Typically this is a size
152 optimization, but there are cases where it also is helpful for speed.
154 A simple code hoisting algorithm is implemented that piggy-backs on
155 the PRE infrastructure. For code hoisting, we have to know ANTIC_OUT
156 which is effectively ANTIC_IN - AVAIL_OUT. The latter two have to be
157 computed for PRE, and we can use them to perform a limited version of
158 code hoisting, too.
160 For the purpose of this implementation, a value is hoistable to a basic
161 block B if the following properties are met:
163 1. The value is in ANTIC_IN(B) -- the value will be computed on all
164 paths from B to function exit and it can be computed in B);
166 2. The value is not in AVAIL_OUT(B) -- there would be no need to
167 compute the value again and make it available twice;
169 3. All successors of B are dominated by B -- makes sure that inserting
170 a computation of the value in B will make the remaining
171 computations fully redundant;
173 4. At least one successor has the value in AVAIL_OUT -- to avoid
174 hoisting values up too far;
176 5. There are at least two successors of B -- hoisting in straight
177 line code is pointless.
179 The third condition is not strictly necessary, but it would complicate
180 the hoisting pass a lot. In fact, I don't know of any code hoisting
181 algorithm that does not have this requirement. Fortunately, experiments
182 have show that most candidate hoistable values are in regions that meet
183 this condition (e.g. diamond-shape regions).
185 The forth condition is necessary to avoid hoisting things up too far
186 away from the uses of the value. Nothing else limits the algorithm
187 from hoisting everything up as far as ANTIC_IN allows. Experiments
188 with SPEC and CSiBE have shown that hoisting up too far results in more
189 spilling, less benefits for code size, and worse benchmark scores.
190 Fortunately, in practice most of the interesting hoisting opportunities
191 are caught despite this limitation.
193 For hoistable values that meet all conditions, expressions are inserted
194 to make the calculation of the hoistable value fully redundant. We
195 perform code hoisting insertions after each round of PRE insertions,
196 because code hoisting never exposes new PRE opportunities, but PRE can
197 create new code hoisting opportunities.
199 The code hoisting algorithm is implemented in do_hoist_insert, driven
200 by insert/insert_aux. */
202 /* Representations of value numbers:
204 Value numbers are represented by a representative SSA_NAME. We
205 will create fake SSA_NAME's in situations where we need a
206 representative but do not have one (because it is a complex
207 expression). In order to facilitate storing the value numbers in
208 bitmaps, and keep the number of wasted SSA_NAME's down, we also
209 associate a value_id with each value number, and create full blown
210 ssa_name's only where we actually need them (IE in operands of
211 existing expressions).
213 Theoretically you could replace all the value_id's with
214 SSA_NAME_VERSION, but this would allocate a large number of
215 SSA_NAME's (which are each > 30 bytes) just to get a 4 byte number.
216 It would also require an additional indirection at each point we
217 use the value id. */
219 /* Representation of expressions on value numbers:
221 Expressions consisting of value numbers are represented the same
222 way as our VN internally represents them, with an additional
223 "pre_expr" wrapping around them in order to facilitate storing all
224 of the expressions in the same sets. */
226 /* Representation of sets:
228 The dataflow sets do not need to be sorted in any particular order
229 for the majority of their lifetime, are simply represented as two
230 bitmaps, one that keeps track of values present in the set, and one
231 that keeps track of expressions present in the set.
233 When we need them in topological order, we produce it on demand by
234 transforming the bitmap into an array and sorting it into topo
235 order. */
237 /* Type of expression, used to know which member of the PRE_EXPR union
238 is valid. */
240 enum pre_expr_kind
242 NAME,
243 NARY,
244 REFERENCE,
245 CONSTANT
248 union pre_expr_union
250 tree name;
251 tree constant;
252 vn_nary_op_t nary;
253 vn_reference_t reference;
256 typedef struct pre_expr_d : nofree_ptr_hash <pre_expr_d>
258 enum pre_expr_kind kind;
259 unsigned int id;
260 pre_expr_union u;
262 /* hash_table support. */
263 static inline hashval_t hash (const pre_expr_d *);
264 static inline int equal (const pre_expr_d *, const pre_expr_d *);
265 } *pre_expr;
267 #define PRE_EXPR_NAME(e) (e)->u.name
268 #define PRE_EXPR_NARY(e) (e)->u.nary
269 #define PRE_EXPR_REFERENCE(e) (e)->u.reference
270 #define PRE_EXPR_CONSTANT(e) (e)->u.constant
272 /* Compare E1 and E1 for equality. */
274 inline int
275 pre_expr_d::equal (const pre_expr_d *e1, const pre_expr_d *e2)
277 if (e1->kind != e2->kind)
278 return false;
280 switch (e1->kind)
282 case CONSTANT:
283 return vn_constant_eq_with_type (PRE_EXPR_CONSTANT (e1),
284 PRE_EXPR_CONSTANT (e2));
285 case NAME:
286 return PRE_EXPR_NAME (e1) == PRE_EXPR_NAME (e2);
287 case NARY:
288 return vn_nary_op_eq (PRE_EXPR_NARY (e1), PRE_EXPR_NARY (e2));
289 case REFERENCE:
290 return vn_reference_eq (PRE_EXPR_REFERENCE (e1),
291 PRE_EXPR_REFERENCE (e2));
292 default:
293 gcc_unreachable ();
297 /* Hash E. */
299 inline hashval_t
300 pre_expr_d::hash (const pre_expr_d *e)
302 switch (e->kind)
304 case CONSTANT:
305 return vn_hash_constant_with_type (PRE_EXPR_CONSTANT (e));
306 case NAME:
307 return SSA_NAME_VERSION (PRE_EXPR_NAME (e));
308 case NARY:
309 return PRE_EXPR_NARY (e)->hashcode;
310 case REFERENCE:
311 return PRE_EXPR_REFERENCE (e)->hashcode;
312 default:
313 gcc_unreachable ();
317 /* Next global expression id number. */
318 static unsigned int next_expression_id;
320 /* Mapping from expression to id number we can use in bitmap sets. */
321 static vec<pre_expr> expressions;
322 static hash_table<pre_expr_d> *expression_to_id;
323 static vec<unsigned> name_to_id;
325 /* Allocate an expression id for EXPR. */
327 static inline unsigned int
328 alloc_expression_id (pre_expr expr)
330 struct pre_expr_d **slot;
331 /* Make sure we won't overflow. */
332 gcc_assert (next_expression_id + 1 > next_expression_id);
333 expr->id = next_expression_id++;
334 expressions.safe_push (expr);
335 if (expr->kind == NAME)
337 unsigned version = SSA_NAME_VERSION (PRE_EXPR_NAME (expr));
338 /* vec::safe_grow_cleared allocates no headroom. Avoid frequent
339 re-allocations by using vec::reserve upfront. */
340 unsigned old_len = name_to_id.length ();
341 name_to_id.reserve (num_ssa_names - old_len);
342 name_to_id.quick_grow_cleared (num_ssa_names);
343 gcc_assert (name_to_id[version] == 0);
344 name_to_id[version] = expr->id;
346 else
348 slot = expression_to_id->find_slot (expr, INSERT);
349 gcc_assert (!*slot);
350 *slot = expr;
352 return next_expression_id - 1;
355 /* Return the expression id for tree EXPR. */
357 static inline unsigned int
358 get_expression_id (const pre_expr expr)
360 return expr->id;
363 static inline unsigned int
364 lookup_expression_id (const pre_expr expr)
366 struct pre_expr_d **slot;
368 if (expr->kind == NAME)
370 unsigned version = SSA_NAME_VERSION (PRE_EXPR_NAME (expr));
371 if (name_to_id.length () <= version)
372 return 0;
373 return name_to_id[version];
375 else
377 slot = expression_to_id->find_slot (expr, NO_INSERT);
378 if (!slot)
379 return 0;
380 return ((pre_expr)*slot)->id;
384 /* Return the existing expression id for EXPR, or create one if one
385 does not exist yet. */
387 static inline unsigned int
388 get_or_alloc_expression_id (pre_expr expr)
390 unsigned int id = lookup_expression_id (expr);
391 if (id == 0)
392 return alloc_expression_id (expr);
393 return expr->id = id;
396 /* Return the expression that has expression id ID */
398 static inline pre_expr
399 expression_for_id (unsigned int id)
401 return expressions[id];
404 static object_allocator<pre_expr_d> pre_expr_pool ("pre_expr nodes");
406 /* Given an SSA_NAME NAME, get or create a pre_expr to represent it. */
408 static pre_expr
409 get_or_alloc_expr_for_name (tree name)
411 struct pre_expr_d expr;
412 pre_expr result;
413 unsigned int result_id;
415 expr.kind = NAME;
416 expr.id = 0;
417 PRE_EXPR_NAME (&expr) = name;
418 result_id = lookup_expression_id (&expr);
419 if (result_id != 0)
420 return expression_for_id (result_id);
422 result = pre_expr_pool.allocate ();
423 result->kind = NAME;
424 PRE_EXPR_NAME (result) = name;
425 alloc_expression_id (result);
426 return result;
429 /* An unordered bitmap set. One bitmap tracks values, the other,
430 expressions. */
431 typedef struct bitmap_set
433 bitmap_head expressions;
434 bitmap_head values;
435 } *bitmap_set_t;
437 #define FOR_EACH_EXPR_ID_IN_SET(set, id, bi) \
438 EXECUTE_IF_SET_IN_BITMAP (&(set)->expressions, 0, (id), (bi))
440 #define FOR_EACH_VALUE_ID_IN_SET(set, id, bi) \
441 EXECUTE_IF_SET_IN_BITMAP (&(set)->values, 0, (id), (bi))
443 /* Mapping from value id to expressions with that value_id. */
444 static vec<bitmap> value_expressions;
446 /* Sets that we need to keep track of. */
447 typedef struct bb_bitmap_sets
449 /* The EXP_GEN set, which represents expressions/values generated in
450 a basic block. */
451 bitmap_set_t exp_gen;
453 /* The PHI_GEN set, which represents PHI results generated in a
454 basic block. */
455 bitmap_set_t phi_gen;
457 /* The TMP_GEN set, which represents results/temporaries generated
458 in a basic block. IE the LHS of an expression. */
459 bitmap_set_t tmp_gen;
461 /* The AVAIL_OUT set, which represents which values are available in
462 a given basic block. */
463 bitmap_set_t avail_out;
465 /* The ANTIC_IN set, which represents which values are anticipatable
466 in a given basic block. */
467 bitmap_set_t antic_in;
469 /* The PA_IN set, which represents which values are
470 partially anticipatable in a given basic block. */
471 bitmap_set_t pa_in;
473 /* The NEW_SETS set, which is used during insertion to augment the
474 AVAIL_OUT set of blocks with the new insertions performed during
475 the current iteration. */
476 bitmap_set_t new_sets;
478 /* A cache for value_dies_in_block_x. */
479 bitmap expr_dies;
481 /* The live virtual operand on successor edges. */
482 tree vop_on_exit;
484 /* True if we have visited this block during ANTIC calculation. */
485 unsigned int visited : 1;
487 /* True when the block contains a call that might not return. */
488 unsigned int contains_may_not_return_call : 1;
489 } *bb_value_sets_t;
491 #define EXP_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->exp_gen
492 #define PHI_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->phi_gen
493 #define TMP_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->tmp_gen
494 #define AVAIL_OUT(BB) ((bb_value_sets_t) ((BB)->aux))->avail_out
495 #define ANTIC_IN(BB) ((bb_value_sets_t) ((BB)->aux))->antic_in
496 #define PA_IN(BB) ((bb_value_sets_t) ((BB)->aux))->pa_in
497 #define NEW_SETS(BB) ((bb_value_sets_t) ((BB)->aux))->new_sets
498 #define EXPR_DIES(BB) ((bb_value_sets_t) ((BB)->aux))->expr_dies
499 #define BB_VISITED(BB) ((bb_value_sets_t) ((BB)->aux))->visited
500 #define BB_MAY_NOTRETURN(BB) ((bb_value_sets_t) ((BB)->aux))->contains_may_not_return_call
501 #define BB_LIVE_VOP_ON_EXIT(BB) ((bb_value_sets_t) ((BB)->aux))->vop_on_exit
504 /* This structure is used to keep track of statistics on what
505 optimization PRE was able to perform. */
506 static struct
508 /* The number of new expressions/temporaries generated by PRE. */
509 int insertions;
511 /* The number of inserts found due to partial anticipation */
512 int pa_insert;
514 /* The number of inserts made for code hoisting. */
515 int hoist_insert;
517 /* The number of new PHI nodes added by PRE. */
518 int phis;
519 } pre_stats;
521 static bool do_partial_partial;
522 static pre_expr bitmap_find_leader (bitmap_set_t, unsigned int);
523 static void bitmap_value_insert_into_set (bitmap_set_t, pre_expr);
524 static void bitmap_value_replace_in_set (bitmap_set_t, pre_expr);
525 static void bitmap_set_copy (bitmap_set_t, bitmap_set_t);
526 static bool bitmap_set_contains_value (bitmap_set_t, unsigned int);
527 static void bitmap_insert_into_set (bitmap_set_t, pre_expr);
528 static bitmap_set_t bitmap_set_new (void);
529 static tree create_expression_by_pieces (basic_block, pre_expr, gimple_seq *,
530 tree);
531 static tree find_or_generate_expression (basic_block, tree, gimple_seq *);
532 static unsigned int get_expr_value_id (pre_expr);
534 /* We can add and remove elements and entries to and from sets
535 and hash tables, so we use alloc pools for them. */
537 static object_allocator<bitmap_set> bitmap_set_pool ("Bitmap sets");
538 static bitmap_obstack grand_bitmap_obstack;
540 /* A three tuple {e, pred, v} used to cache phi translations in the
541 phi_translate_table. */
543 typedef struct expr_pred_trans_d : free_ptr_hash<expr_pred_trans_d>
545 /* The expression. */
546 pre_expr e;
548 /* The predecessor block along which we translated the expression. */
549 basic_block pred;
551 /* The value that resulted from the translation. */
552 pre_expr v;
554 /* The hashcode for the expression, pred pair. This is cached for
555 speed reasons. */
556 hashval_t hashcode;
558 /* hash_table support. */
559 static inline hashval_t hash (const expr_pred_trans_d *);
560 static inline int equal (const expr_pred_trans_d *, const expr_pred_trans_d *);
561 } *expr_pred_trans_t;
562 typedef const struct expr_pred_trans_d *const_expr_pred_trans_t;
564 inline hashval_t
565 expr_pred_trans_d::hash (const expr_pred_trans_d *e)
567 return e->hashcode;
570 inline int
571 expr_pred_trans_d::equal (const expr_pred_trans_d *ve1,
572 const expr_pred_trans_d *ve2)
574 basic_block b1 = ve1->pred;
575 basic_block b2 = ve2->pred;
577 /* If they are not translations for the same basic block, they can't
578 be equal. */
579 if (b1 != b2)
580 return false;
581 return pre_expr_d::equal (ve1->e, ve2->e);
584 /* The phi_translate_table caches phi translations for a given
585 expression and predecessor. */
586 static hash_table<expr_pred_trans_d> *phi_translate_table;
588 /* Add the tuple mapping from {expression E, basic block PRED} to
589 the phi translation table and return whether it pre-existed. */
591 static inline bool
592 phi_trans_add (expr_pred_trans_t *entry, pre_expr e, basic_block pred)
594 expr_pred_trans_t *slot;
595 expr_pred_trans_d tem;
596 hashval_t hash = iterative_hash_hashval_t (pre_expr_d::hash (e),
597 pred->index);
598 tem.e = e;
599 tem.pred = pred;
600 tem.hashcode = hash;
601 slot = phi_translate_table->find_slot_with_hash (&tem, hash, INSERT);
602 if (*slot)
604 *entry = *slot;
605 return true;
608 *entry = *slot = XNEW (struct expr_pred_trans_d);
609 (*entry)->e = e;
610 (*entry)->pred = pred;
611 (*entry)->hashcode = hash;
612 return false;
616 /* Add expression E to the expression set of value id V. */
618 static void
619 add_to_value (unsigned int v, pre_expr e)
621 bitmap set;
623 gcc_checking_assert (get_expr_value_id (e) == v);
625 if (v >= value_expressions.length ())
627 value_expressions.safe_grow_cleared (v + 1);
630 set = value_expressions[v];
631 if (!set)
633 set = BITMAP_ALLOC (&grand_bitmap_obstack);
634 value_expressions[v] = set;
637 bitmap_set_bit (set, get_or_alloc_expression_id (e));
640 /* Create a new bitmap set and return it. */
642 static bitmap_set_t
643 bitmap_set_new (void)
645 bitmap_set_t ret = bitmap_set_pool.allocate ();
646 bitmap_initialize (&ret->expressions, &grand_bitmap_obstack);
647 bitmap_initialize (&ret->values, &grand_bitmap_obstack);
648 return ret;
651 /* Return the value id for a PRE expression EXPR. */
653 static unsigned int
654 get_expr_value_id (pre_expr expr)
656 unsigned int id;
657 switch (expr->kind)
659 case CONSTANT:
660 id = get_constant_value_id (PRE_EXPR_CONSTANT (expr));
661 break;
662 case NAME:
663 id = VN_INFO (PRE_EXPR_NAME (expr))->value_id;
664 break;
665 case NARY:
666 id = PRE_EXPR_NARY (expr)->value_id;
667 break;
668 case REFERENCE:
669 id = PRE_EXPR_REFERENCE (expr)->value_id;
670 break;
671 default:
672 gcc_unreachable ();
674 /* ??? We cannot assert that expr has a value-id (it can be 0), because
675 we assign value-ids only to expressions that have a result
676 in set_hashtable_value_ids. */
677 return id;
680 /* Return a SCCVN valnum (SSA name or constant) for the PRE value-id VAL. */
682 static tree
683 sccvn_valnum_from_value_id (unsigned int val)
685 bitmap_iterator bi;
686 unsigned int i;
687 bitmap exprset = value_expressions[val];
688 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
690 pre_expr vexpr = expression_for_id (i);
691 if (vexpr->kind == NAME)
692 return VN_INFO (PRE_EXPR_NAME (vexpr))->valnum;
693 else if (vexpr->kind == CONSTANT)
694 return PRE_EXPR_CONSTANT (vexpr);
696 return NULL_TREE;
699 /* Remove an expression EXPR from a bitmapped set. */
701 static void
702 bitmap_remove_expr_from_set (bitmap_set_t set, pre_expr expr)
704 unsigned int val = get_expr_value_id (expr);
705 bitmap_clear_bit (&set->values, val);
706 bitmap_clear_bit (&set->expressions, get_expression_id (expr));
709 /* Insert an expression EXPR into a bitmapped set. */
711 static void
712 bitmap_insert_into_set (bitmap_set_t set, pre_expr expr)
714 unsigned int val = get_expr_value_id (expr);
715 if (! value_id_constant_p (val))
717 /* Note this is the only function causing multiple expressions
718 for the same value to appear in a set. This is needed for
719 TMP_GEN, PHI_GEN and NEW_SETs. */
720 bitmap_set_bit (&set->values, val);
721 bitmap_set_bit (&set->expressions, get_or_alloc_expression_id (expr));
725 /* Copy a bitmapped set ORIG, into bitmapped set DEST. */
727 static void
728 bitmap_set_copy (bitmap_set_t dest, bitmap_set_t orig)
730 bitmap_copy (&dest->expressions, &orig->expressions);
731 bitmap_copy (&dest->values, &orig->values);
735 /* Free memory used up by SET. */
736 static void
737 bitmap_set_free (bitmap_set_t set)
739 bitmap_clear (&set->expressions);
740 bitmap_clear (&set->values);
744 /* Generate an topological-ordered array of bitmap set SET. */
746 static vec<pre_expr>
747 sorted_array_from_bitmap_set (bitmap_set_t set)
749 unsigned int i, j;
750 bitmap_iterator bi, bj;
751 vec<pre_expr> result;
753 /* Pre-allocate enough space for the array. */
754 result.create (bitmap_count_bits (&set->expressions));
756 FOR_EACH_VALUE_ID_IN_SET (set, i, bi)
758 /* The number of expressions having a given value is usually
759 relatively small. Thus, rather than making a vector of all
760 the expressions and sorting it by value-id, we walk the values
761 and check in the reverse mapping that tells us what expressions
762 have a given value, to filter those in our set. As a result,
763 the expressions are inserted in value-id order, which means
764 topological order.
766 If this is somehow a significant lose for some cases, we can
767 choose which set to walk based on the set size. */
768 bitmap exprset = value_expressions[i];
769 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, j, bj)
771 if (bitmap_bit_p (&set->expressions, j))
772 result.quick_push (expression_for_id (j));
776 return result;
779 /* Subtract all expressions contained in ORIG from DEST. */
781 static bitmap_set_t
782 bitmap_set_subtract_expressions (bitmap_set_t dest, bitmap_set_t orig)
784 bitmap_set_t result = bitmap_set_new ();
785 bitmap_iterator bi;
786 unsigned int i;
788 bitmap_and_compl (&result->expressions, &dest->expressions,
789 &orig->expressions);
791 FOR_EACH_EXPR_ID_IN_SET (result, i, bi)
793 pre_expr expr = expression_for_id (i);
794 unsigned int value_id = get_expr_value_id (expr);
795 bitmap_set_bit (&result->values, value_id);
798 return result;
801 /* Subtract all values in bitmap set B from bitmap set A. */
803 static void
804 bitmap_set_subtract_values (bitmap_set_t a, bitmap_set_t b)
806 unsigned int i;
807 bitmap_iterator bi;
808 pre_expr to_remove = NULL;
809 FOR_EACH_EXPR_ID_IN_SET (a, i, bi)
811 if (to_remove)
813 bitmap_remove_expr_from_set (a, to_remove);
814 to_remove = NULL;
816 pre_expr expr = expression_for_id (i);
817 if (bitmap_bit_p (&b->values, get_expr_value_id (expr)))
818 to_remove = expr;
820 if (to_remove)
821 bitmap_remove_expr_from_set (a, to_remove);
825 /* Return true if bitmapped set SET contains the value VALUE_ID. */
827 static bool
828 bitmap_set_contains_value (bitmap_set_t set, unsigned int value_id)
830 if (value_id_constant_p (value_id))
831 return true;
833 return bitmap_bit_p (&set->values, value_id);
836 static inline bool
837 bitmap_set_contains_expr (bitmap_set_t set, const pre_expr expr)
839 return bitmap_bit_p (&set->expressions, get_expression_id (expr));
842 /* Return true if two bitmap sets are equal. */
844 static bool
845 bitmap_set_equal (bitmap_set_t a, bitmap_set_t b)
847 return bitmap_equal_p (&a->values, &b->values);
850 /* Replace an instance of EXPR's VALUE with EXPR in SET if it exists,
851 and add it otherwise. */
853 static void
854 bitmap_value_replace_in_set (bitmap_set_t set, pre_expr expr)
856 unsigned int val = get_expr_value_id (expr);
857 if (value_id_constant_p (val))
858 return;
860 if (bitmap_set_contains_value (set, val))
862 /* The number of expressions having a given value is usually
863 significantly less than the total number of expressions in SET.
864 Thus, rather than check, for each expression in SET, whether it
865 has the value LOOKFOR, we walk the reverse mapping that tells us
866 what expressions have a given value, and see if any of those
867 expressions are in our set. For large testcases, this is about
868 5-10x faster than walking the bitmap. If this is somehow a
869 significant lose for some cases, we can choose which set to walk
870 based on the set size. */
871 unsigned int i;
872 bitmap_iterator bi;
873 bitmap exprset = value_expressions[val];
874 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
876 if (bitmap_clear_bit (&set->expressions, i))
878 bitmap_set_bit (&set->expressions, get_expression_id (expr));
879 return;
882 gcc_unreachable ();
884 else
885 bitmap_insert_into_set (set, expr);
888 /* Insert EXPR into SET if EXPR's value is not already present in
889 SET. */
891 static void
892 bitmap_value_insert_into_set (bitmap_set_t set, pre_expr expr)
894 unsigned int val = get_expr_value_id (expr);
896 gcc_checking_assert (expr->id == get_or_alloc_expression_id (expr));
898 /* Constant values are always considered to be part of the set. */
899 if (value_id_constant_p (val))
900 return;
902 /* If the value membership changed, add the expression. */
903 if (bitmap_set_bit (&set->values, val))
904 bitmap_set_bit (&set->expressions, expr->id);
907 /* Print out EXPR to outfile. */
909 static void
910 print_pre_expr (FILE *outfile, const pre_expr expr)
912 if (! expr)
914 fprintf (outfile, "NULL");
915 return;
917 switch (expr->kind)
919 case CONSTANT:
920 print_generic_expr (outfile, PRE_EXPR_CONSTANT (expr));
921 break;
922 case NAME:
923 print_generic_expr (outfile, PRE_EXPR_NAME (expr));
924 break;
925 case NARY:
927 unsigned int i;
928 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
929 fprintf (outfile, "{%s,", get_tree_code_name (nary->opcode));
930 for (i = 0; i < nary->length; i++)
932 print_generic_expr (outfile, nary->op[i]);
933 if (i != (unsigned) nary->length - 1)
934 fprintf (outfile, ",");
936 fprintf (outfile, "}");
938 break;
940 case REFERENCE:
942 vn_reference_op_t vro;
943 unsigned int i;
944 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
945 fprintf (outfile, "{");
946 for (i = 0;
947 ref->operands.iterate (i, &vro);
948 i++)
950 bool closebrace = false;
951 if (vro->opcode != SSA_NAME
952 && TREE_CODE_CLASS (vro->opcode) != tcc_declaration)
954 fprintf (outfile, "%s", get_tree_code_name (vro->opcode));
955 if (vro->op0)
957 fprintf (outfile, "<");
958 closebrace = true;
961 if (vro->op0)
963 print_generic_expr (outfile, vro->op0);
964 if (vro->op1)
966 fprintf (outfile, ",");
967 print_generic_expr (outfile, vro->op1);
969 if (vro->op2)
971 fprintf (outfile, ",");
972 print_generic_expr (outfile, vro->op2);
975 if (closebrace)
976 fprintf (outfile, ">");
977 if (i != ref->operands.length () - 1)
978 fprintf (outfile, ",");
980 fprintf (outfile, "}");
981 if (ref->vuse)
983 fprintf (outfile, "@");
984 print_generic_expr (outfile, ref->vuse);
987 break;
990 void debug_pre_expr (pre_expr);
992 /* Like print_pre_expr but always prints to stderr. */
993 DEBUG_FUNCTION void
994 debug_pre_expr (pre_expr e)
996 print_pre_expr (stderr, e);
997 fprintf (stderr, "\n");
1000 /* Print out SET to OUTFILE. */
1002 static void
1003 print_bitmap_set (FILE *outfile, bitmap_set_t set,
1004 const char *setname, int blockindex)
1006 fprintf (outfile, "%s[%d] := { ", setname, blockindex);
1007 if (set)
1009 bool first = true;
1010 unsigned i;
1011 bitmap_iterator bi;
1013 FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
1015 const pre_expr expr = expression_for_id (i);
1017 if (!first)
1018 fprintf (outfile, ", ");
1019 first = false;
1020 print_pre_expr (outfile, expr);
1022 fprintf (outfile, " (%04d)", get_expr_value_id (expr));
1025 fprintf (outfile, " }\n");
1028 void debug_bitmap_set (bitmap_set_t);
1030 DEBUG_FUNCTION void
1031 debug_bitmap_set (bitmap_set_t set)
1033 print_bitmap_set (stderr, set, "debug", 0);
1036 void debug_bitmap_sets_for (basic_block);
1038 DEBUG_FUNCTION void
1039 debug_bitmap_sets_for (basic_block bb)
1041 print_bitmap_set (stderr, AVAIL_OUT (bb), "avail_out", bb->index);
1042 print_bitmap_set (stderr, EXP_GEN (bb), "exp_gen", bb->index);
1043 print_bitmap_set (stderr, PHI_GEN (bb), "phi_gen", bb->index);
1044 print_bitmap_set (stderr, TMP_GEN (bb), "tmp_gen", bb->index);
1045 print_bitmap_set (stderr, ANTIC_IN (bb), "antic_in", bb->index);
1046 if (do_partial_partial)
1047 print_bitmap_set (stderr, PA_IN (bb), "pa_in", bb->index);
1048 print_bitmap_set (stderr, NEW_SETS (bb), "new_sets", bb->index);
1051 /* Print out the expressions that have VAL to OUTFILE. */
1053 static void
1054 print_value_expressions (FILE *outfile, unsigned int val)
1056 bitmap set = value_expressions[val];
1057 if (set)
1059 bitmap_set x;
1060 char s[10];
1061 sprintf (s, "%04d", val);
1062 x.expressions = *set;
1063 print_bitmap_set (outfile, &x, s, 0);
1068 DEBUG_FUNCTION void
1069 debug_value_expressions (unsigned int val)
1071 print_value_expressions (stderr, val);
1074 /* Given a CONSTANT, allocate a new CONSTANT type PRE_EXPR to
1075 represent it. */
1077 static pre_expr
1078 get_or_alloc_expr_for_constant (tree constant)
1080 unsigned int result_id;
1081 unsigned int value_id;
1082 struct pre_expr_d expr;
1083 pre_expr newexpr;
1085 expr.kind = CONSTANT;
1086 PRE_EXPR_CONSTANT (&expr) = constant;
1087 result_id = lookup_expression_id (&expr);
1088 if (result_id != 0)
1089 return expression_for_id (result_id);
1091 newexpr = pre_expr_pool.allocate ();
1092 newexpr->kind = CONSTANT;
1093 PRE_EXPR_CONSTANT (newexpr) = constant;
1094 alloc_expression_id (newexpr);
1095 value_id = get_or_alloc_constant_value_id (constant);
1096 add_to_value (value_id, newexpr);
1097 return newexpr;
1100 /* Get or allocate a pre_expr for a piece of GIMPLE, and return it.
1101 Currently only supports constants and SSA_NAMES. */
1102 static pre_expr
1103 get_or_alloc_expr_for (tree t)
1105 if (TREE_CODE (t) == SSA_NAME)
1106 return get_or_alloc_expr_for_name (t);
1107 else if (is_gimple_min_invariant (t))
1108 return get_or_alloc_expr_for_constant (t);
1109 gcc_unreachable ();
1112 /* Return the folded version of T if T, when folded, is a gimple
1113 min_invariant or an SSA name. Otherwise, return T. */
1115 static pre_expr
1116 fully_constant_expression (pre_expr e)
1118 switch (e->kind)
1120 case CONSTANT:
1121 return e;
1122 case NARY:
1124 vn_nary_op_t nary = PRE_EXPR_NARY (e);
1125 tree res = vn_nary_simplify (nary);
1126 if (!res)
1127 return e;
1128 if (is_gimple_min_invariant (res))
1129 return get_or_alloc_expr_for_constant (res);
1130 if (TREE_CODE (res) == SSA_NAME)
1131 return get_or_alloc_expr_for_name (res);
1132 return e;
1134 case REFERENCE:
1136 vn_reference_t ref = PRE_EXPR_REFERENCE (e);
1137 tree folded;
1138 if ((folded = fully_constant_vn_reference_p (ref)))
1139 return get_or_alloc_expr_for_constant (folded);
1140 return e;
1142 default:
1143 return e;
1145 return e;
1148 /* Translate the VUSE backwards through phi nodes in PHIBLOCK, so that
1149 it has the value it would have in BLOCK. Set *SAME_VALID to true
1150 in case the new vuse doesn't change the value id of the OPERANDS. */
1152 static tree
1153 translate_vuse_through_block (vec<vn_reference_op_s> operands,
1154 alias_set_type set, tree type, tree vuse,
1155 basic_block phiblock,
1156 basic_block block, bool *same_valid)
1158 gimple *phi = SSA_NAME_DEF_STMT (vuse);
1159 ao_ref ref;
1160 edge e = NULL;
1161 bool use_oracle;
1163 *same_valid = true;
1165 if (gimple_bb (phi) != phiblock)
1166 return vuse;
1168 use_oracle = ao_ref_init_from_vn_reference (&ref, set, type, operands);
1170 /* Use the alias-oracle to find either the PHI node in this block,
1171 the first VUSE used in this block that is equivalent to vuse or
1172 the first VUSE which definition in this block kills the value. */
1173 if (gimple_code (phi) == GIMPLE_PHI)
1174 e = find_edge (block, phiblock);
1175 else if (use_oracle)
1176 while (!stmt_may_clobber_ref_p_1 (phi, &ref))
1178 vuse = gimple_vuse (phi);
1179 phi = SSA_NAME_DEF_STMT (vuse);
1180 if (gimple_bb (phi) != phiblock)
1181 return vuse;
1182 if (gimple_code (phi) == GIMPLE_PHI)
1184 e = find_edge (block, phiblock);
1185 break;
1188 else
1189 return NULL_TREE;
1191 if (e)
1193 if (use_oracle)
1195 bitmap visited = NULL;
1196 unsigned int cnt;
1197 /* Try to find a vuse that dominates this phi node by skipping
1198 non-clobbering statements. */
1199 vuse = get_continuation_for_phi (phi, &ref, &cnt, &visited, false,
1200 NULL, NULL);
1201 if (visited)
1202 BITMAP_FREE (visited);
1204 else
1205 vuse = NULL_TREE;
1206 if (!vuse)
1208 /* If we didn't find any, the value ID can't stay the same,
1209 but return the translated vuse. */
1210 *same_valid = false;
1211 vuse = PHI_ARG_DEF (phi, e->dest_idx);
1213 /* ??? We would like to return vuse here as this is the canonical
1214 upmost vdef that this reference is associated with. But during
1215 insertion of the references into the hash tables we only ever
1216 directly insert with their direct gimple_vuse, hence returning
1217 something else would make us not find the other expression. */
1218 return PHI_ARG_DEF (phi, e->dest_idx);
1221 return NULL_TREE;
1224 /* Like bitmap_find_leader, but checks for the value existing in SET1 *or*
1225 SET2 *or* SET3. This is used to avoid making a set consisting of the union
1226 of PA_IN and ANTIC_IN during insert and phi-translation. */
1228 static inline pre_expr
1229 find_leader_in_sets (unsigned int val, bitmap_set_t set1, bitmap_set_t set2,
1230 bitmap_set_t set3 = NULL)
1232 pre_expr result;
1234 result = bitmap_find_leader (set1, val);
1235 if (!result && set2)
1236 result = bitmap_find_leader (set2, val);
1237 if (!result && set3)
1238 result = bitmap_find_leader (set3, val);
1239 return result;
1242 /* Get the tree type for our PRE expression e. */
1244 static tree
1245 get_expr_type (const pre_expr e)
1247 switch (e->kind)
1249 case NAME:
1250 return TREE_TYPE (PRE_EXPR_NAME (e));
1251 case CONSTANT:
1252 return TREE_TYPE (PRE_EXPR_CONSTANT (e));
1253 case REFERENCE:
1254 return PRE_EXPR_REFERENCE (e)->type;
1255 case NARY:
1256 return PRE_EXPR_NARY (e)->type;
1258 gcc_unreachable ();
1261 /* Get a representative SSA_NAME for a given expression that is available in B.
1262 Since all of our sub-expressions are treated as values, we require
1263 them to be SSA_NAME's for simplicity.
1264 Prior versions of GVNPRE used to use "value handles" here, so that
1265 an expression would be VH.11 + VH.10 instead of d_3 + e_6. In
1266 either case, the operands are really values (IE we do not expect
1267 them to be usable without finding leaders). */
1269 static tree
1270 get_representative_for (const pre_expr e, basic_block b = NULL)
1272 tree name, valnum = NULL_TREE;
1273 unsigned int value_id = get_expr_value_id (e);
1275 switch (e->kind)
1277 case NAME:
1278 return VN_INFO (PRE_EXPR_NAME (e))->valnum;
1279 case CONSTANT:
1280 return PRE_EXPR_CONSTANT (e);
1281 case NARY:
1282 case REFERENCE:
1284 /* Go through all of the expressions representing this value
1285 and pick out an SSA_NAME. */
1286 unsigned int i;
1287 bitmap_iterator bi;
1288 bitmap exprs = value_expressions[value_id];
1289 EXECUTE_IF_SET_IN_BITMAP (exprs, 0, i, bi)
1291 pre_expr rep = expression_for_id (i);
1292 if (rep->kind == NAME)
1294 tree name = PRE_EXPR_NAME (rep);
1295 valnum = VN_INFO (name)->valnum;
1296 gimple *def = SSA_NAME_DEF_STMT (name);
1297 /* We have to return either a new representative or one
1298 that can be used for expression simplification and thus
1299 is available in B. */
1300 if (! b
1301 || gimple_nop_p (def)
1302 || dominated_by_p (CDI_DOMINATORS, b, gimple_bb (def)))
1303 return name;
1305 else if (rep->kind == CONSTANT)
1306 return PRE_EXPR_CONSTANT (rep);
1309 break;
1312 /* If we reached here we couldn't find an SSA_NAME. This can
1313 happen when we've discovered a value that has never appeared in
1314 the program as set to an SSA_NAME, as the result of phi translation.
1315 Create one here.
1316 ??? We should be able to re-use this when we insert the statement
1317 to compute it. */
1318 name = make_temp_ssa_name (get_expr_type (e), gimple_build_nop (), "pretmp");
1319 VN_INFO_GET (name)->value_id = value_id;
1320 VN_INFO (name)->valnum = valnum ? valnum : name;
1321 /* ??? For now mark this SSA name for release by SCCVN. */
1322 VN_INFO (name)->needs_insertion = true;
1323 add_to_value (value_id, get_or_alloc_expr_for_name (name));
1324 if (dump_file && (dump_flags & TDF_DETAILS))
1326 fprintf (dump_file, "Created SSA_NAME representative ");
1327 print_generic_expr (dump_file, name);
1328 fprintf (dump_file, " for expression:");
1329 print_pre_expr (dump_file, e);
1330 fprintf (dump_file, " (%04d)\n", value_id);
1333 return name;
1337 static pre_expr
1338 phi_translate (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1339 basic_block pred, basic_block phiblock);
1341 /* Translate EXPR using phis in PHIBLOCK, so that it has the values of
1342 the phis in PRED. Return NULL if we can't find a leader for each part
1343 of the translated expression. */
1345 static pre_expr
1346 phi_translate_1 (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1347 basic_block pred, basic_block phiblock)
1349 switch (expr->kind)
1351 case NARY:
1353 unsigned int i;
1354 bool changed = false;
1355 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1356 vn_nary_op_t newnary = XALLOCAVAR (struct vn_nary_op_s,
1357 sizeof_vn_nary_op (nary->length));
1358 memcpy (newnary, nary, sizeof_vn_nary_op (nary->length));
1360 for (i = 0; i < newnary->length; i++)
1362 if (TREE_CODE (newnary->op[i]) != SSA_NAME)
1363 continue;
1364 else
1366 pre_expr leader, result;
1367 unsigned int op_val_id = VN_INFO (newnary->op[i])->value_id;
1368 leader = find_leader_in_sets (op_val_id, set1, set2);
1369 result = phi_translate (leader, set1, set2, pred, phiblock);
1370 if (result && result != leader)
1371 /* Force a leader as well as we are simplifying this
1372 expression. */
1373 newnary->op[i] = get_representative_for (result, pred);
1374 else if (!result)
1375 return NULL;
1377 changed |= newnary->op[i] != nary->op[i];
1380 if (changed)
1382 pre_expr constant;
1383 unsigned int new_val_id;
1385 PRE_EXPR_NARY (expr) = newnary;
1386 constant = fully_constant_expression (expr);
1387 PRE_EXPR_NARY (expr) = nary;
1388 if (constant != expr)
1390 /* For non-CONSTANTs we have to make sure we can eventually
1391 insert the expression. Which means we need to have a
1392 leader for it. */
1393 if (constant->kind != CONSTANT)
1395 /* Do not allow simplifications to non-constants over
1396 backedges as this will likely result in a loop PHI node
1397 to be inserted and increased register pressure.
1398 See PR77498 - this avoids doing predcoms work in
1399 a less efficient way. */
1400 if (find_edge (pred, phiblock)->flags & EDGE_DFS_BACK)
1402 else
1404 unsigned value_id = get_expr_value_id (constant);
1405 constant = find_leader_in_sets (value_id, set1, set2,
1406 AVAIL_OUT (pred));
1407 if (constant)
1408 return constant;
1411 else
1412 return constant;
1415 /* vn_nary_* do not valueize operands. */
1416 for (i = 0; i < newnary->length; ++i)
1417 if (TREE_CODE (newnary->op[i]) == SSA_NAME)
1418 newnary->op[i] = VN_INFO (newnary->op[i])->valnum;
1419 tree result = vn_nary_op_lookup_pieces (newnary->length,
1420 newnary->opcode,
1421 newnary->type,
1422 &newnary->op[0],
1423 &nary);
1424 if (result && is_gimple_min_invariant (result))
1425 return get_or_alloc_expr_for_constant (result);
1427 expr = pre_expr_pool.allocate ();
1428 expr->kind = NARY;
1429 expr->id = 0;
1430 if (nary)
1432 PRE_EXPR_NARY (expr) = nary;
1433 new_val_id = nary->value_id;
1434 get_or_alloc_expression_id (expr);
1436 else
1438 new_val_id = get_next_value_id ();
1439 value_expressions.safe_grow_cleared (get_max_value_id () + 1);
1440 nary = vn_nary_op_insert_pieces (newnary->length,
1441 newnary->opcode,
1442 newnary->type,
1443 &newnary->op[0],
1444 result, new_val_id);
1445 PRE_EXPR_NARY (expr) = nary;
1446 get_or_alloc_expression_id (expr);
1448 add_to_value (new_val_id, expr);
1450 return expr;
1452 break;
1454 case REFERENCE:
1456 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1457 vec<vn_reference_op_s> operands = ref->operands;
1458 tree vuse = ref->vuse;
1459 tree newvuse = vuse;
1460 vec<vn_reference_op_s> newoperands = vNULL;
1461 bool changed = false, same_valid = true;
1462 unsigned int i, n;
1463 vn_reference_op_t operand;
1464 vn_reference_t newref;
1466 for (i = 0; operands.iterate (i, &operand); i++)
1468 pre_expr opresult;
1469 pre_expr leader;
1470 tree op[3];
1471 tree type = operand->type;
1472 vn_reference_op_s newop = *operand;
1473 op[0] = operand->op0;
1474 op[1] = operand->op1;
1475 op[2] = operand->op2;
1476 for (n = 0; n < 3; ++n)
1478 unsigned int op_val_id;
1479 if (!op[n])
1480 continue;
1481 if (TREE_CODE (op[n]) != SSA_NAME)
1483 /* We can't possibly insert these. */
1484 if (n != 0
1485 && !is_gimple_min_invariant (op[n]))
1486 break;
1487 continue;
1489 op_val_id = VN_INFO (op[n])->value_id;
1490 leader = find_leader_in_sets (op_val_id, set1, set2);
1491 opresult = phi_translate (leader, set1, set2, pred, phiblock);
1492 if (opresult && opresult != leader)
1494 tree name = get_representative_for (opresult);
1495 changed |= name != op[n];
1496 op[n] = name;
1498 else if (!opresult)
1499 break;
1501 if (n != 3)
1503 newoperands.release ();
1504 return NULL;
1506 if (!changed)
1507 continue;
1508 if (!newoperands.exists ())
1509 newoperands = operands.copy ();
1510 /* We may have changed from an SSA_NAME to a constant */
1511 if (newop.opcode == SSA_NAME && TREE_CODE (op[0]) != SSA_NAME)
1512 newop.opcode = TREE_CODE (op[0]);
1513 newop.type = type;
1514 newop.op0 = op[0];
1515 newop.op1 = op[1];
1516 newop.op2 = op[2];
1517 newoperands[i] = newop;
1519 gcc_checking_assert (i == operands.length ());
1521 if (vuse)
1523 newvuse = translate_vuse_through_block (newoperands.exists ()
1524 ? newoperands : operands,
1525 ref->set, ref->type,
1526 vuse, phiblock, pred,
1527 &same_valid);
1528 if (newvuse == NULL_TREE)
1530 newoperands.release ();
1531 return NULL;
1535 if (changed || newvuse != vuse)
1537 unsigned int new_val_id;
1539 tree result = vn_reference_lookup_pieces (newvuse, ref->set,
1540 ref->type,
1541 newoperands.exists ()
1542 ? newoperands : operands,
1543 &newref, VN_WALK);
1544 if (result)
1545 newoperands.release ();
1547 /* We can always insert constants, so if we have a partial
1548 redundant constant load of another type try to translate it
1549 to a constant of appropriate type. */
1550 if (result && is_gimple_min_invariant (result))
1552 tree tem = result;
1553 if (!useless_type_conversion_p (ref->type, TREE_TYPE (result)))
1555 tem = fold_unary (VIEW_CONVERT_EXPR, ref->type, result);
1556 if (tem && !is_gimple_min_invariant (tem))
1557 tem = NULL_TREE;
1559 if (tem)
1560 return get_or_alloc_expr_for_constant (tem);
1563 /* If we'd have to convert things we would need to validate
1564 if we can insert the translated expression. So fail
1565 here for now - we cannot insert an alias with a different
1566 type in the VN tables either, as that would assert. */
1567 if (result
1568 && !useless_type_conversion_p (ref->type, TREE_TYPE (result)))
1569 return NULL;
1570 else if (!result && newref
1571 && !useless_type_conversion_p (ref->type, newref->type))
1573 newoperands.release ();
1574 return NULL;
1577 expr = pre_expr_pool.allocate ();
1578 expr->kind = REFERENCE;
1579 expr->id = 0;
1581 if (newref)
1582 new_val_id = newref->value_id;
1583 else
1585 if (changed || !same_valid)
1587 new_val_id = get_next_value_id ();
1588 value_expressions.safe_grow_cleared
1589 (get_max_value_id () + 1);
1591 else
1592 new_val_id = ref->value_id;
1593 if (!newoperands.exists ())
1594 newoperands = operands.copy ();
1595 newref = vn_reference_insert_pieces (newvuse, ref->set,
1596 ref->type,
1597 newoperands,
1598 result, new_val_id);
1599 newoperands = vNULL;
1601 PRE_EXPR_REFERENCE (expr) = newref;
1602 get_or_alloc_expression_id (expr);
1603 add_to_value (new_val_id, expr);
1605 newoperands.release ();
1606 return expr;
1608 break;
1610 case NAME:
1612 tree name = PRE_EXPR_NAME (expr);
1613 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
1614 /* If the SSA name is defined by a PHI node in this block,
1615 translate it. */
1616 if (gimple_code (def_stmt) == GIMPLE_PHI
1617 && gimple_bb (def_stmt) == phiblock)
1619 edge e = find_edge (pred, gimple_bb (def_stmt));
1620 tree def = PHI_ARG_DEF (def_stmt, e->dest_idx);
1622 /* Handle constant. */
1623 if (is_gimple_min_invariant (def))
1624 return get_or_alloc_expr_for_constant (def);
1626 return get_or_alloc_expr_for_name (def);
1628 /* Otherwise return it unchanged - it will get removed if its
1629 value is not available in PREDs AVAIL_OUT set of expressions
1630 by the subtraction of TMP_GEN. */
1631 return expr;
1634 default:
1635 gcc_unreachable ();
1639 /* Wrapper around phi_translate_1 providing caching functionality. */
1641 static pre_expr
1642 phi_translate (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1643 basic_block pred, basic_block phiblock)
1645 expr_pred_trans_t slot = NULL;
1646 pre_expr phitrans;
1648 if (!expr)
1649 return NULL;
1651 /* Constants contain no values that need translation. */
1652 if (expr->kind == CONSTANT)
1653 return expr;
1655 if (value_id_constant_p (get_expr_value_id (expr)))
1656 return expr;
1658 /* Don't add translations of NAMEs as those are cheap to translate. */
1659 if (expr->kind != NAME)
1661 if (phi_trans_add (&slot, expr, pred))
1662 return slot->v;
1663 /* Store NULL for the value we want to return in the case of
1664 recursing. */
1665 slot->v = NULL;
1668 /* Translate. */
1669 phitrans = phi_translate_1 (expr, set1, set2, pred, phiblock);
1671 if (slot)
1673 if (phitrans)
1674 slot->v = phitrans;
1675 else
1676 /* Remove failed translations again, they cause insert
1677 iteration to not pick up new opportunities reliably. */
1678 phi_translate_table->remove_elt_with_hash (slot, slot->hashcode);
1681 return phitrans;
1685 /* For each expression in SET, translate the values through phi nodes
1686 in PHIBLOCK using edge PHIBLOCK->PRED, and store the resulting
1687 expressions in DEST. */
1689 static void
1690 phi_translate_set (bitmap_set_t dest, bitmap_set_t set, basic_block pred,
1691 basic_block phiblock)
1693 vec<pre_expr> exprs;
1694 pre_expr expr;
1695 int i;
1697 if (gimple_seq_empty_p (phi_nodes (phiblock)))
1699 bitmap_set_copy (dest, set);
1700 return;
1703 exprs = sorted_array_from_bitmap_set (set);
1704 FOR_EACH_VEC_ELT (exprs, i, expr)
1706 pre_expr translated;
1707 translated = phi_translate (expr, set, NULL, pred, phiblock);
1708 if (!translated)
1709 continue;
1711 /* We might end up with multiple expressions from SET being
1712 translated to the same value. In this case we do not want
1713 to retain the NARY or REFERENCE expression but prefer a NAME
1714 which would be the leader. */
1715 if (translated->kind == NAME)
1716 bitmap_value_replace_in_set (dest, translated);
1717 else
1718 bitmap_value_insert_into_set (dest, translated);
1720 exprs.release ();
1723 /* Find the leader for a value (i.e., the name representing that
1724 value) in a given set, and return it. Return NULL if no leader
1725 is found. */
1727 static pre_expr
1728 bitmap_find_leader (bitmap_set_t set, unsigned int val)
1730 if (value_id_constant_p (val))
1732 unsigned int i;
1733 bitmap_iterator bi;
1734 bitmap exprset = value_expressions[val];
1736 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
1738 pre_expr expr = expression_for_id (i);
1739 if (expr->kind == CONSTANT)
1740 return expr;
1743 if (bitmap_set_contains_value (set, val))
1745 /* Rather than walk the entire bitmap of expressions, and see
1746 whether any of them has the value we are looking for, we look
1747 at the reverse mapping, which tells us the set of expressions
1748 that have a given value (IE value->expressions with that
1749 value) and see if any of those expressions are in our set.
1750 The number of expressions per value is usually significantly
1751 less than the number of expressions in the set. In fact, for
1752 large testcases, doing it this way is roughly 5-10x faster
1753 than walking the bitmap.
1754 If this is somehow a significant lose for some cases, we can
1755 choose which set to walk based on which set is smaller. */
1756 unsigned int i;
1757 bitmap_iterator bi;
1758 bitmap exprset = value_expressions[val];
1760 EXECUTE_IF_AND_IN_BITMAP (exprset, &set->expressions, 0, i, bi)
1761 return expression_for_id (i);
1763 return NULL;
1766 /* Determine if EXPR, a memory expression, is ANTIC_IN at the top of
1767 BLOCK by seeing if it is not killed in the block. Note that we are
1768 only determining whether there is a store that kills it. Because
1769 of the order in which clean iterates over values, we are guaranteed
1770 that altered operands will have caused us to be eliminated from the
1771 ANTIC_IN set already. */
1773 static bool
1774 value_dies_in_block_x (pre_expr expr, basic_block block)
1776 tree vuse = PRE_EXPR_REFERENCE (expr)->vuse;
1777 vn_reference_t refx = PRE_EXPR_REFERENCE (expr);
1778 gimple *def;
1779 gimple_stmt_iterator gsi;
1780 unsigned id = get_expression_id (expr);
1781 bool res = false;
1782 ao_ref ref;
1784 if (!vuse)
1785 return false;
1787 /* Lookup a previously calculated result. */
1788 if (EXPR_DIES (block)
1789 && bitmap_bit_p (EXPR_DIES (block), id * 2))
1790 return bitmap_bit_p (EXPR_DIES (block), id * 2 + 1);
1792 /* A memory expression {e, VUSE} dies in the block if there is a
1793 statement that may clobber e. If, starting statement walk from the
1794 top of the basic block, a statement uses VUSE there can be no kill
1795 inbetween that use and the original statement that loaded {e, VUSE},
1796 so we can stop walking. */
1797 ref.base = NULL_TREE;
1798 for (gsi = gsi_start_bb (block); !gsi_end_p (gsi); gsi_next (&gsi))
1800 tree def_vuse, def_vdef;
1801 def = gsi_stmt (gsi);
1802 def_vuse = gimple_vuse (def);
1803 def_vdef = gimple_vdef (def);
1805 /* Not a memory statement. */
1806 if (!def_vuse)
1807 continue;
1809 /* Not a may-def. */
1810 if (!def_vdef)
1812 /* A load with the same VUSE, we're done. */
1813 if (def_vuse == vuse)
1814 break;
1816 continue;
1819 /* Init ref only if we really need it. */
1820 if (ref.base == NULL_TREE
1821 && !ao_ref_init_from_vn_reference (&ref, refx->set, refx->type,
1822 refx->operands))
1824 res = true;
1825 break;
1827 /* If the statement may clobber expr, it dies. */
1828 if (stmt_may_clobber_ref_p_1 (def, &ref))
1830 res = true;
1831 break;
1835 /* Remember the result. */
1836 if (!EXPR_DIES (block))
1837 EXPR_DIES (block) = BITMAP_ALLOC (&grand_bitmap_obstack);
1838 bitmap_set_bit (EXPR_DIES (block), id * 2);
1839 if (res)
1840 bitmap_set_bit (EXPR_DIES (block), id * 2 + 1);
1842 return res;
1846 /* Determine if OP is valid in SET1 U SET2, which it is when the union
1847 contains its value-id. */
1849 static bool
1850 op_valid_in_sets (bitmap_set_t set1, bitmap_set_t set2, tree op)
1852 if (op && TREE_CODE (op) == SSA_NAME)
1854 unsigned int value_id = VN_INFO (op)->value_id;
1855 if (!(bitmap_set_contains_value (set1, value_id)
1856 || (set2 && bitmap_set_contains_value (set2, value_id))))
1857 return false;
1859 return true;
1862 /* Determine if the expression EXPR is valid in SET1 U SET2.
1863 ONLY SET2 CAN BE NULL.
1864 This means that we have a leader for each part of the expression
1865 (if it consists of values), or the expression is an SSA_NAME.
1866 For loads/calls, we also see if the vuse is killed in this block. */
1868 static bool
1869 valid_in_sets (bitmap_set_t set1, bitmap_set_t set2, pre_expr expr)
1871 switch (expr->kind)
1873 case NAME:
1874 /* By construction all NAMEs are available. Non-available
1875 NAMEs are removed by subtracting TMP_GEN from the sets. */
1876 return true;
1877 case NARY:
1879 unsigned int i;
1880 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1881 for (i = 0; i < nary->length; i++)
1882 if (!op_valid_in_sets (set1, set2, nary->op[i]))
1883 return false;
1884 return true;
1886 break;
1887 case REFERENCE:
1889 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1890 vn_reference_op_t vro;
1891 unsigned int i;
1893 FOR_EACH_VEC_ELT (ref->operands, i, vro)
1895 if (!op_valid_in_sets (set1, set2, vro->op0)
1896 || !op_valid_in_sets (set1, set2, vro->op1)
1897 || !op_valid_in_sets (set1, set2, vro->op2))
1898 return false;
1900 return true;
1902 default:
1903 gcc_unreachable ();
1907 /* Clean the set of expressions SET1 that are no longer valid in SET1 or SET2.
1908 This means expressions that are made up of values we have no leaders for
1909 in SET1 or SET2. */
1911 static void
1912 clean (bitmap_set_t set1, bitmap_set_t set2 = NULL)
1914 vec<pre_expr> exprs = sorted_array_from_bitmap_set (set1);
1915 pre_expr expr;
1916 int i;
1918 FOR_EACH_VEC_ELT (exprs, i, expr)
1920 if (!valid_in_sets (set1, set2, expr))
1921 bitmap_remove_expr_from_set (set1, expr);
1923 exprs.release ();
1926 /* Clean the set of expressions that are no longer valid in SET because
1927 they are clobbered in BLOCK or because they trap and may not be executed. */
1929 static void
1930 prune_clobbered_mems (bitmap_set_t set, basic_block block)
1932 bitmap_iterator bi;
1933 unsigned i;
1934 pre_expr to_remove = NULL;
1936 FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
1938 /* Remove queued expr. */
1939 if (to_remove)
1941 bitmap_remove_expr_from_set (set, to_remove);
1942 to_remove = NULL;
1945 pre_expr expr = expression_for_id (i);
1946 if (expr->kind == REFERENCE)
1948 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1949 if (ref->vuse)
1951 gimple *def_stmt = SSA_NAME_DEF_STMT (ref->vuse);
1952 if (!gimple_nop_p (def_stmt)
1953 && ((gimple_bb (def_stmt) != block
1954 && !dominated_by_p (CDI_DOMINATORS,
1955 block, gimple_bb (def_stmt)))
1956 || (gimple_bb (def_stmt) == block
1957 && value_dies_in_block_x (expr, block))))
1958 to_remove = expr;
1961 else if (expr->kind == NARY)
1963 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1964 /* If the NARY may trap make sure the block does not contain
1965 a possible exit point.
1966 ??? This is overly conservative if we translate AVAIL_OUT
1967 as the available expression might be after the exit point. */
1968 if (BB_MAY_NOTRETURN (block)
1969 && vn_nary_may_trap (nary))
1970 to_remove = expr;
1974 /* Remove queued expr. */
1975 if (to_remove)
1976 bitmap_remove_expr_from_set (set, to_remove);
1979 static sbitmap has_abnormal_preds;
1981 /* Compute the ANTIC set for BLOCK.
1983 If succs(BLOCK) > 1 then
1984 ANTIC_OUT[BLOCK] = intersection of ANTIC_IN[b] for all succ(BLOCK)
1985 else if succs(BLOCK) == 1 then
1986 ANTIC_OUT[BLOCK] = phi_translate (ANTIC_IN[succ(BLOCK)])
1988 ANTIC_IN[BLOCK] = clean(ANTIC_OUT[BLOCK] U EXP_GEN[BLOCK] - TMP_GEN[BLOCK])
1990 Note that clean() is deferred until after the iteration. */
1992 static bool
1993 compute_antic_aux (basic_block block, bool block_has_abnormal_pred_edge)
1995 bitmap_set_t S, old, ANTIC_OUT;
1996 bitmap_iterator bi;
1997 unsigned int bii;
1998 edge e;
1999 edge_iterator ei;
2001 bool changed = ! BB_VISITED (block);
2002 BB_VISITED (block) = 1;
2003 old = ANTIC_OUT = S = NULL;
2005 /* If any edges from predecessors are abnormal, antic_in is empty,
2006 so do nothing. */
2007 if (block_has_abnormal_pred_edge)
2008 goto maybe_dump_sets;
2010 old = ANTIC_IN (block);
2011 ANTIC_OUT = bitmap_set_new ();
2013 /* If the block has no successors, ANTIC_OUT is empty. */
2014 if (EDGE_COUNT (block->succs) == 0)
2016 /* If we have one successor, we could have some phi nodes to
2017 translate through. */
2018 else if (single_succ_p (block))
2020 basic_block succ_bb = single_succ (block);
2021 gcc_assert (BB_VISITED (succ_bb));
2022 phi_translate_set (ANTIC_OUT, ANTIC_IN (succ_bb), block, succ_bb);
2024 /* If we have multiple successors, we take the intersection of all of
2025 them. Note that in the case of loop exit phi nodes, we may have
2026 phis to translate through. */
2027 else
2029 size_t i;
2030 basic_block bprime, first = NULL;
2032 auto_vec<basic_block> worklist (EDGE_COUNT (block->succs));
2033 FOR_EACH_EDGE (e, ei, block->succs)
2035 if (!first
2036 && BB_VISITED (e->dest))
2037 first = e->dest;
2038 else if (BB_VISITED (e->dest))
2039 worklist.quick_push (e->dest);
2040 else
2042 /* Unvisited successors get their ANTIC_IN replaced by the
2043 maximal set to arrive at a maximum ANTIC_IN solution.
2044 We can ignore them in the intersection operation and thus
2045 need not explicitely represent that maximum solution. */
2046 if (dump_file && (dump_flags & TDF_DETAILS))
2047 fprintf (dump_file, "ANTIC_IN is MAX on %d->%d\n",
2048 e->src->index, e->dest->index);
2052 /* Of multiple successors we have to have visited one already
2053 which is guaranteed by iteration order. */
2054 gcc_assert (first != NULL);
2056 phi_translate_set (ANTIC_OUT, ANTIC_IN (first), block, first);
2058 /* If we have multiple successors we need to intersect the ANTIC_OUT
2059 sets. For values that's a simple intersection but for
2060 expressions it is a union. Given we want to have a single
2061 expression per value in our sets we have to canonicalize.
2062 Avoid randomness and running into cycles like for PR82129 and
2063 canonicalize the expression we choose to the one with the
2064 lowest id. This requires we actually compute the union first. */
2065 FOR_EACH_VEC_ELT (worklist, i, bprime)
2067 if (!gimple_seq_empty_p (phi_nodes (bprime)))
2069 bitmap_set_t tmp = bitmap_set_new ();
2070 phi_translate_set (tmp, ANTIC_IN (bprime), block, bprime);
2071 bitmap_and_into (&ANTIC_OUT->values, &tmp->values);
2072 bitmap_ior_into (&ANTIC_OUT->expressions, &tmp->expressions);
2073 bitmap_set_free (tmp);
2075 else
2077 bitmap_and_into (&ANTIC_OUT->values, &ANTIC_IN (bprime)->values);
2078 bitmap_ior_into (&ANTIC_OUT->expressions,
2079 &ANTIC_IN (bprime)->expressions);
2082 if (! worklist.is_empty ())
2084 /* Prune expressions not in the value set, canonicalizing to
2085 expression with lowest ID. */
2086 bitmap_iterator bi;
2087 unsigned int i;
2088 unsigned int to_clear = -1U;
2089 bitmap seen_value = BITMAP_ALLOC (NULL);
2090 FOR_EACH_EXPR_ID_IN_SET (ANTIC_OUT, i, bi)
2092 if (to_clear != -1U)
2094 bitmap_clear_bit (&ANTIC_OUT->expressions, to_clear);
2095 to_clear = -1U;
2097 pre_expr expr = expression_for_id (i);
2098 unsigned int value_id = get_expr_value_id (expr);
2099 if (!bitmap_bit_p (&ANTIC_OUT->values, value_id)
2100 || !bitmap_set_bit (seen_value, value_id))
2101 to_clear = i;
2103 if (to_clear != -1U)
2104 bitmap_clear_bit (&ANTIC_OUT->expressions, to_clear);
2105 BITMAP_FREE (seen_value);
2109 /* Prune expressions that are clobbered in block and thus become
2110 invalid if translated from ANTIC_OUT to ANTIC_IN. */
2111 prune_clobbered_mems (ANTIC_OUT, block);
2113 /* Generate ANTIC_OUT - TMP_GEN. */
2114 S = bitmap_set_subtract_expressions (ANTIC_OUT, TMP_GEN (block));
2116 /* Start ANTIC_IN with EXP_GEN - TMP_GEN. */
2117 ANTIC_IN (block) = bitmap_set_subtract_expressions (EXP_GEN (block),
2118 TMP_GEN (block));
2120 /* Then union in the ANTIC_OUT - TMP_GEN values,
2121 to get ANTIC_OUT U EXP_GEN - TMP_GEN */
2122 FOR_EACH_EXPR_ID_IN_SET (S, bii, bi)
2123 bitmap_value_insert_into_set (ANTIC_IN (block),
2124 expression_for_id (bii));
2126 /* clean (ANTIC_IN (block)) is defered to after the iteration converged
2127 because it can cause non-convergence, see for example PR81181. */
2129 if (!bitmap_set_equal (old, ANTIC_IN (block)))
2130 changed = true;
2132 maybe_dump_sets:
2133 if (dump_file && (dump_flags & TDF_DETAILS))
2135 if (ANTIC_OUT)
2136 print_bitmap_set (dump_file, ANTIC_OUT, "ANTIC_OUT", block->index);
2138 if (changed)
2139 fprintf (dump_file, "[changed] ");
2140 print_bitmap_set (dump_file, ANTIC_IN (block), "ANTIC_IN",
2141 block->index);
2143 if (S)
2144 print_bitmap_set (dump_file, S, "S", block->index);
2146 if (old)
2147 bitmap_set_free (old);
2148 if (S)
2149 bitmap_set_free (S);
2150 if (ANTIC_OUT)
2151 bitmap_set_free (ANTIC_OUT);
2152 return changed;
2155 /* Compute PARTIAL_ANTIC for BLOCK.
2157 If succs(BLOCK) > 1 then
2158 PA_OUT[BLOCK] = value wise union of PA_IN[b] + all ANTIC_IN not
2159 in ANTIC_OUT for all succ(BLOCK)
2160 else if succs(BLOCK) == 1 then
2161 PA_OUT[BLOCK] = phi_translate (PA_IN[succ(BLOCK)])
2163 PA_IN[BLOCK] = clean(PA_OUT[BLOCK] - TMP_GEN[BLOCK] - ANTIC_IN[BLOCK])
2166 static void
2167 compute_partial_antic_aux (basic_block block,
2168 bool block_has_abnormal_pred_edge)
2170 bitmap_set_t old_PA_IN;
2171 bitmap_set_t PA_OUT;
2172 edge e;
2173 edge_iterator ei;
2174 unsigned long max_pa = PARAM_VALUE (PARAM_MAX_PARTIAL_ANTIC_LENGTH);
2176 old_PA_IN = PA_OUT = NULL;
2178 /* If any edges from predecessors are abnormal, antic_in is empty,
2179 so do nothing. */
2180 if (block_has_abnormal_pred_edge)
2181 goto maybe_dump_sets;
2183 /* If there are too many partially anticipatable values in the
2184 block, phi_translate_set can take an exponential time: stop
2185 before the translation starts. */
2186 if (max_pa
2187 && single_succ_p (block)
2188 && bitmap_count_bits (&PA_IN (single_succ (block))->values) > max_pa)
2189 goto maybe_dump_sets;
2191 old_PA_IN = PA_IN (block);
2192 PA_OUT = bitmap_set_new ();
2194 /* If the block has no successors, ANTIC_OUT is empty. */
2195 if (EDGE_COUNT (block->succs) == 0)
2197 /* If we have one successor, we could have some phi nodes to
2198 translate through. Note that we can't phi translate across DFS
2199 back edges in partial antic, because it uses a union operation on
2200 the successors. For recurrences like IV's, we will end up
2201 generating a new value in the set on each go around (i + 3 (VH.1)
2202 VH.1 + 1 (VH.2), VH.2 + 1 (VH.3), etc), forever. */
2203 else if (single_succ_p (block))
2205 basic_block succ = single_succ (block);
2206 if (!(single_succ_edge (block)->flags & EDGE_DFS_BACK))
2207 phi_translate_set (PA_OUT, PA_IN (succ), block, succ);
2209 /* If we have multiple successors, we take the union of all of
2210 them. */
2211 else
2213 size_t i;
2214 basic_block bprime;
2216 auto_vec<basic_block> worklist (EDGE_COUNT (block->succs));
2217 FOR_EACH_EDGE (e, ei, block->succs)
2219 if (e->flags & EDGE_DFS_BACK)
2220 continue;
2221 worklist.quick_push (e->dest);
2223 if (worklist.length () > 0)
2225 FOR_EACH_VEC_ELT (worklist, i, bprime)
2227 unsigned int i;
2228 bitmap_iterator bi;
2230 FOR_EACH_EXPR_ID_IN_SET (ANTIC_IN (bprime), i, bi)
2231 bitmap_value_insert_into_set (PA_OUT,
2232 expression_for_id (i));
2233 if (!gimple_seq_empty_p (phi_nodes (bprime)))
2235 bitmap_set_t pa_in = bitmap_set_new ();
2236 phi_translate_set (pa_in, PA_IN (bprime), block, bprime);
2237 FOR_EACH_EXPR_ID_IN_SET (pa_in, i, bi)
2238 bitmap_value_insert_into_set (PA_OUT,
2239 expression_for_id (i));
2240 bitmap_set_free (pa_in);
2242 else
2243 FOR_EACH_EXPR_ID_IN_SET (PA_IN (bprime), i, bi)
2244 bitmap_value_insert_into_set (PA_OUT,
2245 expression_for_id (i));
2250 /* Prune expressions that are clobbered in block and thus become
2251 invalid if translated from PA_OUT to PA_IN. */
2252 prune_clobbered_mems (PA_OUT, block);
2254 /* PA_IN starts with PA_OUT - TMP_GEN.
2255 Then we subtract things from ANTIC_IN. */
2256 PA_IN (block) = bitmap_set_subtract_expressions (PA_OUT, TMP_GEN (block));
2258 /* For partial antic, we want to put back in the phi results, since
2259 we will properly avoid making them partially antic over backedges. */
2260 bitmap_ior_into (&PA_IN (block)->values, &PHI_GEN (block)->values);
2261 bitmap_ior_into (&PA_IN (block)->expressions, &PHI_GEN (block)->expressions);
2263 /* PA_IN[block] = PA_IN[block] - ANTIC_IN[block] */
2264 bitmap_set_subtract_values (PA_IN (block), ANTIC_IN (block));
2266 clean (PA_IN (block), ANTIC_IN (block));
2268 maybe_dump_sets:
2269 if (dump_file && (dump_flags & TDF_DETAILS))
2271 if (PA_OUT)
2272 print_bitmap_set (dump_file, PA_OUT, "PA_OUT", block->index);
2274 print_bitmap_set (dump_file, PA_IN (block), "PA_IN", block->index);
2276 if (old_PA_IN)
2277 bitmap_set_free (old_PA_IN);
2278 if (PA_OUT)
2279 bitmap_set_free (PA_OUT);
2282 /* Compute ANTIC and partial ANTIC sets. */
2284 static void
2285 compute_antic (void)
2287 bool changed = true;
2288 int num_iterations = 0;
2289 basic_block block;
2290 int i;
2291 edge_iterator ei;
2292 edge e;
2294 /* If any predecessor edges are abnormal, we punt, so antic_in is empty.
2295 We pre-build the map of blocks with incoming abnormal edges here. */
2296 has_abnormal_preds = sbitmap_alloc (last_basic_block_for_fn (cfun));
2297 bitmap_clear (has_abnormal_preds);
2299 FOR_ALL_BB_FN (block, cfun)
2301 BB_VISITED (block) = 0;
2303 FOR_EACH_EDGE (e, ei, block->preds)
2304 if (e->flags & EDGE_ABNORMAL)
2306 bitmap_set_bit (has_abnormal_preds, block->index);
2307 break;
2310 /* While we are here, give empty ANTIC_IN sets to each block. */
2311 ANTIC_IN (block) = bitmap_set_new ();
2312 if (do_partial_partial)
2313 PA_IN (block) = bitmap_set_new ();
2316 /* At the exit block we anticipate nothing. */
2317 BB_VISITED (EXIT_BLOCK_PTR_FOR_FN (cfun)) = 1;
2319 /* For ANTIC computation we need a postorder that also guarantees that
2320 a block with a single successor is visited after its successor.
2321 RPO on the inverted CFG has this property. */
2322 auto_vec<int, 20> postorder;
2323 inverted_post_order_compute (&postorder);
2325 auto_sbitmap worklist (last_basic_block_for_fn (cfun) + 1);
2326 bitmap_clear (worklist);
2327 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR_FOR_FN (cfun)->preds)
2328 bitmap_set_bit (worklist, e->src->index);
2329 while (changed)
2331 if (dump_file && (dump_flags & TDF_DETAILS))
2332 fprintf (dump_file, "Starting iteration %d\n", num_iterations);
2333 /* ??? We need to clear our PHI translation cache here as the
2334 ANTIC sets shrink and we restrict valid translations to
2335 those having operands with leaders in ANTIC. Same below
2336 for PA ANTIC computation. */
2337 num_iterations++;
2338 changed = false;
2339 for (i = postorder.length () - 1; i >= 0; i--)
2341 if (bitmap_bit_p (worklist, postorder[i]))
2343 basic_block block = BASIC_BLOCK_FOR_FN (cfun, postorder[i]);
2344 bitmap_clear_bit (worklist, block->index);
2345 if (compute_antic_aux (block,
2346 bitmap_bit_p (has_abnormal_preds,
2347 block->index)))
2349 FOR_EACH_EDGE (e, ei, block->preds)
2350 bitmap_set_bit (worklist, e->src->index);
2351 changed = true;
2355 /* Theoretically possible, but *highly* unlikely. */
2356 gcc_checking_assert (num_iterations < 500);
2359 /* We have to clean after the dataflow problem converged as cleaning
2360 can cause non-convergence because it is based on expressions
2361 rather than values. */
2362 FOR_EACH_BB_FN (block, cfun)
2363 clean (ANTIC_IN (block));
2365 statistics_histogram_event (cfun, "compute_antic iterations",
2366 num_iterations);
2368 if (do_partial_partial)
2370 /* For partial antic we ignore backedges and thus we do not need
2371 to perform any iteration when we process blocks in postorder. */
2372 int postorder_num
2373 = pre_and_rev_post_order_compute (NULL, postorder.address (), false);
2374 for (i = postorder_num - 1 ; i >= 0; i--)
2376 basic_block block = BASIC_BLOCK_FOR_FN (cfun, postorder[i]);
2377 compute_partial_antic_aux (block,
2378 bitmap_bit_p (has_abnormal_preds,
2379 block->index));
2383 sbitmap_free (has_abnormal_preds);
2387 /* Inserted expressions are placed onto this worklist, which is used
2388 for performing quick dead code elimination of insertions we made
2389 that didn't turn out to be necessary. */
2390 static bitmap inserted_exprs;
2392 /* The actual worker for create_component_ref_by_pieces. */
2394 static tree
2395 create_component_ref_by_pieces_1 (basic_block block, vn_reference_t ref,
2396 unsigned int *operand, gimple_seq *stmts)
2398 vn_reference_op_t currop = &ref->operands[*operand];
2399 tree genop;
2400 ++*operand;
2401 switch (currop->opcode)
2403 case CALL_EXPR:
2404 gcc_unreachable ();
2406 case MEM_REF:
2408 tree baseop = create_component_ref_by_pieces_1 (block, ref, operand,
2409 stmts);
2410 if (!baseop)
2411 return NULL_TREE;
2412 tree offset = currop->op0;
2413 if (TREE_CODE (baseop) == ADDR_EXPR
2414 && handled_component_p (TREE_OPERAND (baseop, 0)))
2416 poly_int64 off;
2417 tree base;
2418 base = get_addr_base_and_unit_offset (TREE_OPERAND (baseop, 0),
2419 &off);
2420 gcc_assert (base);
2421 offset = int_const_binop (PLUS_EXPR, offset,
2422 build_int_cst (TREE_TYPE (offset),
2423 off));
2424 baseop = build_fold_addr_expr (base);
2426 genop = build2 (MEM_REF, currop->type, baseop, offset);
2427 MR_DEPENDENCE_CLIQUE (genop) = currop->clique;
2428 MR_DEPENDENCE_BASE (genop) = currop->base;
2429 REF_REVERSE_STORAGE_ORDER (genop) = currop->reverse;
2430 return genop;
2433 case TARGET_MEM_REF:
2435 tree genop0 = NULL_TREE, genop1 = NULL_TREE;
2436 vn_reference_op_t nextop = &ref->operands[++*operand];
2437 tree baseop = create_component_ref_by_pieces_1 (block, ref, operand,
2438 stmts);
2439 if (!baseop)
2440 return NULL_TREE;
2441 if (currop->op0)
2443 genop0 = find_or_generate_expression (block, currop->op0, stmts);
2444 if (!genop0)
2445 return NULL_TREE;
2447 if (nextop->op0)
2449 genop1 = find_or_generate_expression (block, nextop->op0, stmts);
2450 if (!genop1)
2451 return NULL_TREE;
2453 genop = build5 (TARGET_MEM_REF, currop->type,
2454 baseop, currop->op2, genop0, currop->op1, genop1);
2456 MR_DEPENDENCE_CLIQUE (genop) = currop->clique;
2457 MR_DEPENDENCE_BASE (genop) = currop->base;
2458 return genop;
2461 case ADDR_EXPR:
2462 if (currop->op0)
2464 gcc_assert (is_gimple_min_invariant (currop->op0));
2465 return currop->op0;
2467 /* Fallthrough. */
2468 case REALPART_EXPR:
2469 case IMAGPART_EXPR:
2470 case VIEW_CONVERT_EXPR:
2472 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2473 stmts);
2474 if (!genop0)
2475 return NULL_TREE;
2476 return fold_build1 (currop->opcode, currop->type, genop0);
2479 case WITH_SIZE_EXPR:
2481 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2482 stmts);
2483 if (!genop0)
2484 return NULL_TREE;
2485 tree genop1 = find_or_generate_expression (block, currop->op0, stmts);
2486 if (!genop1)
2487 return NULL_TREE;
2488 return fold_build2 (currop->opcode, currop->type, genop0, genop1);
2491 case BIT_FIELD_REF:
2493 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2494 stmts);
2495 if (!genop0)
2496 return NULL_TREE;
2497 tree op1 = currop->op0;
2498 tree op2 = currop->op1;
2499 tree t = build3 (BIT_FIELD_REF, currop->type, genop0, op1, op2);
2500 REF_REVERSE_STORAGE_ORDER (t) = currop->reverse;
2501 return fold (t);
2504 /* For array ref vn_reference_op's, operand 1 of the array ref
2505 is op0 of the reference op and operand 3 of the array ref is
2506 op1. */
2507 case ARRAY_RANGE_REF:
2508 case ARRAY_REF:
2510 tree genop0;
2511 tree genop1 = currop->op0;
2512 tree genop2 = currop->op1;
2513 tree genop3 = currop->op2;
2514 genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2515 stmts);
2516 if (!genop0)
2517 return NULL_TREE;
2518 genop1 = find_or_generate_expression (block, genop1, stmts);
2519 if (!genop1)
2520 return NULL_TREE;
2521 if (genop2)
2523 tree domain_type = TYPE_DOMAIN (TREE_TYPE (genop0));
2524 /* Drop zero minimum index if redundant. */
2525 if (integer_zerop (genop2)
2526 && (!domain_type
2527 || integer_zerop (TYPE_MIN_VALUE (domain_type))))
2528 genop2 = NULL_TREE;
2529 else
2531 genop2 = find_or_generate_expression (block, genop2, stmts);
2532 if (!genop2)
2533 return NULL_TREE;
2536 if (genop3)
2538 tree elmt_type = TREE_TYPE (TREE_TYPE (genop0));
2539 /* We can't always put a size in units of the element alignment
2540 here as the element alignment may be not visible. See
2541 PR43783. Simply drop the element size for constant
2542 sizes. */
2543 if (TREE_CODE (genop3) == INTEGER_CST
2544 && TREE_CODE (TYPE_SIZE_UNIT (elmt_type)) == INTEGER_CST
2545 && wi::eq_p (wi::to_offset (TYPE_SIZE_UNIT (elmt_type)),
2546 (wi::to_offset (genop3)
2547 * vn_ref_op_align_unit (currop))))
2548 genop3 = NULL_TREE;
2549 else
2551 genop3 = find_or_generate_expression (block, genop3, stmts);
2552 if (!genop3)
2553 return NULL_TREE;
2556 return build4 (currop->opcode, currop->type, genop0, genop1,
2557 genop2, genop3);
2559 case COMPONENT_REF:
2561 tree op0;
2562 tree op1;
2563 tree genop2 = currop->op1;
2564 op0 = create_component_ref_by_pieces_1 (block, ref, operand, stmts);
2565 if (!op0)
2566 return NULL_TREE;
2567 /* op1 should be a FIELD_DECL, which are represented by themselves. */
2568 op1 = currop->op0;
2569 if (genop2)
2571 genop2 = find_or_generate_expression (block, genop2, stmts);
2572 if (!genop2)
2573 return NULL_TREE;
2575 return fold_build3 (COMPONENT_REF, TREE_TYPE (op1), op0, op1, genop2);
2578 case SSA_NAME:
2580 genop = find_or_generate_expression (block, currop->op0, stmts);
2581 return genop;
2583 case STRING_CST:
2584 case INTEGER_CST:
2585 case COMPLEX_CST:
2586 case VECTOR_CST:
2587 case REAL_CST:
2588 case CONSTRUCTOR:
2589 case VAR_DECL:
2590 case PARM_DECL:
2591 case CONST_DECL:
2592 case RESULT_DECL:
2593 case FUNCTION_DECL:
2594 return currop->op0;
2596 default:
2597 gcc_unreachable ();
2601 /* For COMPONENT_REF's and ARRAY_REF's, we can't have any intermediates for the
2602 COMPONENT_REF or MEM_REF or ARRAY_REF portion, because we'd end up with
2603 trying to rename aggregates into ssa form directly, which is a no no.
2605 Thus, this routine doesn't create temporaries, it just builds a
2606 single access expression for the array, calling
2607 find_or_generate_expression to build the innermost pieces.
2609 This function is a subroutine of create_expression_by_pieces, and
2610 should not be called on it's own unless you really know what you
2611 are doing. */
2613 static tree
2614 create_component_ref_by_pieces (basic_block block, vn_reference_t ref,
2615 gimple_seq *stmts)
2617 unsigned int op = 0;
2618 return create_component_ref_by_pieces_1 (block, ref, &op, stmts);
2621 /* Find a simple leader for an expression, or generate one using
2622 create_expression_by_pieces from a NARY expression for the value.
2623 BLOCK is the basic_block we are looking for leaders in.
2624 OP is the tree expression to find a leader for or generate.
2625 Returns the leader or NULL_TREE on failure. */
2627 static tree
2628 find_or_generate_expression (basic_block block, tree op, gimple_seq *stmts)
2630 pre_expr expr = get_or_alloc_expr_for (op);
2631 unsigned int lookfor = get_expr_value_id (expr);
2632 pre_expr leader = bitmap_find_leader (AVAIL_OUT (block), lookfor);
2633 if (leader)
2635 if (leader->kind == NAME)
2636 return PRE_EXPR_NAME (leader);
2637 else if (leader->kind == CONSTANT)
2638 return PRE_EXPR_CONSTANT (leader);
2640 /* Defer. */
2641 return NULL_TREE;
2644 /* It must be a complex expression, so generate it recursively. Note
2645 that this is only necessary to handle gcc.dg/tree-ssa/ssa-pre28.c
2646 where the insert algorithm fails to insert a required expression. */
2647 bitmap exprset = value_expressions[lookfor];
2648 bitmap_iterator bi;
2649 unsigned int i;
2650 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
2652 pre_expr temp = expression_for_id (i);
2653 /* We cannot insert random REFERENCE expressions at arbitrary
2654 places. We can insert NARYs which eventually re-materializes
2655 its operand values. */
2656 if (temp->kind == NARY)
2657 return create_expression_by_pieces (block, temp, stmts,
2658 get_expr_type (expr));
2661 /* Defer. */
2662 return NULL_TREE;
2665 /* Create an expression in pieces, so that we can handle very complex
2666 expressions that may be ANTIC, but not necessary GIMPLE.
2667 BLOCK is the basic block the expression will be inserted into,
2668 EXPR is the expression to insert (in value form)
2669 STMTS is a statement list to append the necessary insertions into.
2671 This function will die if we hit some value that shouldn't be
2672 ANTIC but is (IE there is no leader for it, or its components).
2673 The function returns NULL_TREE in case a different antic expression
2674 has to be inserted first.
2675 This function may also generate expressions that are themselves
2676 partially or fully redundant. Those that are will be either made
2677 fully redundant during the next iteration of insert (for partially
2678 redundant ones), or eliminated by eliminate (for fully redundant
2679 ones). */
2681 static tree
2682 create_expression_by_pieces (basic_block block, pre_expr expr,
2683 gimple_seq *stmts, tree type)
2685 tree name;
2686 tree folded;
2687 gimple_seq forced_stmts = NULL;
2688 unsigned int value_id;
2689 gimple_stmt_iterator gsi;
2690 tree exprtype = type ? type : get_expr_type (expr);
2691 pre_expr nameexpr;
2692 gassign *newstmt;
2694 switch (expr->kind)
2696 /* We may hit the NAME/CONSTANT case if we have to convert types
2697 that value numbering saw through. */
2698 case NAME:
2699 folded = PRE_EXPR_NAME (expr);
2700 if (useless_type_conversion_p (exprtype, TREE_TYPE (folded)))
2701 return folded;
2702 break;
2703 case CONSTANT:
2705 folded = PRE_EXPR_CONSTANT (expr);
2706 tree tem = fold_convert (exprtype, folded);
2707 if (is_gimple_min_invariant (tem))
2708 return tem;
2709 break;
2711 case REFERENCE:
2712 if (PRE_EXPR_REFERENCE (expr)->operands[0].opcode == CALL_EXPR)
2714 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
2715 unsigned int operand = 1;
2716 vn_reference_op_t currop = &ref->operands[0];
2717 tree sc = NULL_TREE;
2718 tree fn;
2719 if (TREE_CODE (currop->op0) == FUNCTION_DECL)
2720 fn = currop->op0;
2721 else
2722 fn = find_or_generate_expression (block, currop->op0, stmts);
2723 if (!fn)
2724 return NULL_TREE;
2725 if (currop->op1)
2727 sc = find_or_generate_expression (block, currop->op1, stmts);
2728 if (!sc)
2729 return NULL_TREE;
2731 auto_vec<tree> args (ref->operands.length () - 1);
2732 while (operand < ref->operands.length ())
2734 tree arg = create_component_ref_by_pieces_1 (block, ref,
2735 &operand, stmts);
2736 if (!arg)
2737 return NULL_TREE;
2738 args.quick_push (arg);
2740 gcall *call
2741 = gimple_build_call_vec ((TREE_CODE (fn) == FUNCTION_DECL
2742 ? build_fold_addr_expr (fn) : fn), args);
2743 gimple_call_set_with_bounds (call, currop->with_bounds);
2744 if (sc)
2745 gimple_call_set_chain (call, sc);
2746 tree forcedname = make_ssa_name (currop->type);
2747 gimple_call_set_lhs (call, forcedname);
2748 gimple_set_vuse (call, BB_LIVE_VOP_ON_EXIT (block));
2749 gimple_seq_add_stmt_without_update (&forced_stmts, call);
2750 folded = forcedname;
2752 else
2754 folded = create_component_ref_by_pieces (block,
2755 PRE_EXPR_REFERENCE (expr),
2756 stmts);
2757 if (!folded)
2758 return NULL_TREE;
2759 name = make_temp_ssa_name (exprtype, NULL, "pretmp");
2760 newstmt = gimple_build_assign (name, folded);
2761 gimple_seq_add_stmt_without_update (&forced_stmts, newstmt);
2762 gimple_set_vuse (newstmt, BB_LIVE_VOP_ON_EXIT (block));
2763 folded = name;
2765 break;
2766 case NARY:
2768 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
2769 tree *genop = XALLOCAVEC (tree, nary->length);
2770 unsigned i;
2771 for (i = 0; i < nary->length; ++i)
2773 genop[i] = find_or_generate_expression (block, nary->op[i], stmts);
2774 if (!genop[i])
2775 return NULL_TREE;
2776 /* Ensure genop[] is properly typed for POINTER_PLUS_EXPR. It
2777 may have conversions stripped. */
2778 if (nary->opcode == POINTER_PLUS_EXPR)
2780 if (i == 0)
2781 genop[i] = gimple_convert (&forced_stmts,
2782 nary->type, genop[i]);
2783 else if (i == 1)
2784 genop[i] = gimple_convert (&forced_stmts,
2785 sizetype, genop[i]);
2787 else
2788 genop[i] = gimple_convert (&forced_stmts,
2789 TREE_TYPE (nary->op[i]), genop[i]);
2791 if (nary->opcode == CONSTRUCTOR)
2793 vec<constructor_elt, va_gc> *elts = NULL;
2794 for (i = 0; i < nary->length; ++i)
2795 CONSTRUCTOR_APPEND_ELT (elts, NULL_TREE, genop[i]);
2796 folded = build_constructor (nary->type, elts);
2797 name = make_temp_ssa_name (exprtype, NULL, "pretmp");
2798 newstmt = gimple_build_assign (name, folded);
2799 gimple_seq_add_stmt_without_update (&forced_stmts, newstmt);
2800 folded = name;
2802 else
2804 switch (nary->length)
2806 case 1:
2807 folded = gimple_build (&forced_stmts, nary->opcode, nary->type,
2808 genop[0]);
2809 break;
2810 case 2:
2811 folded = gimple_build (&forced_stmts, nary->opcode, nary->type,
2812 genop[0], genop[1]);
2813 break;
2814 case 3:
2815 folded = gimple_build (&forced_stmts, nary->opcode, nary->type,
2816 genop[0], genop[1], genop[2]);
2817 break;
2818 default:
2819 gcc_unreachable ();
2823 break;
2824 default:
2825 gcc_unreachable ();
2828 folded = gimple_convert (&forced_stmts, exprtype, folded);
2830 /* If there is nothing to insert, return the simplified result. */
2831 if (gimple_seq_empty_p (forced_stmts))
2832 return folded;
2833 /* If we simplified to a constant return it and discard eventually
2834 built stmts. */
2835 if (is_gimple_min_invariant (folded))
2837 gimple_seq_discard (forced_stmts);
2838 return folded;
2840 /* Likewise if we simplified to sth not queued for insertion. */
2841 bool found = false;
2842 gsi = gsi_last (forced_stmts);
2843 for (; !gsi_end_p (gsi); gsi_prev (&gsi))
2845 gimple *stmt = gsi_stmt (gsi);
2846 tree forcedname = gimple_get_lhs (stmt);
2847 if (forcedname == folded)
2849 found = true;
2850 break;
2853 if (! found)
2855 gimple_seq_discard (forced_stmts);
2856 return folded;
2858 gcc_assert (TREE_CODE (folded) == SSA_NAME);
2860 /* If we have any intermediate expressions to the value sets, add them
2861 to the value sets and chain them in the instruction stream. */
2862 if (forced_stmts)
2864 gsi = gsi_start (forced_stmts);
2865 for (; !gsi_end_p (gsi); gsi_next (&gsi))
2867 gimple *stmt = gsi_stmt (gsi);
2868 tree forcedname = gimple_get_lhs (stmt);
2869 pre_expr nameexpr;
2871 if (forcedname != folded)
2873 VN_INFO_GET (forcedname)->valnum = forcedname;
2874 VN_INFO (forcedname)->value_id = get_next_value_id ();
2875 nameexpr = get_or_alloc_expr_for_name (forcedname);
2876 add_to_value (VN_INFO (forcedname)->value_id, nameexpr);
2877 bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
2878 bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
2881 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (forcedname));
2883 gimple_seq_add_seq (stmts, forced_stmts);
2886 name = folded;
2888 /* Fold the last statement. */
2889 gsi = gsi_last (*stmts);
2890 if (fold_stmt_inplace (&gsi))
2891 update_stmt (gsi_stmt (gsi));
2893 /* Add a value number to the temporary.
2894 The value may already exist in either NEW_SETS, or AVAIL_OUT, because
2895 we are creating the expression by pieces, and this particular piece of
2896 the expression may have been represented. There is no harm in replacing
2897 here. */
2898 value_id = get_expr_value_id (expr);
2899 VN_INFO_GET (name)->value_id = value_id;
2900 VN_INFO (name)->valnum = sccvn_valnum_from_value_id (value_id);
2901 if (VN_INFO (name)->valnum == NULL_TREE)
2902 VN_INFO (name)->valnum = name;
2903 gcc_assert (VN_INFO (name)->valnum != NULL_TREE);
2904 nameexpr = get_or_alloc_expr_for_name (name);
2905 add_to_value (value_id, nameexpr);
2906 if (NEW_SETS (block))
2907 bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
2908 bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
2910 pre_stats.insertions++;
2911 if (dump_file && (dump_flags & TDF_DETAILS))
2913 fprintf (dump_file, "Inserted ");
2914 print_gimple_stmt (dump_file, gsi_stmt (gsi_last (*stmts)), 0);
2915 fprintf (dump_file, " in predecessor %d (%04d)\n",
2916 block->index, value_id);
2919 return name;
2923 /* Insert the to-be-made-available values of expression EXPRNUM for each
2924 predecessor, stored in AVAIL, into the predecessors of BLOCK, and
2925 merge the result with a phi node, given the same value number as
2926 NODE. Return true if we have inserted new stuff. */
2928 static bool
2929 insert_into_preds_of_block (basic_block block, unsigned int exprnum,
2930 vec<pre_expr> avail)
2932 pre_expr expr = expression_for_id (exprnum);
2933 pre_expr newphi;
2934 unsigned int val = get_expr_value_id (expr);
2935 edge pred;
2936 bool insertions = false;
2937 bool nophi = false;
2938 basic_block bprime;
2939 pre_expr eprime;
2940 edge_iterator ei;
2941 tree type = get_expr_type (expr);
2942 tree temp;
2943 gphi *phi;
2945 /* Make sure we aren't creating an induction variable. */
2946 if (bb_loop_depth (block) > 0 && EDGE_COUNT (block->preds) == 2)
2948 bool firstinsideloop = false;
2949 bool secondinsideloop = false;
2950 firstinsideloop = flow_bb_inside_loop_p (block->loop_father,
2951 EDGE_PRED (block, 0)->src);
2952 secondinsideloop = flow_bb_inside_loop_p (block->loop_father,
2953 EDGE_PRED (block, 1)->src);
2954 /* Induction variables only have one edge inside the loop. */
2955 if ((firstinsideloop ^ secondinsideloop)
2956 && expr->kind != REFERENCE)
2958 if (dump_file && (dump_flags & TDF_DETAILS))
2959 fprintf (dump_file, "Skipping insertion of phi for partial redundancy: Looks like an induction variable\n");
2960 nophi = true;
2964 /* Make the necessary insertions. */
2965 FOR_EACH_EDGE (pred, ei, block->preds)
2967 gimple_seq stmts = NULL;
2968 tree builtexpr;
2969 bprime = pred->src;
2970 eprime = avail[pred->dest_idx];
2971 builtexpr = create_expression_by_pieces (bprime, eprime,
2972 &stmts, type);
2973 gcc_assert (!(pred->flags & EDGE_ABNORMAL));
2974 if (!gimple_seq_empty_p (stmts))
2976 basic_block new_bb = gsi_insert_seq_on_edge_immediate (pred, stmts);
2977 gcc_assert (! new_bb);
2978 insertions = true;
2980 if (!builtexpr)
2982 /* We cannot insert a PHI node if we failed to insert
2983 on one edge. */
2984 nophi = true;
2985 continue;
2987 if (is_gimple_min_invariant (builtexpr))
2988 avail[pred->dest_idx] = get_or_alloc_expr_for_constant (builtexpr);
2989 else
2990 avail[pred->dest_idx] = get_or_alloc_expr_for_name (builtexpr);
2992 /* If we didn't want a phi node, and we made insertions, we still have
2993 inserted new stuff, and thus return true. If we didn't want a phi node,
2994 and didn't make insertions, we haven't added anything new, so return
2995 false. */
2996 if (nophi && insertions)
2997 return true;
2998 else if (nophi && !insertions)
2999 return false;
3001 /* Now build a phi for the new variable. */
3002 temp = make_temp_ssa_name (type, NULL, "prephitmp");
3003 phi = create_phi_node (temp, block);
3005 VN_INFO_GET (temp)->value_id = val;
3006 VN_INFO (temp)->valnum = sccvn_valnum_from_value_id (val);
3007 if (VN_INFO (temp)->valnum == NULL_TREE)
3008 VN_INFO (temp)->valnum = temp;
3009 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (temp));
3010 FOR_EACH_EDGE (pred, ei, block->preds)
3012 pre_expr ae = avail[pred->dest_idx];
3013 gcc_assert (get_expr_type (ae) == type
3014 || useless_type_conversion_p (type, get_expr_type (ae)));
3015 if (ae->kind == CONSTANT)
3016 add_phi_arg (phi, unshare_expr (PRE_EXPR_CONSTANT (ae)),
3017 pred, UNKNOWN_LOCATION);
3018 else
3019 add_phi_arg (phi, PRE_EXPR_NAME (ae), pred, UNKNOWN_LOCATION);
3022 newphi = get_or_alloc_expr_for_name (temp);
3023 add_to_value (val, newphi);
3025 /* The value should *not* exist in PHI_GEN, or else we wouldn't be doing
3026 this insertion, since we test for the existence of this value in PHI_GEN
3027 before proceeding with the partial redundancy checks in insert_aux.
3029 The value may exist in AVAIL_OUT, in particular, it could be represented
3030 by the expression we are trying to eliminate, in which case we want the
3031 replacement to occur. If it's not existing in AVAIL_OUT, we want it
3032 inserted there.
3034 Similarly, to the PHI_GEN case, the value should not exist in NEW_SETS of
3035 this block, because if it did, it would have existed in our dominator's
3036 AVAIL_OUT, and would have been skipped due to the full redundancy check.
3039 bitmap_insert_into_set (PHI_GEN (block), newphi);
3040 bitmap_value_replace_in_set (AVAIL_OUT (block),
3041 newphi);
3042 bitmap_insert_into_set (NEW_SETS (block),
3043 newphi);
3045 /* If we insert a PHI node for a conversion of another PHI node
3046 in the same basic-block try to preserve range information.
3047 This is important so that followup loop passes receive optimal
3048 number of iteration analysis results. See PR61743. */
3049 if (expr->kind == NARY
3050 && CONVERT_EXPR_CODE_P (expr->u.nary->opcode)
3051 && TREE_CODE (expr->u.nary->op[0]) == SSA_NAME
3052 && gimple_bb (SSA_NAME_DEF_STMT (expr->u.nary->op[0])) == block
3053 && INTEGRAL_TYPE_P (type)
3054 && INTEGRAL_TYPE_P (TREE_TYPE (expr->u.nary->op[0]))
3055 && (TYPE_PRECISION (type)
3056 >= TYPE_PRECISION (TREE_TYPE (expr->u.nary->op[0])))
3057 && SSA_NAME_RANGE_INFO (expr->u.nary->op[0]))
3059 wide_int min, max;
3060 if (get_range_info (expr->u.nary->op[0], &min, &max) == VR_RANGE
3061 && !wi::neg_p (min, SIGNED)
3062 && !wi::neg_p (max, SIGNED))
3063 /* Just handle extension and sign-changes of all-positive ranges. */
3064 set_range_info (temp,
3065 SSA_NAME_RANGE_TYPE (expr->u.nary->op[0]),
3066 wide_int_storage::from (min, TYPE_PRECISION (type),
3067 TYPE_SIGN (type)),
3068 wide_int_storage::from (max, TYPE_PRECISION (type),
3069 TYPE_SIGN (type)));
3072 if (dump_file && (dump_flags & TDF_DETAILS))
3074 fprintf (dump_file, "Created phi ");
3075 print_gimple_stmt (dump_file, phi, 0);
3076 fprintf (dump_file, " in block %d (%04d)\n", block->index, val);
3078 pre_stats.phis++;
3079 return true;
3084 /* Perform insertion of partially redundant or hoistable values.
3085 For BLOCK, do the following:
3086 1. Propagate the NEW_SETS of the dominator into the current block.
3087 If the block has multiple predecessors,
3088 2a. Iterate over the ANTIC expressions for the block to see if
3089 any of them are partially redundant.
3090 2b. If so, insert them into the necessary predecessors to make
3091 the expression fully redundant.
3092 2c. Insert a new PHI merging the values of the predecessors.
3093 2d. Insert the new PHI, and the new expressions, into the
3094 NEW_SETS set.
3095 If the block has multiple successors,
3096 3a. Iterate over the ANTIC values for the block to see if
3097 any of them are good candidates for hoisting.
3098 3b. If so, insert expressions computing the values in BLOCK,
3099 and add the new expressions into the NEW_SETS set.
3100 4. Recursively call ourselves on the dominator children of BLOCK.
3102 Steps 1, 2a, and 4 are done by insert_aux. 2b, 2c and 2d are done by
3103 do_pre_regular_insertion and do_partial_insertion. 3a and 3b are
3104 done in do_hoist_insertion.
3107 static bool
3108 do_pre_regular_insertion (basic_block block, basic_block dom)
3110 bool new_stuff = false;
3111 vec<pre_expr> exprs;
3112 pre_expr expr;
3113 auto_vec<pre_expr> avail;
3114 int i;
3116 exprs = sorted_array_from_bitmap_set (ANTIC_IN (block));
3117 avail.safe_grow (EDGE_COUNT (block->preds));
3119 FOR_EACH_VEC_ELT (exprs, i, expr)
3121 if (expr->kind == NARY
3122 || expr->kind == REFERENCE)
3124 unsigned int val;
3125 bool by_some = false;
3126 bool cant_insert = false;
3127 bool all_same = true;
3128 pre_expr first_s = NULL;
3129 edge pred;
3130 basic_block bprime;
3131 pre_expr eprime = NULL;
3132 edge_iterator ei;
3133 pre_expr edoubleprime = NULL;
3134 bool do_insertion = false;
3136 val = get_expr_value_id (expr);
3137 if (bitmap_set_contains_value (PHI_GEN (block), val))
3138 continue;
3139 if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3141 if (dump_file && (dump_flags & TDF_DETAILS))
3143 fprintf (dump_file, "Found fully redundant value: ");
3144 print_pre_expr (dump_file, expr);
3145 fprintf (dump_file, "\n");
3147 continue;
3150 FOR_EACH_EDGE (pred, ei, block->preds)
3152 unsigned int vprime;
3154 /* We should never run insertion for the exit block
3155 and so not come across fake pred edges. */
3156 gcc_assert (!(pred->flags & EDGE_FAKE));
3157 bprime = pred->src;
3158 /* We are looking at ANTIC_OUT of bprime. */
3159 eprime = phi_translate (expr, ANTIC_IN (block), NULL,
3160 bprime, block);
3162 /* eprime will generally only be NULL if the
3163 value of the expression, translated
3164 through the PHI for this predecessor, is
3165 undefined. If that is the case, we can't
3166 make the expression fully redundant,
3167 because its value is undefined along a
3168 predecessor path. We can thus break out
3169 early because it doesn't matter what the
3170 rest of the results are. */
3171 if (eprime == NULL)
3173 avail[pred->dest_idx] = NULL;
3174 cant_insert = true;
3175 break;
3178 vprime = get_expr_value_id (eprime);
3179 edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime),
3180 vprime);
3181 if (edoubleprime == NULL)
3183 avail[pred->dest_idx] = eprime;
3184 all_same = false;
3186 else
3188 avail[pred->dest_idx] = edoubleprime;
3189 by_some = true;
3190 /* We want to perform insertions to remove a redundancy on
3191 a path in the CFG we want to optimize for speed. */
3192 if (optimize_edge_for_speed_p (pred))
3193 do_insertion = true;
3194 if (first_s == NULL)
3195 first_s = edoubleprime;
3196 else if (!pre_expr_d::equal (first_s, edoubleprime))
3197 all_same = false;
3200 /* If we can insert it, it's not the same value
3201 already existing along every predecessor, and
3202 it's defined by some predecessor, it is
3203 partially redundant. */
3204 if (!cant_insert && !all_same && by_some)
3206 if (!do_insertion)
3208 if (dump_file && (dump_flags & TDF_DETAILS))
3210 fprintf (dump_file, "Skipping partial redundancy for "
3211 "expression ");
3212 print_pre_expr (dump_file, expr);
3213 fprintf (dump_file, " (%04d), no redundancy on to be "
3214 "optimized for speed edge\n", val);
3217 else if (dbg_cnt (treepre_insert))
3219 if (dump_file && (dump_flags & TDF_DETAILS))
3221 fprintf (dump_file, "Found partial redundancy for "
3222 "expression ");
3223 print_pre_expr (dump_file, expr);
3224 fprintf (dump_file, " (%04d)\n",
3225 get_expr_value_id (expr));
3227 if (insert_into_preds_of_block (block,
3228 get_expression_id (expr),
3229 avail))
3230 new_stuff = true;
3233 /* If all edges produce the same value and that value is
3234 an invariant, then the PHI has the same value on all
3235 edges. Note this. */
3236 else if (!cant_insert && all_same)
3238 gcc_assert (edoubleprime->kind == CONSTANT
3239 || edoubleprime->kind == NAME);
3241 tree temp = make_temp_ssa_name (get_expr_type (expr),
3242 NULL, "pretmp");
3243 gassign *assign
3244 = gimple_build_assign (temp,
3245 edoubleprime->kind == CONSTANT ?
3246 PRE_EXPR_CONSTANT (edoubleprime) :
3247 PRE_EXPR_NAME (edoubleprime));
3248 gimple_stmt_iterator gsi = gsi_after_labels (block);
3249 gsi_insert_before (&gsi, assign, GSI_NEW_STMT);
3251 VN_INFO_GET (temp)->value_id = val;
3252 VN_INFO (temp)->valnum = sccvn_valnum_from_value_id (val);
3253 if (VN_INFO (temp)->valnum == NULL_TREE)
3254 VN_INFO (temp)->valnum = temp;
3255 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (temp));
3256 pre_expr newe = get_or_alloc_expr_for_name (temp);
3257 add_to_value (val, newe);
3258 bitmap_value_replace_in_set (AVAIL_OUT (block), newe);
3259 bitmap_insert_into_set (NEW_SETS (block), newe);
3264 exprs.release ();
3265 return new_stuff;
3269 /* Perform insertion for partially anticipatable expressions. There
3270 is only one case we will perform insertion for these. This case is
3271 if the expression is partially anticipatable, and fully available.
3272 In this case, we know that putting it earlier will enable us to
3273 remove the later computation. */
3275 static bool
3276 do_pre_partial_partial_insertion (basic_block block, basic_block dom)
3278 bool new_stuff = false;
3279 vec<pre_expr> exprs;
3280 pre_expr expr;
3281 auto_vec<pre_expr> avail;
3282 int i;
3284 exprs = sorted_array_from_bitmap_set (PA_IN (block));
3285 avail.safe_grow (EDGE_COUNT (block->preds));
3287 FOR_EACH_VEC_ELT (exprs, i, expr)
3289 if (expr->kind == NARY
3290 || expr->kind == REFERENCE)
3292 unsigned int val;
3293 bool by_all = true;
3294 bool cant_insert = false;
3295 edge pred;
3296 basic_block bprime;
3297 pre_expr eprime = NULL;
3298 edge_iterator ei;
3300 val = get_expr_value_id (expr);
3301 if (bitmap_set_contains_value (PHI_GEN (block), val))
3302 continue;
3303 if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3304 continue;
3306 FOR_EACH_EDGE (pred, ei, block->preds)
3308 unsigned int vprime;
3309 pre_expr edoubleprime;
3311 /* We should never run insertion for the exit block
3312 and so not come across fake pred edges. */
3313 gcc_assert (!(pred->flags & EDGE_FAKE));
3314 bprime = pred->src;
3315 eprime = phi_translate (expr, ANTIC_IN (block),
3316 PA_IN (block),
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 avail[pred->dest_idx] = NULL;
3331 cant_insert = true;
3332 break;
3335 vprime = get_expr_value_id (eprime);
3336 edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime), vprime);
3337 avail[pred->dest_idx] = edoubleprime;
3338 if (edoubleprime == NULL)
3340 by_all = false;
3341 break;
3345 /* If we can insert it, it's not the same value
3346 already existing along every predecessor, and
3347 it's defined by some predecessor, it is
3348 partially redundant. */
3349 if (!cant_insert && by_all)
3351 edge succ;
3352 bool do_insertion = false;
3354 /* Insert only if we can remove a later expression on a path
3355 that we want to optimize for speed.
3356 The phi node that we will be inserting in BLOCK is not free,
3357 and inserting it for the sake of !optimize_for_speed successor
3358 may cause regressions on the speed path. */
3359 FOR_EACH_EDGE (succ, ei, block->succs)
3361 if (bitmap_set_contains_value (PA_IN (succ->dest), val)
3362 || bitmap_set_contains_value (ANTIC_IN (succ->dest), val))
3364 if (optimize_edge_for_speed_p (succ))
3365 do_insertion = true;
3369 if (!do_insertion)
3371 if (dump_file && (dump_flags & TDF_DETAILS))
3373 fprintf (dump_file, "Skipping partial partial redundancy "
3374 "for expression ");
3375 print_pre_expr (dump_file, expr);
3376 fprintf (dump_file, " (%04d), not (partially) anticipated "
3377 "on any to be optimized for speed edges\n", val);
3380 else if (dbg_cnt (treepre_insert))
3382 pre_stats.pa_insert++;
3383 if (dump_file && (dump_flags & TDF_DETAILS))
3385 fprintf (dump_file, "Found partial partial redundancy "
3386 "for expression ");
3387 print_pre_expr (dump_file, expr);
3388 fprintf (dump_file, " (%04d)\n",
3389 get_expr_value_id (expr));
3391 if (insert_into_preds_of_block (block,
3392 get_expression_id (expr),
3393 avail))
3394 new_stuff = true;
3400 exprs.release ();
3401 return new_stuff;
3404 /* Insert expressions in BLOCK to compute hoistable values up.
3405 Return TRUE if something was inserted, otherwise return FALSE.
3406 The caller has to make sure that BLOCK has at least two successors. */
3408 static bool
3409 do_hoist_insertion (basic_block block)
3411 edge e;
3412 edge_iterator ei;
3413 bool new_stuff = false;
3414 unsigned i;
3415 gimple_stmt_iterator last;
3417 /* At least two successors, or else... */
3418 gcc_assert (EDGE_COUNT (block->succs) >= 2);
3420 /* Check that all successors of BLOCK are dominated by block.
3421 We could use dominated_by_p() for this, but actually there is a much
3422 quicker check: any successor that is dominated by BLOCK can't have
3423 more than one predecessor edge. */
3424 FOR_EACH_EDGE (e, ei, block->succs)
3425 if (! single_pred_p (e->dest))
3426 return false;
3428 /* Determine the insertion point. If we cannot safely insert before
3429 the last stmt if we'd have to, bail out. */
3430 last = gsi_last_bb (block);
3431 if (!gsi_end_p (last)
3432 && !is_ctrl_stmt (gsi_stmt (last))
3433 && stmt_ends_bb_p (gsi_stmt (last)))
3434 return false;
3436 /* Compute the set of hoistable expressions from ANTIC_IN. First compute
3437 hoistable values. */
3438 bitmap_set hoistable_set;
3440 /* A hoistable value must be in ANTIC_IN(block)
3441 but not in AVAIL_OUT(BLOCK). */
3442 bitmap_initialize (&hoistable_set.values, &grand_bitmap_obstack);
3443 bitmap_and_compl (&hoistable_set.values,
3444 &ANTIC_IN (block)->values, &AVAIL_OUT (block)->values);
3446 /* Short-cut for a common case: hoistable_set is empty. */
3447 if (bitmap_empty_p (&hoistable_set.values))
3448 return false;
3450 /* Compute which of the hoistable values is in AVAIL_OUT of
3451 at least one of the successors of BLOCK. */
3452 bitmap_head availout_in_some;
3453 bitmap_initialize (&availout_in_some, &grand_bitmap_obstack);
3454 FOR_EACH_EDGE (e, ei, block->succs)
3455 /* Do not consider expressions solely because their availability
3456 on loop exits. They'd be ANTIC-IN throughout the whole loop
3457 and thus effectively hoisted across loops by combination of
3458 PRE and hoisting. */
3459 if (! loop_exit_edge_p (block->loop_father, e))
3460 bitmap_ior_and_into (&availout_in_some, &hoistable_set.values,
3461 &AVAIL_OUT (e->dest)->values);
3462 bitmap_clear (&hoistable_set.values);
3464 /* Short-cut for a common case: availout_in_some is empty. */
3465 if (bitmap_empty_p (&availout_in_some))
3466 return false;
3468 /* Hack hoitable_set in-place so we can use sorted_array_from_bitmap_set. */
3469 hoistable_set.values = availout_in_some;
3470 hoistable_set.expressions = ANTIC_IN (block)->expressions;
3472 /* Now finally construct the topological-ordered expression set. */
3473 vec<pre_expr> exprs = sorted_array_from_bitmap_set (&hoistable_set);
3475 bitmap_clear (&hoistable_set.values);
3477 /* If there are candidate values for hoisting, insert expressions
3478 strategically to make the hoistable expressions fully redundant. */
3479 pre_expr expr;
3480 FOR_EACH_VEC_ELT (exprs, i, expr)
3482 /* While we try to sort expressions topologically above the
3483 sorting doesn't work out perfectly. Catch expressions we
3484 already inserted. */
3485 unsigned int value_id = get_expr_value_id (expr);
3486 if (bitmap_set_contains_value (AVAIL_OUT (block), value_id))
3488 if (dump_file && (dump_flags & TDF_DETAILS))
3490 fprintf (dump_file,
3491 "Already inserted expression for ");
3492 print_pre_expr (dump_file, expr);
3493 fprintf (dump_file, " (%04d)\n", value_id);
3495 continue;
3498 /* OK, we should hoist this value. Perform the transformation. */
3499 pre_stats.hoist_insert++;
3500 if (dump_file && (dump_flags & TDF_DETAILS))
3502 fprintf (dump_file,
3503 "Inserting expression in block %d for code hoisting: ",
3504 block->index);
3505 print_pre_expr (dump_file, expr);
3506 fprintf (dump_file, " (%04d)\n", value_id);
3509 gimple_seq stmts = NULL;
3510 tree res = create_expression_by_pieces (block, expr, &stmts,
3511 get_expr_type (expr));
3513 /* Do not return true if expression creation ultimately
3514 did not insert any statements. */
3515 if (gimple_seq_empty_p (stmts))
3516 res = NULL_TREE;
3517 else
3519 if (gsi_end_p (last) || is_ctrl_stmt (gsi_stmt (last)))
3520 gsi_insert_seq_before (&last, stmts, GSI_SAME_STMT);
3521 else
3522 gsi_insert_seq_after (&last, stmts, GSI_NEW_STMT);
3525 /* Make sure to not return true if expression creation ultimately
3526 failed but also make sure to insert any stmts produced as they
3527 are tracked in inserted_exprs. */
3528 if (! res)
3529 continue;
3531 new_stuff = true;
3534 exprs.release ();
3536 return new_stuff;
3539 /* Do a dominator walk on the control flow graph, and insert computations
3540 of values as necessary for PRE and hoisting. */
3542 static bool
3543 insert_aux (basic_block block, bool do_pre, bool do_hoist)
3545 basic_block son;
3546 bool new_stuff = false;
3548 if (block)
3550 basic_block dom;
3551 dom = get_immediate_dominator (CDI_DOMINATORS, block);
3552 if (dom)
3554 unsigned i;
3555 bitmap_iterator bi;
3556 bitmap_set_t newset;
3558 /* First, update the AVAIL_OUT set with anything we may have
3559 inserted higher up in the dominator tree. */
3560 newset = NEW_SETS (dom);
3561 if (newset)
3563 /* Note that we need to value_replace both NEW_SETS, and
3564 AVAIL_OUT. For both the case of NEW_SETS, the value may be
3565 represented by some non-simple expression here that we want
3566 to replace it with. */
3567 FOR_EACH_EXPR_ID_IN_SET (newset, i, bi)
3569 pre_expr expr = expression_for_id (i);
3570 bitmap_value_replace_in_set (NEW_SETS (block), expr);
3571 bitmap_value_replace_in_set (AVAIL_OUT (block), expr);
3575 /* Insert expressions for partial redundancies. */
3576 if (do_pre && !single_pred_p (block))
3578 new_stuff |= do_pre_regular_insertion (block, dom);
3579 if (do_partial_partial)
3580 new_stuff |= do_pre_partial_partial_insertion (block, dom);
3583 /* Insert expressions for hoisting. */
3584 if (do_hoist && EDGE_COUNT (block->succs) >= 2)
3585 new_stuff |= do_hoist_insertion (block);
3588 for (son = first_dom_son (CDI_DOMINATORS, block);
3589 son;
3590 son = next_dom_son (CDI_DOMINATORS, son))
3592 new_stuff |= insert_aux (son, do_pre, do_hoist);
3595 return new_stuff;
3598 /* Perform insertion of partially redundant and hoistable values. */
3600 static void
3601 insert (void)
3603 bool new_stuff = true;
3604 basic_block bb;
3605 int num_iterations = 0;
3607 FOR_ALL_BB_FN (bb, cfun)
3608 NEW_SETS (bb) = bitmap_set_new ();
3610 while (new_stuff)
3612 num_iterations++;
3613 if (dump_file && dump_flags & TDF_DETAILS)
3614 fprintf (dump_file, "Starting insert iteration %d\n", num_iterations);
3615 new_stuff = insert_aux (ENTRY_BLOCK_PTR_FOR_FN (cfun), flag_tree_pre,
3616 flag_code_hoisting);
3618 /* Clear the NEW sets before the next iteration. We have already
3619 fully propagated its contents. */
3620 if (new_stuff)
3621 FOR_ALL_BB_FN (bb, cfun)
3622 bitmap_set_free (NEW_SETS (bb));
3624 statistics_histogram_event (cfun, "insert iterations", num_iterations);
3628 /* Compute the AVAIL set for all basic blocks.
3630 This function performs value numbering of the statements in each basic
3631 block. The AVAIL sets are built from information we glean while doing
3632 this value numbering, since the AVAIL sets contain only one entry per
3633 value.
3635 AVAIL_IN[BLOCK] = AVAIL_OUT[dom(BLOCK)].
3636 AVAIL_OUT[BLOCK] = AVAIL_IN[BLOCK] U PHI_GEN[BLOCK] U TMP_GEN[BLOCK]. */
3638 static void
3639 compute_avail (void)
3642 basic_block block, son;
3643 basic_block *worklist;
3644 size_t sp = 0;
3645 unsigned i;
3646 tree name;
3648 /* We pretend that default definitions are defined in the entry block.
3649 This includes function arguments and the static chain decl. */
3650 FOR_EACH_SSA_NAME (i, name, cfun)
3652 pre_expr e;
3653 if (!SSA_NAME_IS_DEFAULT_DEF (name)
3654 || has_zero_uses (name)
3655 || virtual_operand_p (name))
3656 continue;
3658 e = get_or_alloc_expr_for_name (name);
3659 add_to_value (get_expr_value_id (e), e);
3660 bitmap_insert_into_set (TMP_GEN (ENTRY_BLOCK_PTR_FOR_FN (cfun)), e);
3661 bitmap_value_insert_into_set (AVAIL_OUT (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
3665 if (dump_file && (dump_flags & TDF_DETAILS))
3667 print_bitmap_set (dump_file, TMP_GEN (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
3668 "tmp_gen", ENTRY_BLOCK);
3669 print_bitmap_set (dump_file, AVAIL_OUT (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
3670 "avail_out", ENTRY_BLOCK);
3673 /* Allocate the worklist. */
3674 worklist = XNEWVEC (basic_block, n_basic_blocks_for_fn (cfun));
3676 /* Seed the algorithm by putting the dominator children of the entry
3677 block on the worklist. */
3678 for (son = first_dom_son (CDI_DOMINATORS, ENTRY_BLOCK_PTR_FOR_FN (cfun));
3679 son;
3680 son = next_dom_son (CDI_DOMINATORS, son))
3681 worklist[sp++] = son;
3683 BB_LIVE_VOP_ON_EXIT (ENTRY_BLOCK_PTR_FOR_FN (cfun))
3684 = ssa_default_def (cfun, gimple_vop (cfun));
3686 /* Loop until the worklist is empty. */
3687 while (sp)
3689 gimple *stmt;
3690 basic_block dom;
3692 /* Pick a block from the worklist. */
3693 block = worklist[--sp];
3695 /* Initially, the set of available values in BLOCK is that of
3696 its immediate dominator. */
3697 dom = get_immediate_dominator (CDI_DOMINATORS, block);
3698 if (dom)
3700 bitmap_set_copy (AVAIL_OUT (block), AVAIL_OUT (dom));
3701 BB_LIVE_VOP_ON_EXIT (block) = BB_LIVE_VOP_ON_EXIT (dom);
3704 /* Generate values for PHI nodes. */
3705 for (gphi_iterator gsi = gsi_start_phis (block); !gsi_end_p (gsi);
3706 gsi_next (&gsi))
3708 tree result = gimple_phi_result (gsi.phi ());
3710 /* We have no need for virtual phis, as they don't represent
3711 actual computations. */
3712 if (virtual_operand_p (result))
3714 BB_LIVE_VOP_ON_EXIT (block) = result;
3715 continue;
3718 pre_expr e = get_or_alloc_expr_for_name (result);
3719 add_to_value (get_expr_value_id (e), e);
3720 bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3721 bitmap_insert_into_set (PHI_GEN (block), e);
3724 BB_MAY_NOTRETURN (block) = 0;
3726 /* Now compute value numbers and populate value sets with all
3727 the expressions computed in BLOCK. */
3728 for (gimple_stmt_iterator gsi = gsi_start_bb (block); !gsi_end_p (gsi);
3729 gsi_next (&gsi))
3731 ssa_op_iter iter;
3732 tree op;
3734 stmt = gsi_stmt (gsi);
3736 /* Cache whether the basic-block has any non-visible side-effect
3737 or control flow.
3738 If this isn't a call or it is the last stmt in the
3739 basic-block then the CFG represents things correctly. */
3740 if (is_gimple_call (stmt) && !stmt_ends_bb_p (stmt))
3742 /* Non-looping const functions always return normally.
3743 Otherwise the call might not return or have side-effects
3744 that forbids hoisting possibly trapping expressions
3745 before it. */
3746 int flags = gimple_call_flags (stmt);
3747 if (!(flags & ECF_CONST)
3748 || (flags & ECF_LOOPING_CONST_OR_PURE))
3749 BB_MAY_NOTRETURN (block) = 1;
3752 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_DEF)
3754 pre_expr e = get_or_alloc_expr_for_name (op);
3756 add_to_value (get_expr_value_id (e), e);
3757 bitmap_insert_into_set (TMP_GEN (block), e);
3758 bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3761 if (gimple_vdef (stmt))
3762 BB_LIVE_VOP_ON_EXIT (block) = gimple_vdef (stmt);
3764 if (gimple_has_side_effects (stmt)
3765 || stmt_could_throw_p (stmt)
3766 || is_gimple_debug (stmt))
3767 continue;
3769 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
3771 if (ssa_undefined_value_p (op))
3772 continue;
3773 pre_expr e = get_or_alloc_expr_for_name (op);
3774 bitmap_value_insert_into_set (EXP_GEN (block), e);
3777 switch (gimple_code (stmt))
3779 case GIMPLE_RETURN:
3780 continue;
3782 case GIMPLE_CALL:
3784 vn_reference_t ref;
3785 vn_reference_s ref1;
3786 pre_expr result = NULL;
3788 /* We can value number only calls to real functions. */
3789 if (gimple_call_internal_p (stmt))
3790 continue;
3792 vn_reference_lookup_call (as_a <gcall *> (stmt), &ref, &ref1);
3793 if (!ref)
3794 continue;
3796 /* If the value of the call is not invalidated in
3797 this block until it is computed, add the expression
3798 to EXP_GEN. */
3799 if (!gimple_vuse (stmt)
3800 || gimple_code
3801 (SSA_NAME_DEF_STMT (gimple_vuse (stmt))) == GIMPLE_PHI
3802 || gimple_bb (SSA_NAME_DEF_STMT
3803 (gimple_vuse (stmt))) != block)
3805 result = pre_expr_pool.allocate ();
3806 result->kind = REFERENCE;
3807 result->id = 0;
3808 PRE_EXPR_REFERENCE (result) = ref;
3810 get_or_alloc_expression_id (result);
3811 add_to_value (get_expr_value_id (result), result);
3812 bitmap_value_insert_into_set (EXP_GEN (block), result);
3814 continue;
3817 case GIMPLE_ASSIGN:
3819 pre_expr result = NULL;
3820 switch (vn_get_stmt_kind (stmt))
3822 case VN_NARY:
3824 enum tree_code code = gimple_assign_rhs_code (stmt);
3825 vn_nary_op_t nary;
3827 /* COND_EXPR and VEC_COND_EXPR are awkward in
3828 that they contain an embedded complex expression.
3829 Don't even try to shove those through PRE. */
3830 if (code == COND_EXPR
3831 || code == VEC_COND_EXPR)
3832 continue;
3834 vn_nary_op_lookup_stmt (stmt, &nary);
3835 if (!nary)
3836 continue;
3838 /* If the NARY traps and there was a preceding
3839 point in the block that might not return avoid
3840 adding the nary to EXP_GEN. */
3841 if (BB_MAY_NOTRETURN (block)
3842 && vn_nary_may_trap (nary))
3843 continue;
3845 result = pre_expr_pool.allocate ();
3846 result->kind = NARY;
3847 result->id = 0;
3848 PRE_EXPR_NARY (result) = nary;
3849 break;
3852 case VN_REFERENCE:
3854 tree rhs1 = gimple_assign_rhs1 (stmt);
3855 alias_set_type set = get_alias_set (rhs1);
3856 vec<vn_reference_op_s> operands
3857 = vn_reference_operands_for_lookup (rhs1);
3858 vn_reference_t ref;
3859 vn_reference_lookup_pieces (gimple_vuse (stmt), set,
3860 TREE_TYPE (rhs1),
3861 operands, &ref, VN_WALK);
3862 if (!ref)
3864 operands.release ();
3865 continue;
3868 /* If the value of the reference is not invalidated in
3869 this block until it is computed, add the expression
3870 to EXP_GEN. */
3871 if (gimple_vuse (stmt))
3873 gimple *def_stmt;
3874 bool ok = true;
3875 def_stmt = SSA_NAME_DEF_STMT (gimple_vuse (stmt));
3876 while (!gimple_nop_p (def_stmt)
3877 && gimple_code (def_stmt) != GIMPLE_PHI
3878 && gimple_bb (def_stmt) == block)
3880 if (stmt_may_clobber_ref_p
3881 (def_stmt, gimple_assign_rhs1 (stmt)))
3883 ok = false;
3884 break;
3886 def_stmt
3887 = SSA_NAME_DEF_STMT (gimple_vuse (def_stmt));
3889 if (!ok)
3891 operands.release ();
3892 continue;
3896 /* If the load was value-numbered to another
3897 load make sure we do not use its expression
3898 for insertion if it wouldn't be a valid
3899 replacement. */
3900 /* At the momemt we have a testcase
3901 for hoist insertion of aligned vs. misaligned
3902 variants in gcc.dg/torture/pr65270-1.c thus
3903 with just alignment to be considered we can
3904 simply replace the expression in the hashtable
3905 with the most conservative one. */
3906 vn_reference_op_t ref1 = &ref->operands.last ();
3907 while (ref1->opcode != TARGET_MEM_REF
3908 && ref1->opcode != MEM_REF
3909 && ref1 != &ref->operands[0])
3910 --ref1;
3911 vn_reference_op_t ref2 = &operands.last ();
3912 while (ref2->opcode != TARGET_MEM_REF
3913 && ref2->opcode != MEM_REF
3914 && ref2 != &operands[0])
3915 --ref2;
3916 if ((ref1->opcode == TARGET_MEM_REF
3917 || ref1->opcode == MEM_REF)
3918 && (TYPE_ALIGN (ref1->type)
3919 > TYPE_ALIGN (ref2->type)))
3920 ref1->type
3921 = build_aligned_type (ref1->type,
3922 TYPE_ALIGN (ref2->type));
3923 /* TBAA behavior is an obvious part so make sure
3924 that the hashtable one covers this as well
3925 by adjusting the ref alias set and its base. */
3926 if (ref->set == set
3927 || alias_set_subset_of (set, ref->set))
3929 else if (alias_set_subset_of (ref->set, set))
3931 ref->set = set;
3932 if (ref1->opcode == MEM_REF)
3933 ref1->op0
3934 = wide_int_to_tree (TREE_TYPE (ref2->op0),
3935 wi::to_wide (ref1->op0));
3936 else
3937 ref1->op2
3938 = wide_int_to_tree (TREE_TYPE (ref2->op2),
3939 wi::to_wide (ref1->op2));
3941 else
3943 ref->set = 0;
3944 if (ref1->opcode == MEM_REF)
3945 ref1->op0
3946 = wide_int_to_tree (ptr_type_node,
3947 wi::to_wide (ref1->op0));
3948 else
3949 ref1->op2
3950 = wide_int_to_tree (ptr_type_node,
3951 wi::to_wide (ref1->op2));
3953 operands.release ();
3955 result = pre_expr_pool.allocate ();
3956 result->kind = REFERENCE;
3957 result->id = 0;
3958 PRE_EXPR_REFERENCE (result) = ref;
3959 break;
3962 default:
3963 continue;
3966 get_or_alloc_expression_id (result);
3967 add_to_value (get_expr_value_id (result), result);
3968 bitmap_value_insert_into_set (EXP_GEN (block), result);
3969 continue;
3971 default:
3972 break;
3976 if (dump_file && (dump_flags & TDF_DETAILS))
3978 print_bitmap_set (dump_file, EXP_GEN (block),
3979 "exp_gen", block->index);
3980 print_bitmap_set (dump_file, PHI_GEN (block),
3981 "phi_gen", block->index);
3982 print_bitmap_set (dump_file, TMP_GEN (block),
3983 "tmp_gen", block->index);
3984 print_bitmap_set (dump_file, AVAIL_OUT (block),
3985 "avail_out", block->index);
3988 /* Put the dominator children of BLOCK on the worklist of blocks
3989 to compute available sets for. */
3990 for (son = first_dom_son (CDI_DOMINATORS, block);
3991 son;
3992 son = next_dom_son (CDI_DOMINATORS, son))
3993 worklist[sp++] = son;
3996 free (worklist);
4000 /* Initialize data structures used by PRE. */
4002 static void
4003 init_pre (void)
4005 basic_block bb;
4007 next_expression_id = 1;
4008 expressions.create (0);
4009 expressions.safe_push (NULL);
4010 value_expressions.create (get_max_value_id () + 1);
4011 value_expressions.safe_grow_cleared (get_max_value_id () + 1);
4012 name_to_id.create (0);
4014 inserted_exprs = BITMAP_ALLOC (NULL);
4016 connect_infinite_loops_to_exit ();
4017 memset (&pre_stats, 0, sizeof (pre_stats));
4019 alloc_aux_for_blocks (sizeof (struct bb_bitmap_sets));
4021 calculate_dominance_info (CDI_DOMINATORS);
4023 bitmap_obstack_initialize (&grand_bitmap_obstack);
4024 phi_translate_table = new hash_table<expr_pred_trans_d> (5110);
4025 expression_to_id = new hash_table<pre_expr_d> (num_ssa_names * 3);
4026 FOR_ALL_BB_FN (bb, cfun)
4028 EXP_GEN (bb) = bitmap_set_new ();
4029 PHI_GEN (bb) = bitmap_set_new ();
4030 TMP_GEN (bb) = bitmap_set_new ();
4031 AVAIL_OUT (bb) = bitmap_set_new ();
4036 /* Deallocate data structures used by PRE. */
4038 static void
4039 fini_pre ()
4041 value_expressions.release ();
4042 expressions.release ();
4043 BITMAP_FREE (inserted_exprs);
4044 bitmap_obstack_release (&grand_bitmap_obstack);
4045 bitmap_set_pool.release ();
4046 pre_expr_pool.release ();
4047 delete phi_translate_table;
4048 phi_translate_table = NULL;
4049 delete expression_to_id;
4050 expression_to_id = NULL;
4051 name_to_id.release ();
4053 free_aux_for_blocks ();
4056 namespace {
4058 const pass_data pass_data_pre =
4060 GIMPLE_PASS, /* type */
4061 "pre", /* name */
4062 OPTGROUP_NONE, /* optinfo_flags */
4063 TV_TREE_PRE, /* tv_id */
4064 ( PROP_cfg | PROP_ssa ), /* properties_required */
4065 0, /* properties_provided */
4066 0, /* properties_destroyed */
4067 TODO_rebuild_alias, /* todo_flags_start */
4068 0, /* todo_flags_finish */
4071 class pass_pre : public gimple_opt_pass
4073 public:
4074 pass_pre (gcc::context *ctxt)
4075 : gimple_opt_pass (pass_data_pre, ctxt)
4078 /* opt_pass methods: */
4079 virtual bool gate (function *)
4080 { return flag_tree_pre != 0 || flag_code_hoisting != 0; }
4081 virtual unsigned int execute (function *);
4083 }; // class pass_pre
4085 unsigned int
4086 pass_pre::execute (function *fun)
4088 unsigned int todo = 0;
4090 do_partial_partial =
4091 flag_tree_partial_pre && optimize_function_for_speed_p (fun);
4093 /* This has to happen before SCCVN runs because
4094 loop_optimizer_init may create new phis, etc. */
4095 loop_optimizer_init (LOOPS_NORMAL);
4096 split_critical_edges ();
4097 scev_initialize ();
4099 run_scc_vn (VN_WALK);
4101 init_pre ();
4103 /* Insert can get quite slow on an incredibly large number of basic
4104 blocks due to some quadratic behavior. Until this behavior is
4105 fixed, don't run it when he have an incredibly large number of
4106 bb's. If we aren't going to run insert, there is no point in
4107 computing ANTIC, either, even though it's plenty fast nor do
4108 we require AVAIL. */
4109 if (n_basic_blocks_for_fn (fun) < 4000)
4111 compute_avail ();
4112 compute_antic ();
4113 insert ();
4116 /* Make sure to remove fake edges before committing our inserts.
4117 This makes sure we don't end up with extra critical edges that
4118 we would need to split. */
4119 remove_fake_exit_edges ();
4120 gsi_commit_edge_inserts ();
4122 /* Eliminate folds statements which might (should not...) end up
4123 not keeping virtual operands up-to-date. */
4124 gcc_assert (!need_ssa_update_p (fun));
4126 statistics_counter_event (fun, "Insertions", pre_stats.insertions);
4127 statistics_counter_event (fun, "PA inserted", pre_stats.pa_insert);
4128 statistics_counter_event (fun, "HOIST inserted", pre_stats.hoist_insert);
4129 statistics_counter_event (fun, "New PHIs", pre_stats.phis);
4131 /* Remove all the redundant expressions. */
4132 todo |= vn_eliminate (inserted_exprs);
4134 /* Because we don't follow exactly the standard PRE algorithm, and decide not
4135 to insert PHI nodes sometimes, and because value numbering of casts isn't
4136 perfect, we sometimes end up inserting dead code. This simple DCE-like
4137 pass removes any insertions we made that weren't actually used. */
4138 simple_dce_from_worklist (inserted_exprs);
4140 fini_pre ();
4142 scev_finalize ();
4143 loop_optimizer_finalize ();
4145 /* Restore SSA info before tail-merging as that resets it as well. */
4146 scc_vn_restore_ssa_info ();
4148 /* TODO: tail_merge_optimize may merge all predecessors of a block, in which
4149 case we can merge the block with the remaining predecessor of the block.
4150 It should either:
4151 - call merge_blocks after each tail merge iteration
4152 - call merge_blocks after all tail merge iterations
4153 - mark TODO_cleanup_cfg when necessary
4154 - share the cfg cleanup with fini_pre. */
4155 todo |= tail_merge_optimize (todo);
4157 free_scc_vn ();
4159 /* Tail merging invalidates the virtual SSA web, together with
4160 cfg-cleanup opportunities exposed by PRE this will wreck the
4161 SSA updating machinery. So make sure to run update-ssa
4162 manually, before eventually scheduling cfg-cleanup as part of
4163 the todo. */
4164 update_ssa (TODO_update_ssa_only_virtuals);
4166 return todo;
4169 } // anon namespace
4171 gimple_opt_pass *
4172 make_pass_pre (gcc::context *ctxt)
4174 return new pass_pre (ctxt);