Don't warn when alignment of global common data exceeds maximum alignment.
[official-gcc.git] / gcc / tree-ssa-pre.c
blobebe95cc6c73f0540db5986869f8d89816df470a4
1 /* Full and partial redundancy elimination and code hoisting on SSA GIMPLE.
2 Copyright (C) 2001-2021 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 "dbgcnt.h"
49 #include "domwalk.h"
50 #include "tree-ssa-propagate.h"
51 #include "tree-ssa-dce.h"
52 #include "tree-cfgcleanup.h"
53 #include "alias.h"
54 #include "gimple-range.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 unsigned value_id;
261 location_t loc;
262 pre_expr_union u;
264 /* hash_table support. */
265 static inline hashval_t hash (const pre_expr_d *);
266 static inline int equal (const pre_expr_d *, const pre_expr_d *);
267 } *pre_expr;
269 #define PRE_EXPR_NAME(e) (e)->u.name
270 #define PRE_EXPR_NARY(e) (e)->u.nary
271 #define PRE_EXPR_REFERENCE(e) (e)->u.reference
272 #define PRE_EXPR_CONSTANT(e) (e)->u.constant
274 /* Compare E1 and E1 for equality. */
276 inline int
277 pre_expr_d::equal (const pre_expr_d *e1, const pre_expr_d *e2)
279 if (e1->kind != e2->kind)
280 return false;
282 switch (e1->kind)
284 case CONSTANT:
285 return vn_constant_eq_with_type (PRE_EXPR_CONSTANT (e1),
286 PRE_EXPR_CONSTANT (e2));
287 case NAME:
288 return PRE_EXPR_NAME (e1) == PRE_EXPR_NAME (e2);
289 case NARY:
290 return vn_nary_op_eq (PRE_EXPR_NARY (e1), PRE_EXPR_NARY (e2));
291 case REFERENCE:
292 return vn_reference_eq (PRE_EXPR_REFERENCE (e1),
293 PRE_EXPR_REFERENCE (e2));
294 default:
295 gcc_unreachable ();
299 /* Hash E. */
301 inline hashval_t
302 pre_expr_d::hash (const pre_expr_d *e)
304 switch (e->kind)
306 case CONSTANT:
307 return vn_hash_constant_with_type (PRE_EXPR_CONSTANT (e));
308 case NAME:
309 return SSA_NAME_VERSION (PRE_EXPR_NAME (e));
310 case NARY:
311 return PRE_EXPR_NARY (e)->hashcode;
312 case REFERENCE:
313 return PRE_EXPR_REFERENCE (e)->hashcode;
314 default:
315 gcc_unreachable ();
319 /* Next global expression id number. */
320 static unsigned int next_expression_id;
322 /* Mapping from expression to id number we can use in bitmap sets. */
323 static vec<pre_expr> expressions;
324 static hash_table<pre_expr_d> *expression_to_id;
325 static vec<unsigned> name_to_id;
327 /* Allocate an expression id for EXPR. */
329 static inline unsigned int
330 alloc_expression_id (pre_expr expr)
332 struct pre_expr_d **slot;
333 /* Make sure we won't overflow. */
334 gcc_assert (next_expression_id + 1 > next_expression_id);
335 expr->id = next_expression_id++;
336 expressions.safe_push (expr);
337 if (expr->kind == NAME)
339 unsigned version = SSA_NAME_VERSION (PRE_EXPR_NAME (expr));
340 /* vec::safe_grow_cleared allocates no headroom. Avoid frequent
341 re-allocations by using vec::reserve upfront. */
342 unsigned old_len = name_to_id.length ();
343 name_to_id.reserve (num_ssa_names - old_len);
344 name_to_id.quick_grow_cleared (num_ssa_names);
345 gcc_assert (name_to_id[version] == 0);
346 name_to_id[version] = expr->id;
348 else
350 slot = expression_to_id->find_slot (expr, INSERT);
351 gcc_assert (!*slot);
352 *slot = expr;
354 return next_expression_id - 1;
357 /* Return the expression id for tree EXPR. */
359 static inline unsigned int
360 get_expression_id (const pre_expr expr)
362 return expr->id;
365 static inline unsigned int
366 lookup_expression_id (const pre_expr expr)
368 struct pre_expr_d **slot;
370 if (expr->kind == NAME)
372 unsigned version = SSA_NAME_VERSION (PRE_EXPR_NAME (expr));
373 if (name_to_id.length () <= version)
374 return 0;
375 return name_to_id[version];
377 else
379 slot = expression_to_id->find_slot (expr, NO_INSERT);
380 if (!slot)
381 return 0;
382 return ((pre_expr)*slot)->id;
386 /* Return the existing expression id for EXPR, or create one if one
387 does not exist yet. */
389 static inline unsigned int
390 get_or_alloc_expression_id (pre_expr expr)
392 unsigned int id = lookup_expression_id (expr);
393 if (id == 0)
394 return alloc_expression_id (expr);
395 return expr->id = id;
398 /* Return the expression that has expression id ID */
400 static inline pre_expr
401 expression_for_id (unsigned int id)
403 return expressions[id];
406 static object_allocator<pre_expr_d> pre_expr_pool ("pre_expr nodes");
408 /* Given an SSA_NAME NAME, get or create a pre_expr to represent it. */
410 static pre_expr
411 get_or_alloc_expr_for_name (tree name)
413 struct pre_expr_d expr;
414 pre_expr result;
415 unsigned int result_id;
417 expr.kind = NAME;
418 expr.id = 0;
419 PRE_EXPR_NAME (&expr) = name;
420 result_id = lookup_expression_id (&expr);
421 if (result_id != 0)
422 return expression_for_id (result_id);
424 result = pre_expr_pool.allocate ();
425 result->kind = NAME;
426 result->loc = UNKNOWN_LOCATION;
427 result->value_id = VN_INFO (name)->value_id;
428 PRE_EXPR_NAME (result) = name;
429 alloc_expression_id (result);
430 return result;
433 /* Given an NARY, get or create a pre_expr to represent it. */
435 static pre_expr
436 get_or_alloc_expr_for_nary (vn_nary_op_t nary,
437 location_t loc = UNKNOWN_LOCATION)
439 struct pre_expr_d expr;
440 pre_expr result;
441 unsigned int result_id;
443 expr.kind = NARY;
444 expr.id = 0;
445 PRE_EXPR_NARY (&expr) = nary;
446 result_id = lookup_expression_id (&expr);
447 if (result_id != 0)
448 return expression_for_id (result_id);
450 result = pre_expr_pool.allocate ();
451 result->kind = NARY;
452 result->loc = loc;
453 result->value_id = nary->value_id;
454 PRE_EXPR_NARY (result) = nary;
455 alloc_expression_id (result);
456 return result;
459 /* Given an REFERENCE, get or create a pre_expr to represent it. */
461 static pre_expr
462 get_or_alloc_expr_for_reference (vn_reference_t reference,
463 location_t loc = UNKNOWN_LOCATION)
465 struct pre_expr_d expr;
466 pre_expr result;
467 unsigned int result_id;
469 expr.kind = REFERENCE;
470 expr.id = 0;
471 PRE_EXPR_REFERENCE (&expr) = reference;
472 result_id = lookup_expression_id (&expr);
473 if (result_id != 0)
474 return expression_for_id (result_id);
476 result = pre_expr_pool.allocate ();
477 result->kind = REFERENCE;
478 result->loc = loc;
479 result->value_id = reference->value_id;
480 PRE_EXPR_REFERENCE (result) = reference;
481 alloc_expression_id (result);
482 return result;
486 /* An unordered bitmap set. One bitmap tracks values, the other,
487 expressions. */
488 typedef class bitmap_set
490 public:
491 bitmap_head expressions;
492 bitmap_head values;
493 } *bitmap_set_t;
495 #define FOR_EACH_EXPR_ID_IN_SET(set, id, bi) \
496 EXECUTE_IF_SET_IN_BITMAP (&(set)->expressions, 0, (id), (bi))
498 #define FOR_EACH_VALUE_ID_IN_SET(set, id, bi) \
499 EXECUTE_IF_SET_IN_BITMAP (&(set)->values, 0, (id), (bi))
501 /* Mapping from value id to expressions with that value_id. */
502 static vec<bitmap> value_expressions;
503 /* We just record a single expression for each constant value,
504 one of kind CONSTANT. */
505 static vec<pre_expr> constant_value_expressions;
508 /* This structure is used to keep track of statistics on what
509 optimization PRE was able to perform. */
510 static struct
512 /* The number of new expressions/temporaries generated by PRE. */
513 int insertions;
515 /* The number of inserts found due to partial anticipation */
516 int pa_insert;
518 /* The number of inserts made for code hoisting. */
519 int hoist_insert;
521 /* The number of new PHI nodes added by PRE. */
522 int phis;
523 } pre_stats;
525 static bool do_partial_partial;
526 static pre_expr bitmap_find_leader (bitmap_set_t, unsigned int);
527 static void bitmap_value_insert_into_set (bitmap_set_t, pre_expr);
528 static bool bitmap_value_replace_in_set (bitmap_set_t, pre_expr);
529 static void bitmap_set_copy (bitmap_set_t, bitmap_set_t);
530 static bool bitmap_set_contains_value (bitmap_set_t, unsigned int);
531 static void bitmap_insert_into_set (bitmap_set_t, pre_expr);
532 static bitmap_set_t bitmap_set_new (void);
533 static tree create_expression_by_pieces (basic_block, pre_expr, gimple_seq *,
534 tree);
535 static tree find_or_generate_expression (basic_block, tree, gimple_seq *);
536 static unsigned int get_expr_value_id (pre_expr);
538 /* We can add and remove elements and entries to and from sets
539 and hash tables, so we use alloc pools for them. */
541 static object_allocator<bitmap_set> bitmap_set_pool ("Bitmap sets");
542 static bitmap_obstack grand_bitmap_obstack;
544 /* A three tuple {e, pred, v} used to cache phi translations in the
545 phi_translate_table. */
547 typedef struct expr_pred_trans_d : public typed_noop_remove <expr_pred_trans_d>
549 typedef expr_pred_trans_d value_type;
550 typedef expr_pred_trans_d compare_type;
552 /* The expression ID. */
553 unsigned e;
555 /* The value expression ID that resulted from the translation. */
556 unsigned v;
558 /* hash_table support. */
559 static inline void mark_empty (expr_pred_trans_d &);
560 static inline bool is_empty (const expr_pred_trans_d &);
561 static inline void mark_deleted (expr_pred_trans_d &);
562 static inline bool is_deleted (const expr_pred_trans_d &);
563 static const bool empty_zero_p = true;
564 static inline hashval_t hash (const expr_pred_trans_d &);
565 static inline int equal (const expr_pred_trans_d &, const expr_pred_trans_d &);
566 } *expr_pred_trans_t;
567 typedef const struct expr_pred_trans_d *const_expr_pred_trans_t;
569 inline bool
570 expr_pred_trans_d::is_empty (const expr_pred_trans_d &e)
572 return e.e == 0;
575 inline bool
576 expr_pred_trans_d::is_deleted (const expr_pred_trans_d &e)
578 return e.e == -1u;
581 inline void
582 expr_pred_trans_d::mark_empty (expr_pred_trans_d &e)
584 e.e = 0;
587 inline void
588 expr_pred_trans_d::mark_deleted (expr_pred_trans_d &e)
590 e.e = -1u;
593 inline hashval_t
594 expr_pred_trans_d::hash (const expr_pred_trans_d &e)
596 return e.e;
599 inline int
600 expr_pred_trans_d::equal (const expr_pred_trans_d &ve1,
601 const expr_pred_trans_d &ve2)
603 return ve1.e == ve2.e;
606 /* Sets that we need to keep track of. */
607 typedef struct bb_bitmap_sets
609 /* The EXP_GEN set, which represents expressions/values generated in
610 a basic block. */
611 bitmap_set_t exp_gen;
613 /* The PHI_GEN set, which represents PHI results generated in a
614 basic block. */
615 bitmap_set_t phi_gen;
617 /* The TMP_GEN set, which represents results/temporaries generated
618 in a basic block. IE the LHS of an expression. */
619 bitmap_set_t tmp_gen;
621 /* The AVAIL_OUT set, which represents which values are available in
622 a given basic block. */
623 bitmap_set_t avail_out;
625 /* The ANTIC_IN set, which represents which values are anticipatable
626 in a given basic block. */
627 bitmap_set_t antic_in;
629 /* The PA_IN set, which represents which values are
630 partially anticipatable in a given basic block. */
631 bitmap_set_t pa_in;
633 /* The NEW_SETS set, which is used during insertion to augment the
634 AVAIL_OUT set of blocks with the new insertions performed during
635 the current iteration. */
636 bitmap_set_t new_sets;
638 /* A cache for value_dies_in_block_x. */
639 bitmap expr_dies;
641 /* The live virtual operand on successor edges. */
642 tree vop_on_exit;
644 /* PHI translate cache for the single successor edge. */
645 hash_table<expr_pred_trans_d> *phi_translate_table;
647 /* True if we have visited this block during ANTIC calculation. */
648 unsigned int visited : 1;
650 /* True when the block contains a call that might not return. */
651 unsigned int contains_may_not_return_call : 1;
652 } *bb_value_sets_t;
654 #define EXP_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->exp_gen
655 #define PHI_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->phi_gen
656 #define TMP_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->tmp_gen
657 #define AVAIL_OUT(BB) ((bb_value_sets_t) ((BB)->aux))->avail_out
658 #define ANTIC_IN(BB) ((bb_value_sets_t) ((BB)->aux))->antic_in
659 #define PA_IN(BB) ((bb_value_sets_t) ((BB)->aux))->pa_in
660 #define NEW_SETS(BB) ((bb_value_sets_t) ((BB)->aux))->new_sets
661 #define EXPR_DIES(BB) ((bb_value_sets_t) ((BB)->aux))->expr_dies
662 #define PHI_TRANS_TABLE(BB) ((bb_value_sets_t) ((BB)->aux))->phi_translate_table
663 #define BB_VISITED(BB) ((bb_value_sets_t) ((BB)->aux))->visited
664 #define BB_MAY_NOTRETURN(BB) ((bb_value_sets_t) ((BB)->aux))->contains_may_not_return_call
665 #define BB_LIVE_VOP_ON_EXIT(BB) ((bb_value_sets_t) ((BB)->aux))->vop_on_exit
668 /* Add the tuple mapping from {expression E, basic block PRED} to
669 the phi translation table and return whether it pre-existed. */
671 static inline bool
672 phi_trans_add (expr_pred_trans_t *entry, pre_expr e, basic_block pred)
674 if (!PHI_TRANS_TABLE (pred))
675 PHI_TRANS_TABLE (pred) = new hash_table<expr_pred_trans_d> (11);
677 expr_pred_trans_t slot;
678 expr_pred_trans_d tem;
679 unsigned id = get_expression_id (e);
680 tem.e = id;
681 slot = PHI_TRANS_TABLE (pred)->find_slot_with_hash (tem, id, INSERT);
682 if (slot->e)
684 *entry = slot;
685 return true;
688 *entry = slot;
689 slot->e = id;
690 return false;
694 /* Add expression E to the expression set of value id V. */
696 static void
697 add_to_value (unsigned int v, pre_expr e)
699 gcc_checking_assert (get_expr_value_id (e) == v);
701 if (value_id_constant_p (v))
703 if (e->kind != CONSTANT)
704 return;
706 if (-v >= constant_value_expressions.length ())
707 constant_value_expressions.safe_grow_cleared (-v + 1);
709 pre_expr leader = constant_value_expressions[-v];
710 if (!leader)
711 constant_value_expressions[-v] = e;
713 else
715 if (v >= value_expressions.length ())
716 value_expressions.safe_grow_cleared (v + 1);
718 bitmap set = value_expressions[v];
719 if (!set)
721 set = BITMAP_ALLOC (&grand_bitmap_obstack);
722 value_expressions[v] = set;
724 bitmap_set_bit (set, get_or_alloc_expression_id (e));
728 /* Create a new bitmap set and return it. */
730 static bitmap_set_t
731 bitmap_set_new (void)
733 bitmap_set_t ret = bitmap_set_pool.allocate ();
734 bitmap_initialize (&ret->expressions, &grand_bitmap_obstack);
735 bitmap_initialize (&ret->values, &grand_bitmap_obstack);
736 return ret;
739 /* Return the value id for a PRE expression EXPR. */
741 static unsigned int
742 get_expr_value_id (pre_expr expr)
744 /* ??? We cannot assert that expr has a value-id (it can be 0), because
745 we assign value-ids only to expressions that have a result
746 in set_hashtable_value_ids. */
747 return expr->value_id;
750 /* Return a VN valnum (SSA name or constant) for the PRE value-id VAL. */
752 static tree
753 vn_valnum_from_value_id (unsigned int val)
755 if (value_id_constant_p (val))
757 pre_expr vexpr = constant_value_expressions[-val];
758 if (vexpr)
759 return PRE_EXPR_CONSTANT (vexpr);
760 return NULL_TREE;
763 bitmap exprset = value_expressions[val];
764 bitmap_iterator bi;
765 unsigned int i;
766 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
768 pre_expr vexpr = expression_for_id (i);
769 if (vexpr->kind == NAME)
770 return VN_INFO (PRE_EXPR_NAME (vexpr))->valnum;
772 return NULL_TREE;
775 /* Insert an expression EXPR into a bitmapped set. */
777 static void
778 bitmap_insert_into_set (bitmap_set_t set, pre_expr expr)
780 unsigned int val = get_expr_value_id (expr);
781 if (! value_id_constant_p (val))
783 /* Note this is the only function causing multiple expressions
784 for the same value to appear in a set. This is needed for
785 TMP_GEN, PHI_GEN and NEW_SETs. */
786 bitmap_set_bit (&set->values, val);
787 bitmap_set_bit (&set->expressions, get_or_alloc_expression_id (expr));
791 /* Copy a bitmapped set ORIG, into bitmapped set DEST. */
793 static void
794 bitmap_set_copy (bitmap_set_t dest, bitmap_set_t orig)
796 bitmap_copy (&dest->expressions, &orig->expressions);
797 bitmap_copy (&dest->values, &orig->values);
801 /* Free memory used up by SET. */
802 static void
803 bitmap_set_free (bitmap_set_t set)
805 bitmap_clear (&set->expressions);
806 bitmap_clear (&set->values);
809 static void
810 pre_expr_DFS (pre_expr expr, bitmap_set_t set, bitmap val_visited,
811 vec<pre_expr> &post);
813 /* DFS walk leaders of VAL to their operands with leaders in SET, collecting
814 expressions in SET in postorder into POST. */
816 static void
817 pre_expr_DFS (unsigned val, bitmap_set_t set, bitmap val_visited,
818 vec<pre_expr> &post)
820 unsigned int i;
821 bitmap_iterator bi;
823 /* Iterate over all leaders and DFS recurse. Borrowed from
824 bitmap_find_leader. */
825 bitmap exprset = value_expressions[val];
826 if (!exprset->first->next)
828 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
829 if (bitmap_bit_p (&set->expressions, i))
830 pre_expr_DFS (expression_for_id (i), set, val_visited, post);
831 return;
834 EXECUTE_IF_AND_IN_BITMAP (exprset, &set->expressions, 0, i, bi)
835 pre_expr_DFS (expression_for_id (i), set, val_visited, post);
838 /* DFS walk EXPR to its operands with leaders in SET, collecting
839 expressions in SET in postorder into POST. */
841 static void
842 pre_expr_DFS (pre_expr expr, bitmap_set_t set, bitmap val_visited,
843 vec<pre_expr> &post)
845 switch (expr->kind)
847 case NARY:
849 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
850 for (unsigned i = 0; i < nary->length; i++)
852 if (TREE_CODE (nary->op[i]) != SSA_NAME)
853 continue;
854 unsigned int op_val_id = VN_INFO (nary->op[i])->value_id;
855 /* If we already found a leader for the value we've
856 recursed already. Avoid the costly bitmap_find_leader. */
857 if (bitmap_bit_p (&set->values, op_val_id)
858 && bitmap_set_bit (val_visited, op_val_id))
859 pre_expr_DFS (op_val_id, set, val_visited, post);
861 break;
863 case REFERENCE:
865 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
866 vec<vn_reference_op_s> operands = ref->operands;
867 vn_reference_op_t operand;
868 for (unsigned i = 0; operands.iterate (i, &operand); i++)
870 tree op[3];
871 op[0] = operand->op0;
872 op[1] = operand->op1;
873 op[2] = operand->op2;
874 for (unsigned n = 0; n < 3; ++n)
876 if (!op[n] || TREE_CODE (op[n]) != SSA_NAME)
877 continue;
878 unsigned op_val_id = VN_INFO (op[n])->value_id;
879 if (bitmap_bit_p (&set->values, op_val_id)
880 && bitmap_set_bit (val_visited, op_val_id))
881 pre_expr_DFS (op_val_id, set, val_visited, post);
884 break;
886 default:;
888 post.quick_push (expr);
891 /* Generate an topological-ordered array of bitmap set SET. */
893 static vec<pre_expr>
894 sorted_array_from_bitmap_set (bitmap_set_t set)
896 unsigned int i;
897 bitmap_iterator bi;
898 vec<pre_expr> result;
900 /* Pre-allocate enough space for the array. */
901 result.create (bitmap_count_bits (&set->expressions));
903 auto_bitmap val_visited (&grand_bitmap_obstack);
904 bitmap_tree_view (val_visited);
905 FOR_EACH_VALUE_ID_IN_SET (set, i, bi)
906 if (bitmap_set_bit (val_visited, i))
907 pre_expr_DFS (i, set, val_visited, result);
909 return result;
912 /* Subtract all expressions contained in ORIG from DEST. */
914 static bitmap_set_t
915 bitmap_set_subtract_expressions (bitmap_set_t dest, bitmap_set_t orig)
917 bitmap_set_t result = bitmap_set_new ();
918 bitmap_iterator bi;
919 unsigned int i;
921 bitmap_and_compl (&result->expressions, &dest->expressions,
922 &orig->expressions);
924 FOR_EACH_EXPR_ID_IN_SET (result, i, bi)
926 pre_expr expr = expression_for_id (i);
927 unsigned int value_id = get_expr_value_id (expr);
928 bitmap_set_bit (&result->values, value_id);
931 return result;
934 /* Subtract all values in bitmap set B from bitmap set A. */
936 static void
937 bitmap_set_subtract_values (bitmap_set_t a, bitmap_set_t b)
939 unsigned int i;
940 bitmap_iterator bi;
941 unsigned to_remove = -1U;
942 bitmap_and_compl_into (&a->values, &b->values);
943 FOR_EACH_EXPR_ID_IN_SET (a, i, bi)
945 if (to_remove != -1U)
947 bitmap_clear_bit (&a->expressions, to_remove);
948 to_remove = -1U;
950 pre_expr expr = expression_for_id (i);
951 if (! bitmap_bit_p (&a->values, get_expr_value_id (expr)))
952 to_remove = i;
954 if (to_remove != -1U)
955 bitmap_clear_bit (&a->expressions, to_remove);
959 /* Return true if bitmapped set SET contains the value VALUE_ID. */
961 static bool
962 bitmap_set_contains_value (bitmap_set_t set, unsigned int value_id)
964 if (value_id_constant_p (value_id))
965 return true;
967 return bitmap_bit_p (&set->values, value_id);
970 /* Return true if two bitmap sets are equal. */
972 static bool
973 bitmap_set_equal (bitmap_set_t a, bitmap_set_t b)
975 return bitmap_equal_p (&a->values, &b->values);
978 /* Replace an instance of EXPR's VALUE with EXPR in SET if it exists,
979 and add it otherwise. Return true if any changes were made. */
981 static bool
982 bitmap_value_replace_in_set (bitmap_set_t set, pre_expr expr)
984 unsigned int val = get_expr_value_id (expr);
985 if (value_id_constant_p (val))
986 return false;
988 if (bitmap_set_contains_value (set, val))
990 /* The number of expressions having a given value is usually
991 significantly less than the total number of expressions in SET.
992 Thus, rather than check, for each expression in SET, whether it
993 has the value LOOKFOR, we walk the reverse mapping that tells us
994 what expressions have a given value, and see if any of those
995 expressions are in our set. For large testcases, this is about
996 5-10x faster than walking the bitmap. If this is somehow a
997 significant lose for some cases, we can choose which set to walk
998 based on the set size. */
999 unsigned int i;
1000 bitmap_iterator bi;
1001 bitmap exprset = value_expressions[val];
1002 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
1004 if (bitmap_clear_bit (&set->expressions, i))
1006 bitmap_set_bit (&set->expressions, get_expression_id (expr));
1007 return i != get_expression_id (expr);
1010 gcc_unreachable ();
1013 bitmap_insert_into_set (set, expr);
1014 return true;
1017 /* Insert EXPR into SET if EXPR's value is not already present in
1018 SET. */
1020 static void
1021 bitmap_value_insert_into_set (bitmap_set_t set, pre_expr expr)
1023 unsigned int val = get_expr_value_id (expr);
1025 gcc_checking_assert (expr->id == get_or_alloc_expression_id (expr));
1027 /* Constant values are always considered to be part of the set. */
1028 if (value_id_constant_p (val))
1029 return;
1031 /* If the value membership changed, add the expression. */
1032 if (bitmap_set_bit (&set->values, val))
1033 bitmap_set_bit (&set->expressions, expr->id);
1036 /* Print out EXPR to outfile. */
1038 static void
1039 print_pre_expr (FILE *outfile, const pre_expr expr)
1041 if (! expr)
1043 fprintf (outfile, "NULL");
1044 return;
1046 switch (expr->kind)
1048 case CONSTANT:
1049 print_generic_expr (outfile, PRE_EXPR_CONSTANT (expr));
1050 break;
1051 case NAME:
1052 print_generic_expr (outfile, PRE_EXPR_NAME (expr));
1053 break;
1054 case NARY:
1056 unsigned int i;
1057 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1058 fprintf (outfile, "{%s,", get_tree_code_name (nary->opcode));
1059 for (i = 0; i < nary->length; i++)
1061 print_generic_expr (outfile, nary->op[i]);
1062 if (i != (unsigned) nary->length - 1)
1063 fprintf (outfile, ",");
1065 fprintf (outfile, "}");
1067 break;
1069 case REFERENCE:
1071 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1072 print_vn_reference_ops (outfile, ref->operands);
1073 if (ref->vuse)
1075 fprintf (outfile, "@");
1076 print_generic_expr (outfile, ref->vuse);
1079 break;
1082 void debug_pre_expr (pre_expr);
1084 /* Like print_pre_expr but always prints to stderr. */
1085 DEBUG_FUNCTION void
1086 debug_pre_expr (pre_expr e)
1088 print_pre_expr (stderr, e);
1089 fprintf (stderr, "\n");
1092 /* Print out SET to OUTFILE. */
1094 static void
1095 print_bitmap_set (FILE *outfile, bitmap_set_t set,
1096 const char *setname, int blockindex)
1098 fprintf (outfile, "%s[%d] := { ", setname, blockindex);
1099 if (set)
1101 bool first = true;
1102 unsigned i;
1103 bitmap_iterator bi;
1105 FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
1107 const pre_expr expr = expression_for_id (i);
1109 if (!first)
1110 fprintf (outfile, ", ");
1111 first = false;
1112 print_pre_expr (outfile, expr);
1114 fprintf (outfile, " (%04d)", get_expr_value_id (expr));
1117 fprintf (outfile, " }\n");
1120 void debug_bitmap_set (bitmap_set_t);
1122 DEBUG_FUNCTION void
1123 debug_bitmap_set (bitmap_set_t set)
1125 print_bitmap_set (stderr, set, "debug", 0);
1128 void debug_bitmap_sets_for (basic_block);
1130 DEBUG_FUNCTION void
1131 debug_bitmap_sets_for (basic_block bb)
1133 print_bitmap_set (stderr, AVAIL_OUT (bb), "avail_out", bb->index);
1134 print_bitmap_set (stderr, EXP_GEN (bb), "exp_gen", bb->index);
1135 print_bitmap_set (stderr, PHI_GEN (bb), "phi_gen", bb->index);
1136 print_bitmap_set (stderr, TMP_GEN (bb), "tmp_gen", bb->index);
1137 print_bitmap_set (stderr, ANTIC_IN (bb), "antic_in", bb->index);
1138 if (do_partial_partial)
1139 print_bitmap_set (stderr, PA_IN (bb), "pa_in", bb->index);
1140 print_bitmap_set (stderr, NEW_SETS (bb), "new_sets", bb->index);
1143 /* Print out the expressions that have VAL to OUTFILE. */
1145 static void
1146 print_value_expressions (FILE *outfile, unsigned int val)
1148 bitmap set = value_expressions[val];
1149 if (set)
1151 bitmap_set x;
1152 char s[10];
1153 sprintf (s, "%04d", val);
1154 x.expressions = *set;
1155 print_bitmap_set (outfile, &x, s, 0);
1160 DEBUG_FUNCTION void
1161 debug_value_expressions (unsigned int val)
1163 print_value_expressions (stderr, val);
1166 /* Given a CONSTANT, allocate a new CONSTANT type PRE_EXPR to
1167 represent it. */
1169 static pre_expr
1170 get_or_alloc_expr_for_constant (tree constant)
1172 unsigned int result_id;
1173 struct pre_expr_d expr;
1174 pre_expr newexpr;
1176 expr.kind = CONSTANT;
1177 PRE_EXPR_CONSTANT (&expr) = constant;
1178 result_id = lookup_expression_id (&expr);
1179 if (result_id != 0)
1180 return expression_for_id (result_id);
1182 newexpr = pre_expr_pool.allocate ();
1183 newexpr->kind = CONSTANT;
1184 newexpr->loc = UNKNOWN_LOCATION;
1185 PRE_EXPR_CONSTANT (newexpr) = constant;
1186 alloc_expression_id (newexpr);
1187 newexpr->value_id = get_or_alloc_constant_value_id (constant);
1188 add_to_value (newexpr->value_id, newexpr);
1189 return newexpr;
1192 /* Get or allocate a pre_expr for a piece of GIMPLE, and return it.
1193 Currently only supports constants and SSA_NAMES. */
1194 static pre_expr
1195 get_or_alloc_expr_for (tree t)
1197 if (TREE_CODE (t) == SSA_NAME)
1198 return get_or_alloc_expr_for_name (t);
1199 else if (is_gimple_min_invariant (t))
1200 return get_or_alloc_expr_for_constant (t);
1201 gcc_unreachable ();
1204 /* Return the folded version of T if T, when folded, is a gimple
1205 min_invariant or an SSA name. Otherwise, return T. */
1207 static pre_expr
1208 fully_constant_expression (pre_expr e)
1210 switch (e->kind)
1212 case CONSTANT:
1213 return e;
1214 case NARY:
1216 vn_nary_op_t nary = PRE_EXPR_NARY (e);
1217 tree res = vn_nary_simplify (nary);
1218 if (!res)
1219 return e;
1220 if (is_gimple_min_invariant (res))
1221 return get_or_alloc_expr_for_constant (res);
1222 if (TREE_CODE (res) == SSA_NAME)
1223 return get_or_alloc_expr_for_name (res);
1224 return e;
1226 case REFERENCE:
1228 vn_reference_t ref = PRE_EXPR_REFERENCE (e);
1229 tree folded;
1230 if ((folded = fully_constant_vn_reference_p (ref)))
1231 return get_or_alloc_expr_for_constant (folded);
1232 return e;
1234 default:
1235 return e;
1237 return e;
1240 /* Translate the VUSE backwards through phi nodes in PHIBLOCK, so that
1241 it has the value it would have in BLOCK. Set *SAME_VALID to true
1242 in case the new vuse doesn't change the value id of the OPERANDS. */
1244 static tree
1245 translate_vuse_through_block (vec<vn_reference_op_s> operands,
1246 alias_set_type set, alias_set_type base_set,
1247 tree type, tree vuse,
1248 basic_block phiblock,
1249 basic_block block, bool *same_valid)
1251 gimple *phi = SSA_NAME_DEF_STMT (vuse);
1252 ao_ref ref;
1253 edge e = NULL;
1254 bool use_oracle;
1256 if (same_valid)
1257 *same_valid = true;
1259 if (gimple_bb (phi) != phiblock)
1260 return vuse;
1262 unsigned int cnt = param_sccvn_max_alias_queries_per_access;
1263 use_oracle = ao_ref_init_from_vn_reference (&ref, set, base_set,
1264 type, operands);
1266 /* Use the alias-oracle to find either the PHI node in this block,
1267 the first VUSE used in this block that is equivalent to vuse or
1268 the first VUSE which definition in this block kills the value. */
1269 if (gimple_code (phi) == GIMPLE_PHI)
1270 e = find_edge (block, phiblock);
1271 else if (use_oracle)
1272 while (cnt > 0
1273 && !stmt_may_clobber_ref_p_1 (phi, &ref))
1275 --cnt;
1276 vuse = gimple_vuse (phi);
1277 phi = SSA_NAME_DEF_STMT (vuse);
1278 if (gimple_bb (phi) != phiblock)
1279 return vuse;
1280 if (gimple_code (phi) == GIMPLE_PHI)
1282 e = find_edge (block, phiblock);
1283 break;
1286 else
1287 return NULL_TREE;
1289 if (e)
1291 if (use_oracle && same_valid)
1293 bitmap visited = NULL;
1294 /* Try to find a vuse that dominates this phi node by skipping
1295 non-clobbering statements. */
1296 vuse = get_continuation_for_phi (phi, &ref, true,
1297 cnt, &visited, false, NULL, NULL);
1298 if (visited)
1299 BITMAP_FREE (visited);
1301 else
1302 vuse = NULL_TREE;
1303 /* If we didn't find any, the value ID can't stay the same. */
1304 if (!vuse && same_valid)
1305 *same_valid = false;
1306 /* ??? We would like to return vuse here as this is the canonical
1307 upmost vdef that this reference is associated with. But during
1308 insertion of the references into the hash tables we only ever
1309 directly insert with their direct gimple_vuse, hence returning
1310 something else would make us not find the other expression. */
1311 return PHI_ARG_DEF (phi, e->dest_idx);
1314 return NULL_TREE;
1317 /* Like bitmap_find_leader, but checks for the value existing in SET1 *or*
1318 SET2 *or* SET3. This is used to avoid making a set consisting of the union
1319 of PA_IN and ANTIC_IN during insert and phi-translation. */
1321 static inline pre_expr
1322 find_leader_in_sets (unsigned int val, bitmap_set_t set1, bitmap_set_t set2,
1323 bitmap_set_t set3 = NULL)
1325 pre_expr result = NULL;
1327 if (set1)
1328 result = bitmap_find_leader (set1, val);
1329 if (!result && set2)
1330 result = bitmap_find_leader (set2, val);
1331 if (!result && set3)
1332 result = bitmap_find_leader (set3, val);
1333 return result;
1336 /* Get the tree type for our PRE expression e. */
1338 static tree
1339 get_expr_type (const pre_expr e)
1341 switch (e->kind)
1343 case NAME:
1344 return TREE_TYPE (PRE_EXPR_NAME (e));
1345 case CONSTANT:
1346 return TREE_TYPE (PRE_EXPR_CONSTANT (e));
1347 case REFERENCE:
1348 return PRE_EXPR_REFERENCE (e)->type;
1349 case NARY:
1350 return PRE_EXPR_NARY (e)->type;
1352 gcc_unreachable ();
1355 /* Get a representative SSA_NAME for a given expression that is available in B.
1356 Since all of our sub-expressions are treated as values, we require
1357 them to be SSA_NAME's for simplicity.
1358 Prior versions of GVNPRE used to use "value handles" here, so that
1359 an expression would be VH.11 + VH.10 instead of d_3 + e_6. In
1360 either case, the operands are really values (IE we do not expect
1361 them to be usable without finding leaders). */
1363 static tree
1364 get_representative_for (const pre_expr e, basic_block b = NULL)
1366 tree name, valnum = NULL_TREE;
1367 unsigned int value_id = get_expr_value_id (e);
1369 switch (e->kind)
1371 case NAME:
1372 return PRE_EXPR_NAME (e);
1373 case CONSTANT:
1374 return PRE_EXPR_CONSTANT (e);
1375 case NARY:
1376 case REFERENCE:
1378 /* Go through all of the expressions representing this value
1379 and pick out an SSA_NAME. */
1380 unsigned int i;
1381 bitmap_iterator bi;
1382 bitmap exprs = value_expressions[value_id];
1383 EXECUTE_IF_SET_IN_BITMAP (exprs, 0, i, bi)
1385 pre_expr rep = expression_for_id (i);
1386 if (rep->kind == NAME)
1388 tree name = PRE_EXPR_NAME (rep);
1389 valnum = VN_INFO (name)->valnum;
1390 gimple *def = SSA_NAME_DEF_STMT (name);
1391 /* We have to return either a new representative or one
1392 that can be used for expression simplification and thus
1393 is available in B. */
1394 if (! b
1395 || gimple_nop_p (def)
1396 || dominated_by_p (CDI_DOMINATORS, b, gimple_bb (def)))
1397 return name;
1399 else if (rep->kind == CONSTANT)
1400 return PRE_EXPR_CONSTANT (rep);
1403 break;
1406 /* If we reached here we couldn't find an SSA_NAME. This can
1407 happen when we've discovered a value that has never appeared in
1408 the program as set to an SSA_NAME, as the result of phi translation.
1409 Create one here.
1410 ??? We should be able to re-use this when we insert the statement
1411 to compute it. */
1412 name = make_temp_ssa_name (get_expr_type (e), gimple_build_nop (), "pretmp");
1413 vn_ssa_aux_t vn_info = VN_INFO (name);
1414 vn_info->value_id = value_id;
1415 vn_info->valnum = valnum ? valnum : name;
1416 /* ??? For now mark this SSA name for release by VN. */
1417 vn_info->needs_insertion = true;
1418 add_to_value (value_id, get_or_alloc_expr_for_name (name));
1419 if (dump_file && (dump_flags & TDF_DETAILS))
1421 fprintf (dump_file, "Created SSA_NAME representative ");
1422 print_generic_expr (dump_file, name);
1423 fprintf (dump_file, " for expression:");
1424 print_pre_expr (dump_file, e);
1425 fprintf (dump_file, " (%04d)\n", value_id);
1428 return name;
1432 static pre_expr
1433 phi_translate (bitmap_set_t, pre_expr, bitmap_set_t, bitmap_set_t, edge);
1435 /* Translate EXPR using phis in PHIBLOCK, so that it has the values of
1436 the phis in PRED. Return NULL if we can't find a leader for each part
1437 of the translated expression. */
1439 static pre_expr
1440 phi_translate_1 (bitmap_set_t dest,
1441 pre_expr expr, bitmap_set_t set1, bitmap_set_t set2, edge e)
1443 basic_block pred = e->src;
1444 basic_block phiblock = e->dest;
1445 location_t expr_loc = expr->loc;
1446 switch (expr->kind)
1448 case NARY:
1450 unsigned int i;
1451 bool changed = false;
1452 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1453 vn_nary_op_t newnary = XALLOCAVAR (struct vn_nary_op_s,
1454 sizeof_vn_nary_op (nary->length));
1455 memcpy (newnary, nary, sizeof_vn_nary_op (nary->length));
1457 for (i = 0; i < newnary->length; i++)
1459 if (TREE_CODE (newnary->op[i]) != SSA_NAME)
1460 continue;
1461 else
1463 pre_expr leader, result;
1464 unsigned int op_val_id = VN_INFO (newnary->op[i])->value_id;
1465 leader = find_leader_in_sets (op_val_id, set1, set2);
1466 result = phi_translate (dest, leader, set1, set2, e);
1467 if (result && result != leader)
1468 /* If op has a leader in the sets we translate make
1469 sure to use the value of the translated expression.
1470 We might need a new representative for that. */
1471 newnary->op[i] = get_representative_for (result, pred);
1472 else if (!result)
1473 return NULL;
1475 changed |= newnary->op[i] != nary->op[i];
1478 if (changed)
1480 pre_expr constant;
1481 unsigned int new_val_id;
1483 PRE_EXPR_NARY (expr) = newnary;
1484 constant = fully_constant_expression (expr);
1485 PRE_EXPR_NARY (expr) = nary;
1486 if (constant != expr)
1488 /* For non-CONSTANTs we have to make sure we can eventually
1489 insert the expression. Which means we need to have a
1490 leader for it. */
1491 if (constant->kind != CONSTANT)
1493 /* Do not allow simplifications to non-constants over
1494 backedges as this will likely result in a loop PHI node
1495 to be inserted and increased register pressure.
1496 See PR77498 - this avoids doing predcoms work in
1497 a less efficient way. */
1498 if (e->flags & EDGE_DFS_BACK)
1500 else
1502 unsigned value_id = get_expr_value_id (constant);
1503 /* We want a leader in ANTIC_OUT or AVAIL_OUT here.
1504 dest has what we computed into ANTIC_OUT sofar
1505 so pick from that - since topological sorting
1506 by sorted_array_from_bitmap_set isn't perfect
1507 we may lose some cases here. */
1508 constant = find_leader_in_sets (value_id, dest,
1509 AVAIL_OUT (pred));
1510 if (constant)
1512 if (dump_file && (dump_flags & TDF_DETAILS))
1514 fprintf (dump_file, "simplifying ");
1515 print_pre_expr (dump_file, expr);
1516 fprintf (dump_file, " translated %d -> %d to ",
1517 phiblock->index, pred->index);
1518 PRE_EXPR_NARY (expr) = newnary;
1519 print_pre_expr (dump_file, expr);
1520 PRE_EXPR_NARY (expr) = nary;
1521 fprintf (dump_file, " to ");
1522 print_pre_expr (dump_file, constant);
1523 fprintf (dump_file, "\n");
1525 return constant;
1529 else
1530 return constant;
1533 /* vn_nary_* do not valueize operands. */
1534 for (i = 0; i < newnary->length; ++i)
1535 if (TREE_CODE (newnary->op[i]) == SSA_NAME)
1536 newnary->op[i] = VN_INFO (newnary->op[i])->valnum;
1537 tree result = vn_nary_op_lookup_pieces (newnary->length,
1538 newnary->opcode,
1539 newnary->type,
1540 &newnary->op[0],
1541 &nary);
1542 if (result && is_gimple_min_invariant (result))
1543 return get_or_alloc_expr_for_constant (result);
1545 if (!nary || nary->predicated_values)
1547 new_val_id = get_next_value_id ();
1548 nary = vn_nary_op_insert_pieces (newnary->length,
1549 newnary->opcode,
1550 newnary->type,
1551 &newnary->op[0],
1552 result, new_val_id);
1554 expr = get_or_alloc_expr_for_nary (nary, expr_loc);
1555 add_to_value (get_expr_value_id (expr), expr);
1557 return expr;
1559 break;
1561 case REFERENCE:
1563 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1564 vec<vn_reference_op_s> operands = ref->operands;
1565 tree vuse = ref->vuse;
1566 tree newvuse = vuse;
1567 vec<vn_reference_op_s> newoperands = vNULL;
1568 bool changed = false, same_valid = true;
1569 unsigned int i, n;
1570 vn_reference_op_t operand;
1571 vn_reference_t newref;
1573 for (i = 0; operands.iterate (i, &operand); i++)
1575 pre_expr opresult;
1576 pre_expr leader;
1577 tree op[3];
1578 tree type = operand->type;
1579 vn_reference_op_s newop = *operand;
1580 op[0] = operand->op0;
1581 op[1] = operand->op1;
1582 op[2] = operand->op2;
1583 for (n = 0; n < 3; ++n)
1585 unsigned int op_val_id;
1586 if (!op[n])
1587 continue;
1588 if (TREE_CODE (op[n]) != SSA_NAME)
1590 /* We can't possibly insert these. */
1591 if (n != 0
1592 && !is_gimple_min_invariant (op[n]))
1593 break;
1594 continue;
1596 op_val_id = VN_INFO (op[n])->value_id;
1597 leader = find_leader_in_sets (op_val_id, set1, set2);
1598 opresult = phi_translate (dest, leader, set1, set2, e);
1599 if (opresult && opresult != leader)
1601 tree name = get_representative_for (opresult);
1602 changed |= name != op[n];
1603 op[n] = name;
1605 else if (!opresult)
1606 break;
1608 if (n != 3)
1610 newoperands.release ();
1611 return NULL;
1613 if (!changed)
1614 continue;
1615 if (!newoperands.exists ())
1616 newoperands = operands.copy ();
1617 /* We may have changed from an SSA_NAME to a constant */
1618 if (newop.opcode == SSA_NAME && TREE_CODE (op[0]) != SSA_NAME)
1619 newop.opcode = TREE_CODE (op[0]);
1620 newop.type = type;
1621 newop.op0 = op[0];
1622 newop.op1 = op[1];
1623 newop.op2 = op[2];
1624 newoperands[i] = newop;
1626 gcc_checking_assert (i == operands.length ());
1628 if (vuse)
1630 newvuse = translate_vuse_through_block (newoperands.exists ()
1631 ? newoperands : operands,
1632 ref->set, ref->base_set,
1633 ref->type,
1634 vuse, phiblock, pred,
1635 changed
1636 ? NULL : &same_valid);
1637 if (newvuse == NULL_TREE)
1639 newoperands.release ();
1640 return NULL;
1644 if (changed || newvuse != vuse)
1646 unsigned int new_val_id;
1648 tree result = vn_reference_lookup_pieces (newvuse, ref->set,
1649 ref->base_set,
1650 ref->type,
1651 newoperands.exists ()
1652 ? newoperands : operands,
1653 &newref, VN_WALK);
1654 if (result)
1655 newoperands.release ();
1657 /* We can always insert constants, so if we have a partial
1658 redundant constant load of another type try to translate it
1659 to a constant of appropriate type. */
1660 if (result && is_gimple_min_invariant (result))
1662 tree tem = result;
1663 if (!useless_type_conversion_p (ref->type, TREE_TYPE (result)))
1665 tem = fold_unary (VIEW_CONVERT_EXPR, ref->type, result);
1666 if (tem && !is_gimple_min_invariant (tem))
1667 tem = NULL_TREE;
1669 if (tem)
1670 return get_or_alloc_expr_for_constant (tem);
1673 /* If we'd have to convert things we would need to validate
1674 if we can insert the translated expression. So fail
1675 here for now - we cannot insert an alias with a different
1676 type in the VN tables either, as that would assert. */
1677 if (result
1678 && !useless_type_conversion_p (ref->type, TREE_TYPE (result)))
1679 return NULL;
1680 else if (!result && newref
1681 && !useless_type_conversion_p (ref->type, newref->type))
1683 newoperands.release ();
1684 return NULL;
1687 if (newref)
1688 new_val_id = newref->value_id;
1689 else
1691 if (changed || !same_valid)
1692 new_val_id = get_next_value_id ();
1693 else
1694 new_val_id = ref->value_id;
1695 if (!newoperands.exists ())
1696 newoperands = operands.copy ();
1697 newref = vn_reference_insert_pieces (newvuse, ref->set,
1698 ref->base_set, ref->type,
1699 newoperands,
1700 result, new_val_id);
1701 newoperands = vNULL;
1703 expr = get_or_alloc_expr_for_reference (newref, expr_loc);
1704 add_to_value (new_val_id, expr);
1706 newoperands.release ();
1707 return expr;
1709 break;
1711 case NAME:
1713 tree name = PRE_EXPR_NAME (expr);
1714 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
1715 /* If the SSA name is defined by a PHI node in this block,
1716 translate it. */
1717 if (gimple_code (def_stmt) == GIMPLE_PHI
1718 && gimple_bb (def_stmt) == phiblock)
1720 tree def = PHI_ARG_DEF (def_stmt, e->dest_idx);
1722 /* Handle constant. */
1723 if (is_gimple_min_invariant (def))
1724 return get_or_alloc_expr_for_constant (def);
1726 return get_or_alloc_expr_for_name (def);
1728 /* Otherwise return it unchanged - it will get removed if its
1729 value is not available in PREDs AVAIL_OUT set of expressions
1730 by the subtraction of TMP_GEN. */
1731 return expr;
1734 default:
1735 gcc_unreachable ();
1739 /* Wrapper around phi_translate_1 providing caching functionality. */
1741 static pre_expr
1742 phi_translate (bitmap_set_t dest, pre_expr expr,
1743 bitmap_set_t set1, bitmap_set_t set2, edge e)
1745 expr_pred_trans_t slot = NULL;
1746 pre_expr phitrans;
1748 if (!expr)
1749 return NULL;
1751 /* Constants contain no values that need translation. */
1752 if (expr->kind == CONSTANT)
1753 return expr;
1755 if (value_id_constant_p (get_expr_value_id (expr)))
1756 return expr;
1758 /* Don't add translations of NAMEs as those are cheap to translate. */
1759 if (expr->kind != NAME)
1761 if (phi_trans_add (&slot, expr, e->src))
1762 return slot->v == 0 ? NULL : expression_for_id (slot->v);
1763 /* Store NULL for the value we want to return in the case of
1764 recursing. */
1765 slot->v = 0;
1768 /* Translate. */
1769 basic_block saved_valueize_bb = vn_context_bb;
1770 vn_context_bb = e->src;
1771 phitrans = phi_translate_1 (dest, expr, set1, set2, e);
1772 vn_context_bb = saved_valueize_bb;
1774 if (slot)
1776 /* We may have reallocated. */
1777 phi_trans_add (&slot, expr, e->src);
1778 if (phitrans)
1779 slot->v = get_expression_id (phitrans);
1780 else
1781 /* Remove failed translations again, they cause insert
1782 iteration to not pick up new opportunities reliably. */
1783 PHI_TRANS_TABLE (e->src)->clear_slot (slot);
1786 return phitrans;
1790 /* For each expression in SET, translate the values through phi nodes
1791 in PHIBLOCK using edge PHIBLOCK->PRED, and store the resulting
1792 expressions in DEST. */
1794 static void
1795 phi_translate_set (bitmap_set_t dest, bitmap_set_t set, edge e)
1797 bitmap_iterator bi;
1798 unsigned int i;
1800 if (gimple_seq_empty_p (phi_nodes (e->dest)))
1802 bitmap_set_copy (dest, set);
1803 return;
1806 /* Allocate the phi-translation cache where we have an idea about
1807 its size. hash-table implementation internals tell us that
1808 allocating the table to fit twice the number of elements will
1809 make sure we do not usually re-allocate. */
1810 if (!PHI_TRANS_TABLE (e->src))
1811 PHI_TRANS_TABLE (e->src) = new hash_table<expr_pred_trans_d>
1812 (2 * bitmap_count_bits (&set->expressions));
1813 FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
1815 pre_expr expr = expression_for_id (i);
1816 pre_expr translated = phi_translate (dest, expr, set, NULL, e);
1817 if (!translated)
1818 continue;
1820 bitmap_insert_into_set (dest, translated);
1824 /* Find the leader for a value (i.e., the name representing that
1825 value) in a given set, and return it. Return NULL if no leader
1826 is found. */
1828 static pre_expr
1829 bitmap_find_leader (bitmap_set_t set, unsigned int val)
1831 if (value_id_constant_p (val))
1832 return constant_value_expressions[-val];
1834 if (bitmap_set_contains_value (set, val))
1836 /* Rather than walk the entire bitmap of expressions, and see
1837 whether any of them has the value we are looking for, we look
1838 at the reverse mapping, which tells us the set of expressions
1839 that have a given value (IE value->expressions with that
1840 value) and see if any of those expressions are in our set.
1841 The number of expressions per value is usually significantly
1842 less than the number of expressions in the set. In fact, for
1843 large testcases, doing it this way is roughly 5-10x faster
1844 than walking the bitmap.
1845 If this is somehow a significant lose for some cases, we can
1846 choose which set to walk based on which set is smaller. */
1847 unsigned int i;
1848 bitmap_iterator bi;
1849 bitmap exprset = value_expressions[val];
1851 if (!exprset->first->next)
1852 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
1853 if (bitmap_bit_p (&set->expressions, i))
1854 return expression_for_id (i);
1856 EXECUTE_IF_AND_IN_BITMAP (exprset, &set->expressions, 0, i, bi)
1857 return expression_for_id (i);
1859 return NULL;
1862 /* Determine if EXPR, a memory expression, is ANTIC_IN at the top of
1863 BLOCK by seeing if it is not killed in the block. Note that we are
1864 only determining whether there is a store that kills it. Because
1865 of the order in which clean iterates over values, we are guaranteed
1866 that altered operands will have caused us to be eliminated from the
1867 ANTIC_IN set already. */
1869 static bool
1870 value_dies_in_block_x (pre_expr expr, basic_block block)
1872 tree vuse = PRE_EXPR_REFERENCE (expr)->vuse;
1873 vn_reference_t refx = PRE_EXPR_REFERENCE (expr);
1874 gimple *def;
1875 gimple_stmt_iterator gsi;
1876 unsigned id = get_expression_id (expr);
1877 bool res = false;
1878 ao_ref ref;
1880 if (!vuse)
1881 return false;
1883 /* Lookup a previously calculated result. */
1884 if (EXPR_DIES (block)
1885 && bitmap_bit_p (EXPR_DIES (block), id * 2))
1886 return bitmap_bit_p (EXPR_DIES (block), id * 2 + 1);
1888 /* A memory expression {e, VUSE} dies in the block if there is a
1889 statement that may clobber e. If, starting statement walk from the
1890 top of the basic block, a statement uses VUSE there can be no kill
1891 inbetween that use and the original statement that loaded {e, VUSE},
1892 so we can stop walking. */
1893 ref.base = NULL_TREE;
1894 for (gsi = gsi_start_bb (block); !gsi_end_p (gsi); gsi_next (&gsi))
1896 tree def_vuse, def_vdef;
1897 def = gsi_stmt (gsi);
1898 def_vuse = gimple_vuse (def);
1899 def_vdef = gimple_vdef (def);
1901 /* Not a memory statement. */
1902 if (!def_vuse)
1903 continue;
1905 /* Not a may-def. */
1906 if (!def_vdef)
1908 /* A load with the same VUSE, we're done. */
1909 if (def_vuse == vuse)
1910 break;
1912 continue;
1915 /* Init ref only if we really need it. */
1916 if (ref.base == NULL_TREE
1917 && !ao_ref_init_from_vn_reference (&ref, refx->set, refx->base_set,
1918 refx->type, refx->operands))
1920 res = true;
1921 break;
1923 /* If the statement may clobber expr, it dies. */
1924 if (stmt_may_clobber_ref_p_1 (def, &ref))
1926 res = true;
1927 break;
1931 /* Remember the result. */
1932 if (!EXPR_DIES (block))
1933 EXPR_DIES (block) = BITMAP_ALLOC (&grand_bitmap_obstack);
1934 bitmap_set_bit (EXPR_DIES (block), id * 2);
1935 if (res)
1936 bitmap_set_bit (EXPR_DIES (block), id * 2 + 1);
1938 return res;
1942 /* Determine if OP is valid in SET1 U SET2, which it is when the union
1943 contains its value-id. */
1945 static bool
1946 op_valid_in_sets (bitmap_set_t set1, bitmap_set_t set2, tree op)
1948 if (op && TREE_CODE (op) == SSA_NAME)
1950 unsigned int value_id = VN_INFO (op)->value_id;
1951 if (!(bitmap_set_contains_value (set1, value_id)
1952 || (set2 && bitmap_set_contains_value (set2, value_id))))
1953 return false;
1955 return true;
1958 /* Determine if the expression EXPR is valid in SET1 U SET2.
1959 ONLY SET2 CAN BE NULL.
1960 This means that we have a leader for each part of the expression
1961 (if it consists of values), or the expression is an SSA_NAME.
1962 For loads/calls, we also see if the vuse is killed in this block. */
1964 static bool
1965 valid_in_sets (bitmap_set_t set1, bitmap_set_t set2, pre_expr expr)
1967 switch (expr->kind)
1969 case NAME:
1970 /* By construction all NAMEs are available. Non-available
1971 NAMEs are removed by subtracting TMP_GEN from the sets. */
1972 return true;
1973 case NARY:
1975 unsigned int i;
1976 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1977 for (i = 0; i < nary->length; i++)
1978 if (!op_valid_in_sets (set1, set2, nary->op[i]))
1979 return false;
1980 return true;
1982 break;
1983 case REFERENCE:
1985 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1986 vn_reference_op_t vro;
1987 unsigned int i;
1989 FOR_EACH_VEC_ELT (ref->operands, i, vro)
1991 if (!op_valid_in_sets (set1, set2, vro->op0)
1992 || !op_valid_in_sets (set1, set2, vro->op1)
1993 || !op_valid_in_sets (set1, set2, vro->op2))
1994 return false;
1996 return true;
1998 default:
1999 gcc_unreachable ();
2003 /* Clean the set of expressions SET1 that are no longer valid in SET1 or SET2.
2004 This means expressions that are made up of values we have no leaders for
2005 in SET1 or SET2. */
2007 static void
2008 clean (bitmap_set_t set1, bitmap_set_t set2 = NULL)
2010 vec<pre_expr> exprs = sorted_array_from_bitmap_set (set1);
2011 pre_expr expr;
2012 int i;
2014 FOR_EACH_VEC_ELT (exprs, i, expr)
2016 if (!valid_in_sets (set1, set2, expr))
2018 unsigned int val = get_expr_value_id (expr);
2019 bitmap_clear_bit (&set1->expressions, get_expression_id (expr));
2020 /* We are entered with possibly multiple expressions for a value
2021 so before removing a value from the set see if there's an
2022 expression for it left. */
2023 if (! bitmap_find_leader (set1, val))
2024 bitmap_clear_bit (&set1->values, val);
2027 exprs.release ();
2029 if (flag_checking)
2031 unsigned j;
2032 bitmap_iterator bi;
2033 FOR_EACH_EXPR_ID_IN_SET (set1, j, bi)
2034 gcc_assert (valid_in_sets (set1, set2, expression_for_id (j)));
2038 /* Clean the set of expressions that are no longer valid in SET because
2039 they are clobbered in BLOCK or because they trap and may not be executed. */
2041 static void
2042 prune_clobbered_mems (bitmap_set_t set, basic_block block)
2044 bitmap_iterator bi;
2045 unsigned i;
2046 unsigned to_remove = -1U;
2047 bool any_removed = false;
2049 FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
2051 /* Remove queued expr. */
2052 if (to_remove != -1U)
2054 bitmap_clear_bit (&set->expressions, to_remove);
2055 any_removed = true;
2056 to_remove = -1U;
2059 pre_expr expr = expression_for_id (i);
2060 if (expr->kind == REFERENCE)
2062 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
2063 if (ref->vuse)
2065 gimple *def_stmt = SSA_NAME_DEF_STMT (ref->vuse);
2066 if (!gimple_nop_p (def_stmt)
2067 && ((gimple_bb (def_stmt) != block
2068 && !dominated_by_p (CDI_DOMINATORS,
2069 block, gimple_bb (def_stmt)))
2070 || (gimple_bb (def_stmt) == block
2071 && value_dies_in_block_x (expr, block))))
2072 to_remove = i;
2074 /* If the REFERENCE may trap make sure the block does not contain
2075 a possible exit point.
2076 ??? This is overly conservative if we translate AVAIL_OUT
2077 as the available expression might be after the exit point. */
2078 if (BB_MAY_NOTRETURN (block)
2079 && vn_reference_may_trap (ref))
2080 to_remove = i;
2082 else if (expr->kind == NARY)
2084 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
2085 /* If the NARY may trap make sure the block does not contain
2086 a possible exit point.
2087 ??? This is overly conservative if we translate AVAIL_OUT
2088 as the available expression might be after the exit point. */
2089 if (BB_MAY_NOTRETURN (block)
2090 && vn_nary_may_trap (nary))
2091 to_remove = i;
2095 /* Remove queued expr. */
2096 if (to_remove != -1U)
2098 bitmap_clear_bit (&set->expressions, to_remove);
2099 any_removed = true;
2102 /* Above we only removed expressions, now clean the set of values
2103 which no longer have any corresponding expression. We cannot
2104 clear the value at the time we remove an expression since there
2105 may be multiple expressions per value.
2106 If we'd queue possibly to be removed values we could use
2107 the bitmap_find_leader way to see if there's still an expression
2108 for it. For some ratio of to be removed values and number of
2109 values/expressions in the set this might be faster than rebuilding
2110 the value-set. */
2111 if (any_removed)
2113 bitmap_clear (&set->values);
2114 FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
2116 pre_expr expr = expression_for_id (i);
2117 unsigned int value_id = get_expr_value_id (expr);
2118 bitmap_set_bit (&set->values, value_id);
2123 /* Compute the ANTIC set for BLOCK.
2125 If succs(BLOCK) > 1 then
2126 ANTIC_OUT[BLOCK] = intersection of ANTIC_IN[b] for all succ(BLOCK)
2127 else if succs(BLOCK) == 1 then
2128 ANTIC_OUT[BLOCK] = phi_translate (ANTIC_IN[succ(BLOCK)])
2130 ANTIC_IN[BLOCK] = clean(ANTIC_OUT[BLOCK] U EXP_GEN[BLOCK] - TMP_GEN[BLOCK])
2132 Note that clean() is deferred until after the iteration. */
2134 static bool
2135 compute_antic_aux (basic_block block, bool block_has_abnormal_pred_edge)
2137 bitmap_set_t S, old, ANTIC_OUT;
2138 edge e;
2139 edge_iterator ei;
2141 bool was_visited = BB_VISITED (block);
2142 bool changed = ! BB_VISITED (block);
2143 BB_VISITED (block) = 1;
2144 old = ANTIC_OUT = S = NULL;
2146 /* If any edges from predecessors are abnormal, antic_in is empty,
2147 so do nothing. */
2148 if (block_has_abnormal_pred_edge)
2149 goto maybe_dump_sets;
2151 old = ANTIC_IN (block);
2152 ANTIC_OUT = bitmap_set_new ();
2154 /* If the block has no successors, ANTIC_OUT is empty. */
2155 if (EDGE_COUNT (block->succs) == 0)
2157 /* If we have one successor, we could have some phi nodes to
2158 translate through. */
2159 else if (single_succ_p (block))
2161 e = single_succ_edge (block);
2162 gcc_assert (BB_VISITED (e->dest));
2163 phi_translate_set (ANTIC_OUT, ANTIC_IN (e->dest), e);
2165 /* If we have multiple successors, we take the intersection of all of
2166 them. Note that in the case of loop exit phi nodes, we may have
2167 phis to translate through. */
2168 else
2170 size_t i;
2171 edge first = NULL;
2173 auto_vec<edge> worklist (EDGE_COUNT (block->succs));
2174 FOR_EACH_EDGE (e, ei, block->succs)
2176 if (!first
2177 && BB_VISITED (e->dest))
2178 first = e;
2179 else if (BB_VISITED (e->dest))
2180 worklist.quick_push (e);
2181 else
2183 /* Unvisited successors get their ANTIC_IN replaced by the
2184 maximal set to arrive at a maximum ANTIC_IN solution.
2185 We can ignore them in the intersection operation and thus
2186 need not explicitely represent that maximum solution. */
2187 if (dump_file && (dump_flags & TDF_DETAILS))
2188 fprintf (dump_file, "ANTIC_IN is MAX on %d->%d\n",
2189 e->src->index, e->dest->index);
2193 /* Of multiple successors we have to have visited one already
2194 which is guaranteed by iteration order. */
2195 gcc_assert (first != NULL);
2197 phi_translate_set (ANTIC_OUT, ANTIC_IN (first->dest), first);
2199 /* If we have multiple successors we need to intersect the ANTIC_OUT
2200 sets. For values that's a simple intersection but for
2201 expressions it is a union. Given we want to have a single
2202 expression per value in our sets we have to canonicalize.
2203 Avoid randomness and running into cycles like for PR82129 and
2204 canonicalize the expression we choose to the one with the
2205 lowest id. This requires we actually compute the union first. */
2206 FOR_EACH_VEC_ELT (worklist, i, e)
2208 if (!gimple_seq_empty_p (phi_nodes (e->dest)))
2210 bitmap_set_t tmp = bitmap_set_new ();
2211 phi_translate_set (tmp, ANTIC_IN (e->dest), e);
2212 bitmap_and_into (&ANTIC_OUT->values, &tmp->values);
2213 bitmap_ior_into (&ANTIC_OUT->expressions, &tmp->expressions);
2214 bitmap_set_free (tmp);
2216 else
2218 bitmap_and_into (&ANTIC_OUT->values, &ANTIC_IN (e->dest)->values);
2219 bitmap_ior_into (&ANTIC_OUT->expressions,
2220 &ANTIC_IN (e->dest)->expressions);
2223 if (! worklist.is_empty ())
2225 /* Prune expressions not in the value set. */
2226 bitmap_iterator bi;
2227 unsigned int i;
2228 unsigned int to_clear = -1U;
2229 FOR_EACH_EXPR_ID_IN_SET (ANTIC_OUT, i, bi)
2231 if (to_clear != -1U)
2233 bitmap_clear_bit (&ANTIC_OUT->expressions, to_clear);
2234 to_clear = -1U;
2236 pre_expr expr = expression_for_id (i);
2237 unsigned int value_id = get_expr_value_id (expr);
2238 if (!bitmap_bit_p (&ANTIC_OUT->values, value_id))
2239 to_clear = i;
2241 if (to_clear != -1U)
2242 bitmap_clear_bit (&ANTIC_OUT->expressions, to_clear);
2246 /* Prune expressions that are clobbered in block and thus become
2247 invalid if translated from ANTIC_OUT to ANTIC_IN. */
2248 prune_clobbered_mems (ANTIC_OUT, block);
2250 /* Generate ANTIC_OUT - TMP_GEN. */
2251 S = bitmap_set_subtract_expressions (ANTIC_OUT, TMP_GEN (block));
2253 /* Start ANTIC_IN with EXP_GEN - TMP_GEN. */
2254 ANTIC_IN (block) = bitmap_set_subtract_expressions (EXP_GEN (block),
2255 TMP_GEN (block));
2257 /* Then union in the ANTIC_OUT - TMP_GEN values,
2258 to get ANTIC_OUT U EXP_GEN - TMP_GEN */
2259 bitmap_ior_into (&ANTIC_IN (block)->values, &S->values);
2260 bitmap_ior_into (&ANTIC_IN (block)->expressions, &S->expressions);
2262 /* clean (ANTIC_IN (block)) is defered to after the iteration converged
2263 because it can cause non-convergence, see for example PR81181. */
2265 /* Intersect ANTIC_IN with the old ANTIC_IN. This is required until
2266 we properly represent the maximum expression set, thus not prune
2267 values without expressions during the iteration. */
2268 if (was_visited
2269 && bitmap_and_into (&ANTIC_IN (block)->values, &old->values))
2271 if (dump_file && (dump_flags & TDF_DETAILS))
2272 fprintf (dump_file, "warning: intersecting with old ANTIC_IN "
2273 "shrinks the set\n");
2274 /* Prune expressions not in the value set. */
2275 bitmap_iterator bi;
2276 unsigned int i;
2277 unsigned int to_clear = -1U;
2278 FOR_EACH_EXPR_ID_IN_SET (ANTIC_IN (block), i, bi)
2280 if (to_clear != -1U)
2282 bitmap_clear_bit (&ANTIC_IN (block)->expressions, to_clear);
2283 to_clear = -1U;
2285 pre_expr expr = expression_for_id (i);
2286 unsigned int value_id = get_expr_value_id (expr);
2287 if (!bitmap_bit_p (&ANTIC_IN (block)->values, value_id))
2288 to_clear = i;
2290 if (to_clear != -1U)
2291 bitmap_clear_bit (&ANTIC_IN (block)->expressions, to_clear);
2294 if (!bitmap_set_equal (old, ANTIC_IN (block)))
2295 changed = true;
2297 maybe_dump_sets:
2298 if (dump_file && (dump_flags & TDF_DETAILS))
2300 if (ANTIC_OUT)
2301 print_bitmap_set (dump_file, ANTIC_OUT, "ANTIC_OUT", block->index);
2303 if (changed)
2304 fprintf (dump_file, "[changed] ");
2305 print_bitmap_set (dump_file, ANTIC_IN (block), "ANTIC_IN",
2306 block->index);
2308 if (S)
2309 print_bitmap_set (dump_file, S, "S", block->index);
2311 if (old)
2312 bitmap_set_free (old);
2313 if (S)
2314 bitmap_set_free (S);
2315 if (ANTIC_OUT)
2316 bitmap_set_free (ANTIC_OUT);
2317 return changed;
2320 /* Compute PARTIAL_ANTIC for BLOCK.
2322 If succs(BLOCK) > 1 then
2323 PA_OUT[BLOCK] = value wise union of PA_IN[b] + all ANTIC_IN not
2324 in ANTIC_OUT for all succ(BLOCK)
2325 else if succs(BLOCK) == 1 then
2326 PA_OUT[BLOCK] = phi_translate (PA_IN[succ(BLOCK)])
2328 PA_IN[BLOCK] = clean(PA_OUT[BLOCK] - TMP_GEN[BLOCK] - ANTIC_IN[BLOCK])
2331 static void
2332 compute_partial_antic_aux (basic_block block,
2333 bool block_has_abnormal_pred_edge)
2335 bitmap_set_t old_PA_IN;
2336 bitmap_set_t PA_OUT;
2337 edge e;
2338 edge_iterator ei;
2339 unsigned long max_pa = param_max_partial_antic_length;
2341 old_PA_IN = PA_OUT = NULL;
2343 /* If any edges from predecessors are abnormal, antic_in is empty,
2344 so do nothing. */
2345 if (block_has_abnormal_pred_edge)
2346 goto maybe_dump_sets;
2348 /* If there are too many partially anticipatable values in the
2349 block, phi_translate_set can take an exponential time: stop
2350 before the translation starts. */
2351 if (max_pa
2352 && single_succ_p (block)
2353 && bitmap_count_bits (&PA_IN (single_succ (block))->values) > max_pa)
2354 goto maybe_dump_sets;
2356 old_PA_IN = PA_IN (block);
2357 PA_OUT = bitmap_set_new ();
2359 /* If the block has no successors, ANTIC_OUT is empty. */
2360 if (EDGE_COUNT (block->succs) == 0)
2362 /* If we have one successor, we could have some phi nodes to
2363 translate through. Note that we can't phi translate across DFS
2364 back edges in partial antic, because it uses a union operation on
2365 the successors. For recurrences like IV's, we will end up
2366 generating a new value in the set on each go around (i + 3 (VH.1)
2367 VH.1 + 1 (VH.2), VH.2 + 1 (VH.3), etc), forever. */
2368 else if (single_succ_p (block))
2370 e = single_succ_edge (block);
2371 if (!(e->flags & EDGE_DFS_BACK))
2372 phi_translate_set (PA_OUT, PA_IN (e->dest), e);
2374 /* If we have multiple successors, we take the union of all of
2375 them. */
2376 else
2378 size_t i;
2380 auto_vec<edge> worklist (EDGE_COUNT (block->succs));
2381 FOR_EACH_EDGE (e, ei, block->succs)
2383 if (e->flags & EDGE_DFS_BACK)
2384 continue;
2385 worklist.quick_push (e);
2387 if (worklist.length () > 0)
2389 FOR_EACH_VEC_ELT (worklist, i, e)
2391 unsigned int i;
2392 bitmap_iterator bi;
2394 FOR_EACH_EXPR_ID_IN_SET (ANTIC_IN (e->dest), i, bi)
2395 bitmap_value_insert_into_set (PA_OUT,
2396 expression_for_id (i));
2397 if (!gimple_seq_empty_p (phi_nodes (e->dest)))
2399 bitmap_set_t pa_in = bitmap_set_new ();
2400 phi_translate_set (pa_in, PA_IN (e->dest), e);
2401 FOR_EACH_EXPR_ID_IN_SET (pa_in, i, bi)
2402 bitmap_value_insert_into_set (PA_OUT,
2403 expression_for_id (i));
2404 bitmap_set_free (pa_in);
2406 else
2407 FOR_EACH_EXPR_ID_IN_SET (PA_IN (e->dest), i, bi)
2408 bitmap_value_insert_into_set (PA_OUT,
2409 expression_for_id (i));
2414 /* Prune expressions that are clobbered in block and thus become
2415 invalid if translated from PA_OUT to PA_IN. */
2416 prune_clobbered_mems (PA_OUT, block);
2418 /* PA_IN starts with PA_OUT - TMP_GEN.
2419 Then we subtract things from ANTIC_IN. */
2420 PA_IN (block) = bitmap_set_subtract_expressions (PA_OUT, TMP_GEN (block));
2422 /* For partial antic, we want to put back in the phi results, since
2423 we will properly avoid making them partially antic over backedges. */
2424 bitmap_ior_into (&PA_IN (block)->values, &PHI_GEN (block)->values);
2425 bitmap_ior_into (&PA_IN (block)->expressions, &PHI_GEN (block)->expressions);
2427 /* PA_IN[block] = PA_IN[block] - ANTIC_IN[block] */
2428 bitmap_set_subtract_values (PA_IN (block), ANTIC_IN (block));
2430 clean (PA_IN (block), ANTIC_IN (block));
2432 maybe_dump_sets:
2433 if (dump_file && (dump_flags & TDF_DETAILS))
2435 if (PA_OUT)
2436 print_bitmap_set (dump_file, PA_OUT, "PA_OUT", block->index);
2438 print_bitmap_set (dump_file, PA_IN (block), "PA_IN", block->index);
2440 if (old_PA_IN)
2441 bitmap_set_free (old_PA_IN);
2442 if (PA_OUT)
2443 bitmap_set_free (PA_OUT);
2446 /* Compute ANTIC and partial ANTIC sets. */
2448 static void
2449 compute_antic (void)
2451 bool changed = true;
2452 int num_iterations = 0;
2453 basic_block block;
2454 int i;
2455 edge_iterator ei;
2456 edge e;
2458 /* If any predecessor edges are abnormal, we punt, so antic_in is empty.
2459 We pre-build the map of blocks with incoming abnormal edges here. */
2460 auto_sbitmap has_abnormal_preds (last_basic_block_for_fn (cfun));
2461 bitmap_clear (has_abnormal_preds);
2463 FOR_ALL_BB_FN (block, cfun)
2465 BB_VISITED (block) = 0;
2467 FOR_EACH_EDGE (e, ei, block->preds)
2468 if (e->flags & EDGE_ABNORMAL)
2470 bitmap_set_bit (has_abnormal_preds, block->index);
2471 break;
2474 /* While we are here, give empty ANTIC_IN sets to each block. */
2475 ANTIC_IN (block) = bitmap_set_new ();
2476 if (do_partial_partial)
2477 PA_IN (block) = bitmap_set_new ();
2480 /* At the exit block we anticipate nothing. */
2481 BB_VISITED (EXIT_BLOCK_PTR_FOR_FN (cfun)) = 1;
2483 /* For ANTIC computation we need a postorder that also guarantees that
2484 a block with a single successor is visited after its successor.
2485 RPO on the inverted CFG has this property. */
2486 auto_vec<int, 20> postorder;
2487 inverted_post_order_compute (&postorder);
2489 auto_sbitmap worklist (last_basic_block_for_fn (cfun) + 1);
2490 bitmap_clear (worklist);
2491 FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR_FOR_FN (cfun)->preds)
2492 bitmap_set_bit (worklist, e->src->index);
2493 while (changed)
2495 if (dump_file && (dump_flags & TDF_DETAILS))
2496 fprintf (dump_file, "Starting iteration %d\n", num_iterations);
2497 /* ??? We need to clear our PHI translation cache here as the
2498 ANTIC sets shrink and we restrict valid translations to
2499 those having operands with leaders in ANTIC. Same below
2500 for PA ANTIC computation. */
2501 num_iterations++;
2502 changed = false;
2503 for (i = postorder.length () - 1; i >= 0; i--)
2505 if (bitmap_bit_p (worklist, postorder[i]))
2507 basic_block block = BASIC_BLOCK_FOR_FN (cfun, postorder[i]);
2508 bitmap_clear_bit (worklist, block->index);
2509 if (compute_antic_aux (block,
2510 bitmap_bit_p (has_abnormal_preds,
2511 block->index)))
2513 FOR_EACH_EDGE (e, ei, block->preds)
2514 bitmap_set_bit (worklist, e->src->index);
2515 changed = true;
2519 /* Theoretically possible, but *highly* unlikely. */
2520 gcc_checking_assert (num_iterations < 500);
2523 /* We have to clean after the dataflow problem converged as cleaning
2524 can cause non-convergence because it is based on expressions
2525 rather than values. */
2526 FOR_EACH_BB_FN (block, cfun)
2527 clean (ANTIC_IN (block));
2529 statistics_histogram_event (cfun, "compute_antic iterations",
2530 num_iterations);
2532 if (do_partial_partial)
2534 /* For partial antic we ignore backedges and thus we do not need
2535 to perform any iteration when we process blocks in postorder. */
2536 for (i = postorder.length () - 1; i >= 0; i--)
2538 basic_block block = BASIC_BLOCK_FOR_FN (cfun, postorder[i]);
2539 compute_partial_antic_aux (block,
2540 bitmap_bit_p (has_abnormal_preds,
2541 block->index));
2547 /* Inserted expressions are placed onto this worklist, which is used
2548 for performing quick dead code elimination of insertions we made
2549 that didn't turn out to be necessary. */
2550 static bitmap inserted_exprs;
2552 /* The actual worker for create_component_ref_by_pieces. */
2554 static tree
2555 create_component_ref_by_pieces_1 (basic_block block, vn_reference_t ref,
2556 unsigned int *operand, gimple_seq *stmts)
2558 vn_reference_op_t currop = &ref->operands[*operand];
2559 tree genop;
2560 ++*operand;
2561 switch (currop->opcode)
2563 case CALL_EXPR:
2564 gcc_unreachable ();
2566 case MEM_REF:
2568 tree baseop = create_component_ref_by_pieces_1 (block, ref, operand,
2569 stmts);
2570 if (!baseop)
2571 return NULL_TREE;
2572 tree offset = currop->op0;
2573 if (TREE_CODE (baseop) == ADDR_EXPR
2574 && handled_component_p (TREE_OPERAND (baseop, 0)))
2576 poly_int64 off;
2577 tree base;
2578 base = get_addr_base_and_unit_offset (TREE_OPERAND (baseop, 0),
2579 &off);
2580 gcc_assert (base);
2581 offset = int_const_binop (PLUS_EXPR, offset,
2582 build_int_cst (TREE_TYPE (offset),
2583 off));
2584 baseop = build_fold_addr_expr (base);
2586 genop = build2 (MEM_REF, currop->type, baseop, offset);
2587 MR_DEPENDENCE_CLIQUE (genop) = currop->clique;
2588 MR_DEPENDENCE_BASE (genop) = currop->base;
2589 REF_REVERSE_STORAGE_ORDER (genop) = currop->reverse;
2590 return genop;
2593 case TARGET_MEM_REF:
2595 tree genop0 = NULL_TREE, genop1 = NULL_TREE;
2596 vn_reference_op_t nextop = &ref->operands[(*operand)++];
2597 tree baseop = create_component_ref_by_pieces_1 (block, ref, operand,
2598 stmts);
2599 if (!baseop)
2600 return NULL_TREE;
2601 if (currop->op0)
2603 genop0 = find_or_generate_expression (block, currop->op0, stmts);
2604 if (!genop0)
2605 return NULL_TREE;
2607 if (nextop->op0)
2609 genop1 = find_or_generate_expression (block, nextop->op0, stmts);
2610 if (!genop1)
2611 return NULL_TREE;
2613 genop = build5 (TARGET_MEM_REF, currop->type,
2614 baseop, currop->op2, genop0, currop->op1, genop1);
2616 MR_DEPENDENCE_CLIQUE (genop) = currop->clique;
2617 MR_DEPENDENCE_BASE (genop) = currop->base;
2618 return genop;
2621 case ADDR_EXPR:
2622 if (currop->op0)
2624 gcc_assert (is_gimple_min_invariant (currop->op0));
2625 return currop->op0;
2627 /* Fallthrough. */
2628 case REALPART_EXPR:
2629 case IMAGPART_EXPR:
2630 case VIEW_CONVERT_EXPR:
2632 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2633 stmts);
2634 if (!genop0)
2635 return NULL_TREE;
2636 return fold_build1 (currop->opcode, currop->type, genop0);
2639 case WITH_SIZE_EXPR:
2641 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2642 stmts);
2643 if (!genop0)
2644 return NULL_TREE;
2645 tree genop1 = find_or_generate_expression (block, currop->op0, stmts);
2646 if (!genop1)
2647 return NULL_TREE;
2648 return fold_build2 (currop->opcode, currop->type, genop0, genop1);
2651 case BIT_FIELD_REF:
2653 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2654 stmts);
2655 if (!genop0)
2656 return NULL_TREE;
2657 tree op1 = currop->op0;
2658 tree op2 = currop->op1;
2659 tree t = build3 (BIT_FIELD_REF, currop->type, genop0, op1, op2);
2660 REF_REVERSE_STORAGE_ORDER (t) = currop->reverse;
2661 return fold (t);
2664 /* For array ref vn_reference_op's, operand 1 of the array ref
2665 is op0 of the reference op and operand 3 of the array ref is
2666 op1. */
2667 case ARRAY_RANGE_REF:
2668 case ARRAY_REF:
2670 tree genop0;
2671 tree genop1 = currop->op0;
2672 tree genop2 = currop->op1;
2673 tree genop3 = currop->op2;
2674 genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2675 stmts);
2676 if (!genop0)
2677 return NULL_TREE;
2678 genop1 = find_or_generate_expression (block, genop1, stmts);
2679 if (!genop1)
2680 return NULL_TREE;
2681 if (genop2)
2683 tree domain_type = TYPE_DOMAIN (TREE_TYPE (genop0));
2684 /* Drop zero minimum index if redundant. */
2685 if (integer_zerop (genop2)
2686 && (!domain_type
2687 || integer_zerop (TYPE_MIN_VALUE (domain_type))))
2688 genop2 = NULL_TREE;
2689 else
2691 genop2 = find_or_generate_expression (block, genop2, stmts);
2692 if (!genop2)
2693 return NULL_TREE;
2696 if (genop3)
2698 tree elmt_type = TREE_TYPE (TREE_TYPE (genop0));
2699 /* We can't always put a size in units of the element alignment
2700 here as the element alignment may be not visible. See
2701 PR43783. Simply drop the element size for constant
2702 sizes. */
2703 if (TREE_CODE (genop3) == INTEGER_CST
2704 && TREE_CODE (TYPE_SIZE_UNIT (elmt_type)) == INTEGER_CST
2705 && wi::eq_p (wi::to_offset (TYPE_SIZE_UNIT (elmt_type)),
2706 (wi::to_offset (genop3)
2707 * vn_ref_op_align_unit (currop))))
2708 genop3 = NULL_TREE;
2709 else
2711 genop3 = find_or_generate_expression (block, genop3, stmts);
2712 if (!genop3)
2713 return NULL_TREE;
2716 return build4 (currop->opcode, currop->type, genop0, genop1,
2717 genop2, genop3);
2719 case COMPONENT_REF:
2721 tree op0;
2722 tree op1;
2723 tree genop2 = currop->op1;
2724 op0 = create_component_ref_by_pieces_1 (block, ref, operand, stmts);
2725 if (!op0)
2726 return NULL_TREE;
2727 /* op1 should be a FIELD_DECL, which are represented by themselves. */
2728 op1 = currop->op0;
2729 if (genop2)
2731 genop2 = find_or_generate_expression (block, genop2, stmts);
2732 if (!genop2)
2733 return NULL_TREE;
2735 return fold_build3 (COMPONENT_REF, TREE_TYPE (op1), op0, op1, genop2);
2738 case SSA_NAME:
2740 genop = find_or_generate_expression (block, currop->op0, stmts);
2741 return genop;
2743 case STRING_CST:
2744 case INTEGER_CST:
2745 case POLY_INT_CST:
2746 case COMPLEX_CST:
2747 case VECTOR_CST:
2748 case REAL_CST:
2749 case CONSTRUCTOR:
2750 case VAR_DECL:
2751 case PARM_DECL:
2752 case CONST_DECL:
2753 case RESULT_DECL:
2754 case FUNCTION_DECL:
2755 return currop->op0;
2757 default:
2758 gcc_unreachable ();
2762 /* For COMPONENT_REF's and ARRAY_REF's, we can't have any intermediates for the
2763 COMPONENT_REF or MEM_REF or ARRAY_REF portion, because we'd end up with
2764 trying to rename aggregates into ssa form directly, which is a no no.
2766 Thus, this routine doesn't create temporaries, it just builds a
2767 single access expression for the array, calling
2768 find_or_generate_expression to build the innermost pieces.
2770 This function is a subroutine of create_expression_by_pieces, and
2771 should not be called on it's own unless you really know what you
2772 are doing. */
2774 static tree
2775 create_component_ref_by_pieces (basic_block block, vn_reference_t ref,
2776 gimple_seq *stmts)
2778 unsigned int op = 0;
2779 return create_component_ref_by_pieces_1 (block, ref, &op, stmts);
2782 /* Find a simple leader for an expression, or generate one using
2783 create_expression_by_pieces from a NARY expression for the value.
2784 BLOCK is the basic_block we are looking for leaders in.
2785 OP is the tree expression to find a leader for or generate.
2786 Returns the leader or NULL_TREE on failure. */
2788 static tree
2789 find_or_generate_expression (basic_block block, tree op, gimple_seq *stmts)
2791 pre_expr expr = get_or_alloc_expr_for (op);
2792 unsigned int lookfor = get_expr_value_id (expr);
2793 pre_expr leader = bitmap_find_leader (AVAIL_OUT (block), lookfor);
2794 if (leader)
2796 if (leader->kind == NAME)
2797 return PRE_EXPR_NAME (leader);
2798 else if (leader->kind == CONSTANT)
2799 return PRE_EXPR_CONSTANT (leader);
2801 /* Defer. */
2802 return NULL_TREE;
2805 /* It must be a complex expression, so generate it recursively. Note
2806 that this is only necessary to handle gcc.dg/tree-ssa/ssa-pre28.c
2807 where the insert algorithm fails to insert a required expression. */
2808 bitmap exprset = value_expressions[lookfor];
2809 bitmap_iterator bi;
2810 unsigned int i;
2811 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
2813 pre_expr temp = expression_for_id (i);
2814 /* We cannot insert random REFERENCE expressions at arbitrary
2815 places. We can insert NARYs which eventually re-materializes
2816 its operand values. */
2817 if (temp->kind == NARY)
2818 return create_expression_by_pieces (block, temp, stmts,
2819 get_expr_type (expr));
2822 /* Defer. */
2823 return NULL_TREE;
2826 /* Create an expression in pieces, so that we can handle very complex
2827 expressions that may be ANTIC, but not necessary GIMPLE.
2828 BLOCK is the basic block the expression will be inserted into,
2829 EXPR is the expression to insert (in value form)
2830 STMTS is a statement list to append the necessary insertions into.
2832 This function will die if we hit some value that shouldn't be
2833 ANTIC but is (IE there is no leader for it, or its components).
2834 The function returns NULL_TREE in case a different antic expression
2835 has to be inserted first.
2836 This function may also generate expressions that are themselves
2837 partially or fully redundant. Those that are will be either made
2838 fully redundant during the next iteration of insert (for partially
2839 redundant ones), or eliminated by eliminate (for fully redundant
2840 ones). */
2842 static tree
2843 create_expression_by_pieces (basic_block block, pre_expr expr,
2844 gimple_seq *stmts, tree type)
2846 tree name;
2847 tree folded;
2848 gimple_seq forced_stmts = NULL;
2849 unsigned int value_id;
2850 gimple_stmt_iterator gsi;
2851 tree exprtype = type ? type : get_expr_type (expr);
2852 pre_expr nameexpr;
2853 gassign *newstmt;
2855 switch (expr->kind)
2857 /* We may hit the NAME/CONSTANT case if we have to convert types
2858 that value numbering saw through. */
2859 case NAME:
2860 folded = PRE_EXPR_NAME (expr);
2861 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (folded))
2862 return NULL_TREE;
2863 if (useless_type_conversion_p (exprtype, TREE_TYPE (folded)))
2864 return folded;
2865 break;
2866 case CONSTANT:
2868 folded = PRE_EXPR_CONSTANT (expr);
2869 tree tem = fold_convert (exprtype, folded);
2870 if (is_gimple_min_invariant (tem))
2871 return tem;
2872 break;
2874 case REFERENCE:
2875 if (PRE_EXPR_REFERENCE (expr)->operands[0].opcode == CALL_EXPR)
2877 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
2878 unsigned int operand = 1;
2879 vn_reference_op_t currop = &ref->operands[0];
2880 tree sc = NULL_TREE;
2881 tree fn = find_or_generate_expression (block, currop->op0, stmts);
2882 if (!fn)
2883 return NULL_TREE;
2884 if (currop->op1)
2886 sc = find_or_generate_expression (block, currop->op1, stmts);
2887 if (!sc)
2888 return NULL_TREE;
2890 auto_vec<tree> args (ref->operands.length () - 1);
2891 while (operand < ref->operands.length ())
2893 tree arg = create_component_ref_by_pieces_1 (block, ref,
2894 &operand, stmts);
2895 if (!arg)
2896 return NULL_TREE;
2897 args.quick_push (arg);
2899 gcall *call = gimple_build_call_vec (fn, args);
2900 gimple_set_location (call, expr->loc);
2901 gimple_call_set_fntype (call, currop->type);
2902 if (sc)
2903 gimple_call_set_chain (call, sc);
2904 tree forcedname = make_ssa_name (TREE_TYPE (currop->type));
2905 gimple_call_set_lhs (call, forcedname);
2906 /* There's no CCP pass after PRE which would re-compute alignment
2907 information so make sure we re-materialize this here. */
2908 if (gimple_call_builtin_p (call, BUILT_IN_ASSUME_ALIGNED)
2909 && args.length () - 2 <= 1
2910 && tree_fits_uhwi_p (args[1])
2911 && (args.length () != 3 || tree_fits_uhwi_p (args[2])))
2913 unsigned HOST_WIDE_INT halign = tree_to_uhwi (args[1]);
2914 unsigned HOST_WIDE_INT hmisalign
2915 = args.length () == 3 ? tree_to_uhwi (args[2]) : 0;
2916 if ((halign & (halign - 1)) == 0
2917 && (hmisalign & ~(halign - 1)) == 0
2918 && (unsigned int)halign != 0)
2919 set_ptr_info_alignment (get_ptr_info (forcedname),
2920 halign, hmisalign);
2922 gimple_set_vuse (call, BB_LIVE_VOP_ON_EXIT (block));
2923 gimple_seq_add_stmt_without_update (&forced_stmts, call);
2924 folded = forcedname;
2926 else
2928 folded = create_component_ref_by_pieces (block,
2929 PRE_EXPR_REFERENCE (expr),
2930 stmts);
2931 if (!folded)
2932 return NULL_TREE;
2933 name = make_temp_ssa_name (exprtype, NULL, "pretmp");
2934 newstmt = gimple_build_assign (name, folded);
2935 gimple_set_location (newstmt, expr->loc);
2936 gimple_seq_add_stmt_without_update (&forced_stmts, newstmt);
2937 gimple_set_vuse (newstmt, BB_LIVE_VOP_ON_EXIT (block));
2938 folded = name;
2940 break;
2941 case NARY:
2943 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
2944 tree *genop = XALLOCAVEC (tree, nary->length);
2945 unsigned i;
2946 for (i = 0; i < nary->length; ++i)
2948 genop[i] = find_or_generate_expression (block, nary->op[i], stmts);
2949 if (!genop[i])
2950 return NULL_TREE;
2951 /* Ensure genop[] is properly typed for POINTER_PLUS_EXPR. It
2952 may have conversions stripped. */
2953 if (nary->opcode == POINTER_PLUS_EXPR)
2955 if (i == 0)
2956 genop[i] = gimple_convert (&forced_stmts,
2957 nary->type, genop[i]);
2958 else if (i == 1)
2959 genop[i] = gimple_convert (&forced_stmts,
2960 sizetype, genop[i]);
2962 else
2963 genop[i] = gimple_convert (&forced_stmts,
2964 TREE_TYPE (nary->op[i]), genop[i]);
2966 if (nary->opcode == CONSTRUCTOR)
2968 vec<constructor_elt, va_gc> *elts = NULL;
2969 for (i = 0; i < nary->length; ++i)
2970 CONSTRUCTOR_APPEND_ELT (elts, NULL_TREE, genop[i]);
2971 folded = build_constructor (nary->type, elts);
2972 name = make_temp_ssa_name (exprtype, NULL, "pretmp");
2973 newstmt = gimple_build_assign (name, folded);
2974 gimple_set_location (newstmt, expr->loc);
2975 gimple_seq_add_stmt_without_update (&forced_stmts, newstmt);
2976 folded = name;
2978 else
2980 switch (nary->length)
2982 case 1:
2983 folded = gimple_build (&forced_stmts, expr->loc,
2984 nary->opcode, nary->type, genop[0]);
2985 break;
2986 case 2:
2987 folded = gimple_build (&forced_stmts, expr->loc, nary->opcode,
2988 nary->type, genop[0], genop[1]);
2989 break;
2990 case 3:
2991 folded = gimple_build (&forced_stmts, expr->loc, nary->opcode,
2992 nary->type, genop[0], genop[1],
2993 genop[2]);
2994 break;
2995 default:
2996 gcc_unreachable ();
3000 break;
3001 default:
3002 gcc_unreachable ();
3005 folded = gimple_convert (&forced_stmts, exprtype, folded);
3007 /* If there is nothing to insert, return the simplified result. */
3008 if (gimple_seq_empty_p (forced_stmts))
3009 return folded;
3010 /* If we simplified to a constant return it and discard eventually
3011 built stmts. */
3012 if (is_gimple_min_invariant (folded))
3014 gimple_seq_discard (forced_stmts);
3015 return folded;
3017 /* Likewise if we simplified to sth not queued for insertion. */
3018 bool found = false;
3019 gsi = gsi_last (forced_stmts);
3020 for (; !gsi_end_p (gsi); gsi_prev (&gsi))
3022 gimple *stmt = gsi_stmt (gsi);
3023 tree forcedname = gimple_get_lhs (stmt);
3024 if (forcedname == folded)
3026 found = true;
3027 break;
3030 if (! found)
3032 gimple_seq_discard (forced_stmts);
3033 return folded;
3035 gcc_assert (TREE_CODE (folded) == SSA_NAME);
3037 /* If we have any intermediate expressions to the value sets, add them
3038 to the value sets and chain them in the instruction stream. */
3039 if (forced_stmts)
3041 gsi = gsi_start (forced_stmts);
3042 for (; !gsi_end_p (gsi); gsi_next (&gsi))
3044 gimple *stmt = gsi_stmt (gsi);
3045 tree forcedname = gimple_get_lhs (stmt);
3046 pre_expr nameexpr;
3048 if (forcedname != folded)
3050 vn_ssa_aux_t vn_info = VN_INFO (forcedname);
3051 vn_info->valnum = forcedname;
3052 vn_info->value_id = get_next_value_id ();
3053 nameexpr = get_or_alloc_expr_for_name (forcedname);
3054 add_to_value (vn_info->value_id, nameexpr);
3055 if (NEW_SETS (block))
3056 bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
3057 bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
3060 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (forcedname));
3062 gimple_seq_add_seq (stmts, forced_stmts);
3065 name = folded;
3067 /* Fold the last statement. */
3068 gsi = gsi_last (*stmts);
3069 if (fold_stmt_inplace (&gsi))
3070 update_stmt (gsi_stmt (gsi));
3072 /* Add a value number to the temporary.
3073 The value may already exist in either NEW_SETS, or AVAIL_OUT, because
3074 we are creating the expression by pieces, and this particular piece of
3075 the expression may have been represented. There is no harm in replacing
3076 here. */
3077 value_id = get_expr_value_id (expr);
3078 vn_ssa_aux_t vn_info = VN_INFO (name);
3079 vn_info->value_id = value_id;
3080 vn_info->valnum = vn_valnum_from_value_id (value_id);
3081 if (vn_info->valnum == NULL_TREE)
3082 vn_info->valnum = name;
3083 gcc_assert (vn_info->valnum != NULL_TREE);
3084 nameexpr = get_or_alloc_expr_for_name (name);
3085 add_to_value (value_id, nameexpr);
3086 if (NEW_SETS (block))
3087 bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
3088 bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
3090 pre_stats.insertions++;
3091 if (dump_file && (dump_flags & TDF_DETAILS))
3093 fprintf (dump_file, "Inserted ");
3094 print_gimple_stmt (dump_file, gsi_stmt (gsi_last (*stmts)), 0);
3095 fprintf (dump_file, " in predecessor %d (%04d)\n",
3096 block->index, value_id);
3099 return name;
3103 /* Insert the to-be-made-available values of expression EXPRNUM for each
3104 predecessor, stored in AVAIL, into the predecessors of BLOCK, and
3105 merge the result with a phi node, given the same value number as
3106 NODE. Return true if we have inserted new stuff. */
3108 static bool
3109 insert_into_preds_of_block (basic_block block, unsigned int exprnum,
3110 vec<pre_expr> &avail)
3112 pre_expr expr = expression_for_id (exprnum);
3113 pre_expr newphi;
3114 unsigned int val = get_expr_value_id (expr);
3115 edge pred;
3116 bool insertions = false;
3117 bool nophi = false;
3118 basic_block bprime;
3119 pre_expr eprime;
3120 edge_iterator ei;
3121 tree type = get_expr_type (expr);
3122 tree temp;
3123 gphi *phi;
3125 /* Make sure we aren't creating an induction variable. */
3126 if (bb_loop_depth (block) > 0 && EDGE_COUNT (block->preds) == 2)
3128 bool firstinsideloop = false;
3129 bool secondinsideloop = false;
3130 firstinsideloop = flow_bb_inside_loop_p (block->loop_father,
3131 EDGE_PRED (block, 0)->src);
3132 secondinsideloop = flow_bb_inside_loop_p (block->loop_father,
3133 EDGE_PRED (block, 1)->src);
3134 /* Induction variables only have one edge inside the loop. */
3135 if ((firstinsideloop ^ secondinsideloop)
3136 && expr->kind != REFERENCE)
3138 if (dump_file && (dump_flags & TDF_DETAILS))
3139 fprintf (dump_file, "Skipping insertion of phi for partial "
3140 "redundancy: Looks like an induction variable\n");
3141 nophi = true;
3145 /* Make the necessary insertions. */
3146 FOR_EACH_EDGE (pred, ei, block->preds)
3148 /* When we are not inserting a PHI node do not bother inserting
3149 into places that do not dominate the anticipated computations. */
3150 if (nophi && !dominated_by_p (CDI_DOMINATORS, block, pred->src))
3151 continue;
3152 gimple_seq stmts = NULL;
3153 tree builtexpr;
3154 bprime = pred->src;
3155 eprime = avail[pred->dest_idx];
3156 builtexpr = create_expression_by_pieces (bprime, eprime,
3157 &stmts, type);
3158 gcc_assert (!(pred->flags & EDGE_ABNORMAL));
3159 if (!gimple_seq_empty_p (stmts))
3161 basic_block new_bb = gsi_insert_seq_on_edge_immediate (pred, stmts);
3162 gcc_assert (! new_bb);
3163 insertions = true;
3165 if (!builtexpr)
3167 /* We cannot insert a PHI node if we failed to insert
3168 on one edge. */
3169 nophi = true;
3170 continue;
3172 if (is_gimple_min_invariant (builtexpr))
3173 avail[pred->dest_idx] = get_or_alloc_expr_for_constant (builtexpr);
3174 else
3175 avail[pred->dest_idx] = get_or_alloc_expr_for_name (builtexpr);
3177 /* If we didn't want a phi node, and we made insertions, we still have
3178 inserted new stuff, and thus return true. If we didn't want a phi node,
3179 and didn't make insertions, we haven't added anything new, so return
3180 false. */
3181 if (nophi && insertions)
3182 return true;
3183 else if (nophi && !insertions)
3184 return false;
3186 /* Now build a phi for the new variable. */
3187 temp = make_temp_ssa_name (type, NULL, "prephitmp");
3188 phi = create_phi_node (temp, block);
3190 vn_ssa_aux_t vn_info = VN_INFO (temp);
3191 vn_info->value_id = val;
3192 vn_info->valnum = vn_valnum_from_value_id (val);
3193 if (vn_info->valnum == NULL_TREE)
3194 vn_info->valnum = temp;
3195 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (temp));
3196 FOR_EACH_EDGE (pred, ei, block->preds)
3198 pre_expr ae = avail[pred->dest_idx];
3199 gcc_assert (get_expr_type (ae) == type
3200 || useless_type_conversion_p (type, get_expr_type (ae)));
3201 if (ae->kind == CONSTANT)
3202 add_phi_arg (phi, unshare_expr (PRE_EXPR_CONSTANT (ae)),
3203 pred, UNKNOWN_LOCATION);
3204 else
3205 add_phi_arg (phi, PRE_EXPR_NAME (ae), pred, UNKNOWN_LOCATION);
3208 newphi = get_or_alloc_expr_for_name (temp);
3209 add_to_value (val, newphi);
3211 /* The value should *not* exist in PHI_GEN, or else we wouldn't be doing
3212 this insertion, since we test for the existence of this value in PHI_GEN
3213 before proceeding with the partial redundancy checks in insert_aux.
3215 The value may exist in AVAIL_OUT, in particular, it could be represented
3216 by the expression we are trying to eliminate, in which case we want the
3217 replacement to occur. If it's not existing in AVAIL_OUT, we want it
3218 inserted there.
3220 Similarly, to the PHI_GEN case, the value should not exist in NEW_SETS of
3221 this block, because if it did, it would have existed in our dominator's
3222 AVAIL_OUT, and would have been skipped due to the full redundancy check.
3225 bitmap_insert_into_set (PHI_GEN (block), newphi);
3226 bitmap_value_replace_in_set (AVAIL_OUT (block),
3227 newphi);
3228 if (NEW_SETS (block))
3229 bitmap_insert_into_set (NEW_SETS (block), newphi);
3231 /* If we insert a PHI node for a conversion of another PHI node
3232 in the same basic-block try to preserve range information.
3233 This is important so that followup loop passes receive optimal
3234 number of iteration analysis results. See PR61743. */
3235 if (expr->kind == NARY
3236 && CONVERT_EXPR_CODE_P (expr->u.nary->opcode)
3237 && TREE_CODE (expr->u.nary->op[0]) == SSA_NAME
3238 && gimple_bb (SSA_NAME_DEF_STMT (expr->u.nary->op[0])) == block
3239 && INTEGRAL_TYPE_P (type)
3240 && INTEGRAL_TYPE_P (TREE_TYPE (expr->u.nary->op[0]))
3241 && (TYPE_PRECISION (type)
3242 >= TYPE_PRECISION (TREE_TYPE (expr->u.nary->op[0])))
3243 && SSA_NAME_RANGE_INFO (expr->u.nary->op[0]))
3245 value_range r;
3246 if (get_range_query (cfun)->range_of_expr (r, expr->u.nary->op[0])
3247 && r.kind () == VR_RANGE
3248 && !wi::neg_p (r.lower_bound (), SIGNED)
3249 && !wi::neg_p (r.upper_bound (), SIGNED))
3250 /* Just handle extension and sign-changes of all-positive ranges. */
3251 set_range_info (temp, VR_RANGE,
3252 wide_int_storage::from (r.lower_bound (),
3253 TYPE_PRECISION (type),
3254 TYPE_SIGN (type)),
3255 wide_int_storage::from (r.upper_bound (),
3256 TYPE_PRECISION (type),
3257 TYPE_SIGN (type)));
3260 if (dump_file && (dump_flags & TDF_DETAILS))
3262 fprintf (dump_file, "Created phi ");
3263 print_gimple_stmt (dump_file, phi, 0);
3264 fprintf (dump_file, " in block %d (%04d)\n", block->index, val);
3266 pre_stats.phis++;
3267 return true;
3272 /* Perform insertion of partially redundant or hoistable values.
3273 For BLOCK, do the following:
3274 1. Propagate the NEW_SETS of the dominator into the current block.
3275 If the block has multiple predecessors,
3276 2a. Iterate over the ANTIC expressions for the block to see if
3277 any of them are partially redundant.
3278 2b. If so, insert them into the necessary predecessors to make
3279 the expression fully redundant.
3280 2c. Insert a new PHI merging the values of the predecessors.
3281 2d. Insert the new PHI, and the new expressions, into the
3282 NEW_SETS set.
3283 If the block has multiple successors,
3284 3a. Iterate over the ANTIC values for the block to see if
3285 any of them are good candidates for hoisting.
3286 3b. If so, insert expressions computing the values in BLOCK,
3287 and add the new expressions into the NEW_SETS set.
3288 4. Recursively call ourselves on the dominator children of BLOCK.
3290 Steps 1, 2a, and 4 are done by insert_aux. 2b, 2c and 2d are done by
3291 do_pre_regular_insertion and do_partial_insertion. 3a and 3b are
3292 done in do_hoist_insertion.
3295 static bool
3296 do_pre_regular_insertion (basic_block block, basic_block dom,
3297 vec<pre_expr> exprs)
3299 bool new_stuff = false;
3300 pre_expr expr;
3301 auto_vec<pre_expr, 2> avail;
3302 int i;
3304 avail.safe_grow (EDGE_COUNT (block->preds), true);
3306 FOR_EACH_VEC_ELT (exprs, i, expr)
3308 if (expr->kind == NARY
3309 || expr->kind == REFERENCE)
3311 unsigned int val;
3312 bool by_some = false;
3313 bool cant_insert = false;
3314 bool all_same = true;
3315 pre_expr first_s = NULL;
3316 edge pred;
3317 basic_block bprime;
3318 pre_expr eprime = NULL;
3319 edge_iterator ei;
3320 pre_expr edoubleprime = NULL;
3321 bool do_insertion = false;
3323 val = get_expr_value_id (expr);
3324 if (bitmap_set_contains_value (PHI_GEN (block), val))
3325 continue;
3326 if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3328 if (dump_file && (dump_flags & TDF_DETAILS))
3330 fprintf (dump_file, "Found fully redundant value: ");
3331 print_pre_expr (dump_file, expr);
3332 fprintf (dump_file, "\n");
3334 continue;
3337 FOR_EACH_EDGE (pred, ei, block->preds)
3339 unsigned int vprime;
3341 /* We should never run insertion for the exit block
3342 and so not come across fake pred edges. */
3343 gcc_assert (!(pred->flags & EDGE_FAKE));
3344 bprime = pred->src;
3345 /* We are looking at ANTIC_OUT of bprime. */
3346 eprime = phi_translate (NULL, expr, ANTIC_IN (block), NULL, pred);
3348 /* eprime will generally only be NULL if the
3349 value of the expression, translated
3350 through the PHI for this predecessor, is
3351 undefined. If that is the case, we can't
3352 make the expression fully redundant,
3353 because its value is undefined along a
3354 predecessor path. We can thus break out
3355 early because it doesn't matter what the
3356 rest of the results are. */
3357 if (eprime == NULL)
3359 avail[pred->dest_idx] = NULL;
3360 cant_insert = true;
3361 break;
3364 vprime = get_expr_value_id (eprime);
3365 edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime),
3366 vprime);
3367 if (edoubleprime == NULL)
3369 avail[pred->dest_idx] = eprime;
3370 all_same = false;
3372 else
3374 avail[pred->dest_idx] = edoubleprime;
3375 by_some = true;
3376 /* We want to perform insertions to remove a redundancy on
3377 a path in the CFG we want to optimize for speed. */
3378 if (optimize_edge_for_speed_p (pred))
3379 do_insertion = true;
3380 if (first_s == NULL)
3381 first_s = edoubleprime;
3382 else if (!pre_expr_d::equal (first_s, edoubleprime))
3383 all_same = false;
3386 /* If we can insert it, it's not the same value
3387 already existing along every predecessor, and
3388 it's defined by some predecessor, it is
3389 partially redundant. */
3390 if (!cant_insert && !all_same && by_some)
3392 if (!do_insertion)
3394 if (dump_file && (dump_flags & TDF_DETAILS))
3396 fprintf (dump_file, "Skipping partial redundancy for "
3397 "expression ");
3398 print_pre_expr (dump_file, expr);
3399 fprintf (dump_file, " (%04d), no redundancy on to be "
3400 "optimized for speed edge\n", val);
3403 else if (dbg_cnt (treepre_insert))
3405 if (dump_file && (dump_flags & TDF_DETAILS))
3407 fprintf (dump_file, "Found partial redundancy for "
3408 "expression ");
3409 print_pre_expr (dump_file, expr);
3410 fprintf (dump_file, " (%04d)\n",
3411 get_expr_value_id (expr));
3413 if (insert_into_preds_of_block (block,
3414 get_expression_id (expr),
3415 avail))
3416 new_stuff = true;
3419 /* If all edges produce the same value and that value is
3420 an invariant, then the PHI has the same value on all
3421 edges. Note this. */
3422 else if (!cant_insert
3423 && all_same
3424 && (edoubleprime->kind != NAME
3425 || !SSA_NAME_OCCURS_IN_ABNORMAL_PHI
3426 (PRE_EXPR_NAME (edoubleprime))))
3428 gcc_assert (edoubleprime->kind == CONSTANT
3429 || edoubleprime->kind == NAME);
3431 tree temp = make_temp_ssa_name (get_expr_type (expr),
3432 NULL, "pretmp");
3433 gassign *assign
3434 = gimple_build_assign (temp,
3435 edoubleprime->kind == CONSTANT ?
3436 PRE_EXPR_CONSTANT (edoubleprime) :
3437 PRE_EXPR_NAME (edoubleprime));
3438 gimple_stmt_iterator gsi = gsi_after_labels (block);
3439 gsi_insert_before (&gsi, assign, GSI_NEW_STMT);
3441 vn_ssa_aux_t vn_info = VN_INFO (temp);
3442 vn_info->value_id = val;
3443 vn_info->valnum = vn_valnum_from_value_id (val);
3444 if (vn_info->valnum == NULL_TREE)
3445 vn_info->valnum = temp;
3446 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (temp));
3447 pre_expr newe = get_or_alloc_expr_for_name (temp);
3448 add_to_value (val, newe);
3449 bitmap_value_replace_in_set (AVAIL_OUT (block), newe);
3450 bitmap_insert_into_set (NEW_SETS (block), newe);
3451 bitmap_insert_into_set (PHI_GEN (block), newe);
3456 return new_stuff;
3460 /* Perform insertion for partially anticipatable expressions. There
3461 is only one case we will perform insertion for these. This case is
3462 if the expression is partially anticipatable, and fully available.
3463 In this case, we know that putting it earlier will enable us to
3464 remove the later computation. */
3466 static bool
3467 do_pre_partial_partial_insertion (basic_block block, basic_block dom,
3468 vec<pre_expr> exprs)
3470 bool new_stuff = false;
3471 pre_expr expr;
3472 auto_vec<pre_expr, 2> avail;
3473 int i;
3475 avail.safe_grow (EDGE_COUNT (block->preds), true);
3477 FOR_EACH_VEC_ELT (exprs, i, expr)
3479 if (expr->kind == NARY
3480 || expr->kind == REFERENCE)
3482 unsigned int val;
3483 bool by_all = true;
3484 bool cant_insert = false;
3485 edge pred;
3486 basic_block bprime;
3487 pre_expr eprime = NULL;
3488 edge_iterator ei;
3490 val = get_expr_value_id (expr);
3491 if (bitmap_set_contains_value (PHI_GEN (block), val))
3492 continue;
3493 if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3494 continue;
3496 FOR_EACH_EDGE (pred, ei, block->preds)
3498 unsigned int vprime;
3499 pre_expr edoubleprime;
3501 /* We should never run insertion for the exit block
3502 and so not come across fake pred edges. */
3503 gcc_assert (!(pred->flags & EDGE_FAKE));
3504 bprime = pred->src;
3505 eprime = phi_translate (NULL, expr, ANTIC_IN (block),
3506 PA_IN (block), pred);
3508 /* eprime will generally only be NULL if the
3509 value of the expression, translated
3510 through the PHI for this predecessor, is
3511 undefined. If that is the case, we can't
3512 make the expression fully redundant,
3513 because its value is undefined along a
3514 predecessor path. We can thus break out
3515 early because it doesn't matter what the
3516 rest of the results are. */
3517 if (eprime == NULL)
3519 avail[pred->dest_idx] = NULL;
3520 cant_insert = true;
3521 break;
3524 vprime = get_expr_value_id (eprime);
3525 edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime), vprime);
3526 avail[pred->dest_idx] = edoubleprime;
3527 if (edoubleprime == NULL)
3529 by_all = false;
3530 break;
3534 /* If we can insert it, it's not the same value
3535 already existing along every predecessor, and
3536 it's defined by some predecessor, it is
3537 partially redundant. */
3538 if (!cant_insert && by_all)
3540 edge succ;
3541 bool do_insertion = false;
3543 /* Insert only if we can remove a later expression on a path
3544 that we want to optimize for speed.
3545 The phi node that we will be inserting in BLOCK is not free,
3546 and inserting it for the sake of !optimize_for_speed successor
3547 may cause regressions on the speed path. */
3548 FOR_EACH_EDGE (succ, ei, block->succs)
3550 if (bitmap_set_contains_value (PA_IN (succ->dest), val)
3551 || bitmap_set_contains_value (ANTIC_IN (succ->dest), val))
3553 if (optimize_edge_for_speed_p (succ))
3554 do_insertion = true;
3558 if (!do_insertion)
3560 if (dump_file && (dump_flags & TDF_DETAILS))
3562 fprintf (dump_file, "Skipping partial partial redundancy "
3563 "for expression ");
3564 print_pre_expr (dump_file, expr);
3565 fprintf (dump_file, " (%04d), not (partially) anticipated "
3566 "on any to be optimized for speed edges\n", val);
3569 else if (dbg_cnt (treepre_insert))
3571 pre_stats.pa_insert++;
3572 if (dump_file && (dump_flags & TDF_DETAILS))
3574 fprintf (dump_file, "Found partial partial redundancy "
3575 "for expression ");
3576 print_pre_expr (dump_file, expr);
3577 fprintf (dump_file, " (%04d)\n",
3578 get_expr_value_id (expr));
3580 if (insert_into_preds_of_block (block,
3581 get_expression_id (expr),
3582 avail))
3583 new_stuff = true;
3589 return new_stuff;
3592 /* Insert expressions in BLOCK to compute hoistable values up.
3593 Return TRUE if something was inserted, otherwise return FALSE.
3594 The caller has to make sure that BLOCK has at least two successors. */
3596 static bool
3597 do_hoist_insertion (basic_block block)
3599 edge e;
3600 edge_iterator ei;
3601 bool new_stuff = false;
3602 unsigned i;
3603 gimple_stmt_iterator last;
3605 /* At least two successors, or else... */
3606 gcc_assert (EDGE_COUNT (block->succs) >= 2);
3608 /* Check that all successors of BLOCK are dominated by block.
3609 We could use dominated_by_p() for this, but actually there is a much
3610 quicker check: any successor that is dominated by BLOCK can't have
3611 more than one predecessor edge. */
3612 FOR_EACH_EDGE (e, ei, block->succs)
3613 if (! single_pred_p (e->dest))
3614 return false;
3616 /* Determine the insertion point. If we cannot safely insert before
3617 the last stmt if we'd have to, bail out. */
3618 last = gsi_last_bb (block);
3619 if (!gsi_end_p (last)
3620 && !is_ctrl_stmt (gsi_stmt (last))
3621 && stmt_ends_bb_p (gsi_stmt (last)))
3622 return false;
3624 /* Compute the set of hoistable expressions from ANTIC_IN. First compute
3625 hoistable values. */
3626 bitmap_set hoistable_set;
3628 /* A hoistable value must be in ANTIC_IN(block)
3629 but not in AVAIL_OUT(BLOCK). */
3630 bitmap_initialize (&hoistable_set.values, &grand_bitmap_obstack);
3631 bitmap_and_compl (&hoistable_set.values,
3632 &ANTIC_IN (block)->values, &AVAIL_OUT (block)->values);
3634 /* Short-cut for a common case: hoistable_set is empty. */
3635 if (bitmap_empty_p (&hoistable_set.values))
3636 return false;
3638 /* Compute which of the hoistable values is in AVAIL_OUT of
3639 at least one of the successors of BLOCK. */
3640 bitmap_head availout_in_some;
3641 bitmap_initialize (&availout_in_some, &grand_bitmap_obstack);
3642 FOR_EACH_EDGE (e, ei, block->succs)
3643 /* Do not consider expressions solely because their availability
3644 on loop exits. They'd be ANTIC-IN throughout the whole loop
3645 and thus effectively hoisted across loops by combination of
3646 PRE and hoisting. */
3647 if (! loop_exit_edge_p (block->loop_father, e))
3648 bitmap_ior_and_into (&availout_in_some, &hoistable_set.values,
3649 &AVAIL_OUT (e->dest)->values);
3650 bitmap_clear (&hoistable_set.values);
3652 /* Short-cut for a common case: availout_in_some is empty. */
3653 if (bitmap_empty_p (&availout_in_some))
3654 return false;
3656 /* Hack hoitable_set in-place so we can use sorted_array_from_bitmap_set. */
3657 bitmap_move (&hoistable_set.values, &availout_in_some);
3658 hoistable_set.expressions = ANTIC_IN (block)->expressions;
3660 /* Now finally construct the topological-ordered expression set. */
3661 vec<pre_expr> exprs = sorted_array_from_bitmap_set (&hoistable_set);
3663 bitmap_clear (&hoistable_set.values);
3665 /* If there are candidate values for hoisting, insert expressions
3666 strategically to make the hoistable expressions fully redundant. */
3667 pre_expr expr;
3668 FOR_EACH_VEC_ELT (exprs, i, expr)
3670 /* While we try to sort expressions topologically above the
3671 sorting doesn't work out perfectly. Catch expressions we
3672 already inserted. */
3673 unsigned int value_id = get_expr_value_id (expr);
3674 if (bitmap_set_contains_value (AVAIL_OUT (block), value_id))
3676 if (dump_file && (dump_flags & TDF_DETAILS))
3678 fprintf (dump_file,
3679 "Already inserted expression for ");
3680 print_pre_expr (dump_file, expr);
3681 fprintf (dump_file, " (%04d)\n", value_id);
3683 continue;
3686 /* If we end up with a punned expression representation and this
3687 happens to be a float typed one give up - we can't know for
3688 sure whether all paths perform the floating-point load we are
3689 about to insert and on some targets this can cause correctness
3690 issues. See PR88240. */
3691 if (expr->kind == REFERENCE
3692 && PRE_EXPR_REFERENCE (expr)->punned
3693 && FLOAT_TYPE_P (get_expr_type (expr)))
3694 continue;
3696 /* OK, we should hoist this value. Perform the transformation. */
3697 pre_stats.hoist_insert++;
3698 if (dump_file && (dump_flags & TDF_DETAILS))
3700 fprintf (dump_file,
3701 "Inserting expression in block %d for code hoisting: ",
3702 block->index);
3703 print_pre_expr (dump_file, expr);
3704 fprintf (dump_file, " (%04d)\n", value_id);
3707 gimple_seq stmts = NULL;
3708 tree res = create_expression_by_pieces (block, expr, &stmts,
3709 get_expr_type (expr));
3711 /* Do not return true if expression creation ultimately
3712 did not insert any statements. */
3713 if (gimple_seq_empty_p (stmts))
3714 res = NULL_TREE;
3715 else
3717 if (gsi_end_p (last) || is_ctrl_stmt (gsi_stmt (last)))
3718 gsi_insert_seq_before (&last, stmts, GSI_SAME_STMT);
3719 else
3720 gsi_insert_seq_after (&last, stmts, GSI_NEW_STMT);
3723 /* Make sure to not return true if expression creation ultimately
3724 failed but also make sure to insert any stmts produced as they
3725 are tracked in inserted_exprs. */
3726 if (! res)
3727 continue;
3729 new_stuff = true;
3732 exprs.release ();
3734 return new_stuff;
3737 /* Perform insertion of partially redundant and hoistable values. */
3739 static void
3740 insert (void)
3742 basic_block bb;
3744 FOR_ALL_BB_FN (bb, cfun)
3745 NEW_SETS (bb) = bitmap_set_new ();
3747 int *rpo = XNEWVEC (int, n_basic_blocks_for_fn (cfun));
3748 int *bb_rpo = XNEWVEC (int, last_basic_block_for_fn (cfun) + 1);
3749 int rpo_num = pre_and_rev_post_order_compute (NULL, rpo, false);
3750 for (int i = 0; i < rpo_num; ++i)
3751 bb_rpo[rpo[i]] = i;
3753 int num_iterations = 0;
3754 bool changed;
3757 num_iterations++;
3758 if (dump_file && dump_flags & TDF_DETAILS)
3759 fprintf (dump_file, "Starting insert iteration %d\n", num_iterations);
3761 changed = false;
3762 for (int idx = 0; idx < rpo_num; ++idx)
3764 basic_block block = BASIC_BLOCK_FOR_FN (cfun, rpo[idx]);
3765 basic_block dom = get_immediate_dominator (CDI_DOMINATORS, block);
3766 if (dom)
3768 unsigned i;
3769 bitmap_iterator bi;
3770 bitmap_set_t newset;
3772 /* First, update the AVAIL_OUT set with anything we may have
3773 inserted higher up in the dominator tree. */
3774 newset = NEW_SETS (dom);
3776 /* Note that we need to value_replace both NEW_SETS, and
3777 AVAIL_OUT. For both the case of NEW_SETS, the value may be
3778 represented by some non-simple expression here that we want
3779 to replace it with. */
3780 bool avail_out_changed = false;
3781 FOR_EACH_EXPR_ID_IN_SET (newset, i, bi)
3783 pre_expr expr = expression_for_id (i);
3784 bitmap_value_replace_in_set (NEW_SETS (block), expr);
3785 avail_out_changed
3786 |= bitmap_value_replace_in_set (AVAIL_OUT (block), expr);
3788 /* We need to iterate if AVAIL_OUT of an already processed
3789 block source changed. */
3790 if (avail_out_changed && !changed)
3792 edge_iterator ei;
3793 edge e;
3794 FOR_EACH_EDGE (e, ei, block->succs)
3795 if (e->dest->index != EXIT_BLOCK
3796 && bb_rpo[e->dest->index] < idx)
3797 changed = true;
3800 /* Insert expressions for partial redundancies. */
3801 if (flag_tree_pre && !single_pred_p (block))
3803 vec<pre_expr> exprs
3804 = sorted_array_from_bitmap_set (ANTIC_IN (block));
3805 /* Sorting is not perfect, iterate locally. */
3806 while (do_pre_regular_insertion (block, dom, exprs))
3808 exprs.release ();
3809 if (do_partial_partial)
3811 exprs = sorted_array_from_bitmap_set (PA_IN (block));
3812 while (do_pre_partial_partial_insertion (block, dom,
3813 exprs))
3815 exprs.release ();
3821 /* Clear the NEW sets before the next iteration. We have already
3822 fully propagated its contents. */
3823 if (changed)
3824 FOR_ALL_BB_FN (bb, cfun)
3825 bitmap_set_free (NEW_SETS (bb));
3827 while (changed);
3829 statistics_histogram_event (cfun, "insert iterations", num_iterations);
3831 /* AVAIL_OUT is not needed after insertion so we don't have to
3832 propagate NEW_SETS from hoist insertion. */
3833 FOR_ALL_BB_FN (bb, cfun)
3835 bitmap_set_free (NEW_SETS (bb));
3836 bitmap_set_pool.remove (NEW_SETS (bb));
3837 NEW_SETS (bb) = NULL;
3840 /* Insert expressions for hoisting. Do a backward walk here since
3841 inserting into BLOCK exposes new opportunities in its predecessors.
3842 Since PRE and hoist insertions can cause back-to-back iteration
3843 and we are interested in PRE insertion exposed hoisting opportunities
3844 but not in hoisting exposed PRE ones do hoist insertion only after
3845 PRE insertion iteration finished and do not iterate it. */
3846 if (flag_code_hoisting)
3847 for (int idx = rpo_num - 1; idx >= 0; --idx)
3849 basic_block block = BASIC_BLOCK_FOR_FN (cfun, rpo[idx]);
3850 if (EDGE_COUNT (block->succs) >= 2)
3851 changed |= do_hoist_insertion (block);
3854 free (rpo);
3855 free (bb_rpo);
3859 /* Compute the AVAIL set for all basic blocks.
3861 This function performs value numbering of the statements in each basic
3862 block. The AVAIL sets are built from information we glean while doing
3863 this value numbering, since the AVAIL sets contain only one entry per
3864 value.
3866 AVAIL_IN[BLOCK] = AVAIL_OUT[dom(BLOCK)].
3867 AVAIL_OUT[BLOCK] = AVAIL_IN[BLOCK] U PHI_GEN[BLOCK] U TMP_GEN[BLOCK]. */
3869 static void
3870 compute_avail (function *fun)
3873 basic_block block, son;
3874 basic_block *worklist;
3875 size_t sp = 0;
3876 unsigned i;
3877 tree name;
3879 /* We pretend that default definitions are defined in the entry block.
3880 This includes function arguments and the static chain decl. */
3881 FOR_EACH_SSA_NAME (i, name, fun)
3883 pre_expr e;
3884 if (!SSA_NAME_IS_DEFAULT_DEF (name)
3885 || has_zero_uses (name)
3886 || virtual_operand_p (name))
3887 continue;
3889 e = get_or_alloc_expr_for_name (name);
3890 add_to_value (get_expr_value_id (e), e);
3891 bitmap_insert_into_set (TMP_GEN (ENTRY_BLOCK_PTR_FOR_FN (fun)), e);
3892 bitmap_value_insert_into_set (AVAIL_OUT (ENTRY_BLOCK_PTR_FOR_FN (fun)),
3896 if (dump_file && (dump_flags & TDF_DETAILS))
3898 print_bitmap_set (dump_file, TMP_GEN (ENTRY_BLOCK_PTR_FOR_FN (fun)),
3899 "tmp_gen", ENTRY_BLOCK);
3900 print_bitmap_set (dump_file, AVAIL_OUT (ENTRY_BLOCK_PTR_FOR_FN (fun)),
3901 "avail_out", ENTRY_BLOCK);
3904 /* Allocate the worklist. */
3905 worklist = XNEWVEC (basic_block, n_basic_blocks_for_fn (fun));
3907 /* Seed the algorithm by putting the dominator children of the entry
3908 block on the worklist. */
3909 for (son = first_dom_son (CDI_DOMINATORS, ENTRY_BLOCK_PTR_FOR_FN (fun));
3910 son;
3911 son = next_dom_son (CDI_DOMINATORS, son))
3912 worklist[sp++] = son;
3914 BB_LIVE_VOP_ON_EXIT (ENTRY_BLOCK_PTR_FOR_FN (fun))
3915 = ssa_default_def (fun, gimple_vop (fun));
3917 /* Loop until the worklist is empty. */
3918 while (sp)
3920 gimple *stmt;
3921 basic_block dom;
3923 /* Pick a block from the worklist. */
3924 block = worklist[--sp];
3925 vn_context_bb = block;
3927 /* Initially, the set of available values in BLOCK is that of
3928 its immediate dominator. */
3929 dom = get_immediate_dominator (CDI_DOMINATORS, block);
3930 if (dom)
3932 bitmap_set_copy (AVAIL_OUT (block), AVAIL_OUT (dom));
3933 BB_LIVE_VOP_ON_EXIT (block) = BB_LIVE_VOP_ON_EXIT (dom);
3936 /* Generate values for PHI nodes. */
3937 for (gphi_iterator gsi = gsi_start_phis (block); !gsi_end_p (gsi);
3938 gsi_next (&gsi))
3940 tree result = gimple_phi_result (gsi.phi ());
3942 /* We have no need for virtual phis, as they don't represent
3943 actual computations. */
3944 if (virtual_operand_p (result))
3946 BB_LIVE_VOP_ON_EXIT (block) = result;
3947 continue;
3950 pre_expr e = get_or_alloc_expr_for_name (result);
3951 add_to_value (get_expr_value_id (e), e);
3952 bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3953 bitmap_insert_into_set (PHI_GEN (block), e);
3956 BB_MAY_NOTRETURN (block) = 0;
3958 /* Now compute value numbers and populate value sets with all
3959 the expressions computed in BLOCK. */
3960 for (gimple_stmt_iterator gsi = gsi_start_bb (block); !gsi_end_p (gsi);
3961 gsi_next (&gsi))
3963 ssa_op_iter iter;
3964 tree op;
3966 stmt = gsi_stmt (gsi);
3968 /* Cache whether the basic-block has any non-visible side-effect
3969 or control flow.
3970 If this isn't a call or it is the last stmt in the
3971 basic-block then the CFG represents things correctly. */
3972 if (is_gimple_call (stmt) && !stmt_ends_bb_p (stmt))
3974 /* Non-looping const functions always return normally.
3975 Otherwise the call might not return or have side-effects
3976 that forbids hoisting possibly trapping expressions
3977 before it. */
3978 int flags = gimple_call_flags (stmt);
3979 if (!(flags & ECF_CONST)
3980 || (flags & ECF_LOOPING_CONST_OR_PURE)
3981 || stmt_can_throw_external (fun, stmt))
3982 BB_MAY_NOTRETURN (block) = 1;
3985 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_DEF)
3987 pre_expr e = get_or_alloc_expr_for_name (op);
3989 add_to_value (get_expr_value_id (e), e);
3990 bitmap_insert_into_set (TMP_GEN (block), e);
3991 bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3994 if (gimple_vdef (stmt))
3995 BB_LIVE_VOP_ON_EXIT (block) = gimple_vdef (stmt);
3997 if (gimple_has_side_effects (stmt)
3998 || stmt_could_throw_p (fun, stmt)
3999 || is_gimple_debug (stmt))
4000 continue;
4002 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
4004 if (ssa_undefined_value_p (op))
4005 continue;
4006 pre_expr e = get_or_alloc_expr_for_name (op);
4007 bitmap_value_insert_into_set (EXP_GEN (block), e);
4010 switch (gimple_code (stmt))
4012 case GIMPLE_RETURN:
4013 continue;
4015 case GIMPLE_CALL:
4017 vn_reference_t ref;
4018 vn_reference_s ref1;
4019 pre_expr result = NULL;
4021 /* We can value number only calls to real functions. */
4022 if (gimple_call_internal_p (stmt))
4023 continue;
4025 vn_reference_lookup_call (as_a <gcall *> (stmt), &ref, &ref1);
4026 /* There is no point to PRE a call without a value. */
4027 if (!ref || !ref->result)
4028 continue;
4030 /* If the value of the call is not invalidated in
4031 this block until it is computed, add the expression
4032 to EXP_GEN. */
4033 if (!gimple_vuse (stmt)
4034 || gimple_code
4035 (SSA_NAME_DEF_STMT (gimple_vuse (stmt))) == GIMPLE_PHI
4036 || gimple_bb (SSA_NAME_DEF_STMT
4037 (gimple_vuse (stmt))) != block)
4039 result = get_or_alloc_expr_for_reference
4040 (ref, gimple_location (stmt));
4041 add_to_value (get_expr_value_id (result), result);
4042 bitmap_value_insert_into_set (EXP_GEN (block), result);
4044 continue;
4047 case GIMPLE_ASSIGN:
4049 pre_expr result = NULL;
4050 switch (vn_get_stmt_kind (stmt))
4052 case VN_NARY:
4054 enum tree_code code = gimple_assign_rhs_code (stmt);
4055 vn_nary_op_t nary;
4057 /* COND_EXPR is awkward in that it contains an
4058 embedded complex expression.
4059 Don't even try to shove it through PRE. */
4060 if (code == COND_EXPR)
4061 continue;
4063 vn_nary_op_lookup_stmt (stmt, &nary);
4064 if (!nary || nary->predicated_values)
4065 continue;
4067 /* If the NARY traps and there was a preceding
4068 point in the block that might not return avoid
4069 adding the nary to EXP_GEN. */
4070 if (BB_MAY_NOTRETURN (block)
4071 && vn_nary_may_trap (nary))
4072 continue;
4074 result = get_or_alloc_expr_for_nary
4075 (nary, gimple_location (stmt));
4076 break;
4079 case VN_REFERENCE:
4081 tree rhs1 = gimple_assign_rhs1 (stmt);
4082 ao_ref rhs1_ref;
4083 ao_ref_init (&rhs1_ref, rhs1);
4084 alias_set_type set = ao_ref_alias_set (&rhs1_ref);
4085 alias_set_type base_set
4086 = ao_ref_base_alias_set (&rhs1_ref);
4087 vec<vn_reference_op_s> operands
4088 = vn_reference_operands_for_lookup (rhs1);
4089 vn_reference_t ref;
4090 vn_reference_lookup_pieces (gimple_vuse (stmt), set,
4091 base_set, TREE_TYPE (rhs1),
4092 operands, &ref, VN_WALK);
4093 if (!ref)
4095 operands.release ();
4096 continue;
4099 /* If the REFERENCE traps and there was a preceding
4100 point in the block that might not return avoid
4101 adding the reference to EXP_GEN. */
4102 if (BB_MAY_NOTRETURN (block)
4103 && vn_reference_may_trap (ref))
4105 operands.release ();
4106 continue;
4109 /* If the value of the reference is not invalidated in
4110 this block until it is computed, add the expression
4111 to EXP_GEN. */
4112 if (gimple_vuse (stmt))
4114 gimple *def_stmt;
4115 bool ok = true;
4116 def_stmt = SSA_NAME_DEF_STMT (gimple_vuse (stmt));
4117 while (!gimple_nop_p (def_stmt)
4118 && gimple_code (def_stmt) != GIMPLE_PHI
4119 && gimple_bb (def_stmt) == block)
4121 if (stmt_may_clobber_ref_p
4122 (def_stmt, gimple_assign_rhs1 (stmt)))
4124 ok = false;
4125 break;
4127 def_stmt
4128 = SSA_NAME_DEF_STMT (gimple_vuse (def_stmt));
4130 if (!ok)
4132 operands.release ();
4133 continue;
4137 /* If the load was value-numbered to another
4138 load make sure we do not use its expression
4139 for insertion if it wouldn't be a valid
4140 replacement. */
4141 /* At the momemt we have a testcase
4142 for hoist insertion of aligned vs. misaligned
4143 variants in gcc.dg/torture/pr65270-1.c thus
4144 with just alignment to be considered we can
4145 simply replace the expression in the hashtable
4146 with the most conservative one. */
4147 vn_reference_op_t ref1 = &ref->operands.last ();
4148 while (ref1->opcode != TARGET_MEM_REF
4149 && ref1->opcode != MEM_REF
4150 && ref1 != &ref->operands[0])
4151 --ref1;
4152 vn_reference_op_t ref2 = &operands.last ();
4153 while (ref2->opcode != TARGET_MEM_REF
4154 && ref2->opcode != MEM_REF
4155 && ref2 != &operands[0])
4156 --ref2;
4157 if ((ref1->opcode == TARGET_MEM_REF
4158 || ref1->opcode == MEM_REF)
4159 && (TYPE_ALIGN (ref1->type)
4160 > TYPE_ALIGN (ref2->type)))
4161 ref1->type
4162 = build_aligned_type (ref1->type,
4163 TYPE_ALIGN (ref2->type));
4164 /* TBAA behavior is an obvious part so make sure
4165 that the hashtable one covers this as well
4166 by adjusting the ref alias set and its base. */
4167 if (ref->set == set
4168 || alias_set_subset_of (set, ref->set))
4170 else if (ref1->opcode != ref2->opcode
4171 || (ref1->opcode != MEM_REF
4172 && ref1->opcode != TARGET_MEM_REF))
4174 /* With mismatching base opcodes or bases
4175 other than MEM_REF or TARGET_MEM_REF we
4176 can't do any easy TBAA adjustment. */
4177 operands.release ();
4178 continue;
4180 else if (alias_set_subset_of (ref->set, set))
4182 ref->set = set;
4183 if (ref1->opcode == MEM_REF)
4184 ref1->op0
4185 = wide_int_to_tree (TREE_TYPE (ref2->op0),
4186 wi::to_wide (ref1->op0));
4187 else
4188 ref1->op2
4189 = wide_int_to_tree (TREE_TYPE (ref2->op2),
4190 wi::to_wide (ref1->op2));
4192 else
4194 ref->set = 0;
4195 if (ref1->opcode == MEM_REF)
4196 ref1->op0
4197 = wide_int_to_tree (ptr_type_node,
4198 wi::to_wide (ref1->op0));
4199 else
4200 ref1->op2
4201 = wide_int_to_tree (ptr_type_node,
4202 wi::to_wide (ref1->op2));
4204 operands.release ();
4206 result = get_or_alloc_expr_for_reference
4207 (ref, gimple_location (stmt));
4208 break;
4211 default:
4212 continue;
4215 add_to_value (get_expr_value_id (result), result);
4216 bitmap_value_insert_into_set (EXP_GEN (block), result);
4217 continue;
4219 default:
4220 break;
4224 if (dump_file && (dump_flags & TDF_DETAILS))
4226 print_bitmap_set (dump_file, EXP_GEN (block),
4227 "exp_gen", block->index);
4228 print_bitmap_set (dump_file, PHI_GEN (block),
4229 "phi_gen", block->index);
4230 print_bitmap_set (dump_file, TMP_GEN (block),
4231 "tmp_gen", block->index);
4232 print_bitmap_set (dump_file, AVAIL_OUT (block),
4233 "avail_out", block->index);
4236 /* Put the dominator children of BLOCK on the worklist of blocks
4237 to compute available sets for. */
4238 for (son = first_dom_son (CDI_DOMINATORS, block);
4239 son;
4240 son = next_dom_son (CDI_DOMINATORS, son))
4241 worklist[sp++] = son;
4243 vn_context_bb = NULL;
4245 free (worklist);
4249 /* Initialize data structures used by PRE. */
4251 static void
4252 init_pre (void)
4254 basic_block bb;
4256 next_expression_id = 1;
4257 expressions.create (0);
4258 expressions.safe_push (NULL);
4259 value_expressions.create (get_max_value_id () + 1);
4260 value_expressions.quick_grow_cleared (get_max_value_id () + 1);
4261 constant_value_expressions.create (get_max_constant_value_id () + 1);
4262 constant_value_expressions.quick_grow_cleared (get_max_constant_value_id () + 1);
4263 name_to_id.create (0);
4265 inserted_exprs = BITMAP_ALLOC (NULL);
4267 connect_infinite_loops_to_exit ();
4268 memset (&pre_stats, 0, sizeof (pre_stats));
4270 alloc_aux_for_blocks (sizeof (struct bb_bitmap_sets));
4272 calculate_dominance_info (CDI_DOMINATORS);
4274 bitmap_obstack_initialize (&grand_bitmap_obstack);
4275 expression_to_id = new hash_table<pre_expr_d> (num_ssa_names * 3);
4276 FOR_ALL_BB_FN (bb, cfun)
4278 EXP_GEN (bb) = bitmap_set_new ();
4279 PHI_GEN (bb) = bitmap_set_new ();
4280 TMP_GEN (bb) = bitmap_set_new ();
4281 AVAIL_OUT (bb) = bitmap_set_new ();
4282 PHI_TRANS_TABLE (bb) = NULL;
4287 /* Deallocate data structures used by PRE. */
4289 static void
4290 fini_pre ()
4292 value_expressions.release ();
4293 constant_value_expressions.release ();
4294 expressions.release ();
4295 BITMAP_FREE (inserted_exprs);
4296 bitmap_obstack_release (&grand_bitmap_obstack);
4297 bitmap_set_pool.release ();
4298 pre_expr_pool.release ();
4299 delete expression_to_id;
4300 expression_to_id = NULL;
4301 name_to_id.release ();
4303 basic_block bb;
4304 FOR_ALL_BB_FN (bb, cfun)
4305 if (bb->aux && PHI_TRANS_TABLE (bb))
4306 delete PHI_TRANS_TABLE (bb);
4307 free_aux_for_blocks ();
4310 namespace {
4312 const pass_data pass_data_pre =
4314 GIMPLE_PASS, /* type */
4315 "pre", /* name */
4316 OPTGROUP_NONE, /* optinfo_flags */
4317 TV_TREE_PRE, /* tv_id */
4318 ( PROP_cfg | PROP_ssa ), /* properties_required */
4319 0, /* properties_provided */
4320 0, /* properties_destroyed */
4321 TODO_rebuild_alias, /* todo_flags_start */
4322 0, /* todo_flags_finish */
4325 class pass_pre : public gimple_opt_pass
4327 public:
4328 pass_pre (gcc::context *ctxt)
4329 : gimple_opt_pass (pass_data_pre, ctxt)
4332 /* opt_pass methods: */
4333 virtual bool gate (function *)
4334 { return flag_tree_pre != 0 || flag_code_hoisting != 0; }
4335 virtual unsigned int execute (function *);
4337 }; // class pass_pre
4339 /* Valueization hook for RPO VN when we are calling back to it
4340 at ANTIC compute time. */
4342 static tree
4343 pre_valueize (tree name)
4345 if (TREE_CODE (name) == SSA_NAME)
4347 tree tem = VN_INFO (name)->valnum;
4348 if (tem != VN_TOP && tem != name)
4350 if (TREE_CODE (tem) != SSA_NAME
4351 || SSA_NAME_IS_DEFAULT_DEF (tem))
4352 return tem;
4353 /* We create temporary SSA names for representatives that
4354 do not have a definition (yet) but are not default defs either
4355 assume they are fine to use. */
4356 basic_block def_bb = gimple_bb (SSA_NAME_DEF_STMT (tem));
4357 if (! def_bb
4358 || dominated_by_p (CDI_DOMINATORS, vn_context_bb, def_bb))
4359 return tem;
4360 /* ??? Now we could look for a leader. Ideally we'd somehow
4361 expose RPO VN leaders and get rid of AVAIL_OUT as well... */
4364 return name;
4367 unsigned int
4368 pass_pre::execute (function *fun)
4370 unsigned int todo = 0;
4372 do_partial_partial =
4373 flag_tree_partial_pre && optimize_function_for_speed_p (fun);
4375 /* This has to happen before VN runs because
4376 loop_optimizer_init may create new phis, etc. */
4377 loop_optimizer_init (LOOPS_NORMAL);
4378 split_edges_for_insertion ();
4379 scev_initialize ();
4380 calculate_dominance_info (CDI_DOMINATORS);
4382 run_rpo_vn (VN_WALK);
4384 init_pre ();
4386 vn_valueize = pre_valueize;
4388 /* Insert can get quite slow on an incredibly large number of basic
4389 blocks due to some quadratic behavior. Until this behavior is
4390 fixed, don't run it when he have an incredibly large number of
4391 bb's. If we aren't going to run insert, there is no point in
4392 computing ANTIC, either, even though it's plenty fast nor do
4393 we require AVAIL. */
4394 if (n_basic_blocks_for_fn (fun) < 4000)
4396 compute_avail (fun);
4397 compute_antic ();
4398 insert ();
4401 /* Make sure to remove fake edges before committing our inserts.
4402 This makes sure we don't end up with extra critical edges that
4403 we would need to split. */
4404 remove_fake_exit_edges ();
4405 gsi_commit_edge_inserts ();
4407 /* Eliminate folds statements which might (should not...) end up
4408 not keeping virtual operands up-to-date. */
4409 gcc_assert (!need_ssa_update_p (fun));
4411 statistics_counter_event (fun, "Insertions", pre_stats.insertions);
4412 statistics_counter_event (fun, "PA inserted", pre_stats.pa_insert);
4413 statistics_counter_event (fun, "HOIST inserted", pre_stats.hoist_insert);
4414 statistics_counter_event (fun, "New PHIs", pre_stats.phis);
4416 todo |= eliminate_with_rpo_vn (inserted_exprs);
4418 vn_valueize = NULL;
4420 /* Because we don't follow exactly the standard PRE algorithm, and decide not
4421 to insert PHI nodes sometimes, and because value numbering of casts isn't
4422 perfect, we sometimes end up inserting dead code. This simple DCE-like
4423 pass removes any insertions we made that weren't actually used. */
4424 simple_dce_from_worklist (inserted_exprs);
4426 fini_pre ();
4428 scev_finalize ();
4429 loop_optimizer_finalize ();
4431 /* TODO: tail_merge_optimize may merge all predecessors of a block, in which
4432 case we can merge the block with the remaining predecessor of the block.
4433 It should either:
4434 - call merge_blocks after each tail merge iteration
4435 - call merge_blocks after all tail merge iterations
4436 - mark TODO_cleanup_cfg when necessary
4437 - share the cfg cleanup with fini_pre. */
4438 todo |= tail_merge_optimize (todo);
4440 free_rpo_vn ();
4442 /* Tail merging invalidates the virtual SSA web, together with
4443 cfg-cleanup opportunities exposed by PRE this will wreck the
4444 SSA updating machinery. So make sure to run update-ssa
4445 manually, before eventually scheduling cfg-cleanup as part of
4446 the todo. */
4447 update_ssa (TODO_update_ssa_only_virtuals);
4449 return todo;
4452 } // anon namespace
4454 gimple_opt_pass *
4455 make_pass_pre (gcc::context *ctxt)
4457 return new pass_pre (ctxt);