2018-02-19 Sebastian Perta <sebastian.perta@renesas.com>
[official-gcc.git] / gcc / tree-ssa-pre.c
blob55295e171e9e48d3538205b066f7c0e9309ac77e
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 (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (folded))
2701 return NULL_TREE;
2702 if (useless_type_conversion_p (exprtype, TREE_TYPE (folded)))
2703 return folded;
2704 break;
2705 case CONSTANT:
2707 folded = PRE_EXPR_CONSTANT (expr);
2708 tree tem = fold_convert (exprtype, folded);
2709 if (is_gimple_min_invariant (tem))
2710 return tem;
2711 break;
2713 case REFERENCE:
2714 if (PRE_EXPR_REFERENCE (expr)->operands[0].opcode == CALL_EXPR)
2716 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
2717 unsigned int operand = 1;
2718 vn_reference_op_t currop = &ref->operands[0];
2719 tree sc = NULL_TREE;
2720 tree fn;
2721 if (TREE_CODE (currop->op0) == FUNCTION_DECL)
2722 fn = currop->op0;
2723 else
2724 fn = find_or_generate_expression (block, currop->op0, stmts);
2725 if (!fn)
2726 return NULL_TREE;
2727 if (currop->op1)
2729 sc = find_or_generate_expression (block, currop->op1, stmts);
2730 if (!sc)
2731 return NULL_TREE;
2733 auto_vec<tree> args (ref->operands.length () - 1);
2734 while (operand < ref->operands.length ())
2736 tree arg = create_component_ref_by_pieces_1 (block, ref,
2737 &operand, stmts);
2738 if (!arg)
2739 return NULL_TREE;
2740 args.quick_push (arg);
2742 gcall *call
2743 = gimple_build_call_vec ((TREE_CODE (fn) == FUNCTION_DECL
2744 ? build_fold_addr_expr (fn) : fn), args);
2745 gimple_call_set_with_bounds (call, currop->with_bounds);
2746 if (sc)
2747 gimple_call_set_chain (call, sc);
2748 tree forcedname = make_ssa_name (currop->type);
2749 gimple_call_set_lhs (call, forcedname);
2750 gimple_set_vuse (call, BB_LIVE_VOP_ON_EXIT (block));
2751 gimple_seq_add_stmt_without_update (&forced_stmts, call);
2752 folded = forcedname;
2754 else
2756 folded = create_component_ref_by_pieces (block,
2757 PRE_EXPR_REFERENCE (expr),
2758 stmts);
2759 if (!folded)
2760 return NULL_TREE;
2761 name = make_temp_ssa_name (exprtype, NULL, "pretmp");
2762 newstmt = gimple_build_assign (name, folded);
2763 gimple_seq_add_stmt_without_update (&forced_stmts, newstmt);
2764 gimple_set_vuse (newstmt, BB_LIVE_VOP_ON_EXIT (block));
2765 folded = name;
2767 break;
2768 case NARY:
2770 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
2771 tree *genop = XALLOCAVEC (tree, nary->length);
2772 unsigned i;
2773 for (i = 0; i < nary->length; ++i)
2775 genop[i] = find_or_generate_expression (block, nary->op[i], stmts);
2776 if (!genop[i])
2777 return NULL_TREE;
2778 /* Ensure genop[] is properly typed for POINTER_PLUS_EXPR. It
2779 may have conversions stripped. */
2780 if (nary->opcode == POINTER_PLUS_EXPR)
2782 if (i == 0)
2783 genop[i] = gimple_convert (&forced_stmts,
2784 nary->type, genop[i]);
2785 else if (i == 1)
2786 genop[i] = gimple_convert (&forced_stmts,
2787 sizetype, genop[i]);
2789 else
2790 genop[i] = gimple_convert (&forced_stmts,
2791 TREE_TYPE (nary->op[i]), genop[i]);
2793 if (nary->opcode == CONSTRUCTOR)
2795 vec<constructor_elt, va_gc> *elts = NULL;
2796 for (i = 0; i < nary->length; ++i)
2797 CONSTRUCTOR_APPEND_ELT (elts, NULL_TREE, genop[i]);
2798 folded = build_constructor (nary->type, elts);
2799 name = make_temp_ssa_name (exprtype, NULL, "pretmp");
2800 newstmt = gimple_build_assign (name, folded);
2801 gimple_seq_add_stmt_without_update (&forced_stmts, newstmt);
2802 folded = name;
2804 else
2806 switch (nary->length)
2808 case 1:
2809 folded = gimple_build (&forced_stmts, nary->opcode, nary->type,
2810 genop[0]);
2811 break;
2812 case 2:
2813 folded = gimple_build (&forced_stmts, nary->opcode, nary->type,
2814 genop[0], genop[1]);
2815 break;
2816 case 3:
2817 folded = gimple_build (&forced_stmts, nary->opcode, nary->type,
2818 genop[0], genop[1], genop[2]);
2819 break;
2820 default:
2821 gcc_unreachable ();
2825 break;
2826 default:
2827 gcc_unreachable ();
2830 folded = gimple_convert (&forced_stmts, exprtype, folded);
2832 /* If there is nothing to insert, return the simplified result. */
2833 if (gimple_seq_empty_p (forced_stmts))
2834 return folded;
2835 /* If we simplified to a constant return it and discard eventually
2836 built stmts. */
2837 if (is_gimple_min_invariant (folded))
2839 gimple_seq_discard (forced_stmts);
2840 return folded;
2842 /* Likewise if we simplified to sth not queued for insertion. */
2843 bool found = false;
2844 gsi = gsi_last (forced_stmts);
2845 for (; !gsi_end_p (gsi); gsi_prev (&gsi))
2847 gimple *stmt = gsi_stmt (gsi);
2848 tree forcedname = gimple_get_lhs (stmt);
2849 if (forcedname == folded)
2851 found = true;
2852 break;
2855 if (! found)
2857 gimple_seq_discard (forced_stmts);
2858 return folded;
2860 gcc_assert (TREE_CODE (folded) == SSA_NAME);
2862 /* If we have any intermediate expressions to the value sets, add them
2863 to the value sets and chain them in the instruction stream. */
2864 if (forced_stmts)
2866 gsi = gsi_start (forced_stmts);
2867 for (; !gsi_end_p (gsi); gsi_next (&gsi))
2869 gimple *stmt = gsi_stmt (gsi);
2870 tree forcedname = gimple_get_lhs (stmt);
2871 pre_expr nameexpr;
2873 if (forcedname != folded)
2875 VN_INFO_GET (forcedname)->valnum = forcedname;
2876 VN_INFO (forcedname)->value_id = get_next_value_id ();
2877 nameexpr = get_or_alloc_expr_for_name (forcedname);
2878 add_to_value (VN_INFO (forcedname)->value_id, nameexpr);
2879 bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
2880 bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
2883 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (forcedname));
2885 gimple_seq_add_seq (stmts, forced_stmts);
2888 name = folded;
2890 /* Fold the last statement. */
2891 gsi = gsi_last (*stmts);
2892 if (fold_stmt_inplace (&gsi))
2893 update_stmt (gsi_stmt (gsi));
2895 /* Add a value number to the temporary.
2896 The value may already exist in either NEW_SETS, or AVAIL_OUT, because
2897 we are creating the expression by pieces, and this particular piece of
2898 the expression may have been represented. There is no harm in replacing
2899 here. */
2900 value_id = get_expr_value_id (expr);
2901 VN_INFO_GET (name)->value_id = value_id;
2902 VN_INFO (name)->valnum = sccvn_valnum_from_value_id (value_id);
2903 if (VN_INFO (name)->valnum == NULL_TREE)
2904 VN_INFO (name)->valnum = name;
2905 gcc_assert (VN_INFO (name)->valnum != NULL_TREE);
2906 nameexpr = get_or_alloc_expr_for_name (name);
2907 add_to_value (value_id, nameexpr);
2908 if (NEW_SETS (block))
2909 bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
2910 bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
2912 pre_stats.insertions++;
2913 if (dump_file && (dump_flags & TDF_DETAILS))
2915 fprintf (dump_file, "Inserted ");
2916 print_gimple_stmt (dump_file, gsi_stmt (gsi_last (*stmts)), 0);
2917 fprintf (dump_file, " in predecessor %d (%04d)\n",
2918 block->index, value_id);
2921 return name;
2925 /* Insert the to-be-made-available values of expression EXPRNUM for each
2926 predecessor, stored in AVAIL, into the predecessors of BLOCK, and
2927 merge the result with a phi node, given the same value number as
2928 NODE. Return true if we have inserted new stuff. */
2930 static bool
2931 insert_into_preds_of_block (basic_block block, unsigned int exprnum,
2932 vec<pre_expr> avail)
2934 pre_expr expr = expression_for_id (exprnum);
2935 pre_expr newphi;
2936 unsigned int val = get_expr_value_id (expr);
2937 edge pred;
2938 bool insertions = false;
2939 bool nophi = false;
2940 basic_block bprime;
2941 pre_expr eprime;
2942 edge_iterator ei;
2943 tree type = get_expr_type (expr);
2944 tree temp;
2945 gphi *phi;
2947 /* Make sure we aren't creating an induction variable. */
2948 if (bb_loop_depth (block) > 0 && EDGE_COUNT (block->preds) == 2)
2950 bool firstinsideloop = false;
2951 bool secondinsideloop = false;
2952 firstinsideloop = flow_bb_inside_loop_p (block->loop_father,
2953 EDGE_PRED (block, 0)->src);
2954 secondinsideloop = flow_bb_inside_loop_p (block->loop_father,
2955 EDGE_PRED (block, 1)->src);
2956 /* Induction variables only have one edge inside the loop. */
2957 if ((firstinsideloop ^ secondinsideloop)
2958 && expr->kind != REFERENCE)
2960 if (dump_file && (dump_flags & TDF_DETAILS))
2961 fprintf (dump_file, "Skipping insertion of phi for partial redundancy: Looks like an induction variable\n");
2962 nophi = true;
2966 /* Make the necessary insertions. */
2967 FOR_EACH_EDGE (pred, ei, block->preds)
2969 gimple_seq stmts = NULL;
2970 tree builtexpr;
2971 bprime = pred->src;
2972 eprime = avail[pred->dest_idx];
2973 builtexpr = create_expression_by_pieces (bprime, eprime,
2974 &stmts, type);
2975 gcc_assert (!(pred->flags & EDGE_ABNORMAL));
2976 if (!gimple_seq_empty_p (stmts))
2978 basic_block new_bb = gsi_insert_seq_on_edge_immediate (pred, stmts);
2979 gcc_assert (! new_bb);
2980 insertions = true;
2982 if (!builtexpr)
2984 /* We cannot insert a PHI node if we failed to insert
2985 on one edge. */
2986 nophi = true;
2987 continue;
2989 if (is_gimple_min_invariant (builtexpr))
2990 avail[pred->dest_idx] = get_or_alloc_expr_for_constant (builtexpr);
2991 else
2992 avail[pred->dest_idx] = get_or_alloc_expr_for_name (builtexpr);
2994 /* If we didn't want a phi node, and we made insertions, we still have
2995 inserted new stuff, and thus return true. If we didn't want a phi node,
2996 and didn't make insertions, we haven't added anything new, so return
2997 false. */
2998 if (nophi && insertions)
2999 return true;
3000 else if (nophi && !insertions)
3001 return false;
3003 /* Now build a phi for the new variable. */
3004 temp = make_temp_ssa_name (type, NULL, "prephitmp");
3005 phi = create_phi_node (temp, block);
3007 VN_INFO_GET (temp)->value_id = val;
3008 VN_INFO (temp)->valnum = sccvn_valnum_from_value_id (val);
3009 if (VN_INFO (temp)->valnum == NULL_TREE)
3010 VN_INFO (temp)->valnum = temp;
3011 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (temp));
3012 FOR_EACH_EDGE (pred, ei, block->preds)
3014 pre_expr ae = avail[pred->dest_idx];
3015 gcc_assert (get_expr_type (ae) == type
3016 || useless_type_conversion_p (type, get_expr_type (ae)));
3017 if (ae->kind == CONSTANT)
3018 add_phi_arg (phi, unshare_expr (PRE_EXPR_CONSTANT (ae)),
3019 pred, UNKNOWN_LOCATION);
3020 else
3021 add_phi_arg (phi, PRE_EXPR_NAME (ae), pred, UNKNOWN_LOCATION);
3024 newphi = get_or_alloc_expr_for_name (temp);
3025 add_to_value (val, newphi);
3027 /* The value should *not* exist in PHI_GEN, or else we wouldn't be doing
3028 this insertion, since we test for the existence of this value in PHI_GEN
3029 before proceeding with the partial redundancy checks in insert_aux.
3031 The value may exist in AVAIL_OUT, in particular, it could be represented
3032 by the expression we are trying to eliminate, in which case we want the
3033 replacement to occur. If it's not existing in AVAIL_OUT, we want it
3034 inserted there.
3036 Similarly, to the PHI_GEN case, the value should not exist in NEW_SETS of
3037 this block, because if it did, it would have existed in our dominator's
3038 AVAIL_OUT, and would have been skipped due to the full redundancy check.
3041 bitmap_insert_into_set (PHI_GEN (block), newphi);
3042 bitmap_value_replace_in_set (AVAIL_OUT (block),
3043 newphi);
3044 bitmap_insert_into_set (NEW_SETS (block),
3045 newphi);
3047 /* If we insert a PHI node for a conversion of another PHI node
3048 in the same basic-block try to preserve range information.
3049 This is important so that followup loop passes receive optimal
3050 number of iteration analysis results. See PR61743. */
3051 if (expr->kind == NARY
3052 && CONVERT_EXPR_CODE_P (expr->u.nary->opcode)
3053 && TREE_CODE (expr->u.nary->op[0]) == SSA_NAME
3054 && gimple_bb (SSA_NAME_DEF_STMT (expr->u.nary->op[0])) == block
3055 && INTEGRAL_TYPE_P (type)
3056 && INTEGRAL_TYPE_P (TREE_TYPE (expr->u.nary->op[0]))
3057 && (TYPE_PRECISION (type)
3058 >= TYPE_PRECISION (TREE_TYPE (expr->u.nary->op[0])))
3059 && SSA_NAME_RANGE_INFO (expr->u.nary->op[0]))
3061 wide_int min, max;
3062 if (get_range_info (expr->u.nary->op[0], &min, &max) == VR_RANGE
3063 && !wi::neg_p (min, SIGNED)
3064 && !wi::neg_p (max, SIGNED))
3065 /* Just handle extension and sign-changes of all-positive ranges. */
3066 set_range_info (temp,
3067 SSA_NAME_RANGE_TYPE (expr->u.nary->op[0]),
3068 wide_int_storage::from (min, TYPE_PRECISION (type),
3069 TYPE_SIGN (type)),
3070 wide_int_storage::from (max, TYPE_PRECISION (type),
3071 TYPE_SIGN (type)));
3074 if (dump_file && (dump_flags & TDF_DETAILS))
3076 fprintf (dump_file, "Created phi ");
3077 print_gimple_stmt (dump_file, phi, 0);
3078 fprintf (dump_file, " in block %d (%04d)\n", block->index, val);
3080 pre_stats.phis++;
3081 return true;
3086 /* Perform insertion of partially redundant or hoistable values.
3087 For BLOCK, do the following:
3088 1. Propagate the NEW_SETS of the dominator into the current block.
3089 If the block has multiple predecessors,
3090 2a. Iterate over the ANTIC expressions for the block to see if
3091 any of them are partially redundant.
3092 2b. If so, insert them into the necessary predecessors to make
3093 the expression fully redundant.
3094 2c. Insert a new PHI merging the values of the predecessors.
3095 2d. Insert the new PHI, and the new expressions, into the
3096 NEW_SETS set.
3097 If the block has multiple successors,
3098 3a. Iterate over the ANTIC values for the block to see if
3099 any of them are good candidates for hoisting.
3100 3b. If so, insert expressions computing the values in BLOCK,
3101 and add the new expressions into the NEW_SETS set.
3102 4. Recursively call ourselves on the dominator children of BLOCK.
3104 Steps 1, 2a, and 4 are done by insert_aux. 2b, 2c and 2d are done by
3105 do_pre_regular_insertion and do_partial_insertion. 3a and 3b are
3106 done in do_hoist_insertion.
3109 static bool
3110 do_pre_regular_insertion (basic_block block, basic_block dom)
3112 bool new_stuff = false;
3113 vec<pre_expr> exprs;
3114 pre_expr expr;
3115 auto_vec<pre_expr> avail;
3116 int i;
3118 exprs = sorted_array_from_bitmap_set (ANTIC_IN (block));
3119 avail.safe_grow (EDGE_COUNT (block->preds));
3121 FOR_EACH_VEC_ELT (exprs, i, expr)
3123 if (expr->kind == NARY
3124 || expr->kind == REFERENCE)
3126 unsigned int val;
3127 bool by_some = false;
3128 bool cant_insert = false;
3129 bool all_same = true;
3130 pre_expr first_s = NULL;
3131 edge pred;
3132 basic_block bprime;
3133 pre_expr eprime = NULL;
3134 edge_iterator ei;
3135 pre_expr edoubleprime = NULL;
3136 bool do_insertion = false;
3138 val = get_expr_value_id (expr);
3139 if (bitmap_set_contains_value (PHI_GEN (block), val))
3140 continue;
3141 if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3143 if (dump_file && (dump_flags & TDF_DETAILS))
3145 fprintf (dump_file, "Found fully redundant value: ");
3146 print_pre_expr (dump_file, expr);
3147 fprintf (dump_file, "\n");
3149 continue;
3152 FOR_EACH_EDGE (pred, ei, block->preds)
3154 unsigned int vprime;
3156 /* We should never run insertion for the exit block
3157 and so not come across fake pred edges. */
3158 gcc_assert (!(pred->flags & EDGE_FAKE));
3159 bprime = pred->src;
3160 /* We are looking at ANTIC_OUT of bprime. */
3161 eprime = phi_translate (expr, ANTIC_IN (block), NULL,
3162 bprime, block);
3164 /* eprime will generally only be NULL if the
3165 value of the expression, translated
3166 through the PHI for this predecessor, is
3167 undefined. If that is the case, we can't
3168 make the expression fully redundant,
3169 because its value is undefined along a
3170 predecessor path. We can thus break out
3171 early because it doesn't matter what the
3172 rest of the results are. */
3173 if (eprime == NULL)
3175 avail[pred->dest_idx] = NULL;
3176 cant_insert = true;
3177 break;
3180 vprime = get_expr_value_id (eprime);
3181 edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime),
3182 vprime);
3183 if (edoubleprime == NULL)
3185 avail[pred->dest_idx] = eprime;
3186 all_same = false;
3188 else
3190 avail[pred->dest_idx] = edoubleprime;
3191 by_some = true;
3192 /* We want to perform insertions to remove a redundancy on
3193 a path in the CFG we want to optimize for speed. */
3194 if (optimize_edge_for_speed_p (pred))
3195 do_insertion = true;
3196 if (first_s == NULL)
3197 first_s = edoubleprime;
3198 else if (!pre_expr_d::equal (first_s, edoubleprime))
3199 all_same = false;
3202 /* If we can insert it, it's not the same value
3203 already existing along every predecessor, and
3204 it's defined by some predecessor, it is
3205 partially redundant. */
3206 if (!cant_insert && !all_same && by_some)
3208 if (!do_insertion)
3210 if (dump_file && (dump_flags & TDF_DETAILS))
3212 fprintf (dump_file, "Skipping partial redundancy for "
3213 "expression ");
3214 print_pre_expr (dump_file, expr);
3215 fprintf (dump_file, " (%04d), no redundancy on to be "
3216 "optimized for speed edge\n", val);
3219 else if (dbg_cnt (treepre_insert))
3221 if (dump_file && (dump_flags & TDF_DETAILS))
3223 fprintf (dump_file, "Found partial redundancy for "
3224 "expression ");
3225 print_pre_expr (dump_file, expr);
3226 fprintf (dump_file, " (%04d)\n",
3227 get_expr_value_id (expr));
3229 if (insert_into_preds_of_block (block,
3230 get_expression_id (expr),
3231 avail))
3232 new_stuff = true;
3235 /* If all edges produce the same value and that value is
3236 an invariant, then the PHI has the same value on all
3237 edges. Note this. */
3238 else if (!cant_insert && all_same)
3240 gcc_assert (edoubleprime->kind == CONSTANT
3241 || edoubleprime->kind == NAME);
3243 tree temp = make_temp_ssa_name (get_expr_type (expr),
3244 NULL, "pretmp");
3245 gassign *assign
3246 = gimple_build_assign (temp,
3247 edoubleprime->kind == CONSTANT ?
3248 PRE_EXPR_CONSTANT (edoubleprime) :
3249 PRE_EXPR_NAME (edoubleprime));
3250 gimple_stmt_iterator gsi = gsi_after_labels (block);
3251 gsi_insert_before (&gsi, assign, GSI_NEW_STMT);
3253 VN_INFO_GET (temp)->value_id = val;
3254 VN_INFO (temp)->valnum = sccvn_valnum_from_value_id (val);
3255 if (VN_INFO (temp)->valnum == NULL_TREE)
3256 VN_INFO (temp)->valnum = temp;
3257 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (temp));
3258 pre_expr newe = get_or_alloc_expr_for_name (temp);
3259 add_to_value (val, newe);
3260 bitmap_value_replace_in_set (AVAIL_OUT (block), newe);
3261 bitmap_insert_into_set (NEW_SETS (block), newe);
3266 exprs.release ();
3267 return new_stuff;
3271 /* Perform insertion for partially anticipatable expressions. There
3272 is only one case we will perform insertion for these. This case is
3273 if the expression is partially anticipatable, and fully available.
3274 In this case, we know that putting it earlier will enable us to
3275 remove the later computation. */
3277 static bool
3278 do_pre_partial_partial_insertion (basic_block block, basic_block dom)
3280 bool new_stuff = false;
3281 vec<pre_expr> exprs;
3282 pre_expr expr;
3283 auto_vec<pre_expr> avail;
3284 int i;
3286 exprs = sorted_array_from_bitmap_set (PA_IN (block));
3287 avail.safe_grow (EDGE_COUNT (block->preds));
3289 FOR_EACH_VEC_ELT (exprs, i, expr)
3291 if (expr->kind == NARY
3292 || expr->kind == REFERENCE)
3294 unsigned int val;
3295 bool by_all = true;
3296 bool cant_insert = false;
3297 edge pred;
3298 basic_block bprime;
3299 pre_expr eprime = NULL;
3300 edge_iterator ei;
3302 val = get_expr_value_id (expr);
3303 if (bitmap_set_contains_value (PHI_GEN (block), val))
3304 continue;
3305 if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3306 continue;
3308 FOR_EACH_EDGE (pred, ei, block->preds)
3310 unsigned int vprime;
3311 pre_expr edoubleprime;
3313 /* We should never run insertion for the exit block
3314 and so not come across fake pred edges. */
3315 gcc_assert (!(pred->flags & EDGE_FAKE));
3316 bprime = pred->src;
3317 eprime = phi_translate (expr, ANTIC_IN (block),
3318 PA_IN (block),
3319 bprime, block);
3321 /* eprime will generally only be NULL if the
3322 value of the expression, translated
3323 through the PHI for this predecessor, is
3324 undefined. If that is the case, we can't
3325 make the expression fully redundant,
3326 because its value is undefined along a
3327 predecessor path. We can thus break out
3328 early because it doesn't matter what the
3329 rest of the results are. */
3330 if (eprime == NULL)
3332 avail[pred->dest_idx] = NULL;
3333 cant_insert = true;
3334 break;
3337 vprime = get_expr_value_id (eprime);
3338 edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime), vprime);
3339 avail[pred->dest_idx] = edoubleprime;
3340 if (edoubleprime == NULL)
3342 by_all = false;
3343 break;
3347 /* If we can insert it, it's not the same value
3348 already existing along every predecessor, and
3349 it's defined by some predecessor, it is
3350 partially redundant. */
3351 if (!cant_insert && by_all)
3353 edge succ;
3354 bool do_insertion = false;
3356 /* Insert only if we can remove a later expression on a path
3357 that we want to optimize for speed.
3358 The phi node that we will be inserting in BLOCK is not free,
3359 and inserting it for the sake of !optimize_for_speed successor
3360 may cause regressions on the speed path. */
3361 FOR_EACH_EDGE (succ, ei, block->succs)
3363 if (bitmap_set_contains_value (PA_IN (succ->dest), val)
3364 || bitmap_set_contains_value (ANTIC_IN (succ->dest), val))
3366 if (optimize_edge_for_speed_p (succ))
3367 do_insertion = true;
3371 if (!do_insertion)
3373 if (dump_file && (dump_flags & TDF_DETAILS))
3375 fprintf (dump_file, "Skipping partial partial redundancy "
3376 "for expression ");
3377 print_pre_expr (dump_file, expr);
3378 fprintf (dump_file, " (%04d), not (partially) anticipated "
3379 "on any to be optimized for speed edges\n", val);
3382 else if (dbg_cnt (treepre_insert))
3384 pre_stats.pa_insert++;
3385 if (dump_file && (dump_flags & TDF_DETAILS))
3387 fprintf (dump_file, "Found partial partial redundancy "
3388 "for expression ");
3389 print_pre_expr (dump_file, expr);
3390 fprintf (dump_file, " (%04d)\n",
3391 get_expr_value_id (expr));
3393 if (insert_into_preds_of_block (block,
3394 get_expression_id (expr),
3395 avail))
3396 new_stuff = true;
3402 exprs.release ();
3403 return new_stuff;
3406 /* Insert expressions in BLOCK to compute hoistable values up.
3407 Return TRUE if something was inserted, otherwise return FALSE.
3408 The caller has to make sure that BLOCK has at least two successors. */
3410 static bool
3411 do_hoist_insertion (basic_block block)
3413 edge e;
3414 edge_iterator ei;
3415 bool new_stuff = false;
3416 unsigned i;
3417 gimple_stmt_iterator last;
3419 /* At least two successors, or else... */
3420 gcc_assert (EDGE_COUNT (block->succs) >= 2);
3422 /* Check that all successors of BLOCK are dominated by block.
3423 We could use dominated_by_p() for this, but actually there is a much
3424 quicker check: any successor that is dominated by BLOCK can't have
3425 more than one predecessor edge. */
3426 FOR_EACH_EDGE (e, ei, block->succs)
3427 if (! single_pred_p (e->dest))
3428 return false;
3430 /* Determine the insertion point. If we cannot safely insert before
3431 the last stmt if we'd have to, bail out. */
3432 last = gsi_last_bb (block);
3433 if (!gsi_end_p (last)
3434 && !is_ctrl_stmt (gsi_stmt (last))
3435 && stmt_ends_bb_p (gsi_stmt (last)))
3436 return false;
3438 /* Compute the set of hoistable expressions from ANTIC_IN. First compute
3439 hoistable values. */
3440 bitmap_set hoistable_set;
3442 /* A hoistable value must be in ANTIC_IN(block)
3443 but not in AVAIL_OUT(BLOCK). */
3444 bitmap_initialize (&hoistable_set.values, &grand_bitmap_obstack);
3445 bitmap_and_compl (&hoistable_set.values,
3446 &ANTIC_IN (block)->values, &AVAIL_OUT (block)->values);
3448 /* Short-cut for a common case: hoistable_set is empty. */
3449 if (bitmap_empty_p (&hoistable_set.values))
3450 return false;
3452 /* Compute which of the hoistable values is in AVAIL_OUT of
3453 at least one of the successors of BLOCK. */
3454 bitmap_head availout_in_some;
3455 bitmap_initialize (&availout_in_some, &grand_bitmap_obstack);
3456 FOR_EACH_EDGE (e, ei, block->succs)
3457 /* Do not consider expressions solely because their availability
3458 on loop exits. They'd be ANTIC-IN throughout the whole loop
3459 and thus effectively hoisted across loops by combination of
3460 PRE and hoisting. */
3461 if (! loop_exit_edge_p (block->loop_father, e))
3462 bitmap_ior_and_into (&availout_in_some, &hoistable_set.values,
3463 &AVAIL_OUT (e->dest)->values);
3464 bitmap_clear (&hoistable_set.values);
3466 /* Short-cut for a common case: availout_in_some is empty. */
3467 if (bitmap_empty_p (&availout_in_some))
3468 return false;
3470 /* Hack hoitable_set in-place so we can use sorted_array_from_bitmap_set. */
3471 hoistable_set.values = availout_in_some;
3472 hoistable_set.expressions = ANTIC_IN (block)->expressions;
3474 /* Now finally construct the topological-ordered expression set. */
3475 vec<pre_expr> exprs = sorted_array_from_bitmap_set (&hoistable_set);
3477 bitmap_clear (&hoistable_set.values);
3479 /* If there are candidate values for hoisting, insert expressions
3480 strategically to make the hoistable expressions fully redundant. */
3481 pre_expr expr;
3482 FOR_EACH_VEC_ELT (exprs, i, expr)
3484 /* While we try to sort expressions topologically above the
3485 sorting doesn't work out perfectly. Catch expressions we
3486 already inserted. */
3487 unsigned int value_id = get_expr_value_id (expr);
3488 if (bitmap_set_contains_value (AVAIL_OUT (block), value_id))
3490 if (dump_file && (dump_flags & TDF_DETAILS))
3492 fprintf (dump_file,
3493 "Already inserted expression for ");
3494 print_pre_expr (dump_file, expr);
3495 fprintf (dump_file, " (%04d)\n", value_id);
3497 continue;
3500 /* OK, we should hoist this value. Perform the transformation. */
3501 pre_stats.hoist_insert++;
3502 if (dump_file && (dump_flags & TDF_DETAILS))
3504 fprintf (dump_file,
3505 "Inserting expression in block %d for code hoisting: ",
3506 block->index);
3507 print_pre_expr (dump_file, expr);
3508 fprintf (dump_file, " (%04d)\n", value_id);
3511 gimple_seq stmts = NULL;
3512 tree res = create_expression_by_pieces (block, expr, &stmts,
3513 get_expr_type (expr));
3515 /* Do not return true if expression creation ultimately
3516 did not insert any statements. */
3517 if (gimple_seq_empty_p (stmts))
3518 res = NULL_TREE;
3519 else
3521 if (gsi_end_p (last) || is_ctrl_stmt (gsi_stmt (last)))
3522 gsi_insert_seq_before (&last, stmts, GSI_SAME_STMT);
3523 else
3524 gsi_insert_seq_after (&last, stmts, GSI_NEW_STMT);
3527 /* Make sure to not return true if expression creation ultimately
3528 failed but also make sure to insert any stmts produced as they
3529 are tracked in inserted_exprs. */
3530 if (! res)
3531 continue;
3533 new_stuff = true;
3536 exprs.release ();
3538 return new_stuff;
3541 /* Do a dominator walk on the control flow graph, and insert computations
3542 of values as necessary for PRE and hoisting. */
3544 static bool
3545 insert_aux (basic_block block, bool do_pre, bool do_hoist)
3547 basic_block son;
3548 bool new_stuff = false;
3550 if (block)
3552 basic_block dom;
3553 dom = get_immediate_dominator (CDI_DOMINATORS, block);
3554 if (dom)
3556 unsigned i;
3557 bitmap_iterator bi;
3558 bitmap_set_t newset;
3560 /* First, update the AVAIL_OUT set with anything we may have
3561 inserted higher up in the dominator tree. */
3562 newset = NEW_SETS (dom);
3563 if (newset)
3565 /* Note that we need to value_replace both NEW_SETS, and
3566 AVAIL_OUT. For both the case of NEW_SETS, the value may be
3567 represented by some non-simple expression here that we want
3568 to replace it with. */
3569 FOR_EACH_EXPR_ID_IN_SET (newset, i, bi)
3571 pre_expr expr = expression_for_id (i);
3572 bitmap_value_replace_in_set (NEW_SETS (block), expr);
3573 bitmap_value_replace_in_set (AVAIL_OUT (block), expr);
3577 /* Insert expressions for partial redundancies. */
3578 if (do_pre && !single_pred_p (block))
3580 new_stuff |= do_pre_regular_insertion (block, dom);
3581 if (do_partial_partial)
3582 new_stuff |= do_pre_partial_partial_insertion (block, dom);
3585 /* Insert expressions for hoisting. */
3586 if (do_hoist && EDGE_COUNT (block->succs) >= 2)
3587 new_stuff |= do_hoist_insertion (block);
3590 for (son = first_dom_son (CDI_DOMINATORS, block);
3591 son;
3592 son = next_dom_son (CDI_DOMINATORS, son))
3594 new_stuff |= insert_aux (son, do_pre, do_hoist);
3597 return new_stuff;
3600 /* Perform insertion of partially redundant and hoistable values. */
3602 static void
3603 insert (void)
3605 bool new_stuff = true;
3606 basic_block bb;
3607 int num_iterations = 0;
3609 FOR_ALL_BB_FN (bb, cfun)
3610 NEW_SETS (bb) = bitmap_set_new ();
3612 while (new_stuff)
3614 num_iterations++;
3615 if (dump_file && dump_flags & TDF_DETAILS)
3616 fprintf (dump_file, "Starting insert iteration %d\n", num_iterations);
3617 new_stuff = insert_aux (ENTRY_BLOCK_PTR_FOR_FN (cfun), flag_tree_pre,
3618 flag_code_hoisting);
3620 /* Clear the NEW sets before the next iteration. We have already
3621 fully propagated its contents. */
3622 if (new_stuff)
3623 FOR_ALL_BB_FN (bb, cfun)
3624 bitmap_set_free (NEW_SETS (bb));
3626 statistics_histogram_event (cfun, "insert iterations", num_iterations);
3630 /* Compute the AVAIL set for all basic blocks.
3632 This function performs value numbering of the statements in each basic
3633 block. The AVAIL sets are built from information we glean while doing
3634 this value numbering, since the AVAIL sets contain only one entry per
3635 value.
3637 AVAIL_IN[BLOCK] = AVAIL_OUT[dom(BLOCK)].
3638 AVAIL_OUT[BLOCK] = AVAIL_IN[BLOCK] U PHI_GEN[BLOCK] U TMP_GEN[BLOCK]. */
3640 static void
3641 compute_avail (void)
3644 basic_block block, son;
3645 basic_block *worklist;
3646 size_t sp = 0;
3647 unsigned i;
3648 tree name;
3650 /* We pretend that default definitions are defined in the entry block.
3651 This includes function arguments and the static chain decl. */
3652 FOR_EACH_SSA_NAME (i, name, cfun)
3654 pre_expr e;
3655 if (!SSA_NAME_IS_DEFAULT_DEF (name)
3656 || has_zero_uses (name)
3657 || virtual_operand_p (name))
3658 continue;
3660 e = get_or_alloc_expr_for_name (name);
3661 add_to_value (get_expr_value_id (e), e);
3662 bitmap_insert_into_set (TMP_GEN (ENTRY_BLOCK_PTR_FOR_FN (cfun)), e);
3663 bitmap_value_insert_into_set (AVAIL_OUT (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
3667 if (dump_file && (dump_flags & TDF_DETAILS))
3669 print_bitmap_set (dump_file, TMP_GEN (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
3670 "tmp_gen", ENTRY_BLOCK);
3671 print_bitmap_set (dump_file, AVAIL_OUT (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
3672 "avail_out", ENTRY_BLOCK);
3675 /* Allocate the worklist. */
3676 worklist = XNEWVEC (basic_block, n_basic_blocks_for_fn (cfun));
3678 /* Seed the algorithm by putting the dominator children of the entry
3679 block on the worklist. */
3680 for (son = first_dom_son (CDI_DOMINATORS, ENTRY_BLOCK_PTR_FOR_FN (cfun));
3681 son;
3682 son = next_dom_son (CDI_DOMINATORS, son))
3683 worklist[sp++] = son;
3685 BB_LIVE_VOP_ON_EXIT (ENTRY_BLOCK_PTR_FOR_FN (cfun))
3686 = ssa_default_def (cfun, gimple_vop (cfun));
3688 /* Loop until the worklist is empty. */
3689 while (sp)
3691 gimple *stmt;
3692 basic_block dom;
3694 /* Pick a block from the worklist. */
3695 block = worklist[--sp];
3697 /* Initially, the set of available values in BLOCK is that of
3698 its immediate dominator. */
3699 dom = get_immediate_dominator (CDI_DOMINATORS, block);
3700 if (dom)
3702 bitmap_set_copy (AVAIL_OUT (block), AVAIL_OUT (dom));
3703 BB_LIVE_VOP_ON_EXIT (block) = BB_LIVE_VOP_ON_EXIT (dom);
3706 /* Generate values for PHI nodes. */
3707 for (gphi_iterator gsi = gsi_start_phis (block); !gsi_end_p (gsi);
3708 gsi_next (&gsi))
3710 tree result = gimple_phi_result (gsi.phi ());
3712 /* We have no need for virtual phis, as they don't represent
3713 actual computations. */
3714 if (virtual_operand_p (result))
3716 BB_LIVE_VOP_ON_EXIT (block) = result;
3717 continue;
3720 pre_expr e = get_or_alloc_expr_for_name (result);
3721 add_to_value (get_expr_value_id (e), e);
3722 bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3723 bitmap_insert_into_set (PHI_GEN (block), e);
3726 BB_MAY_NOTRETURN (block) = 0;
3728 /* Now compute value numbers and populate value sets with all
3729 the expressions computed in BLOCK. */
3730 for (gimple_stmt_iterator gsi = gsi_start_bb (block); !gsi_end_p (gsi);
3731 gsi_next (&gsi))
3733 ssa_op_iter iter;
3734 tree op;
3736 stmt = gsi_stmt (gsi);
3738 /* Cache whether the basic-block has any non-visible side-effect
3739 or control flow.
3740 If this isn't a call or it is the last stmt in the
3741 basic-block then the CFG represents things correctly. */
3742 if (is_gimple_call (stmt) && !stmt_ends_bb_p (stmt))
3744 /* Non-looping const functions always return normally.
3745 Otherwise the call might not return or have side-effects
3746 that forbids hoisting possibly trapping expressions
3747 before it. */
3748 int flags = gimple_call_flags (stmt);
3749 if (!(flags & ECF_CONST)
3750 || (flags & ECF_LOOPING_CONST_OR_PURE))
3751 BB_MAY_NOTRETURN (block) = 1;
3754 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_DEF)
3756 pre_expr e = get_or_alloc_expr_for_name (op);
3758 add_to_value (get_expr_value_id (e), e);
3759 bitmap_insert_into_set (TMP_GEN (block), e);
3760 bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3763 if (gimple_vdef (stmt))
3764 BB_LIVE_VOP_ON_EXIT (block) = gimple_vdef (stmt);
3766 if (gimple_has_side_effects (stmt)
3767 || stmt_could_throw_p (stmt)
3768 || is_gimple_debug (stmt))
3769 continue;
3771 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
3773 if (ssa_undefined_value_p (op))
3774 continue;
3775 pre_expr e = get_or_alloc_expr_for_name (op);
3776 bitmap_value_insert_into_set (EXP_GEN (block), e);
3779 switch (gimple_code (stmt))
3781 case GIMPLE_RETURN:
3782 continue;
3784 case GIMPLE_CALL:
3786 vn_reference_t ref;
3787 vn_reference_s ref1;
3788 pre_expr result = NULL;
3790 /* We can value number only calls to real functions. */
3791 if (gimple_call_internal_p (stmt))
3792 continue;
3794 vn_reference_lookup_call (as_a <gcall *> (stmt), &ref, &ref1);
3795 if (!ref)
3796 continue;
3798 /* If the value of the call is not invalidated in
3799 this block until it is computed, add the expression
3800 to EXP_GEN. */
3801 if (!gimple_vuse (stmt)
3802 || gimple_code
3803 (SSA_NAME_DEF_STMT (gimple_vuse (stmt))) == GIMPLE_PHI
3804 || gimple_bb (SSA_NAME_DEF_STMT
3805 (gimple_vuse (stmt))) != block)
3807 result = pre_expr_pool.allocate ();
3808 result->kind = REFERENCE;
3809 result->id = 0;
3810 PRE_EXPR_REFERENCE (result) = ref;
3812 get_or_alloc_expression_id (result);
3813 add_to_value (get_expr_value_id (result), result);
3814 bitmap_value_insert_into_set (EXP_GEN (block), result);
3816 continue;
3819 case GIMPLE_ASSIGN:
3821 pre_expr result = NULL;
3822 switch (vn_get_stmt_kind (stmt))
3824 case VN_NARY:
3826 enum tree_code code = gimple_assign_rhs_code (stmt);
3827 vn_nary_op_t nary;
3829 /* COND_EXPR and VEC_COND_EXPR are awkward in
3830 that they contain an embedded complex expression.
3831 Don't even try to shove those through PRE. */
3832 if (code == COND_EXPR
3833 || code == VEC_COND_EXPR)
3834 continue;
3836 vn_nary_op_lookup_stmt (stmt, &nary);
3837 if (!nary)
3838 continue;
3840 /* If the NARY traps and there was a preceding
3841 point in the block that might not return avoid
3842 adding the nary to EXP_GEN. */
3843 if (BB_MAY_NOTRETURN (block)
3844 && vn_nary_may_trap (nary))
3845 continue;
3847 result = pre_expr_pool.allocate ();
3848 result->kind = NARY;
3849 result->id = 0;
3850 PRE_EXPR_NARY (result) = nary;
3851 break;
3854 case VN_REFERENCE:
3856 tree rhs1 = gimple_assign_rhs1 (stmt);
3857 alias_set_type set = get_alias_set (rhs1);
3858 vec<vn_reference_op_s> operands
3859 = vn_reference_operands_for_lookup (rhs1);
3860 vn_reference_t ref;
3861 vn_reference_lookup_pieces (gimple_vuse (stmt), set,
3862 TREE_TYPE (rhs1),
3863 operands, &ref, VN_WALK);
3864 if (!ref)
3866 operands.release ();
3867 continue;
3870 /* If the value of the reference is not invalidated in
3871 this block until it is computed, add the expression
3872 to EXP_GEN. */
3873 if (gimple_vuse (stmt))
3875 gimple *def_stmt;
3876 bool ok = true;
3877 def_stmt = SSA_NAME_DEF_STMT (gimple_vuse (stmt));
3878 while (!gimple_nop_p (def_stmt)
3879 && gimple_code (def_stmt) != GIMPLE_PHI
3880 && gimple_bb (def_stmt) == block)
3882 if (stmt_may_clobber_ref_p
3883 (def_stmt, gimple_assign_rhs1 (stmt)))
3885 ok = false;
3886 break;
3888 def_stmt
3889 = SSA_NAME_DEF_STMT (gimple_vuse (def_stmt));
3891 if (!ok)
3893 operands.release ();
3894 continue;
3898 /* If the load was value-numbered to another
3899 load make sure we do not use its expression
3900 for insertion if it wouldn't be a valid
3901 replacement. */
3902 /* At the momemt we have a testcase
3903 for hoist insertion of aligned vs. misaligned
3904 variants in gcc.dg/torture/pr65270-1.c thus
3905 with just alignment to be considered we can
3906 simply replace the expression in the hashtable
3907 with the most conservative one. */
3908 vn_reference_op_t ref1 = &ref->operands.last ();
3909 while (ref1->opcode != TARGET_MEM_REF
3910 && ref1->opcode != MEM_REF
3911 && ref1 != &ref->operands[0])
3912 --ref1;
3913 vn_reference_op_t ref2 = &operands.last ();
3914 while (ref2->opcode != TARGET_MEM_REF
3915 && ref2->opcode != MEM_REF
3916 && ref2 != &operands[0])
3917 --ref2;
3918 if ((ref1->opcode == TARGET_MEM_REF
3919 || ref1->opcode == MEM_REF)
3920 && (TYPE_ALIGN (ref1->type)
3921 > TYPE_ALIGN (ref2->type)))
3922 ref1->type
3923 = build_aligned_type (ref1->type,
3924 TYPE_ALIGN (ref2->type));
3925 /* TBAA behavior is an obvious part so make sure
3926 that the hashtable one covers this as well
3927 by adjusting the ref alias set and its base. */
3928 if (ref->set == set
3929 || alias_set_subset_of (set, ref->set))
3931 else if (alias_set_subset_of (ref->set, set))
3933 ref->set = set;
3934 if (ref1->opcode == MEM_REF)
3935 ref1->op0
3936 = wide_int_to_tree (TREE_TYPE (ref2->op0),
3937 wi::to_wide (ref1->op0));
3938 else
3939 ref1->op2
3940 = wide_int_to_tree (TREE_TYPE (ref2->op2),
3941 wi::to_wide (ref1->op2));
3943 else
3945 ref->set = 0;
3946 if (ref1->opcode == MEM_REF)
3947 ref1->op0
3948 = wide_int_to_tree (ptr_type_node,
3949 wi::to_wide (ref1->op0));
3950 else
3951 ref1->op2
3952 = wide_int_to_tree (ptr_type_node,
3953 wi::to_wide (ref1->op2));
3955 operands.release ();
3957 result = pre_expr_pool.allocate ();
3958 result->kind = REFERENCE;
3959 result->id = 0;
3960 PRE_EXPR_REFERENCE (result) = ref;
3961 break;
3964 default:
3965 continue;
3968 get_or_alloc_expression_id (result);
3969 add_to_value (get_expr_value_id (result), result);
3970 bitmap_value_insert_into_set (EXP_GEN (block), result);
3971 continue;
3973 default:
3974 break;
3978 if (dump_file && (dump_flags & TDF_DETAILS))
3980 print_bitmap_set (dump_file, EXP_GEN (block),
3981 "exp_gen", block->index);
3982 print_bitmap_set (dump_file, PHI_GEN (block),
3983 "phi_gen", block->index);
3984 print_bitmap_set (dump_file, TMP_GEN (block),
3985 "tmp_gen", block->index);
3986 print_bitmap_set (dump_file, AVAIL_OUT (block),
3987 "avail_out", block->index);
3990 /* Put the dominator children of BLOCK on the worklist of blocks
3991 to compute available sets for. */
3992 for (son = first_dom_son (CDI_DOMINATORS, block);
3993 son;
3994 son = next_dom_son (CDI_DOMINATORS, son))
3995 worklist[sp++] = son;
3998 free (worklist);
4002 /* Initialize data structures used by PRE. */
4004 static void
4005 init_pre (void)
4007 basic_block bb;
4009 next_expression_id = 1;
4010 expressions.create (0);
4011 expressions.safe_push (NULL);
4012 value_expressions.create (get_max_value_id () + 1);
4013 value_expressions.safe_grow_cleared (get_max_value_id () + 1);
4014 name_to_id.create (0);
4016 inserted_exprs = BITMAP_ALLOC (NULL);
4018 connect_infinite_loops_to_exit ();
4019 memset (&pre_stats, 0, sizeof (pre_stats));
4021 alloc_aux_for_blocks (sizeof (struct bb_bitmap_sets));
4023 calculate_dominance_info (CDI_DOMINATORS);
4025 bitmap_obstack_initialize (&grand_bitmap_obstack);
4026 phi_translate_table = new hash_table<expr_pred_trans_d> (5110);
4027 expression_to_id = new hash_table<pre_expr_d> (num_ssa_names * 3);
4028 FOR_ALL_BB_FN (bb, cfun)
4030 EXP_GEN (bb) = bitmap_set_new ();
4031 PHI_GEN (bb) = bitmap_set_new ();
4032 TMP_GEN (bb) = bitmap_set_new ();
4033 AVAIL_OUT (bb) = bitmap_set_new ();
4038 /* Deallocate data structures used by PRE. */
4040 static void
4041 fini_pre ()
4043 value_expressions.release ();
4044 expressions.release ();
4045 BITMAP_FREE (inserted_exprs);
4046 bitmap_obstack_release (&grand_bitmap_obstack);
4047 bitmap_set_pool.release ();
4048 pre_expr_pool.release ();
4049 delete phi_translate_table;
4050 phi_translate_table = NULL;
4051 delete expression_to_id;
4052 expression_to_id = NULL;
4053 name_to_id.release ();
4055 free_aux_for_blocks ();
4058 namespace {
4060 const pass_data pass_data_pre =
4062 GIMPLE_PASS, /* type */
4063 "pre", /* name */
4064 OPTGROUP_NONE, /* optinfo_flags */
4065 TV_TREE_PRE, /* tv_id */
4066 ( PROP_cfg | PROP_ssa ), /* properties_required */
4067 0, /* properties_provided */
4068 0, /* properties_destroyed */
4069 TODO_rebuild_alias, /* todo_flags_start */
4070 0, /* todo_flags_finish */
4073 class pass_pre : public gimple_opt_pass
4075 public:
4076 pass_pre (gcc::context *ctxt)
4077 : gimple_opt_pass (pass_data_pre, ctxt)
4080 /* opt_pass methods: */
4081 virtual bool gate (function *)
4082 { return flag_tree_pre != 0 || flag_code_hoisting != 0; }
4083 virtual unsigned int execute (function *);
4085 }; // class pass_pre
4087 unsigned int
4088 pass_pre::execute (function *fun)
4090 unsigned int todo = 0;
4092 do_partial_partial =
4093 flag_tree_partial_pre && optimize_function_for_speed_p (fun);
4095 /* This has to happen before SCCVN runs because
4096 loop_optimizer_init may create new phis, etc. */
4097 loop_optimizer_init (LOOPS_NORMAL);
4098 split_critical_edges ();
4099 scev_initialize ();
4101 run_scc_vn (VN_WALK);
4103 init_pre ();
4105 /* Insert can get quite slow on an incredibly large number of basic
4106 blocks due to some quadratic behavior. Until this behavior is
4107 fixed, don't run it when he have an incredibly large number of
4108 bb's. If we aren't going to run insert, there is no point in
4109 computing ANTIC, either, even though it's plenty fast nor do
4110 we require AVAIL. */
4111 if (n_basic_blocks_for_fn (fun) < 4000)
4113 compute_avail ();
4114 compute_antic ();
4115 insert ();
4118 /* Make sure to remove fake edges before committing our inserts.
4119 This makes sure we don't end up with extra critical edges that
4120 we would need to split. */
4121 remove_fake_exit_edges ();
4122 gsi_commit_edge_inserts ();
4124 /* Eliminate folds statements which might (should not...) end up
4125 not keeping virtual operands up-to-date. */
4126 gcc_assert (!need_ssa_update_p (fun));
4128 statistics_counter_event (fun, "Insertions", pre_stats.insertions);
4129 statistics_counter_event (fun, "PA inserted", pre_stats.pa_insert);
4130 statistics_counter_event (fun, "HOIST inserted", pre_stats.hoist_insert);
4131 statistics_counter_event (fun, "New PHIs", pre_stats.phis);
4133 /* Remove all the redundant expressions. */
4134 todo |= vn_eliminate (inserted_exprs);
4136 /* Because we don't follow exactly the standard PRE algorithm, and decide not
4137 to insert PHI nodes sometimes, and because value numbering of casts isn't
4138 perfect, we sometimes end up inserting dead code. This simple DCE-like
4139 pass removes any insertions we made that weren't actually used. */
4140 simple_dce_from_worklist (inserted_exprs);
4142 fini_pre ();
4144 scev_finalize ();
4145 loop_optimizer_finalize ();
4147 /* Restore SSA info before tail-merging as that resets it as well. */
4148 scc_vn_restore_ssa_info ();
4150 /* TODO: tail_merge_optimize may merge all predecessors of a block, in which
4151 case we can merge the block with the remaining predecessor of the block.
4152 It should either:
4153 - call merge_blocks after each tail merge iteration
4154 - call merge_blocks after all tail merge iterations
4155 - mark TODO_cleanup_cfg when necessary
4156 - share the cfg cleanup with fini_pre. */
4157 todo |= tail_merge_optimize (todo);
4159 free_scc_vn ();
4161 /* Tail merging invalidates the virtual SSA web, together with
4162 cfg-cleanup opportunities exposed by PRE this will wreck the
4163 SSA updating machinery. So make sure to run update-ssa
4164 manually, before eventually scheduling cfg-cleanup as part of
4165 the todo. */
4166 update_ssa (TODO_update_ssa_only_virtuals);
4168 return todo;
4171 } // anon namespace
4173 gimple_opt_pass *
4174 make_pass_pre (gcc::context *ctxt)
4176 return new pass_pre (ctxt);