use auto_sbitmap in various places
[official-gcc.git] / gcc / tree-ssa-pre.c
blobc2c7495d02d912c2f664bdcb4cc4e5ef545e021b
1 /* Full and partial redundancy elimination and code hoisting on SSA GIMPLE.
2 Copyright (C) 2001-2016 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-ssa-loop.h"
43 #include "tree-into-ssa.h"
44 #include "tree-dfa.h"
45 #include "tree-ssa.h"
46 #include "cfgloop.h"
47 #include "tree-ssa-sccvn.h"
48 #include "tree-scalar-evolution.h"
49 #include "params.h"
50 #include "dbgcnt.h"
51 #include "domwalk.h"
52 #include "tree-ssa-propagate.h"
53 #include "ipa-utils.h"
54 #include "tree-cfgcleanup.h"
55 #include "langhooks.h"
56 #include "alias.h"
58 /* Even though this file is called tree-ssa-pre.c, we actually
59 implement a bit more than just PRE here. All of them piggy-back
60 on GVN which is implemented in tree-ssa-sccvn.c.
62 1. Full Redundancy Elimination (FRE)
63 This is the elimination phase of GVN.
65 2. Partial Redundancy Elimination (PRE)
66 This is adds computation of AVAIL_OUT and ANTIC_IN and
67 doing expression insertion to form GVN-PRE.
69 3. Code hoisting
70 This optimization uses the ANTIC_IN sets computed for PRE
71 to move expressions further up than PRE would do, to make
72 multiple computations of the same value fully redundant.
73 This pass is explained below (after the explanation of the
74 basic algorithm for PRE).
77 /* TODO:
79 1. Avail sets can be shared by making an avail_find_leader that
80 walks up the dominator tree and looks in those avail sets.
81 This might affect code optimality, it's unclear right now.
82 Currently the AVAIL_OUT sets are the remaining quadraticness in
83 memory of GVN-PRE.
84 2. Strength reduction can be performed by anticipating expressions
85 we can repair later on.
86 3. We can do back-substitution or smarter value numbering to catch
87 commutative expressions split up over multiple statements.
90 /* For ease of terminology, "expression node" in the below refers to
91 every expression node but GIMPLE_ASSIGN, because GIMPLE_ASSIGNs
92 represent the actual statement containing the expressions we care about,
93 and we cache the value number by putting it in the expression. */
95 /* Basic algorithm for Partial Redundancy Elimination:
97 First we walk the statements to generate the AVAIL sets, the
98 EXP_GEN sets, and the tmp_gen sets. EXP_GEN sets represent the
99 generation of values/expressions by a given block. We use them
100 when computing the ANTIC sets. The AVAIL sets consist of
101 SSA_NAME's that represent values, so we know what values are
102 available in what blocks. AVAIL is a forward dataflow problem. In
103 SSA, values are never killed, so we don't need a kill set, or a
104 fixpoint iteration, in order to calculate the AVAIL sets. In
105 traditional parlance, AVAIL sets tell us the downsafety of the
106 expressions/values.
108 Next, we generate the ANTIC sets. These sets represent the
109 anticipatable expressions. ANTIC is a backwards dataflow
110 problem. An expression is anticipatable in a given block if it could
111 be generated in that block. This means that if we had to perform
112 an insertion in that block, of the value of that expression, we
113 could. Calculating the ANTIC sets requires phi translation of
114 expressions, because the flow goes backwards through phis. We must
115 iterate to a fixpoint of the ANTIC sets, because we have a kill
116 set. Even in SSA form, values are not live over the entire
117 function, only from their definition point onwards. So we have to
118 remove values from the ANTIC set once we go past the definition
119 point of the leaders that make them up.
120 compute_antic/compute_antic_aux performs this computation.
122 Third, we perform insertions to make partially redundant
123 expressions fully redundant.
125 An expression is partially redundant (excluding partial
126 anticipation) if:
128 1. It is AVAIL in some, but not all, of the predecessors of a
129 given block.
130 2. It is ANTIC in all the predecessors.
132 In order to make it fully redundant, we insert the expression into
133 the predecessors where it is not available, but is ANTIC.
135 When optimizing for size, we only eliminate the partial redundancy
136 if we need to insert in only one predecessor. This avoids almost
137 completely the code size increase that PRE usually causes.
139 For the partial anticipation case, we only perform insertion if it
140 is partially anticipated in some block, and fully available in all
141 of the predecessors.
143 do_pre_regular_insertion/do_pre_partial_partial_insertion
144 performs these steps, driven by insert/insert_aux.
146 Fourth, we eliminate fully redundant expressions.
147 This is a simple statement walk that replaces redundant
148 calculations with the now available values. */
150 /* Basic algorithm for Code Hoisting:
152 Code hoisting is: Moving value computations up in the control flow
153 graph to make multiple copies redundant. Typically this is a size
154 optimization, but there are cases where it also is helpful for speed.
156 A simple code hoisting algorithm is implemented that piggy-backs on
157 the PRE infrastructure. For code hoisting, we have to know ANTIC_OUT
158 which is effectively ANTIC_IN - AVAIL_OUT. The latter two have to be
159 computed for PRE, and we can use them to perform a limited version of
160 code hoisting, too.
162 For the purpose of this implementation, a value is hoistable to a basic
163 block B if the following properties are met:
165 1. The value is in ANTIC_IN(B) -- the value will be computed on all
166 paths from B to function exit and it can be computed in B);
168 2. The value is not in AVAIL_OUT(B) -- there would be no need to
169 compute the value again and make it available twice;
171 3. All successors of B are dominated by B -- makes sure that inserting
172 a computation of the value in B will make the remaining
173 computations fully redundant;
175 4. At least one successor has the value in AVAIL_OUT -- to avoid
176 hoisting values up too far;
178 5. There are at least two successors of B -- hoisting in straight
179 line code is pointless.
181 The third condition is not strictly necessary, but it would complicate
182 the hoisting pass a lot. In fact, I don't know of any code hoisting
183 algorithm that does not have this requirement. Fortunately, experiments
184 have show that most candidate hoistable values are in regions that meet
185 this condition (e.g. diamond-shape regions).
187 The forth condition is necessary to avoid hoisting things up too far
188 away from the uses of the value. Nothing else limits the algorithm
189 from hoisting everything up as far as ANTIC_IN allows. Experiments
190 with SPEC and CSiBE have shown that hoisting up too far results in more
191 spilling, less benefits for code size, and worse benchmark scores.
192 Fortunately, in practice most of the interesting hoisting opportunities
193 are caught despite this limitation.
195 For hoistable values that meet all conditions, expressions are inserted
196 to make the calculation of the hoistable value fully redundant. We
197 perform code hoisting insertions after each round of PRE insertions,
198 because code hoisting never exposes new PRE opportunities, but PRE can
199 create new code hoisting opportunities.
201 The code hoisting algorithm is implemented in do_hoist_insert, driven
202 by insert/insert_aux. */
204 /* Representations of value numbers:
206 Value numbers are represented by a representative SSA_NAME. We
207 will create fake SSA_NAME's in situations where we need a
208 representative but do not have one (because it is a complex
209 expression). In order to facilitate storing the value numbers in
210 bitmaps, and keep the number of wasted SSA_NAME's down, we also
211 associate a value_id with each value number, and create full blown
212 ssa_name's only where we actually need them (IE in operands of
213 existing expressions).
215 Theoretically you could replace all the value_id's with
216 SSA_NAME_VERSION, but this would allocate a large number of
217 SSA_NAME's (which are each > 30 bytes) just to get a 4 byte number.
218 It would also require an additional indirection at each point we
219 use the value id. */
221 /* Representation of expressions on value numbers:
223 Expressions consisting of value numbers are represented the same
224 way as our VN internally represents them, with an additional
225 "pre_expr" wrapping around them in order to facilitate storing all
226 of the expressions in the same sets. */
228 /* Representation of sets:
230 The dataflow sets do not need to be sorted in any particular order
231 for the majority of their lifetime, are simply represented as two
232 bitmaps, one that keeps track of values present in the set, and one
233 that keeps track of expressions present in the set.
235 When we need them in topological order, we produce it on demand by
236 transforming the bitmap into an array and sorting it into topo
237 order. */
239 /* Type of expression, used to know which member of the PRE_EXPR union
240 is valid. */
242 enum pre_expr_kind
244 NAME,
245 NARY,
246 REFERENCE,
247 CONSTANT
250 union pre_expr_union
252 tree name;
253 tree constant;
254 vn_nary_op_t nary;
255 vn_reference_t reference;
258 typedef struct pre_expr_d : nofree_ptr_hash <pre_expr_d>
260 enum pre_expr_kind kind;
261 unsigned int id;
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 /* Free the expression id field in all of our expressions,
407 and then destroy the expressions array. */
409 static void
410 clear_expression_ids (void)
412 expressions.release ();
415 static object_allocator<pre_expr_d> pre_expr_pool ("pre_expr nodes");
417 /* Given an SSA_NAME NAME, get or create a pre_expr to represent it. */
419 static pre_expr
420 get_or_alloc_expr_for_name (tree name)
422 struct pre_expr_d expr;
423 pre_expr result;
424 unsigned int result_id;
426 expr.kind = NAME;
427 expr.id = 0;
428 PRE_EXPR_NAME (&expr) = name;
429 result_id = lookup_expression_id (&expr);
430 if (result_id != 0)
431 return expression_for_id (result_id);
433 result = pre_expr_pool.allocate ();
434 result->kind = NAME;
435 PRE_EXPR_NAME (result) = name;
436 alloc_expression_id (result);
437 return result;
440 /* An unordered bitmap set. One bitmap tracks values, the other,
441 expressions. */
442 typedef struct bitmap_set
444 bitmap_head expressions;
445 bitmap_head values;
446 } *bitmap_set_t;
448 #define FOR_EACH_EXPR_ID_IN_SET(set, id, bi) \
449 EXECUTE_IF_SET_IN_BITMAP (&(set)->expressions, 0, (id), (bi))
451 #define FOR_EACH_VALUE_ID_IN_SET(set, id, bi) \
452 EXECUTE_IF_SET_IN_BITMAP (&(set)->values, 0, (id), (bi))
454 /* Mapping from value id to expressions with that value_id. */
455 static vec<bitmap> value_expressions;
457 /* Sets that we need to keep track of. */
458 typedef struct bb_bitmap_sets
460 /* The EXP_GEN set, which represents expressions/values generated in
461 a basic block. */
462 bitmap_set_t exp_gen;
464 /* The PHI_GEN set, which represents PHI results generated in a
465 basic block. */
466 bitmap_set_t phi_gen;
468 /* The TMP_GEN set, which represents results/temporaries generated
469 in a basic block. IE the LHS of an expression. */
470 bitmap_set_t tmp_gen;
472 /* The AVAIL_OUT set, which represents which values are available in
473 a given basic block. */
474 bitmap_set_t avail_out;
476 /* The ANTIC_IN set, which represents which values are anticipatable
477 in a given basic block. */
478 bitmap_set_t antic_in;
480 /* The PA_IN set, which represents which values are
481 partially anticipatable in a given basic block. */
482 bitmap_set_t pa_in;
484 /* The NEW_SETS set, which is used during insertion to augment the
485 AVAIL_OUT set of blocks with the new insertions performed during
486 the current iteration. */
487 bitmap_set_t new_sets;
489 /* A cache for value_dies_in_block_x. */
490 bitmap expr_dies;
492 /* The live virtual operand on successor edges. */
493 tree vop_on_exit;
495 /* True if we have visited this block during ANTIC calculation. */
496 unsigned int visited : 1;
498 /* True when the block contains a call that might not return. */
499 unsigned int contains_may_not_return_call : 1;
500 } *bb_value_sets_t;
502 #define EXP_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->exp_gen
503 #define PHI_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->phi_gen
504 #define TMP_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->tmp_gen
505 #define AVAIL_OUT(BB) ((bb_value_sets_t) ((BB)->aux))->avail_out
506 #define ANTIC_IN(BB) ((bb_value_sets_t) ((BB)->aux))->antic_in
507 #define PA_IN(BB) ((bb_value_sets_t) ((BB)->aux))->pa_in
508 #define NEW_SETS(BB) ((bb_value_sets_t) ((BB)->aux))->new_sets
509 #define EXPR_DIES(BB) ((bb_value_sets_t) ((BB)->aux))->expr_dies
510 #define BB_VISITED(BB) ((bb_value_sets_t) ((BB)->aux))->visited
511 #define BB_MAY_NOTRETURN(BB) ((bb_value_sets_t) ((BB)->aux))->contains_may_not_return_call
512 #define BB_LIVE_VOP_ON_EXIT(BB) ((bb_value_sets_t) ((BB)->aux))->vop_on_exit
515 /* This structure is used to keep track of statistics on what
516 optimization PRE was able to perform. */
517 static struct
519 /* The number of RHS computations eliminated by PRE. */
520 int eliminations;
522 /* The number of new expressions/temporaries generated by PRE. */
523 int insertions;
525 /* The number of inserts found due to partial anticipation */
526 int pa_insert;
528 /* The number of inserts made for code hoisting. */
529 int hoist_insert;
531 /* The number of new PHI nodes added by PRE. */
532 int phis;
533 } pre_stats;
535 static bool do_partial_partial;
536 static pre_expr bitmap_find_leader (bitmap_set_t, unsigned int);
537 static void bitmap_value_insert_into_set (bitmap_set_t, pre_expr);
538 static void bitmap_value_replace_in_set (bitmap_set_t, pre_expr);
539 static void bitmap_set_copy (bitmap_set_t, bitmap_set_t);
540 static void bitmap_set_and (bitmap_set_t, bitmap_set_t);
541 static bool bitmap_set_contains_value (bitmap_set_t, unsigned int);
542 static void bitmap_insert_into_set (bitmap_set_t, pre_expr);
543 static void bitmap_insert_into_set_1 (bitmap_set_t, pre_expr,
544 unsigned int, bool);
545 static bitmap_set_t bitmap_set_new (void);
546 static tree create_expression_by_pieces (basic_block, pre_expr, gimple_seq *,
547 tree);
548 static tree find_or_generate_expression (basic_block, tree, gimple_seq *);
549 static unsigned int get_expr_value_id (pre_expr);
551 /* We can add and remove elements and entries to and from sets
552 and hash tables, so we use alloc pools for them. */
554 static object_allocator<bitmap_set> bitmap_set_pool ("Bitmap sets");
555 static bitmap_obstack grand_bitmap_obstack;
557 /* Set of blocks with statements that have had their EH properties changed. */
558 static bitmap need_eh_cleanup;
560 /* Set of blocks with statements that have had their AB properties changed. */
561 static bitmap need_ab_cleanup;
563 /* A three tuple {e, pred, v} used to cache phi translations in the
564 phi_translate_table. */
566 typedef struct expr_pred_trans_d : free_ptr_hash<expr_pred_trans_d>
568 /* The expression. */
569 pre_expr e;
571 /* The predecessor block along which we translated the expression. */
572 basic_block pred;
574 /* The value that resulted from the translation. */
575 pre_expr v;
577 /* The hashcode for the expression, pred pair. This is cached for
578 speed reasons. */
579 hashval_t hashcode;
581 /* hash_table support. */
582 static inline hashval_t hash (const expr_pred_trans_d *);
583 static inline int equal (const expr_pred_trans_d *, const expr_pred_trans_d *);
584 } *expr_pred_trans_t;
585 typedef const struct expr_pred_trans_d *const_expr_pred_trans_t;
587 inline hashval_t
588 expr_pred_trans_d::hash (const expr_pred_trans_d *e)
590 return e->hashcode;
593 inline int
594 expr_pred_trans_d::equal (const expr_pred_trans_d *ve1,
595 const expr_pred_trans_d *ve2)
597 basic_block b1 = ve1->pred;
598 basic_block b2 = ve2->pred;
600 /* If they are not translations for the same basic block, they can't
601 be equal. */
602 if (b1 != b2)
603 return false;
604 return pre_expr_d::equal (ve1->e, ve2->e);
607 /* The phi_translate_table caches phi translations for a given
608 expression and predecessor. */
609 static hash_table<expr_pred_trans_d> *phi_translate_table;
611 /* Add the tuple mapping from {expression E, basic block PRED} to
612 the phi translation table and return whether it pre-existed. */
614 static inline bool
615 phi_trans_add (expr_pred_trans_t *entry, pre_expr e, basic_block pred)
617 expr_pred_trans_t *slot;
618 expr_pred_trans_d tem;
619 hashval_t hash = iterative_hash_hashval_t (pre_expr_d::hash (e),
620 pred->index);
621 tem.e = e;
622 tem.pred = pred;
623 tem.hashcode = hash;
624 slot = phi_translate_table->find_slot_with_hash (&tem, hash, INSERT);
625 if (*slot)
627 *entry = *slot;
628 return true;
631 *entry = *slot = XNEW (struct expr_pred_trans_d);
632 (*entry)->e = e;
633 (*entry)->pred = pred;
634 (*entry)->hashcode = hash;
635 return false;
639 /* Add expression E to the expression set of value id V. */
641 static void
642 add_to_value (unsigned int v, pre_expr e)
644 bitmap set;
646 gcc_checking_assert (get_expr_value_id (e) == v);
648 if (v >= value_expressions.length ())
650 value_expressions.safe_grow_cleared (v + 1);
653 set = value_expressions[v];
654 if (!set)
656 set = BITMAP_ALLOC (&grand_bitmap_obstack);
657 value_expressions[v] = set;
660 bitmap_set_bit (set, get_or_alloc_expression_id (e));
663 /* Create a new bitmap set and return it. */
665 static bitmap_set_t
666 bitmap_set_new (void)
668 bitmap_set_t ret = bitmap_set_pool.allocate ();
669 bitmap_initialize (&ret->expressions, &grand_bitmap_obstack);
670 bitmap_initialize (&ret->values, &grand_bitmap_obstack);
671 return ret;
674 /* Return the value id for a PRE expression EXPR. */
676 static unsigned int
677 get_expr_value_id (pre_expr expr)
679 unsigned int id;
680 switch (expr->kind)
682 case CONSTANT:
683 id = get_constant_value_id (PRE_EXPR_CONSTANT (expr));
684 break;
685 case NAME:
686 id = VN_INFO (PRE_EXPR_NAME (expr))->value_id;
687 break;
688 case NARY:
689 id = PRE_EXPR_NARY (expr)->value_id;
690 break;
691 case REFERENCE:
692 id = PRE_EXPR_REFERENCE (expr)->value_id;
693 break;
694 default:
695 gcc_unreachable ();
697 /* ??? We cannot assert that expr has a value-id (it can be 0), because
698 we assign value-ids only to expressions that have a result
699 in set_hashtable_value_ids. */
700 return id;
703 /* Return a SCCVN valnum (SSA name or constant) for the PRE value-id VAL. */
705 static tree
706 sccvn_valnum_from_value_id (unsigned int val)
708 bitmap_iterator bi;
709 unsigned int i;
710 bitmap exprset = value_expressions[val];
711 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
713 pre_expr vexpr = expression_for_id (i);
714 if (vexpr->kind == NAME)
715 return VN_INFO (PRE_EXPR_NAME (vexpr))->valnum;
716 else if (vexpr->kind == CONSTANT)
717 return PRE_EXPR_CONSTANT (vexpr);
719 return NULL_TREE;
722 /* Remove an expression EXPR from a bitmapped set. */
724 static void
725 bitmap_remove_from_set (bitmap_set_t set, pre_expr expr)
727 unsigned int val = get_expr_value_id (expr);
728 if (!value_id_constant_p (val))
730 bitmap_clear_bit (&set->values, val);
731 bitmap_clear_bit (&set->expressions, get_expression_id (expr));
735 static void
736 bitmap_insert_into_set_1 (bitmap_set_t set, pre_expr expr,
737 unsigned int val, bool allow_constants)
739 if (allow_constants || !value_id_constant_p (val))
741 /* We specifically expect this and only this function to be able to
742 insert constants into a set. */
743 bitmap_set_bit (&set->values, val);
744 bitmap_set_bit (&set->expressions, get_or_alloc_expression_id (expr));
748 /* Insert an expression EXPR into a bitmapped set. */
750 static void
751 bitmap_insert_into_set (bitmap_set_t set, pre_expr expr)
753 bitmap_insert_into_set_1 (set, expr, get_expr_value_id (expr), false);
756 /* Copy a bitmapped set ORIG, into bitmapped set DEST. */
758 static void
759 bitmap_set_copy (bitmap_set_t dest, bitmap_set_t orig)
761 bitmap_copy (&dest->expressions, &orig->expressions);
762 bitmap_copy (&dest->values, &orig->values);
766 /* Free memory used up by SET. */
767 static void
768 bitmap_set_free (bitmap_set_t set)
770 bitmap_clear (&set->expressions);
771 bitmap_clear (&set->values);
775 /* Generate an topological-ordered array of bitmap set SET. */
777 static vec<pre_expr>
778 sorted_array_from_bitmap_set (bitmap_set_t set)
780 unsigned int i, j;
781 bitmap_iterator bi, bj;
782 vec<pre_expr> result;
784 /* Pre-allocate enough space for the array. */
785 result.create (bitmap_count_bits (&set->expressions));
787 FOR_EACH_VALUE_ID_IN_SET (set, i, bi)
789 /* The number of expressions having a given value is usually
790 relatively small. Thus, rather than making a vector of all
791 the expressions and sorting it by value-id, we walk the values
792 and check in the reverse mapping that tells us what expressions
793 have a given value, to filter those in our set. As a result,
794 the expressions are inserted in value-id order, which means
795 topological order.
797 If this is somehow a significant lose for some cases, we can
798 choose which set to walk based on the set size. */
799 bitmap exprset = value_expressions[i];
800 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, j, bj)
802 if (bitmap_bit_p (&set->expressions, j))
803 result.quick_push (expression_for_id (j));
807 return result;
810 /* Perform bitmapped set operation DEST &= ORIG. */
812 static void
813 bitmap_set_and (bitmap_set_t dest, bitmap_set_t orig)
815 bitmap_iterator bi;
816 unsigned int i;
818 if (dest != orig)
820 bitmap_head temp;
821 bitmap_initialize (&temp, &grand_bitmap_obstack);
823 bitmap_and_into (&dest->values, &orig->values);
824 bitmap_copy (&temp, &dest->expressions);
825 EXECUTE_IF_SET_IN_BITMAP (&temp, 0, i, bi)
827 pre_expr expr = expression_for_id (i);
828 unsigned int value_id = get_expr_value_id (expr);
829 if (!bitmap_bit_p (&dest->values, value_id))
830 bitmap_clear_bit (&dest->expressions, i);
832 bitmap_clear (&temp);
836 /* Subtract all values and expressions contained in ORIG from DEST. */
838 static bitmap_set_t
839 bitmap_set_subtract (bitmap_set_t dest, bitmap_set_t orig)
841 bitmap_set_t result = bitmap_set_new ();
842 bitmap_iterator bi;
843 unsigned int i;
845 bitmap_and_compl (&result->expressions, &dest->expressions,
846 &orig->expressions);
848 FOR_EACH_EXPR_ID_IN_SET (result, i, bi)
850 pre_expr expr = expression_for_id (i);
851 unsigned int value_id = get_expr_value_id (expr);
852 bitmap_set_bit (&result->values, value_id);
855 return result;
858 /* Subtract all the values in bitmap set B from bitmap set A. */
860 static void
861 bitmap_set_subtract_values (bitmap_set_t a, bitmap_set_t b)
863 unsigned int i;
864 bitmap_iterator bi;
865 bitmap_head temp;
867 bitmap_initialize (&temp, &grand_bitmap_obstack);
869 bitmap_copy (&temp, &a->expressions);
870 EXECUTE_IF_SET_IN_BITMAP (&temp, 0, i, bi)
872 pre_expr expr = expression_for_id (i);
873 if (bitmap_set_contains_value (b, get_expr_value_id (expr)))
874 bitmap_remove_from_set (a, expr);
876 bitmap_clear (&temp);
880 /* Return true if bitmapped set SET contains the value VALUE_ID. */
882 static bool
883 bitmap_set_contains_value (bitmap_set_t set, unsigned int value_id)
885 if (value_id_constant_p (value_id))
886 return true;
888 if (!set || bitmap_empty_p (&set->expressions))
889 return false;
891 return bitmap_bit_p (&set->values, value_id);
894 static inline bool
895 bitmap_set_contains_expr (bitmap_set_t set, const pre_expr expr)
897 return bitmap_bit_p (&set->expressions, get_expression_id (expr));
900 /* Replace an instance of value LOOKFOR with expression EXPR in SET. */
902 static void
903 bitmap_set_replace_value (bitmap_set_t set, unsigned int lookfor,
904 const pre_expr expr)
906 bitmap exprset;
907 unsigned int i;
908 bitmap_iterator bi;
910 if (value_id_constant_p (lookfor))
911 return;
913 if (!bitmap_set_contains_value (set, lookfor))
914 return;
916 /* The number of expressions having a given value is usually
917 significantly less than the total number of expressions in SET.
918 Thus, rather than check, for each expression in SET, whether it
919 has the value LOOKFOR, we walk the reverse mapping that tells us
920 what expressions have a given value, and see if any of those
921 expressions are in our set. For large testcases, this is about
922 5-10x faster than walking the bitmap. If this is somehow a
923 significant lose for some cases, we can choose which set to walk
924 based on the set size. */
925 exprset = value_expressions[lookfor];
926 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
928 if (bitmap_clear_bit (&set->expressions, i))
930 bitmap_set_bit (&set->expressions, get_expression_id (expr));
931 return;
935 gcc_unreachable ();
938 /* Return true if two bitmap sets are equal. */
940 static bool
941 bitmap_set_equal (bitmap_set_t a, bitmap_set_t b)
943 return bitmap_equal_p (&a->values, &b->values);
946 /* Replace an instance of EXPR's VALUE with EXPR in SET if it exists,
947 and add it otherwise. */
949 static void
950 bitmap_value_replace_in_set (bitmap_set_t set, pre_expr expr)
952 unsigned int val = get_expr_value_id (expr);
954 if (bitmap_set_contains_value (set, val))
955 bitmap_set_replace_value (set, val, expr);
956 else
957 bitmap_insert_into_set (set, expr);
960 /* Insert EXPR into SET if EXPR's value is not already present in
961 SET. */
963 static void
964 bitmap_value_insert_into_set (bitmap_set_t set, pre_expr expr)
966 unsigned int val = get_expr_value_id (expr);
968 gcc_checking_assert (expr->id == get_or_alloc_expression_id (expr));
970 /* Constant values are always considered to be part of the set. */
971 if (value_id_constant_p (val))
972 return;
974 /* If the value membership changed, add the expression. */
975 if (bitmap_set_bit (&set->values, val))
976 bitmap_set_bit (&set->expressions, expr->id);
979 /* Print out EXPR to outfile. */
981 static void
982 print_pre_expr (FILE *outfile, const pre_expr expr)
984 switch (expr->kind)
986 case CONSTANT:
987 print_generic_expr (outfile, PRE_EXPR_CONSTANT (expr), 0);
988 break;
989 case NAME:
990 print_generic_expr (outfile, PRE_EXPR_NAME (expr), 0);
991 break;
992 case NARY:
994 unsigned int i;
995 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
996 fprintf (outfile, "{%s,", get_tree_code_name (nary->opcode));
997 for (i = 0; i < nary->length; i++)
999 print_generic_expr (outfile, nary->op[i], 0);
1000 if (i != (unsigned) nary->length - 1)
1001 fprintf (outfile, ",");
1003 fprintf (outfile, "}");
1005 break;
1007 case REFERENCE:
1009 vn_reference_op_t vro;
1010 unsigned int i;
1011 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1012 fprintf (outfile, "{");
1013 for (i = 0;
1014 ref->operands.iterate (i, &vro);
1015 i++)
1017 bool closebrace = false;
1018 if (vro->opcode != SSA_NAME
1019 && TREE_CODE_CLASS (vro->opcode) != tcc_declaration)
1021 fprintf (outfile, "%s", get_tree_code_name (vro->opcode));
1022 if (vro->op0)
1024 fprintf (outfile, "<");
1025 closebrace = true;
1028 if (vro->op0)
1030 print_generic_expr (outfile, vro->op0, 0);
1031 if (vro->op1)
1033 fprintf (outfile, ",");
1034 print_generic_expr (outfile, vro->op1, 0);
1036 if (vro->op2)
1038 fprintf (outfile, ",");
1039 print_generic_expr (outfile, vro->op2, 0);
1042 if (closebrace)
1043 fprintf (outfile, ">");
1044 if (i != ref->operands.length () - 1)
1045 fprintf (outfile, ",");
1047 fprintf (outfile, "}");
1048 if (ref->vuse)
1050 fprintf (outfile, "@");
1051 print_generic_expr (outfile, ref->vuse, 0);
1054 break;
1057 void debug_pre_expr (pre_expr);
1059 /* Like print_pre_expr but always prints to stderr. */
1060 DEBUG_FUNCTION void
1061 debug_pre_expr (pre_expr e)
1063 print_pre_expr (stderr, e);
1064 fprintf (stderr, "\n");
1067 /* Print out SET to OUTFILE. */
1069 static void
1070 print_bitmap_set (FILE *outfile, bitmap_set_t set,
1071 const char *setname, int blockindex)
1073 fprintf (outfile, "%s[%d] := { ", setname, blockindex);
1074 if (set)
1076 bool first = true;
1077 unsigned i;
1078 bitmap_iterator bi;
1080 FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
1082 const pre_expr expr = expression_for_id (i);
1084 if (!first)
1085 fprintf (outfile, ", ");
1086 first = false;
1087 print_pre_expr (outfile, expr);
1089 fprintf (outfile, " (%04d)", get_expr_value_id (expr));
1092 fprintf (outfile, " }\n");
1095 void debug_bitmap_set (bitmap_set_t);
1097 DEBUG_FUNCTION void
1098 debug_bitmap_set (bitmap_set_t set)
1100 print_bitmap_set (stderr, set, "debug", 0);
1103 void debug_bitmap_sets_for (basic_block);
1105 DEBUG_FUNCTION void
1106 debug_bitmap_sets_for (basic_block bb)
1108 print_bitmap_set (stderr, AVAIL_OUT (bb), "avail_out", bb->index);
1109 print_bitmap_set (stderr, EXP_GEN (bb), "exp_gen", bb->index);
1110 print_bitmap_set (stderr, PHI_GEN (bb), "phi_gen", bb->index);
1111 print_bitmap_set (stderr, TMP_GEN (bb), "tmp_gen", bb->index);
1112 print_bitmap_set (stderr, ANTIC_IN (bb), "antic_in", bb->index);
1113 if (do_partial_partial)
1114 print_bitmap_set (stderr, PA_IN (bb), "pa_in", bb->index);
1115 print_bitmap_set (stderr, NEW_SETS (bb), "new_sets", bb->index);
1118 /* Print out the expressions that have VAL to OUTFILE. */
1120 static void
1121 print_value_expressions (FILE *outfile, unsigned int val)
1123 bitmap set = value_expressions[val];
1124 if (set)
1126 bitmap_set x;
1127 char s[10];
1128 sprintf (s, "%04d", val);
1129 x.expressions = *set;
1130 print_bitmap_set (outfile, &x, s, 0);
1135 DEBUG_FUNCTION void
1136 debug_value_expressions (unsigned int val)
1138 print_value_expressions (stderr, val);
1141 /* Given a CONSTANT, allocate a new CONSTANT type PRE_EXPR to
1142 represent it. */
1144 static pre_expr
1145 get_or_alloc_expr_for_constant (tree constant)
1147 unsigned int result_id;
1148 unsigned int value_id;
1149 struct pre_expr_d expr;
1150 pre_expr newexpr;
1152 expr.kind = CONSTANT;
1153 PRE_EXPR_CONSTANT (&expr) = constant;
1154 result_id = lookup_expression_id (&expr);
1155 if (result_id != 0)
1156 return expression_for_id (result_id);
1158 newexpr = pre_expr_pool.allocate ();
1159 newexpr->kind = CONSTANT;
1160 PRE_EXPR_CONSTANT (newexpr) = constant;
1161 alloc_expression_id (newexpr);
1162 value_id = get_or_alloc_constant_value_id (constant);
1163 add_to_value (value_id, newexpr);
1164 return newexpr;
1167 /* Get or allocate a pre_expr for a piece of GIMPLE, and return it.
1168 Currently only supports constants and SSA_NAMES. */
1169 static pre_expr
1170 get_or_alloc_expr_for (tree t)
1172 if (TREE_CODE (t) == SSA_NAME)
1173 return get_or_alloc_expr_for_name (t);
1174 else if (is_gimple_min_invariant (t))
1175 return get_or_alloc_expr_for_constant (t);
1176 else
1178 /* More complex expressions can result from SCCVN expression
1179 simplification that inserts values for them. As they all
1180 do not have VOPs the get handled by the nary ops struct. */
1181 vn_nary_op_t result;
1182 unsigned int result_id;
1183 vn_nary_op_lookup (t, &result);
1184 if (result != NULL)
1186 pre_expr e = pre_expr_pool.allocate ();
1187 e->kind = NARY;
1188 PRE_EXPR_NARY (e) = result;
1189 result_id = lookup_expression_id (e);
1190 if (result_id != 0)
1192 pre_expr_pool.remove (e);
1193 e = expression_for_id (result_id);
1194 return e;
1196 alloc_expression_id (e);
1197 return e;
1200 return NULL;
1203 /* Return the folded version of T if T, when folded, is a gimple
1204 min_invariant. Otherwise, return T. */
1206 static pre_expr
1207 fully_constant_expression (pre_expr e)
1209 switch (e->kind)
1211 case CONSTANT:
1212 return e;
1213 case NARY:
1215 vn_nary_op_t nary = PRE_EXPR_NARY (e);
1216 tree res = vn_nary_simplify (nary);
1217 if (!res)
1218 return e;
1219 if (is_gimple_min_invariant (res))
1220 return get_or_alloc_expr_for_constant (res);
1221 /* We might have simplified the expression to a
1222 SSA_NAME for example from x_1 * 1. But we cannot
1223 insert a PHI for x_1 unconditionally as x_1 might
1224 not be available readily. */
1225 return e;
1227 case REFERENCE:
1229 vn_reference_t ref = PRE_EXPR_REFERENCE (e);
1230 tree folded;
1231 if ((folded = fully_constant_vn_reference_p (ref)))
1232 return get_or_alloc_expr_for_constant (folded);
1233 return e;
1235 default:
1236 return e;
1238 return e;
1241 /* Translate the VUSE backwards through phi nodes in PHIBLOCK, so that
1242 it has the value it would have in BLOCK. Set *SAME_VALID to true
1243 in case the new vuse doesn't change the value id of the OPERANDS. */
1245 static tree
1246 translate_vuse_through_block (vec<vn_reference_op_s> operands,
1247 alias_set_type set, 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 *same_valid = true;
1258 if (gimple_bb (phi) != phiblock)
1259 return vuse;
1261 use_oracle = ao_ref_init_from_vn_reference (&ref, set, type, operands);
1263 /* Use the alias-oracle to find either the PHI node in this block,
1264 the first VUSE used in this block that is equivalent to vuse or
1265 the first VUSE which definition in this block kills the value. */
1266 if (gimple_code (phi) == GIMPLE_PHI)
1267 e = find_edge (block, phiblock);
1268 else if (use_oracle)
1269 while (!stmt_may_clobber_ref_p_1 (phi, &ref))
1271 vuse = gimple_vuse (phi);
1272 phi = SSA_NAME_DEF_STMT (vuse);
1273 if (gimple_bb (phi) != phiblock)
1274 return vuse;
1275 if (gimple_code (phi) == GIMPLE_PHI)
1277 e = find_edge (block, phiblock);
1278 break;
1281 else
1282 return NULL_TREE;
1284 if (e)
1286 if (use_oracle)
1288 bitmap visited = NULL;
1289 unsigned int cnt;
1290 /* Try to find a vuse that dominates this phi node by skipping
1291 non-clobbering statements. */
1292 vuse = get_continuation_for_phi (phi, &ref, &cnt, &visited, false,
1293 NULL, NULL);
1294 if (visited)
1295 BITMAP_FREE (visited);
1297 else
1298 vuse = NULL_TREE;
1299 if (!vuse)
1301 /* If we didn't find any, the value ID can't stay the same,
1302 but return the translated vuse. */
1303 *same_valid = false;
1304 vuse = PHI_ARG_DEF (phi, e->dest_idx);
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. This is used to avoid making a set consisting of the union
1319 of PA_IN and ANTIC_IN during insert. */
1321 static inline pre_expr
1322 find_leader_in_sets (unsigned int val, bitmap_set_t set1, bitmap_set_t set2)
1324 pre_expr result;
1326 result = bitmap_find_leader (set1, val);
1327 if (!result && set2)
1328 result = bitmap_find_leader (set2, val);
1329 return result;
1332 /* Get the tree type for our PRE expression e. */
1334 static tree
1335 get_expr_type (const pre_expr e)
1337 switch (e->kind)
1339 case NAME:
1340 return TREE_TYPE (PRE_EXPR_NAME (e));
1341 case CONSTANT:
1342 return TREE_TYPE (PRE_EXPR_CONSTANT (e));
1343 case REFERENCE:
1344 return PRE_EXPR_REFERENCE (e)->type;
1345 case NARY:
1346 return PRE_EXPR_NARY (e)->type;
1348 gcc_unreachable ();
1351 /* Get a representative SSA_NAME for a given expression.
1352 Since all of our sub-expressions are treated as values, we require
1353 them to be SSA_NAME's for simplicity.
1354 Prior versions of GVNPRE used to use "value handles" here, so that
1355 an expression would be VH.11 + VH.10 instead of d_3 + e_6. In
1356 either case, the operands are really values (IE we do not expect
1357 them to be usable without finding leaders). */
1359 static tree
1360 get_representative_for (const pre_expr e)
1362 tree name;
1363 unsigned int value_id = get_expr_value_id (e);
1365 switch (e->kind)
1367 case NAME:
1368 return VN_INFO (PRE_EXPR_NAME (e))->valnum;
1369 case CONSTANT:
1370 return PRE_EXPR_CONSTANT (e);
1371 case NARY:
1372 case REFERENCE:
1374 /* Go through all of the expressions representing this value
1375 and pick out an SSA_NAME. */
1376 unsigned int i;
1377 bitmap_iterator bi;
1378 bitmap exprs = value_expressions[value_id];
1379 EXECUTE_IF_SET_IN_BITMAP (exprs, 0, i, bi)
1381 pre_expr rep = expression_for_id (i);
1382 if (rep->kind == NAME)
1383 return VN_INFO (PRE_EXPR_NAME (rep))->valnum;
1384 else if (rep->kind == CONSTANT)
1385 return PRE_EXPR_CONSTANT (rep);
1388 break;
1391 /* If we reached here we couldn't find an SSA_NAME. This can
1392 happen when we've discovered a value that has never appeared in
1393 the program as set to an SSA_NAME, as the result of phi translation.
1394 Create one here.
1395 ??? We should be able to re-use this when we insert the statement
1396 to compute it. */
1397 name = make_temp_ssa_name (get_expr_type (e), gimple_build_nop (), "pretmp");
1398 VN_INFO_GET (name)->value_id = value_id;
1399 VN_INFO (name)->valnum = name;
1400 /* ??? For now mark this SSA name for release by SCCVN. */
1401 VN_INFO (name)->needs_insertion = true;
1402 add_to_value (value_id, get_or_alloc_expr_for_name (name));
1403 if (dump_file && (dump_flags & TDF_DETAILS))
1405 fprintf (dump_file, "Created SSA_NAME representative ");
1406 print_generic_expr (dump_file, name, 0);
1407 fprintf (dump_file, " for expression:");
1408 print_pre_expr (dump_file, e);
1409 fprintf (dump_file, " (%04d)\n", value_id);
1412 return name;
1417 static pre_expr
1418 phi_translate (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1419 basic_block pred, basic_block phiblock);
1421 /* Translate EXPR using phis in PHIBLOCK, so that it has the values of
1422 the phis in PRED. Return NULL if we can't find a leader for each part
1423 of the translated expression. */
1425 static pre_expr
1426 phi_translate_1 (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1427 basic_block pred, basic_block phiblock)
1429 switch (expr->kind)
1431 case NARY:
1433 unsigned int i;
1434 bool changed = false;
1435 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1436 vn_nary_op_t newnary = XALLOCAVAR (struct vn_nary_op_s,
1437 sizeof_vn_nary_op (nary->length));
1438 memcpy (newnary, nary, sizeof_vn_nary_op (nary->length));
1440 for (i = 0; i < newnary->length; i++)
1442 if (TREE_CODE (newnary->op[i]) != SSA_NAME)
1443 continue;
1444 else
1446 pre_expr leader, result;
1447 unsigned int op_val_id = VN_INFO (newnary->op[i])->value_id;
1448 leader = find_leader_in_sets (op_val_id, set1, set2);
1449 result = phi_translate (leader, set1, set2, pred, phiblock);
1450 if (result && result != leader)
1451 newnary->op[i] = get_representative_for (result);
1452 else if (!result)
1453 return NULL;
1455 changed |= newnary->op[i] != nary->op[i];
1458 if (changed)
1460 pre_expr constant;
1461 unsigned int new_val_id;
1463 PRE_EXPR_NARY (expr) = newnary;
1464 constant = fully_constant_expression (expr);
1465 PRE_EXPR_NARY (expr) = nary;
1466 if (constant != expr)
1467 return constant;
1469 tree result = vn_nary_op_lookup_pieces (newnary->length,
1470 newnary->opcode,
1471 newnary->type,
1472 &newnary->op[0],
1473 &nary);
1474 if (result && is_gimple_min_invariant (result))
1475 return get_or_alloc_expr_for_constant (result);
1477 expr = pre_expr_pool.allocate ();
1478 expr->kind = NARY;
1479 expr->id = 0;
1480 if (nary)
1482 PRE_EXPR_NARY (expr) = nary;
1483 new_val_id = nary->value_id;
1484 get_or_alloc_expression_id (expr);
1486 else
1488 new_val_id = get_next_value_id ();
1489 value_expressions.safe_grow_cleared (get_max_value_id () + 1);
1490 nary = vn_nary_op_insert_pieces (newnary->length,
1491 newnary->opcode,
1492 newnary->type,
1493 &newnary->op[0],
1494 result, new_val_id);
1495 PRE_EXPR_NARY (expr) = nary;
1496 get_or_alloc_expression_id (expr);
1498 add_to_value (new_val_id, expr);
1500 return expr;
1502 break;
1504 case REFERENCE:
1506 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1507 vec<vn_reference_op_s> operands = ref->operands;
1508 tree vuse = ref->vuse;
1509 tree newvuse = vuse;
1510 vec<vn_reference_op_s> newoperands = vNULL;
1511 bool changed = false, same_valid = true;
1512 unsigned int i, n;
1513 vn_reference_op_t operand;
1514 vn_reference_t newref;
1516 for (i = 0; operands.iterate (i, &operand); i++)
1518 pre_expr opresult;
1519 pre_expr leader;
1520 tree op[3];
1521 tree type = operand->type;
1522 vn_reference_op_s newop = *operand;
1523 op[0] = operand->op0;
1524 op[1] = operand->op1;
1525 op[2] = operand->op2;
1526 for (n = 0; n < 3; ++n)
1528 unsigned int op_val_id;
1529 if (!op[n])
1530 continue;
1531 if (TREE_CODE (op[n]) != SSA_NAME)
1533 /* We can't possibly insert these. */
1534 if (n != 0
1535 && !is_gimple_min_invariant (op[n]))
1536 break;
1537 continue;
1539 op_val_id = VN_INFO (op[n])->value_id;
1540 leader = find_leader_in_sets (op_val_id, set1, set2);
1541 opresult = phi_translate (leader, set1, set2, pred, phiblock);
1542 if (opresult && opresult != leader)
1544 tree name = get_representative_for (opresult);
1545 changed |= name != op[n];
1546 op[n] = name;
1548 else if (!opresult)
1549 break;
1551 if (n != 3)
1553 newoperands.release ();
1554 return NULL;
1556 if (!changed)
1557 continue;
1558 if (!newoperands.exists ())
1559 newoperands = operands.copy ();
1560 /* We may have changed from an SSA_NAME to a constant */
1561 if (newop.opcode == SSA_NAME && TREE_CODE (op[0]) != SSA_NAME)
1562 newop.opcode = TREE_CODE (op[0]);
1563 newop.type = type;
1564 newop.op0 = op[0];
1565 newop.op1 = op[1];
1566 newop.op2 = op[2];
1567 newoperands[i] = newop;
1569 gcc_checking_assert (i == operands.length ());
1571 if (vuse)
1573 newvuse = translate_vuse_through_block (newoperands.exists ()
1574 ? newoperands : operands,
1575 ref->set, ref->type,
1576 vuse, phiblock, pred,
1577 &same_valid);
1578 if (newvuse == NULL_TREE)
1580 newoperands.release ();
1581 return NULL;
1585 if (changed || newvuse != vuse)
1587 unsigned int new_val_id;
1588 pre_expr constant;
1590 tree result = vn_reference_lookup_pieces (newvuse, ref->set,
1591 ref->type,
1592 newoperands.exists ()
1593 ? newoperands : operands,
1594 &newref, VN_WALK);
1595 if (result)
1596 newoperands.release ();
1598 /* We can always insert constants, so if we have a partial
1599 redundant constant load of another type try to translate it
1600 to a constant of appropriate type. */
1601 if (result && is_gimple_min_invariant (result))
1603 tree tem = result;
1604 if (!useless_type_conversion_p (ref->type, TREE_TYPE (result)))
1606 tem = fold_unary (VIEW_CONVERT_EXPR, ref->type, result);
1607 if (tem && !is_gimple_min_invariant (tem))
1608 tem = NULL_TREE;
1610 if (tem)
1611 return get_or_alloc_expr_for_constant (tem);
1614 /* If we'd have to convert things we would need to validate
1615 if we can insert the translated expression. So fail
1616 here for now - we cannot insert an alias with a different
1617 type in the VN tables either, as that would assert. */
1618 if (result
1619 && !useless_type_conversion_p (ref->type, TREE_TYPE (result)))
1620 return NULL;
1621 else if (!result && newref
1622 && !useless_type_conversion_p (ref->type, newref->type))
1624 newoperands.release ();
1625 return NULL;
1628 expr = pre_expr_pool.allocate ();
1629 expr->kind = REFERENCE;
1630 expr->id = 0;
1632 if (newref)
1634 PRE_EXPR_REFERENCE (expr) = newref;
1635 constant = fully_constant_expression (expr);
1636 if (constant != expr)
1637 return constant;
1639 new_val_id = newref->value_id;
1640 get_or_alloc_expression_id (expr);
1642 else
1644 if (changed || !same_valid)
1646 new_val_id = get_next_value_id ();
1647 value_expressions.safe_grow_cleared
1648 (get_max_value_id () + 1);
1650 else
1651 new_val_id = ref->value_id;
1652 if (!newoperands.exists ())
1653 newoperands = operands.copy ();
1654 newref = vn_reference_insert_pieces (newvuse, ref->set,
1655 ref->type,
1656 newoperands,
1657 result, new_val_id);
1658 newoperands = vNULL;
1659 PRE_EXPR_REFERENCE (expr) = newref;
1660 constant = fully_constant_expression (expr);
1661 if (constant != expr)
1662 return constant;
1663 get_or_alloc_expression_id (expr);
1665 add_to_value (new_val_id, expr);
1667 newoperands.release ();
1668 return expr;
1670 break;
1672 case NAME:
1674 tree name = PRE_EXPR_NAME (expr);
1675 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
1676 /* If the SSA name is defined by a PHI node in this block,
1677 translate it. */
1678 if (gimple_code (def_stmt) == GIMPLE_PHI
1679 && gimple_bb (def_stmt) == phiblock)
1681 edge e = find_edge (pred, gimple_bb (def_stmt));
1682 tree def = PHI_ARG_DEF (def_stmt, e->dest_idx);
1684 /* Handle constant. */
1685 if (is_gimple_min_invariant (def))
1686 return get_or_alloc_expr_for_constant (def);
1688 return get_or_alloc_expr_for_name (def);
1690 /* Otherwise return it unchanged - it will get removed if its
1691 value is not available in PREDs AVAIL_OUT set of expressions
1692 by the subtraction of TMP_GEN. */
1693 return expr;
1696 default:
1697 gcc_unreachable ();
1701 /* Wrapper around phi_translate_1 providing caching functionality. */
1703 static pre_expr
1704 phi_translate (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1705 basic_block pred, basic_block phiblock)
1707 expr_pred_trans_t slot = NULL;
1708 pre_expr phitrans;
1710 if (!expr)
1711 return NULL;
1713 /* Constants contain no values that need translation. */
1714 if (expr->kind == CONSTANT)
1715 return expr;
1717 if (value_id_constant_p (get_expr_value_id (expr)))
1718 return expr;
1720 /* Don't add translations of NAMEs as those are cheap to translate. */
1721 if (expr->kind != NAME)
1723 if (phi_trans_add (&slot, expr, pred))
1724 return slot->v;
1725 /* Store NULL for the value we want to return in the case of
1726 recursing. */
1727 slot->v = NULL;
1730 /* Translate. */
1731 phitrans = phi_translate_1 (expr, set1, set2, pred, phiblock);
1733 if (slot)
1735 if (phitrans)
1736 slot->v = phitrans;
1737 else
1738 /* Remove failed translations again, they cause insert
1739 iteration to not pick up new opportunities reliably. */
1740 phi_translate_table->remove_elt_with_hash (slot, slot->hashcode);
1743 return phitrans;
1747 /* For each expression in SET, translate the values through phi nodes
1748 in PHIBLOCK using edge PHIBLOCK->PRED, and store the resulting
1749 expressions in DEST. */
1751 static void
1752 phi_translate_set (bitmap_set_t dest, bitmap_set_t set, basic_block pred,
1753 basic_block phiblock)
1755 vec<pre_expr> exprs;
1756 pre_expr expr;
1757 int i;
1759 if (gimple_seq_empty_p (phi_nodes (phiblock)))
1761 bitmap_set_copy (dest, set);
1762 return;
1765 exprs = sorted_array_from_bitmap_set (set);
1766 FOR_EACH_VEC_ELT (exprs, i, expr)
1768 pre_expr translated;
1769 translated = phi_translate (expr, set, NULL, pred, phiblock);
1770 if (!translated)
1771 continue;
1773 /* We might end up with multiple expressions from SET being
1774 translated to the same value. In this case we do not want
1775 to retain the NARY or REFERENCE expression but prefer a NAME
1776 which would be the leader. */
1777 if (translated->kind == NAME)
1778 bitmap_value_replace_in_set (dest, translated);
1779 else
1780 bitmap_value_insert_into_set (dest, translated);
1782 exprs.release ();
1785 /* Find the leader for a value (i.e., the name representing that
1786 value) in a given set, and return it. Return NULL if no leader
1787 is found. */
1789 static pre_expr
1790 bitmap_find_leader (bitmap_set_t set, unsigned int val)
1792 if (value_id_constant_p (val))
1794 unsigned int i;
1795 bitmap_iterator bi;
1796 bitmap exprset = value_expressions[val];
1798 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
1800 pre_expr expr = expression_for_id (i);
1801 if (expr->kind == CONSTANT)
1802 return expr;
1805 if (bitmap_set_contains_value (set, val))
1807 /* Rather than walk the entire bitmap of expressions, and see
1808 whether any of them has the value we are looking for, we look
1809 at the reverse mapping, which tells us the set of expressions
1810 that have a given value (IE value->expressions with that
1811 value) and see if any of those expressions are in our set.
1812 The number of expressions per value is usually significantly
1813 less than the number of expressions in the set. In fact, for
1814 large testcases, doing it this way is roughly 5-10x faster
1815 than walking the bitmap.
1816 If this is somehow a significant lose for some cases, we can
1817 choose which set to walk based on which set is smaller. */
1818 unsigned int i;
1819 bitmap_iterator bi;
1820 bitmap exprset = value_expressions[val];
1822 EXECUTE_IF_AND_IN_BITMAP (exprset, &set->expressions, 0, i, bi)
1823 return expression_for_id (i);
1825 return NULL;
1828 /* Determine if EXPR, a memory expression, is ANTIC_IN at the top of
1829 BLOCK by seeing if it is not killed in the block. Note that we are
1830 only determining whether there is a store that kills it. Because
1831 of the order in which clean iterates over values, we are guaranteed
1832 that altered operands will have caused us to be eliminated from the
1833 ANTIC_IN set already. */
1835 static bool
1836 value_dies_in_block_x (pre_expr expr, basic_block block)
1838 tree vuse = PRE_EXPR_REFERENCE (expr)->vuse;
1839 vn_reference_t refx = PRE_EXPR_REFERENCE (expr);
1840 gimple *def;
1841 gimple_stmt_iterator gsi;
1842 unsigned id = get_expression_id (expr);
1843 bool res = false;
1844 ao_ref ref;
1846 if (!vuse)
1847 return false;
1849 /* Lookup a previously calculated result. */
1850 if (EXPR_DIES (block)
1851 && bitmap_bit_p (EXPR_DIES (block), id * 2))
1852 return bitmap_bit_p (EXPR_DIES (block), id * 2 + 1);
1854 /* A memory expression {e, VUSE} dies in the block if there is a
1855 statement that may clobber e. If, starting statement walk from the
1856 top of the basic block, a statement uses VUSE there can be no kill
1857 inbetween that use and the original statement that loaded {e, VUSE},
1858 so we can stop walking. */
1859 ref.base = NULL_TREE;
1860 for (gsi = gsi_start_bb (block); !gsi_end_p (gsi); gsi_next (&gsi))
1862 tree def_vuse, def_vdef;
1863 def = gsi_stmt (gsi);
1864 def_vuse = gimple_vuse (def);
1865 def_vdef = gimple_vdef (def);
1867 /* Not a memory statement. */
1868 if (!def_vuse)
1869 continue;
1871 /* Not a may-def. */
1872 if (!def_vdef)
1874 /* A load with the same VUSE, we're done. */
1875 if (def_vuse == vuse)
1876 break;
1878 continue;
1881 /* Init ref only if we really need it. */
1882 if (ref.base == NULL_TREE
1883 && !ao_ref_init_from_vn_reference (&ref, refx->set, refx->type,
1884 refx->operands))
1886 res = true;
1887 break;
1889 /* If the statement may clobber expr, it dies. */
1890 if (stmt_may_clobber_ref_p_1 (def, &ref))
1892 res = true;
1893 break;
1897 /* Remember the result. */
1898 if (!EXPR_DIES (block))
1899 EXPR_DIES (block) = BITMAP_ALLOC (&grand_bitmap_obstack);
1900 bitmap_set_bit (EXPR_DIES (block), id * 2);
1901 if (res)
1902 bitmap_set_bit (EXPR_DIES (block), id * 2 + 1);
1904 return res;
1908 /* Determine if OP is valid in SET1 U SET2, which it is when the union
1909 contains its value-id. */
1911 static bool
1912 op_valid_in_sets (bitmap_set_t set1, bitmap_set_t set2, tree op)
1914 if (op && TREE_CODE (op) == SSA_NAME)
1916 unsigned int value_id = VN_INFO (op)->value_id;
1917 if (!(bitmap_set_contains_value (set1, value_id)
1918 || (set2 && bitmap_set_contains_value (set2, value_id))))
1919 return false;
1921 return true;
1924 /* Determine if the expression EXPR is valid in SET1 U SET2.
1925 ONLY SET2 CAN BE NULL.
1926 This means that we have a leader for each part of the expression
1927 (if it consists of values), or the expression is an SSA_NAME.
1928 For loads/calls, we also see if the vuse is killed in this block. */
1930 static bool
1931 valid_in_sets (bitmap_set_t set1, bitmap_set_t set2, pre_expr expr)
1933 switch (expr->kind)
1935 case NAME:
1936 /* By construction all NAMEs are available. Non-available
1937 NAMEs are removed by subtracting TMP_GEN from the sets. */
1938 return true;
1939 case NARY:
1941 unsigned int i;
1942 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1943 for (i = 0; i < nary->length; i++)
1944 if (!op_valid_in_sets (set1, set2, nary->op[i]))
1945 return false;
1946 return true;
1948 break;
1949 case REFERENCE:
1951 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1952 vn_reference_op_t vro;
1953 unsigned int i;
1955 FOR_EACH_VEC_ELT (ref->operands, i, vro)
1957 if (!op_valid_in_sets (set1, set2, vro->op0)
1958 || !op_valid_in_sets (set1, set2, vro->op1)
1959 || !op_valid_in_sets (set1, set2, vro->op2))
1960 return false;
1962 return true;
1964 default:
1965 gcc_unreachable ();
1969 /* Clean the set of expressions that are no longer valid in SET1 or
1970 SET2. This means expressions that are made up of values we have no
1971 leaders for in SET1 or SET2. This version is used for partial
1972 anticipation, which means it is not valid in either ANTIC_IN or
1973 PA_IN. */
1975 static void
1976 dependent_clean (bitmap_set_t set1, bitmap_set_t set2)
1978 vec<pre_expr> exprs = sorted_array_from_bitmap_set (set1);
1979 pre_expr expr;
1980 int i;
1982 FOR_EACH_VEC_ELT (exprs, i, expr)
1984 if (!valid_in_sets (set1, set2, expr))
1985 bitmap_remove_from_set (set1, expr);
1987 exprs.release ();
1990 /* Clean the set of expressions that are no longer valid in SET. This
1991 means expressions that are made up of values we have no leaders for
1992 in SET. */
1994 static void
1995 clean (bitmap_set_t set)
1997 vec<pre_expr> exprs = sorted_array_from_bitmap_set (set);
1998 pre_expr expr;
1999 int i;
2001 FOR_EACH_VEC_ELT (exprs, i, expr)
2003 if (!valid_in_sets (set, NULL, expr))
2004 bitmap_remove_from_set (set, expr);
2006 exprs.release ();
2009 /* Clean the set of expressions that are no longer valid in SET because
2010 they are clobbered in BLOCK or because they trap and may not be executed. */
2012 static void
2013 prune_clobbered_mems (bitmap_set_t set, basic_block block)
2015 bitmap_iterator bi;
2016 unsigned i;
2018 FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
2020 pre_expr expr = expression_for_id (i);
2021 if (expr->kind == REFERENCE)
2023 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
2024 if (ref->vuse)
2026 gimple *def_stmt = SSA_NAME_DEF_STMT (ref->vuse);
2027 if (!gimple_nop_p (def_stmt)
2028 && ((gimple_bb (def_stmt) != block
2029 && !dominated_by_p (CDI_DOMINATORS,
2030 block, gimple_bb (def_stmt)))
2031 || (gimple_bb (def_stmt) == block
2032 && value_dies_in_block_x (expr, block))))
2033 bitmap_remove_from_set (set, expr);
2036 else if (expr->kind == NARY)
2038 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
2039 /* If the NARY may trap make sure the block does not contain
2040 a possible exit point.
2041 ??? This is overly conservative if we translate AVAIL_OUT
2042 as the available expression might be after the exit point. */
2043 if (BB_MAY_NOTRETURN (block)
2044 && vn_nary_may_trap (nary))
2045 bitmap_remove_from_set (set, expr);
2050 static sbitmap has_abnormal_preds;
2052 /* Compute the ANTIC set for BLOCK.
2054 If succs(BLOCK) > 1 then
2055 ANTIC_OUT[BLOCK] = intersection of ANTIC_IN[b] for all succ(BLOCK)
2056 else if succs(BLOCK) == 1 then
2057 ANTIC_OUT[BLOCK] = phi_translate (ANTIC_IN[succ(BLOCK)])
2059 ANTIC_IN[BLOCK] = clean(ANTIC_OUT[BLOCK] U EXP_GEN[BLOCK] - TMP_GEN[BLOCK])
2062 static bool
2063 compute_antic_aux (basic_block block, bool block_has_abnormal_pred_edge)
2065 bool changed = false;
2066 bitmap_set_t S, old, ANTIC_OUT;
2067 bitmap_iterator bi;
2068 unsigned int bii;
2069 edge e;
2070 edge_iterator ei;
2071 bool was_visited = BB_VISITED (block);
2073 old = ANTIC_OUT = S = NULL;
2074 BB_VISITED (block) = 1;
2076 /* If any edges from predecessors are abnormal, antic_in is empty,
2077 so do nothing. */
2078 if (block_has_abnormal_pred_edge)
2079 goto maybe_dump_sets;
2081 old = ANTIC_IN (block);
2082 ANTIC_OUT = bitmap_set_new ();
2084 /* If the block has no successors, ANTIC_OUT is empty. */
2085 if (EDGE_COUNT (block->succs) == 0)
2087 /* If we have one successor, we could have some phi nodes to
2088 translate through. */
2089 else if (single_succ_p (block))
2091 basic_block succ_bb = single_succ (block);
2092 gcc_assert (BB_VISITED (succ_bb));
2093 phi_translate_set (ANTIC_OUT, ANTIC_IN (succ_bb), block, succ_bb);
2095 /* If we have multiple successors, we take the intersection of all of
2096 them. Note that in the case of loop exit phi nodes, we may have
2097 phis to translate through. */
2098 else
2100 size_t i;
2101 basic_block bprime, first = NULL;
2103 auto_vec<basic_block> worklist (EDGE_COUNT (block->succs));
2104 FOR_EACH_EDGE (e, ei, block->succs)
2106 if (!first
2107 && BB_VISITED (e->dest))
2108 first = e->dest;
2109 else if (BB_VISITED (e->dest))
2110 worklist.quick_push (e->dest);
2111 else
2113 /* Unvisited successors get their ANTIC_IN replaced by the
2114 maximal set to arrive at a maximum ANTIC_IN solution.
2115 We can ignore them in the intersection operation and thus
2116 need not explicitely represent that maximum solution. */
2117 if (dump_file && (dump_flags & TDF_DETAILS))
2118 fprintf (dump_file, "ANTIC_IN is MAX on %d->%d\n",
2119 e->src->index, e->dest->index);
2123 /* Of multiple successors we have to have visited one already
2124 which is guaranteed by iteration order. */
2125 gcc_assert (first != NULL);
2127 phi_translate_set (ANTIC_OUT, ANTIC_IN (first), block, first);
2129 FOR_EACH_VEC_ELT (worklist, i, bprime)
2131 if (!gimple_seq_empty_p (phi_nodes (bprime)))
2133 bitmap_set_t tmp = bitmap_set_new ();
2134 phi_translate_set (tmp, ANTIC_IN (bprime), block, bprime);
2135 bitmap_set_and (ANTIC_OUT, tmp);
2136 bitmap_set_free (tmp);
2138 else
2139 bitmap_set_and (ANTIC_OUT, ANTIC_IN (bprime));
2143 /* Prune expressions that are clobbered in block and thus become
2144 invalid if translated from ANTIC_OUT to ANTIC_IN. */
2145 prune_clobbered_mems (ANTIC_OUT, block);
2147 /* Generate ANTIC_OUT - TMP_GEN. */
2148 S = bitmap_set_subtract (ANTIC_OUT, TMP_GEN (block));
2150 /* Start ANTIC_IN with EXP_GEN - TMP_GEN. */
2151 ANTIC_IN (block) = bitmap_set_subtract (EXP_GEN (block),
2152 TMP_GEN (block));
2154 /* Then union in the ANTIC_OUT - TMP_GEN values,
2155 to get ANTIC_OUT U EXP_GEN - TMP_GEN */
2156 FOR_EACH_EXPR_ID_IN_SET (S, bii, bi)
2157 bitmap_value_insert_into_set (ANTIC_IN (block),
2158 expression_for_id (bii));
2160 clean (ANTIC_IN (block));
2162 if (!was_visited || !bitmap_set_equal (old, ANTIC_IN (block)))
2163 changed = true;
2165 maybe_dump_sets:
2166 if (dump_file && (dump_flags & TDF_DETAILS))
2168 if (ANTIC_OUT)
2169 print_bitmap_set (dump_file, ANTIC_OUT, "ANTIC_OUT", block->index);
2171 if (changed)
2172 fprintf (dump_file, "[changed] ");
2173 print_bitmap_set (dump_file, ANTIC_IN (block), "ANTIC_IN",
2174 block->index);
2176 if (S)
2177 print_bitmap_set (dump_file, S, "S", block->index);
2179 if (old)
2180 bitmap_set_free (old);
2181 if (S)
2182 bitmap_set_free (S);
2183 if (ANTIC_OUT)
2184 bitmap_set_free (ANTIC_OUT);
2185 return changed;
2188 /* Compute PARTIAL_ANTIC for BLOCK.
2190 If succs(BLOCK) > 1 then
2191 PA_OUT[BLOCK] = value wise union of PA_IN[b] + all ANTIC_IN not
2192 in ANTIC_OUT for all succ(BLOCK)
2193 else if succs(BLOCK) == 1 then
2194 PA_OUT[BLOCK] = phi_translate (PA_IN[succ(BLOCK)])
2196 PA_IN[BLOCK] = dependent_clean(PA_OUT[BLOCK] - TMP_GEN[BLOCK]
2197 - ANTIC_IN[BLOCK])
2200 static void
2201 compute_partial_antic_aux (basic_block block,
2202 bool block_has_abnormal_pred_edge)
2204 bitmap_set_t old_PA_IN;
2205 bitmap_set_t PA_OUT;
2206 edge e;
2207 edge_iterator ei;
2208 unsigned long max_pa = PARAM_VALUE (PARAM_MAX_PARTIAL_ANTIC_LENGTH);
2210 old_PA_IN = PA_OUT = NULL;
2212 /* If any edges from predecessors are abnormal, antic_in is empty,
2213 so do nothing. */
2214 if (block_has_abnormal_pred_edge)
2215 goto maybe_dump_sets;
2217 /* If there are too many partially anticipatable values in the
2218 block, phi_translate_set can take an exponential time: stop
2219 before the translation starts. */
2220 if (max_pa
2221 && single_succ_p (block)
2222 && bitmap_count_bits (&PA_IN (single_succ (block))->values) > max_pa)
2223 goto maybe_dump_sets;
2225 old_PA_IN = PA_IN (block);
2226 PA_OUT = bitmap_set_new ();
2228 /* If the block has no successors, ANTIC_OUT is empty. */
2229 if (EDGE_COUNT (block->succs) == 0)
2231 /* If we have one successor, we could have some phi nodes to
2232 translate through. Note that we can't phi translate across DFS
2233 back edges in partial antic, because it uses a union operation on
2234 the successors. For recurrences like IV's, we will end up
2235 generating a new value in the set on each go around (i + 3 (VH.1)
2236 VH.1 + 1 (VH.2), VH.2 + 1 (VH.3), etc), forever. */
2237 else if (single_succ_p (block))
2239 basic_block succ = single_succ (block);
2240 if (!(single_succ_edge (block)->flags & EDGE_DFS_BACK))
2241 phi_translate_set (PA_OUT, PA_IN (succ), block, succ);
2243 /* If we have multiple successors, we take the union of all of
2244 them. */
2245 else
2247 size_t i;
2248 basic_block bprime;
2250 auto_vec<basic_block> worklist (EDGE_COUNT (block->succs));
2251 FOR_EACH_EDGE (e, ei, block->succs)
2253 if (e->flags & EDGE_DFS_BACK)
2254 continue;
2255 worklist.quick_push (e->dest);
2257 if (worklist.length () > 0)
2259 FOR_EACH_VEC_ELT (worklist, i, bprime)
2261 unsigned int i;
2262 bitmap_iterator bi;
2264 FOR_EACH_EXPR_ID_IN_SET (ANTIC_IN (bprime), i, bi)
2265 bitmap_value_insert_into_set (PA_OUT,
2266 expression_for_id (i));
2267 if (!gimple_seq_empty_p (phi_nodes (bprime)))
2269 bitmap_set_t pa_in = bitmap_set_new ();
2270 phi_translate_set (pa_in, PA_IN (bprime), block, bprime);
2271 FOR_EACH_EXPR_ID_IN_SET (pa_in, i, bi)
2272 bitmap_value_insert_into_set (PA_OUT,
2273 expression_for_id (i));
2274 bitmap_set_free (pa_in);
2276 else
2277 FOR_EACH_EXPR_ID_IN_SET (PA_IN (bprime), i, bi)
2278 bitmap_value_insert_into_set (PA_OUT,
2279 expression_for_id (i));
2284 /* Prune expressions that are clobbered in block and thus become
2285 invalid if translated from PA_OUT to PA_IN. */
2286 prune_clobbered_mems (PA_OUT, block);
2288 /* PA_IN starts with PA_OUT - TMP_GEN.
2289 Then we subtract things from ANTIC_IN. */
2290 PA_IN (block) = bitmap_set_subtract (PA_OUT, TMP_GEN (block));
2292 /* For partial antic, we want to put back in the phi results, since
2293 we will properly avoid making them partially antic over backedges. */
2294 bitmap_ior_into (&PA_IN (block)->values, &PHI_GEN (block)->values);
2295 bitmap_ior_into (&PA_IN (block)->expressions, &PHI_GEN (block)->expressions);
2297 /* PA_IN[block] = PA_IN[block] - ANTIC_IN[block] */
2298 bitmap_set_subtract_values (PA_IN (block), ANTIC_IN (block));
2300 dependent_clean (PA_IN (block), ANTIC_IN (block));
2302 maybe_dump_sets:
2303 if (dump_file && (dump_flags & TDF_DETAILS))
2305 if (PA_OUT)
2306 print_bitmap_set (dump_file, PA_OUT, "PA_OUT", block->index);
2308 print_bitmap_set (dump_file, PA_IN (block), "PA_IN", block->index);
2310 if (old_PA_IN)
2311 bitmap_set_free (old_PA_IN);
2312 if (PA_OUT)
2313 bitmap_set_free (PA_OUT);
2316 /* Compute ANTIC and partial ANTIC sets. */
2318 static void
2319 compute_antic (void)
2321 bool changed = true;
2322 int num_iterations = 0;
2323 basic_block block;
2324 int i;
2325 edge_iterator ei;
2326 edge e;
2328 /* If any predecessor edges are abnormal, we punt, so antic_in is empty.
2329 We pre-build the map of blocks with incoming abnormal edges here. */
2330 has_abnormal_preds = sbitmap_alloc (last_basic_block_for_fn (cfun));
2331 bitmap_clear (has_abnormal_preds);
2333 FOR_ALL_BB_FN (block, cfun)
2335 BB_VISITED (block) = 0;
2337 FOR_EACH_EDGE (e, ei, block->preds)
2338 if (e->flags & EDGE_ABNORMAL)
2340 bitmap_set_bit (has_abnormal_preds, block->index);
2342 /* We also anticipate nothing. */
2343 BB_VISITED (block) = 1;
2344 break;
2347 /* While we are here, give empty ANTIC_IN sets to each block. */
2348 ANTIC_IN (block) = bitmap_set_new ();
2349 if (do_partial_partial)
2350 PA_IN (block) = bitmap_set_new ();
2353 /* At the exit block we anticipate nothing. */
2354 BB_VISITED (EXIT_BLOCK_PTR_FOR_FN (cfun)) = 1;
2356 /* For ANTIC computation we need a postorder that also guarantees that
2357 a block with a single successor is visited after its successor.
2358 RPO on the inverted CFG has this property. */
2359 int *postorder = XNEWVEC (int, n_basic_blocks_for_fn (cfun));
2360 int postorder_num = inverted_post_order_compute (postorder);
2362 auto_sbitmap worklist (last_basic_block_for_fn (cfun) + 1);
2363 bitmap_ones (worklist);
2364 while (changed)
2366 if (dump_file && (dump_flags & TDF_DETAILS))
2367 fprintf (dump_file, "Starting iteration %d\n", num_iterations);
2368 /* ??? We need to clear our PHI translation cache here as the
2369 ANTIC sets shrink and we restrict valid translations to
2370 those having operands with leaders in ANTIC. Same below
2371 for PA ANTIC computation. */
2372 num_iterations++;
2373 changed = false;
2374 for (i = postorder_num - 1; i >= 0; i--)
2376 if (bitmap_bit_p (worklist, postorder[i]))
2378 basic_block block = BASIC_BLOCK_FOR_FN (cfun, postorder[i]);
2379 bitmap_clear_bit (worklist, block->index);
2380 if (compute_antic_aux (block,
2381 bitmap_bit_p (has_abnormal_preds,
2382 block->index)))
2384 FOR_EACH_EDGE (e, ei, block->preds)
2385 bitmap_set_bit (worklist, e->src->index);
2386 changed = true;
2390 /* Theoretically possible, but *highly* unlikely. */
2391 gcc_checking_assert (num_iterations < 500);
2394 statistics_histogram_event (cfun, "compute_antic iterations",
2395 num_iterations);
2397 if (do_partial_partial)
2399 /* For partial antic we ignore backedges and thus we do not need
2400 to perform any iteration when we process blocks in postorder. */
2401 postorder_num = pre_and_rev_post_order_compute (NULL, postorder, false);
2402 for (i = postorder_num - 1 ; i >= 0; i--)
2404 basic_block block = BASIC_BLOCK_FOR_FN (cfun, postorder[i]);
2405 compute_partial_antic_aux (block,
2406 bitmap_bit_p (has_abnormal_preds,
2407 block->index));
2411 sbitmap_free (has_abnormal_preds);
2412 free (postorder);
2416 /* Inserted expressions are placed onto this worklist, which is used
2417 for performing quick dead code elimination of insertions we made
2418 that didn't turn out to be necessary. */
2419 static bitmap inserted_exprs;
2421 /* The actual worker for create_component_ref_by_pieces. */
2423 static tree
2424 create_component_ref_by_pieces_1 (basic_block block, vn_reference_t ref,
2425 unsigned int *operand, gimple_seq *stmts)
2427 vn_reference_op_t currop = &ref->operands[*operand];
2428 tree genop;
2429 ++*operand;
2430 switch (currop->opcode)
2432 case CALL_EXPR:
2433 gcc_unreachable ();
2435 case MEM_REF:
2437 tree baseop = create_component_ref_by_pieces_1 (block, ref, operand,
2438 stmts);
2439 if (!baseop)
2440 return NULL_TREE;
2441 tree offset = currop->op0;
2442 if (TREE_CODE (baseop) == ADDR_EXPR
2443 && handled_component_p (TREE_OPERAND (baseop, 0)))
2445 HOST_WIDE_INT off;
2446 tree base;
2447 base = get_addr_base_and_unit_offset (TREE_OPERAND (baseop, 0),
2448 &off);
2449 gcc_assert (base);
2450 offset = int_const_binop (PLUS_EXPR, offset,
2451 build_int_cst (TREE_TYPE (offset),
2452 off));
2453 baseop = build_fold_addr_expr (base);
2455 genop = build2 (MEM_REF, currop->type, baseop, offset);
2456 MR_DEPENDENCE_CLIQUE (genop) = currop->clique;
2457 MR_DEPENDENCE_BASE (genop) = currop->base;
2458 REF_REVERSE_STORAGE_ORDER (genop) = currop->reverse;
2459 return genop;
2462 case TARGET_MEM_REF:
2464 tree genop0 = NULL_TREE, genop1 = NULL_TREE;
2465 vn_reference_op_t nextop = &ref->operands[++*operand];
2466 tree baseop = create_component_ref_by_pieces_1 (block, ref, operand,
2467 stmts);
2468 if (!baseop)
2469 return NULL_TREE;
2470 if (currop->op0)
2472 genop0 = find_or_generate_expression (block, currop->op0, stmts);
2473 if (!genop0)
2474 return NULL_TREE;
2476 if (nextop->op0)
2478 genop1 = find_or_generate_expression (block, nextop->op0, stmts);
2479 if (!genop1)
2480 return NULL_TREE;
2482 genop = build5 (TARGET_MEM_REF, currop->type,
2483 baseop, currop->op2, genop0, currop->op1, genop1);
2485 MR_DEPENDENCE_CLIQUE (genop) = currop->clique;
2486 MR_DEPENDENCE_BASE (genop) = currop->base;
2487 return genop;
2490 case ADDR_EXPR:
2491 if (currop->op0)
2493 gcc_assert (is_gimple_min_invariant (currop->op0));
2494 return currop->op0;
2496 /* Fallthrough. */
2497 case REALPART_EXPR:
2498 case IMAGPART_EXPR:
2499 case VIEW_CONVERT_EXPR:
2501 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2502 stmts);
2503 if (!genop0)
2504 return NULL_TREE;
2505 return fold_build1 (currop->opcode, currop->type, genop0);
2508 case WITH_SIZE_EXPR:
2510 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2511 stmts);
2512 if (!genop0)
2513 return NULL_TREE;
2514 tree genop1 = find_or_generate_expression (block, currop->op0, stmts);
2515 if (!genop1)
2516 return NULL_TREE;
2517 return fold_build2 (currop->opcode, currop->type, genop0, genop1);
2520 case BIT_FIELD_REF:
2522 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2523 stmts);
2524 if (!genop0)
2525 return NULL_TREE;
2526 tree op1 = currop->op0;
2527 tree op2 = currop->op1;
2528 tree t = build3 (BIT_FIELD_REF, currop->type, genop0, op1, op2);
2529 REF_REVERSE_STORAGE_ORDER (t) = currop->reverse;
2530 return fold (t);
2533 /* For array ref vn_reference_op's, operand 1 of the array ref
2534 is op0 of the reference op and operand 3 of the array ref is
2535 op1. */
2536 case ARRAY_RANGE_REF:
2537 case ARRAY_REF:
2539 tree genop0;
2540 tree genop1 = currop->op0;
2541 tree genop2 = currop->op1;
2542 tree genop3 = currop->op2;
2543 genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2544 stmts);
2545 if (!genop0)
2546 return NULL_TREE;
2547 genop1 = find_or_generate_expression (block, genop1, stmts);
2548 if (!genop1)
2549 return NULL_TREE;
2550 if (genop2)
2552 tree domain_type = TYPE_DOMAIN (TREE_TYPE (genop0));
2553 /* Drop zero minimum index if redundant. */
2554 if (integer_zerop (genop2)
2555 && (!domain_type
2556 || integer_zerop (TYPE_MIN_VALUE (domain_type))))
2557 genop2 = NULL_TREE;
2558 else
2560 genop2 = find_or_generate_expression (block, genop2, stmts);
2561 if (!genop2)
2562 return NULL_TREE;
2565 if (genop3)
2567 tree elmt_type = TREE_TYPE (TREE_TYPE (genop0));
2568 /* We can't always put a size in units of the element alignment
2569 here as the element alignment may be not visible. See
2570 PR43783. Simply drop the element size for constant
2571 sizes. */
2572 if (TREE_CODE (genop3) == INTEGER_CST
2573 && TREE_CODE (TYPE_SIZE_UNIT (elmt_type)) == INTEGER_CST
2574 && wi::eq_p (wi::to_offset (TYPE_SIZE_UNIT (elmt_type)),
2575 (wi::to_offset (genop3)
2576 * vn_ref_op_align_unit (currop))))
2577 genop3 = NULL_TREE;
2578 else
2580 genop3 = find_or_generate_expression (block, genop3, stmts);
2581 if (!genop3)
2582 return NULL_TREE;
2585 return build4 (currop->opcode, currop->type, genop0, genop1,
2586 genop2, genop3);
2588 case COMPONENT_REF:
2590 tree op0;
2591 tree op1;
2592 tree genop2 = currop->op1;
2593 op0 = create_component_ref_by_pieces_1 (block, ref, operand, stmts);
2594 if (!op0)
2595 return NULL_TREE;
2596 /* op1 should be a FIELD_DECL, which are represented by themselves. */
2597 op1 = currop->op0;
2598 if (genop2)
2600 genop2 = find_or_generate_expression (block, genop2, stmts);
2601 if (!genop2)
2602 return NULL_TREE;
2604 return fold_build3 (COMPONENT_REF, TREE_TYPE (op1), op0, op1, genop2);
2607 case SSA_NAME:
2609 genop = find_or_generate_expression (block, currop->op0, stmts);
2610 return genop;
2612 case STRING_CST:
2613 case INTEGER_CST:
2614 case COMPLEX_CST:
2615 case VECTOR_CST:
2616 case REAL_CST:
2617 case CONSTRUCTOR:
2618 case VAR_DECL:
2619 case PARM_DECL:
2620 case CONST_DECL:
2621 case RESULT_DECL:
2622 case FUNCTION_DECL:
2623 return currop->op0;
2625 default:
2626 gcc_unreachable ();
2630 /* For COMPONENT_REF's and ARRAY_REF's, we can't have any intermediates for the
2631 COMPONENT_REF or MEM_REF or ARRAY_REF portion, because we'd end up with
2632 trying to rename aggregates into ssa form directly, which is a no no.
2634 Thus, this routine doesn't create temporaries, it just builds a
2635 single access expression for the array, calling
2636 find_or_generate_expression to build the innermost pieces.
2638 This function is a subroutine of create_expression_by_pieces, and
2639 should not be called on it's own unless you really know what you
2640 are doing. */
2642 static tree
2643 create_component_ref_by_pieces (basic_block block, vn_reference_t ref,
2644 gimple_seq *stmts)
2646 unsigned int op = 0;
2647 return create_component_ref_by_pieces_1 (block, ref, &op, stmts);
2650 /* Find a simple leader for an expression, or generate one using
2651 create_expression_by_pieces from a NARY expression for the value.
2652 BLOCK is the basic_block we are looking for leaders in.
2653 OP is the tree expression to find a leader for or generate.
2654 Returns the leader or NULL_TREE on failure. */
2656 static tree
2657 find_or_generate_expression (basic_block block, tree op, gimple_seq *stmts)
2659 pre_expr expr = get_or_alloc_expr_for (op);
2660 unsigned int lookfor = get_expr_value_id (expr);
2661 pre_expr leader = bitmap_find_leader (AVAIL_OUT (block), lookfor);
2662 if (leader)
2664 if (leader->kind == NAME)
2665 return PRE_EXPR_NAME (leader);
2666 else if (leader->kind == CONSTANT)
2667 return PRE_EXPR_CONSTANT (leader);
2669 /* Defer. */
2670 return NULL_TREE;
2673 /* It must be a complex expression, so generate it recursively. Note
2674 that this is only necessary to handle gcc.dg/tree-ssa/ssa-pre28.c
2675 where the insert algorithm fails to insert a required expression. */
2676 bitmap exprset = value_expressions[lookfor];
2677 bitmap_iterator bi;
2678 unsigned int i;
2679 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
2681 pre_expr temp = expression_for_id (i);
2682 /* We cannot insert random REFERENCE expressions at arbitrary
2683 places. We can insert NARYs which eventually re-materializes
2684 its operand values. */
2685 if (temp->kind == NARY)
2686 return create_expression_by_pieces (block, temp, stmts,
2687 get_expr_type (expr));
2690 /* Defer. */
2691 return NULL_TREE;
2694 #define NECESSARY GF_PLF_1
2696 /* Create an expression in pieces, so that we can handle very complex
2697 expressions that may be ANTIC, but not necessary GIMPLE.
2698 BLOCK is the basic block the expression will be inserted into,
2699 EXPR is the expression to insert (in value form)
2700 STMTS is a statement list to append the necessary insertions into.
2702 This function will die if we hit some value that shouldn't be
2703 ANTIC but is (IE there is no leader for it, or its components).
2704 The function returns NULL_TREE in case a different antic expression
2705 has to be inserted first.
2706 This function may also generate expressions that are themselves
2707 partially or fully redundant. Those that are will be either made
2708 fully redundant during the next iteration of insert (for partially
2709 redundant ones), or eliminated by eliminate (for fully redundant
2710 ones). */
2712 static tree
2713 create_expression_by_pieces (basic_block block, pre_expr expr,
2714 gimple_seq *stmts, tree type)
2716 tree name;
2717 tree folded;
2718 gimple_seq forced_stmts = NULL;
2719 unsigned int value_id;
2720 gimple_stmt_iterator gsi;
2721 tree exprtype = type ? type : get_expr_type (expr);
2722 pre_expr nameexpr;
2723 gassign *newstmt;
2725 switch (expr->kind)
2727 /* We may hit the NAME/CONSTANT case if we have to convert types
2728 that value numbering saw through. */
2729 case NAME:
2730 folded = PRE_EXPR_NAME (expr);
2731 if (useless_type_conversion_p (exprtype, TREE_TYPE (folded)))
2732 return folded;
2733 break;
2734 case CONSTANT:
2736 folded = PRE_EXPR_CONSTANT (expr);
2737 tree tem = fold_convert (exprtype, folded);
2738 if (is_gimple_min_invariant (tem))
2739 return tem;
2740 break;
2742 case REFERENCE:
2743 if (PRE_EXPR_REFERENCE (expr)->operands[0].opcode == CALL_EXPR)
2745 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
2746 unsigned int operand = 1;
2747 vn_reference_op_t currop = &ref->operands[0];
2748 tree sc = NULL_TREE;
2749 tree fn;
2750 if (TREE_CODE (currop->op0) == FUNCTION_DECL)
2751 fn = currop->op0;
2752 else
2753 fn = find_or_generate_expression (block, currop->op0, stmts);
2754 if (!fn)
2755 return NULL_TREE;
2756 if (currop->op1)
2758 sc = find_or_generate_expression (block, currop->op1, stmts);
2759 if (!sc)
2760 return NULL_TREE;
2762 auto_vec<tree> args (ref->operands.length () - 1);
2763 while (operand < ref->operands.length ())
2765 tree arg = create_component_ref_by_pieces_1 (block, ref,
2766 &operand, stmts);
2767 if (!arg)
2768 return NULL_TREE;
2769 args.quick_push (arg);
2771 gcall *call
2772 = gimple_build_call_vec ((TREE_CODE (fn) == FUNCTION_DECL
2773 ? build_fold_addr_expr (fn) : fn), args);
2774 gimple_call_set_with_bounds (call, currop->with_bounds);
2775 if (sc)
2776 gimple_call_set_chain (call, sc);
2777 tree forcedname = make_ssa_name (currop->type);
2778 gimple_call_set_lhs (call, forcedname);
2779 gimple_set_vuse (call, BB_LIVE_VOP_ON_EXIT (block));
2780 gimple_seq_add_stmt_without_update (&forced_stmts, call);
2781 folded = forcedname;
2783 else
2785 folded = create_component_ref_by_pieces (block,
2786 PRE_EXPR_REFERENCE (expr),
2787 stmts);
2788 if (!folded)
2789 return NULL_TREE;
2790 name = make_temp_ssa_name (exprtype, NULL, "pretmp");
2791 newstmt = gimple_build_assign (name, folded);
2792 gimple_seq_add_stmt_without_update (&forced_stmts, newstmt);
2793 gimple_set_vuse (newstmt, BB_LIVE_VOP_ON_EXIT (block));
2794 folded = name;
2796 break;
2797 case NARY:
2799 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
2800 tree *genop = XALLOCAVEC (tree, nary->length);
2801 unsigned i;
2802 for (i = 0; i < nary->length; ++i)
2804 genop[i] = find_or_generate_expression (block, nary->op[i], stmts);
2805 if (!genop[i])
2806 return NULL_TREE;
2807 /* Ensure genop[] is properly typed for POINTER_PLUS_EXPR. It
2808 may have conversions stripped. */
2809 if (nary->opcode == POINTER_PLUS_EXPR)
2811 if (i == 0)
2812 genop[i] = gimple_convert (&forced_stmts,
2813 nary->type, genop[i]);
2814 else if (i == 1)
2815 genop[i] = gimple_convert (&forced_stmts,
2816 sizetype, genop[i]);
2818 else
2819 genop[i] = gimple_convert (&forced_stmts,
2820 TREE_TYPE (nary->op[i]), genop[i]);
2822 if (nary->opcode == CONSTRUCTOR)
2824 vec<constructor_elt, va_gc> *elts = NULL;
2825 for (i = 0; i < nary->length; ++i)
2826 CONSTRUCTOR_APPEND_ELT (elts, NULL_TREE, genop[i]);
2827 folded = build_constructor (nary->type, elts);
2828 name = make_temp_ssa_name (exprtype, NULL, "pretmp");
2829 newstmt = gimple_build_assign (name, folded);
2830 gimple_seq_add_stmt_without_update (&forced_stmts, newstmt);
2831 folded = name;
2833 else
2835 switch (nary->length)
2837 case 1:
2838 folded = gimple_build (&forced_stmts, nary->opcode, nary->type,
2839 genop[0]);
2840 break;
2841 case 2:
2842 folded = gimple_build (&forced_stmts, nary->opcode, nary->type,
2843 genop[0], genop[1]);
2844 break;
2845 case 3:
2846 folded = gimple_build (&forced_stmts, nary->opcode, nary->type,
2847 genop[0], genop[1], genop[2]);
2848 break;
2849 default:
2850 gcc_unreachable ();
2854 break;
2855 default:
2856 gcc_unreachable ();
2859 folded = gimple_convert (&forced_stmts, exprtype, folded);
2861 /* If there is nothing to insert, return the simplified result. */
2862 if (gimple_seq_empty_p (forced_stmts))
2863 return folded;
2864 /* If we simplified to a constant return it and discard eventually
2865 built stmts. */
2866 if (is_gimple_min_invariant (folded))
2868 gimple_seq_discard (forced_stmts);
2869 return folded;
2872 gcc_assert (TREE_CODE (folded) == SSA_NAME);
2874 /* If we have any intermediate expressions to the value sets, add them
2875 to the value sets and chain them in the instruction stream. */
2876 if (forced_stmts)
2878 gsi = gsi_start (forced_stmts);
2879 for (; !gsi_end_p (gsi); gsi_next (&gsi))
2881 gimple *stmt = gsi_stmt (gsi);
2882 tree forcedname = gimple_get_lhs (stmt);
2883 pre_expr nameexpr;
2885 if (forcedname != folded)
2887 VN_INFO_GET (forcedname)->valnum = forcedname;
2888 VN_INFO (forcedname)->value_id = get_next_value_id ();
2889 nameexpr = get_or_alloc_expr_for_name (forcedname);
2890 add_to_value (VN_INFO (forcedname)->value_id, nameexpr);
2891 bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
2892 bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
2895 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (forcedname));
2896 gimple_set_plf (stmt, NECESSARY, false);
2898 gimple_seq_add_seq (stmts, forced_stmts);
2901 name = folded;
2903 /* Fold the last statement. */
2904 gsi = gsi_last (*stmts);
2905 if (fold_stmt_inplace (&gsi))
2906 update_stmt (gsi_stmt (gsi));
2908 /* Add a value number to the temporary.
2909 The value may already exist in either NEW_SETS, or AVAIL_OUT, because
2910 we are creating the expression by pieces, and this particular piece of
2911 the expression may have been represented. There is no harm in replacing
2912 here. */
2913 value_id = get_expr_value_id (expr);
2914 VN_INFO_GET (name)->value_id = value_id;
2915 VN_INFO (name)->valnum = sccvn_valnum_from_value_id (value_id);
2916 if (VN_INFO (name)->valnum == NULL_TREE)
2917 VN_INFO (name)->valnum = name;
2918 gcc_assert (VN_INFO (name)->valnum != NULL_TREE);
2919 nameexpr = get_or_alloc_expr_for_name (name);
2920 add_to_value (value_id, nameexpr);
2921 if (NEW_SETS (block))
2922 bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
2923 bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
2925 pre_stats.insertions++;
2926 if (dump_file && (dump_flags & TDF_DETAILS))
2928 fprintf (dump_file, "Inserted ");
2929 print_gimple_stmt (dump_file, gsi_stmt (gsi_last (*stmts)), 0, 0);
2930 fprintf (dump_file, " in predecessor %d (%04d)\n",
2931 block->index, value_id);
2934 return name;
2938 /* Insert the to-be-made-available values of expression EXPRNUM for each
2939 predecessor, stored in AVAIL, into the predecessors of BLOCK, and
2940 merge the result with a phi node, given the same value number as
2941 NODE. Return true if we have inserted new stuff. */
2943 static bool
2944 insert_into_preds_of_block (basic_block block, unsigned int exprnum,
2945 vec<pre_expr> avail)
2947 pre_expr expr = expression_for_id (exprnum);
2948 pre_expr newphi;
2949 unsigned int val = get_expr_value_id (expr);
2950 edge pred;
2951 bool insertions = false;
2952 bool nophi = false;
2953 basic_block bprime;
2954 pre_expr eprime;
2955 edge_iterator ei;
2956 tree type = get_expr_type (expr);
2957 tree temp;
2958 gphi *phi;
2960 /* Make sure we aren't creating an induction variable. */
2961 if (bb_loop_depth (block) > 0 && EDGE_COUNT (block->preds) == 2)
2963 bool firstinsideloop = false;
2964 bool secondinsideloop = false;
2965 firstinsideloop = flow_bb_inside_loop_p (block->loop_father,
2966 EDGE_PRED (block, 0)->src);
2967 secondinsideloop = flow_bb_inside_loop_p (block->loop_father,
2968 EDGE_PRED (block, 1)->src);
2969 /* Induction variables only have one edge inside the loop. */
2970 if ((firstinsideloop ^ secondinsideloop)
2971 && expr->kind != REFERENCE)
2973 if (dump_file && (dump_flags & TDF_DETAILS))
2974 fprintf (dump_file, "Skipping insertion of phi for partial redundancy: Looks like an induction variable\n");
2975 nophi = true;
2979 /* Make the necessary insertions. */
2980 FOR_EACH_EDGE (pred, ei, block->preds)
2982 gimple_seq stmts = NULL;
2983 tree builtexpr;
2984 bprime = pred->src;
2985 eprime = avail[pred->dest_idx];
2986 builtexpr = create_expression_by_pieces (bprime, eprime,
2987 &stmts, type);
2988 gcc_assert (!(pred->flags & EDGE_ABNORMAL));
2989 if (!gimple_seq_empty_p (stmts))
2991 gsi_insert_seq_on_edge (pred, stmts);
2992 insertions = true;
2994 if (!builtexpr)
2996 /* We cannot insert a PHI node if we failed to insert
2997 on one edge. */
2998 nophi = true;
2999 continue;
3001 if (is_gimple_min_invariant (builtexpr))
3002 avail[pred->dest_idx] = get_or_alloc_expr_for_constant (builtexpr);
3003 else
3004 avail[pred->dest_idx] = get_or_alloc_expr_for_name (builtexpr);
3006 /* If we didn't want a phi node, and we made insertions, we still have
3007 inserted new stuff, and thus return true. If we didn't want a phi node,
3008 and didn't make insertions, we haven't added anything new, so return
3009 false. */
3010 if (nophi && insertions)
3011 return true;
3012 else if (nophi && !insertions)
3013 return false;
3015 /* Now build a phi for the new variable. */
3016 temp = make_temp_ssa_name (type, NULL, "prephitmp");
3017 phi = create_phi_node (temp, block);
3019 gimple_set_plf (phi, NECESSARY, false);
3020 VN_INFO_GET (temp)->value_id = val;
3021 VN_INFO (temp)->valnum = sccvn_valnum_from_value_id (val);
3022 if (VN_INFO (temp)->valnum == NULL_TREE)
3023 VN_INFO (temp)->valnum = temp;
3024 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (temp));
3025 FOR_EACH_EDGE (pred, ei, block->preds)
3027 pre_expr ae = avail[pred->dest_idx];
3028 gcc_assert (get_expr_type (ae) == type
3029 || useless_type_conversion_p (type, get_expr_type (ae)));
3030 if (ae->kind == CONSTANT)
3031 add_phi_arg (phi, unshare_expr (PRE_EXPR_CONSTANT (ae)),
3032 pred, UNKNOWN_LOCATION);
3033 else
3034 add_phi_arg (phi, PRE_EXPR_NAME (ae), pred, UNKNOWN_LOCATION);
3037 newphi = get_or_alloc_expr_for_name (temp);
3038 add_to_value (val, newphi);
3040 /* The value should *not* exist in PHI_GEN, or else we wouldn't be doing
3041 this insertion, since we test for the existence of this value in PHI_GEN
3042 before proceeding with the partial redundancy checks in insert_aux.
3044 The value may exist in AVAIL_OUT, in particular, it could be represented
3045 by the expression we are trying to eliminate, in which case we want the
3046 replacement to occur. If it's not existing in AVAIL_OUT, we want it
3047 inserted there.
3049 Similarly, to the PHI_GEN case, the value should not exist in NEW_SETS of
3050 this block, because if it did, it would have existed in our dominator's
3051 AVAIL_OUT, and would have been skipped due to the full redundancy check.
3054 bitmap_insert_into_set (PHI_GEN (block), newphi);
3055 bitmap_value_replace_in_set (AVAIL_OUT (block),
3056 newphi);
3057 bitmap_insert_into_set (NEW_SETS (block),
3058 newphi);
3060 /* If we insert a PHI node for a conversion of another PHI node
3061 in the same basic-block try to preserve range information.
3062 This is important so that followup loop passes receive optimal
3063 number of iteration analysis results. See PR61743. */
3064 if (expr->kind == NARY
3065 && CONVERT_EXPR_CODE_P (expr->u.nary->opcode)
3066 && TREE_CODE (expr->u.nary->op[0]) == SSA_NAME
3067 && gimple_bb (SSA_NAME_DEF_STMT (expr->u.nary->op[0])) == block
3068 && INTEGRAL_TYPE_P (type)
3069 && INTEGRAL_TYPE_P (TREE_TYPE (expr->u.nary->op[0]))
3070 && (TYPE_PRECISION (type)
3071 >= TYPE_PRECISION (TREE_TYPE (expr->u.nary->op[0])))
3072 && SSA_NAME_RANGE_INFO (expr->u.nary->op[0]))
3074 wide_int min, max;
3075 if (get_range_info (expr->u.nary->op[0], &min, &max) == VR_RANGE
3076 && !wi::neg_p (min, SIGNED)
3077 && !wi::neg_p (max, SIGNED))
3078 /* Just handle extension and sign-changes of all-positive ranges. */
3079 set_range_info (temp,
3080 SSA_NAME_RANGE_TYPE (expr->u.nary->op[0]),
3081 wide_int_storage::from (min, TYPE_PRECISION (type),
3082 TYPE_SIGN (type)),
3083 wide_int_storage::from (max, TYPE_PRECISION (type),
3084 TYPE_SIGN (type)));
3087 if (dump_file && (dump_flags & TDF_DETAILS))
3089 fprintf (dump_file, "Created phi ");
3090 print_gimple_stmt (dump_file, phi, 0, 0);
3091 fprintf (dump_file, " in block %d (%04d)\n", block->index, val);
3093 pre_stats.phis++;
3094 return true;
3099 /* Perform insertion of partially redundant or hoistable values.
3100 For BLOCK, do the following:
3101 1. Propagate the NEW_SETS of the dominator into the current block.
3102 If the block has multiple predecessors,
3103 2a. Iterate over the ANTIC expressions for the block to see if
3104 any of them are partially redundant.
3105 2b. If so, insert them into the necessary predecessors to make
3106 the expression fully redundant.
3107 2c. Insert a new PHI merging the values of the predecessors.
3108 2d. Insert the new PHI, and the new expressions, into the
3109 NEW_SETS set.
3110 If the block has multiple successors,
3111 3a. Iterate over the ANTIC values for the block to see if
3112 any of them are good candidates for hoisting.
3113 3b. If so, insert expressions computing the values in BLOCK,
3114 and add the new expressions into the NEW_SETS set.
3115 4. Recursively call ourselves on the dominator children of BLOCK.
3117 Steps 1, 2a, and 4 are done by insert_aux. 2b, 2c and 2d are done by
3118 do_pre_regular_insertion and do_partial_insertion. 3a and 3b are
3119 done in do_hoist_insertion.
3122 static bool
3123 do_pre_regular_insertion (basic_block block, basic_block dom)
3125 bool new_stuff = false;
3126 vec<pre_expr> exprs;
3127 pre_expr expr;
3128 auto_vec<pre_expr> avail;
3129 int i;
3131 exprs = sorted_array_from_bitmap_set (ANTIC_IN (block));
3132 avail.safe_grow (EDGE_COUNT (block->preds));
3134 FOR_EACH_VEC_ELT (exprs, i, expr)
3136 if (expr->kind == NARY
3137 || expr->kind == REFERENCE)
3139 unsigned int val;
3140 bool by_some = false;
3141 bool cant_insert = false;
3142 bool all_same = true;
3143 pre_expr first_s = NULL;
3144 edge pred;
3145 basic_block bprime;
3146 pre_expr eprime = NULL;
3147 edge_iterator ei;
3148 pre_expr edoubleprime = NULL;
3149 bool do_insertion = false;
3151 val = get_expr_value_id (expr);
3152 if (bitmap_set_contains_value (PHI_GEN (block), val))
3153 continue;
3154 if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3156 if (dump_file && (dump_flags & TDF_DETAILS))
3158 fprintf (dump_file, "Found fully redundant value: ");
3159 print_pre_expr (dump_file, expr);
3160 fprintf (dump_file, "\n");
3162 continue;
3165 FOR_EACH_EDGE (pred, ei, block->preds)
3167 unsigned int vprime;
3169 /* We should never run insertion for the exit block
3170 and so not come across fake pred edges. */
3171 gcc_assert (!(pred->flags & EDGE_FAKE));
3172 bprime = pred->src;
3173 /* We are looking at ANTIC_OUT of bprime. */
3174 eprime = phi_translate (expr, ANTIC_IN (block), NULL,
3175 bprime, block);
3177 /* eprime will generally only be NULL if the
3178 value of the expression, translated
3179 through the PHI for this predecessor, is
3180 undefined. If that is the case, we can't
3181 make the expression fully redundant,
3182 because its value is undefined along a
3183 predecessor path. We can thus break out
3184 early because it doesn't matter what the
3185 rest of the results are. */
3186 if (eprime == NULL)
3188 avail[pred->dest_idx] = NULL;
3189 cant_insert = true;
3190 break;
3193 vprime = get_expr_value_id (eprime);
3194 edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime),
3195 vprime);
3196 if (edoubleprime == NULL)
3198 avail[pred->dest_idx] = eprime;
3199 all_same = false;
3201 else
3203 avail[pred->dest_idx] = edoubleprime;
3204 by_some = true;
3205 /* We want to perform insertions to remove a redundancy on
3206 a path in the CFG we want to optimize for speed. */
3207 if (optimize_edge_for_speed_p (pred))
3208 do_insertion = true;
3209 if (first_s == NULL)
3210 first_s = edoubleprime;
3211 else if (!pre_expr_d::equal (first_s, edoubleprime))
3212 all_same = false;
3215 /* If we can insert it, it's not the same value
3216 already existing along every predecessor, and
3217 it's defined by some predecessor, it is
3218 partially redundant. */
3219 if (!cant_insert && !all_same && by_some)
3221 if (!do_insertion)
3223 if (dump_file && (dump_flags & TDF_DETAILS))
3225 fprintf (dump_file, "Skipping partial redundancy for "
3226 "expression ");
3227 print_pre_expr (dump_file, expr);
3228 fprintf (dump_file, " (%04d), no redundancy on to be "
3229 "optimized for speed edge\n", val);
3232 else if (dbg_cnt (treepre_insert))
3234 if (dump_file && (dump_flags & TDF_DETAILS))
3236 fprintf (dump_file, "Found partial redundancy for "
3237 "expression ");
3238 print_pre_expr (dump_file, expr);
3239 fprintf (dump_file, " (%04d)\n",
3240 get_expr_value_id (expr));
3242 if (insert_into_preds_of_block (block,
3243 get_expression_id (expr),
3244 avail))
3245 new_stuff = true;
3248 /* If all edges produce the same value and that value is
3249 an invariant, then the PHI has the same value on all
3250 edges. Note this. */
3251 else if (!cant_insert && all_same)
3253 gcc_assert (edoubleprime->kind == CONSTANT
3254 || edoubleprime->kind == NAME);
3256 tree temp = make_temp_ssa_name (get_expr_type (expr),
3257 NULL, "pretmp");
3258 gassign *assign
3259 = gimple_build_assign (temp,
3260 edoubleprime->kind == CONSTANT ?
3261 PRE_EXPR_CONSTANT (edoubleprime) :
3262 PRE_EXPR_NAME (edoubleprime));
3263 gimple_stmt_iterator gsi = gsi_after_labels (block);
3264 gsi_insert_before (&gsi, assign, GSI_NEW_STMT);
3266 gimple_set_plf (assign, NECESSARY, false);
3267 VN_INFO_GET (temp)->value_id = val;
3268 VN_INFO (temp)->valnum = sccvn_valnum_from_value_id (val);
3269 if (VN_INFO (temp)->valnum == NULL_TREE)
3270 VN_INFO (temp)->valnum = temp;
3271 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (temp));
3272 pre_expr newe = get_or_alloc_expr_for_name (temp);
3273 add_to_value (val, newe);
3274 bitmap_value_replace_in_set (AVAIL_OUT (block), newe);
3275 bitmap_insert_into_set (NEW_SETS (block), newe);
3280 exprs.release ();
3281 return new_stuff;
3285 /* Perform insertion for partially anticipatable expressions. There
3286 is only one case we will perform insertion for these. This case is
3287 if the expression is partially anticipatable, and fully available.
3288 In this case, we know that putting it earlier will enable us to
3289 remove the later computation. */
3291 static bool
3292 do_pre_partial_partial_insertion (basic_block block, basic_block dom)
3294 bool new_stuff = false;
3295 vec<pre_expr> exprs;
3296 pre_expr expr;
3297 auto_vec<pre_expr> avail;
3298 int i;
3300 exprs = sorted_array_from_bitmap_set (PA_IN (block));
3301 avail.safe_grow (EDGE_COUNT (block->preds));
3303 FOR_EACH_VEC_ELT (exprs, i, expr)
3305 if (expr->kind == NARY
3306 || expr->kind == REFERENCE)
3308 unsigned int val;
3309 bool by_all = true;
3310 bool cant_insert = false;
3311 edge pred;
3312 basic_block bprime;
3313 pre_expr eprime = NULL;
3314 edge_iterator ei;
3316 val = get_expr_value_id (expr);
3317 if (bitmap_set_contains_value (PHI_GEN (block), val))
3318 continue;
3319 if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3320 continue;
3322 FOR_EACH_EDGE (pred, ei, block->preds)
3324 unsigned int vprime;
3325 pre_expr edoubleprime;
3327 /* We should never run insertion for the exit block
3328 and so not come across fake pred edges. */
3329 gcc_assert (!(pred->flags & EDGE_FAKE));
3330 bprime = pred->src;
3331 eprime = phi_translate (expr, ANTIC_IN (block),
3332 PA_IN (block),
3333 bprime, block);
3335 /* eprime will generally only be NULL if the
3336 value of the expression, translated
3337 through the PHI for this predecessor, is
3338 undefined. If that is the case, we can't
3339 make the expression fully redundant,
3340 because its value is undefined along a
3341 predecessor path. We can thus break out
3342 early because it doesn't matter what the
3343 rest of the results are. */
3344 if (eprime == NULL)
3346 avail[pred->dest_idx] = NULL;
3347 cant_insert = true;
3348 break;
3351 vprime = get_expr_value_id (eprime);
3352 edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime), vprime);
3353 avail[pred->dest_idx] = edoubleprime;
3354 if (edoubleprime == NULL)
3356 by_all = false;
3357 break;
3361 /* If we can insert it, it's not the same value
3362 already existing along every predecessor, and
3363 it's defined by some predecessor, it is
3364 partially redundant. */
3365 if (!cant_insert && by_all)
3367 edge succ;
3368 bool do_insertion = false;
3370 /* Insert only if we can remove a later expression on a path
3371 that we want to optimize for speed.
3372 The phi node that we will be inserting in BLOCK is not free,
3373 and inserting it for the sake of !optimize_for_speed successor
3374 may cause regressions on the speed path. */
3375 FOR_EACH_EDGE (succ, ei, block->succs)
3377 if (bitmap_set_contains_value (PA_IN (succ->dest), val)
3378 || bitmap_set_contains_value (ANTIC_IN (succ->dest), val))
3380 if (optimize_edge_for_speed_p (succ))
3381 do_insertion = true;
3385 if (!do_insertion)
3387 if (dump_file && (dump_flags & TDF_DETAILS))
3389 fprintf (dump_file, "Skipping partial partial redundancy "
3390 "for expression ");
3391 print_pre_expr (dump_file, expr);
3392 fprintf (dump_file, " (%04d), not (partially) anticipated "
3393 "on any to be optimized for speed edges\n", val);
3396 else if (dbg_cnt (treepre_insert))
3398 pre_stats.pa_insert++;
3399 if (dump_file && (dump_flags & TDF_DETAILS))
3401 fprintf (dump_file, "Found partial partial redundancy "
3402 "for expression ");
3403 print_pre_expr (dump_file, expr);
3404 fprintf (dump_file, " (%04d)\n",
3405 get_expr_value_id (expr));
3407 if (insert_into_preds_of_block (block,
3408 get_expression_id (expr),
3409 avail))
3410 new_stuff = true;
3416 exprs.release ();
3417 return new_stuff;
3420 /* Insert expressions in BLOCK to compute hoistable values up.
3421 Return TRUE if something was inserted, otherwise return FALSE.
3422 The caller has to make sure that BLOCK has at least two successors. */
3424 static bool
3425 do_hoist_insertion (basic_block block)
3427 edge e;
3428 edge_iterator ei;
3429 bool new_stuff = false;
3430 unsigned i;
3431 gimple_stmt_iterator last;
3433 /* At least two successors, or else... */
3434 gcc_assert (EDGE_COUNT (block->succs) >= 2);
3436 /* Check that all successors of BLOCK are dominated by block.
3437 We could use dominated_by_p() for this, but actually there is a much
3438 quicker check: any successor that is dominated by BLOCK can't have
3439 more than one predecessor edge. */
3440 FOR_EACH_EDGE (e, ei, block->succs)
3441 if (! single_pred_p (e->dest))
3442 return false;
3444 /* Determine the insertion point. If we cannot safely insert before
3445 the last stmt if we'd have to, bail out. */
3446 last = gsi_last_bb (block);
3447 if (!gsi_end_p (last)
3448 && !is_ctrl_stmt (gsi_stmt (last))
3449 && stmt_ends_bb_p (gsi_stmt (last)))
3450 return false;
3452 /* Compute the set of hoistable expressions from ANTIC_IN. First compute
3453 hoistable values. */
3454 bitmap_set hoistable_set;
3456 /* A hoistable value must be in ANTIC_IN(block)
3457 but not in AVAIL_OUT(BLOCK). */
3458 bitmap_initialize (&hoistable_set.values, &grand_bitmap_obstack);
3459 bitmap_and_compl (&hoistable_set.values,
3460 &ANTIC_IN (block)->values, &AVAIL_OUT (block)->values);
3462 /* Short-cut for a common case: hoistable_set is empty. */
3463 if (bitmap_empty_p (&hoistable_set.values))
3464 return false;
3466 /* Compute which of the hoistable values is in AVAIL_OUT of
3467 at least one of the successors of BLOCK. */
3468 bitmap_head availout_in_some;
3469 bitmap_initialize (&availout_in_some, &grand_bitmap_obstack);
3470 FOR_EACH_EDGE (e, ei, block->succs)
3471 /* Do not consider expressions solely because their availability
3472 on loop exits. They'd be ANTIC-IN throughout the whole loop
3473 and thus effectively hoisted across loops by combination of
3474 PRE and hoisting. */
3475 if (! loop_exit_edge_p (block->loop_father, e))
3476 bitmap_ior_and_into (&availout_in_some, &hoistable_set.values,
3477 &AVAIL_OUT (e->dest)->values);
3478 bitmap_clear (&hoistable_set.values);
3480 /* Short-cut for a common case: availout_in_some is empty. */
3481 if (bitmap_empty_p (&availout_in_some))
3482 return false;
3484 /* Hack hoitable_set in-place so we can use sorted_array_from_bitmap_set. */
3485 hoistable_set.values = availout_in_some;
3486 hoistable_set.expressions = ANTIC_IN (block)->expressions;
3488 /* Now finally construct the topological-ordered expression set. */
3489 vec<pre_expr> exprs = sorted_array_from_bitmap_set (&hoistable_set);
3491 bitmap_clear (&hoistable_set.values);
3493 /* If there are candidate values for hoisting, insert expressions
3494 strategically to make the hoistable expressions fully redundant. */
3495 pre_expr expr;
3496 FOR_EACH_VEC_ELT (exprs, i, expr)
3498 /* While we try to sort expressions topologically above the
3499 sorting doesn't work out perfectly. Catch expressions we
3500 already inserted. */
3501 unsigned int value_id = get_expr_value_id (expr);
3502 if (bitmap_set_contains_value (AVAIL_OUT (block), value_id))
3504 if (dump_file && (dump_flags & TDF_DETAILS))
3506 fprintf (dump_file,
3507 "Already inserted expression for ");
3508 print_pre_expr (dump_file, expr);
3509 fprintf (dump_file, " (%04d)\n", value_id);
3511 continue;
3514 /* OK, we should hoist this value. Perform the transformation. */
3515 pre_stats.hoist_insert++;
3516 if (dump_file && (dump_flags & TDF_DETAILS))
3518 fprintf (dump_file,
3519 "Inserting expression in block %d for code hoisting: ",
3520 block->index);
3521 print_pre_expr (dump_file, expr);
3522 fprintf (dump_file, " (%04d)\n", value_id);
3525 gimple_seq stmts = NULL;
3526 tree res = create_expression_by_pieces (block, expr, &stmts,
3527 get_expr_type (expr));
3529 /* Do not return true if expression creation ultimately
3530 did not insert any statements. */
3531 if (gimple_seq_empty_p (stmts))
3532 res = NULL_TREE;
3533 else
3535 if (gsi_end_p (last) || is_ctrl_stmt (gsi_stmt (last)))
3536 gsi_insert_seq_before (&last, stmts, GSI_SAME_STMT);
3537 else
3538 gsi_insert_seq_after (&last, stmts, GSI_NEW_STMT);
3541 /* Make sure to not return true if expression creation ultimately
3542 failed but also make sure to insert any stmts produced as they
3543 are tracked in inserted_exprs. */
3544 if (! res)
3545 continue;
3547 new_stuff = true;
3550 exprs.release ();
3552 return new_stuff;
3555 /* Do a dominator walk on the control flow graph, and insert computations
3556 of values as necessary for PRE and hoisting. */
3558 static bool
3559 insert_aux (basic_block block, bool do_pre, bool do_hoist)
3561 basic_block son;
3562 bool new_stuff = false;
3564 if (block)
3566 basic_block dom;
3567 dom = get_immediate_dominator (CDI_DOMINATORS, block);
3568 if (dom)
3570 unsigned i;
3571 bitmap_iterator bi;
3572 bitmap_set_t newset;
3574 /* First, update the AVAIL_OUT set with anything we may have
3575 inserted higher up in the dominator tree. */
3576 newset = NEW_SETS (dom);
3577 if (newset)
3579 /* Note that we need to value_replace both NEW_SETS, and
3580 AVAIL_OUT. For both the case of NEW_SETS, the value may be
3581 represented by some non-simple expression here that we want
3582 to replace it with. */
3583 FOR_EACH_EXPR_ID_IN_SET (newset, i, bi)
3585 pre_expr expr = expression_for_id (i);
3586 bitmap_value_replace_in_set (NEW_SETS (block), expr);
3587 bitmap_value_replace_in_set (AVAIL_OUT (block), expr);
3591 /* Insert expressions for partial redundancies. */
3592 if (do_pre && !single_pred_p (block))
3594 new_stuff |= do_pre_regular_insertion (block, dom);
3595 if (do_partial_partial)
3596 new_stuff |= do_pre_partial_partial_insertion (block, dom);
3599 /* Insert expressions for hoisting. */
3600 if (do_hoist && EDGE_COUNT (block->succs) >= 2)
3601 new_stuff |= do_hoist_insertion (block);
3604 for (son = first_dom_son (CDI_DOMINATORS, block);
3605 son;
3606 son = next_dom_son (CDI_DOMINATORS, son))
3608 new_stuff |= insert_aux (son, do_pre, do_hoist);
3611 return new_stuff;
3614 /* Perform insertion of partially redundant and hoistable values. */
3616 static void
3617 insert (void)
3619 bool new_stuff = true;
3620 basic_block bb;
3621 int num_iterations = 0;
3623 FOR_ALL_BB_FN (bb, cfun)
3624 NEW_SETS (bb) = bitmap_set_new ();
3626 while (new_stuff)
3628 num_iterations++;
3629 if (dump_file && dump_flags & TDF_DETAILS)
3630 fprintf (dump_file, "Starting insert iteration %d\n", num_iterations);
3631 new_stuff = insert_aux (ENTRY_BLOCK_PTR_FOR_FN (cfun), flag_tree_pre,
3632 flag_code_hoisting);
3634 /* Clear the NEW sets before the next iteration. We have already
3635 fully propagated its contents. */
3636 if (new_stuff)
3637 FOR_ALL_BB_FN (bb, cfun)
3638 bitmap_set_free (NEW_SETS (bb));
3640 statistics_histogram_event (cfun, "insert iterations", num_iterations);
3644 /* Compute the AVAIL set for all basic blocks.
3646 This function performs value numbering of the statements in each basic
3647 block. The AVAIL sets are built from information we glean while doing
3648 this value numbering, since the AVAIL sets contain only one entry per
3649 value.
3651 AVAIL_IN[BLOCK] = AVAIL_OUT[dom(BLOCK)].
3652 AVAIL_OUT[BLOCK] = AVAIL_IN[BLOCK] U PHI_GEN[BLOCK] U TMP_GEN[BLOCK]. */
3654 static void
3655 compute_avail (void)
3658 basic_block block, son;
3659 basic_block *worklist;
3660 size_t sp = 0;
3661 unsigned i;
3663 /* We pretend that default definitions are defined in the entry block.
3664 This includes function arguments and the static chain decl. */
3665 for (i = 1; i < num_ssa_names; ++i)
3667 tree name = ssa_name (i);
3668 pre_expr e;
3669 if (!name
3670 || !SSA_NAME_IS_DEFAULT_DEF (name)
3671 || has_zero_uses (name)
3672 || virtual_operand_p (name))
3673 continue;
3675 e = get_or_alloc_expr_for_name (name);
3676 add_to_value (get_expr_value_id (e), e);
3677 bitmap_insert_into_set (TMP_GEN (ENTRY_BLOCK_PTR_FOR_FN (cfun)), e);
3678 bitmap_value_insert_into_set (AVAIL_OUT (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
3682 if (dump_file && (dump_flags & TDF_DETAILS))
3684 print_bitmap_set (dump_file, TMP_GEN (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
3685 "tmp_gen", ENTRY_BLOCK);
3686 print_bitmap_set (dump_file, AVAIL_OUT (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
3687 "avail_out", ENTRY_BLOCK);
3690 /* Allocate the worklist. */
3691 worklist = XNEWVEC (basic_block, n_basic_blocks_for_fn (cfun));
3693 /* Seed the algorithm by putting the dominator children of the entry
3694 block on the worklist. */
3695 for (son = first_dom_son (CDI_DOMINATORS, ENTRY_BLOCK_PTR_FOR_FN (cfun));
3696 son;
3697 son = next_dom_son (CDI_DOMINATORS, son))
3698 worklist[sp++] = son;
3700 BB_LIVE_VOP_ON_EXIT (ENTRY_BLOCK_PTR_FOR_FN (cfun))
3701 = ssa_default_def (cfun, gimple_vop (cfun));
3703 /* Loop until the worklist is empty. */
3704 while (sp)
3706 gimple *stmt;
3707 basic_block dom;
3709 /* Pick a block from the worklist. */
3710 block = worklist[--sp];
3712 /* Initially, the set of available values in BLOCK is that of
3713 its immediate dominator. */
3714 dom = get_immediate_dominator (CDI_DOMINATORS, block);
3715 if (dom)
3717 bitmap_set_copy (AVAIL_OUT (block), AVAIL_OUT (dom));
3718 BB_LIVE_VOP_ON_EXIT (block) = BB_LIVE_VOP_ON_EXIT (dom);
3721 /* Generate values for PHI nodes. */
3722 for (gphi_iterator gsi = gsi_start_phis (block); !gsi_end_p (gsi);
3723 gsi_next (&gsi))
3725 tree result = gimple_phi_result (gsi.phi ());
3727 /* We have no need for virtual phis, as they don't represent
3728 actual computations. */
3729 if (virtual_operand_p (result))
3731 BB_LIVE_VOP_ON_EXIT (block) = result;
3732 continue;
3735 pre_expr e = get_or_alloc_expr_for_name (result);
3736 add_to_value (get_expr_value_id (e), e);
3737 bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3738 bitmap_insert_into_set (PHI_GEN (block), e);
3741 BB_MAY_NOTRETURN (block) = 0;
3743 /* Now compute value numbers and populate value sets with all
3744 the expressions computed in BLOCK. */
3745 for (gimple_stmt_iterator gsi = gsi_start_bb (block); !gsi_end_p (gsi);
3746 gsi_next (&gsi))
3748 ssa_op_iter iter;
3749 tree op;
3751 stmt = gsi_stmt (gsi);
3753 /* Cache whether the basic-block has any non-visible side-effect
3754 or control flow.
3755 If this isn't a call or it is the last stmt in the
3756 basic-block then the CFG represents things correctly. */
3757 if (is_gimple_call (stmt) && !stmt_ends_bb_p (stmt))
3759 /* Non-looping const functions always return normally.
3760 Otherwise the call might not return or have side-effects
3761 that forbids hoisting possibly trapping expressions
3762 before it. */
3763 int flags = gimple_call_flags (stmt);
3764 if (!(flags & ECF_CONST)
3765 || (flags & ECF_LOOPING_CONST_OR_PURE))
3766 BB_MAY_NOTRETURN (block) = 1;
3769 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_DEF)
3771 pre_expr e = get_or_alloc_expr_for_name (op);
3773 add_to_value (get_expr_value_id (e), e);
3774 bitmap_insert_into_set (TMP_GEN (block), e);
3775 bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3778 if (gimple_vdef (stmt))
3779 BB_LIVE_VOP_ON_EXIT (block) = gimple_vdef (stmt);
3781 if (gimple_has_side_effects (stmt)
3782 || stmt_could_throw_p (stmt)
3783 || is_gimple_debug (stmt))
3784 continue;
3786 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
3788 if (ssa_undefined_value_p (op))
3789 continue;
3790 pre_expr e = get_or_alloc_expr_for_name (op);
3791 bitmap_value_insert_into_set (EXP_GEN (block), e);
3794 switch (gimple_code (stmt))
3796 case GIMPLE_RETURN:
3797 continue;
3799 case GIMPLE_CALL:
3801 vn_reference_t ref;
3802 vn_reference_s ref1;
3803 pre_expr result = NULL;
3805 /* We can value number only calls to real functions. */
3806 if (gimple_call_internal_p (stmt))
3807 continue;
3809 vn_reference_lookup_call (as_a <gcall *> (stmt), &ref, &ref1);
3810 if (!ref)
3811 continue;
3813 /* If the value of the call is not invalidated in
3814 this block until it is computed, add the expression
3815 to EXP_GEN. */
3816 if (!gimple_vuse (stmt)
3817 || gimple_code
3818 (SSA_NAME_DEF_STMT (gimple_vuse (stmt))) == GIMPLE_PHI
3819 || gimple_bb (SSA_NAME_DEF_STMT
3820 (gimple_vuse (stmt))) != block)
3822 result = pre_expr_pool.allocate ();
3823 result->kind = REFERENCE;
3824 result->id = 0;
3825 PRE_EXPR_REFERENCE (result) = ref;
3827 get_or_alloc_expression_id (result);
3828 add_to_value (get_expr_value_id (result), result);
3829 bitmap_value_insert_into_set (EXP_GEN (block), result);
3831 continue;
3834 case GIMPLE_ASSIGN:
3836 pre_expr result = NULL;
3837 switch (vn_get_stmt_kind (stmt))
3839 case VN_NARY:
3841 enum tree_code code = gimple_assign_rhs_code (stmt);
3842 vn_nary_op_t nary;
3844 /* COND_EXPR and VEC_COND_EXPR are awkward in
3845 that they contain an embedded complex expression.
3846 Don't even try to shove those through PRE. */
3847 if (code == COND_EXPR
3848 || code == VEC_COND_EXPR)
3849 continue;
3851 vn_nary_op_lookup_stmt (stmt, &nary);
3852 if (!nary)
3853 continue;
3855 /* If the NARY traps and there was a preceding
3856 point in the block that might not return avoid
3857 adding the nary to EXP_GEN. */
3858 if (BB_MAY_NOTRETURN (block)
3859 && vn_nary_may_trap (nary))
3860 continue;
3862 result = pre_expr_pool.allocate ();
3863 result->kind = NARY;
3864 result->id = 0;
3865 PRE_EXPR_NARY (result) = nary;
3866 break;
3869 case VN_REFERENCE:
3871 tree rhs1 = gimple_assign_rhs1 (stmt);
3872 alias_set_type set = get_alias_set (rhs1);
3873 vec<vn_reference_op_s> operands
3874 = vn_reference_operands_for_lookup (rhs1);
3875 vn_reference_t ref;
3876 vn_reference_lookup_pieces (gimple_vuse (stmt), set,
3877 TREE_TYPE (rhs1),
3878 operands, &ref, VN_WALK);
3879 if (!ref)
3881 operands.release ();
3882 continue;
3885 /* If the value of the reference is not invalidated in
3886 this block until it is computed, add the expression
3887 to EXP_GEN. */
3888 if (gimple_vuse (stmt))
3890 gimple *def_stmt;
3891 bool ok = true;
3892 def_stmt = SSA_NAME_DEF_STMT (gimple_vuse (stmt));
3893 while (!gimple_nop_p (def_stmt)
3894 && gimple_code (def_stmt) != GIMPLE_PHI
3895 && gimple_bb (def_stmt) == block)
3897 if (stmt_may_clobber_ref_p
3898 (def_stmt, gimple_assign_rhs1 (stmt)))
3900 ok = false;
3901 break;
3903 def_stmt
3904 = SSA_NAME_DEF_STMT (gimple_vuse (def_stmt));
3906 if (!ok)
3908 operands.release ();
3909 continue;
3913 /* If the load was value-numbered to another
3914 load make sure we do not use its expression
3915 for insertion if it wouldn't be a valid
3916 replacement. */
3917 /* At the momemt we have a testcase
3918 for hoist insertion of aligned vs. misaligned
3919 variants in gcc.dg/torture/pr65270-1.c thus
3920 with just alignment to be considered we can
3921 simply replace the expression in the hashtable
3922 with the most conservative one. */
3923 vn_reference_op_t ref1 = &ref->operands.last ();
3924 while (ref1->opcode != TARGET_MEM_REF
3925 && ref1->opcode != MEM_REF
3926 && ref1 != &ref->operands[0])
3927 --ref1;
3928 vn_reference_op_t ref2 = &operands.last ();
3929 while (ref2->opcode != TARGET_MEM_REF
3930 && ref2->opcode != MEM_REF
3931 && ref2 != &operands[0])
3932 --ref2;
3933 if ((ref1->opcode == TARGET_MEM_REF
3934 || ref1->opcode == MEM_REF)
3935 && (TYPE_ALIGN (ref1->type)
3936 > TYPE_ALIGN (ref2->type)))
3937 ref1->type
3938 = build_aligned_type (ref1->type,
3939 TYPE_ALIGN (ref2->type));
3940 /* TBAA behavior is an obvious part so make sure
3941 that the hashtable one covers this as well
3942 by adjusting the ref alias set and its base. */
3943 if (ref->set == set
3944 || alias_set_subset_of (set, ref->set))
3946 else if (alias_set_subset_of (ref->set, set))
3948 ref->set = set;
3949 if (ref1->opcode == MEM_REF)
3950 ref1->op0 = fold_convert (TREE_TYPE (ref2->op0),
3951 ref1->op0);
3952 else
3953 ref1->op2 = fold_convert (TREE_TYPE (ref2->op2),
3954 ref1->op2);
3956 else
3958 ref->set = 0;
3959 if (ref1->opcode == MEM_REF)
3960 ref1->op0 = fold_convert (ptr_type_node,
3961 ref1->op0);
3962 else
3963 ref1->op2 = fold_convert (ptr_type_node,
3964 ref1->op2);
3966 operands.release ();
3968 result = pre_expr_pool.allocate ();
3969 result->kind = REFERENCE;
3970 result->id = 0;
3971 PRE_EXPR_REFERENCE (result) = ref;
3972 break;
3975 default:
3976 continue;
3979 get_or_alloc_expression_id (result);
3980 add_to_value (get_expr_value_id (result), result);
3981 bitmap_value_insert_into_set (EXP_GEN (block), result);
3982 continue;
3984 default:
3985 break;
3989 if (dump_file && (dump_flags & TDF_DETAILS))
3991 print_bitmap_set (dump_file, EXP_GEN (block),
3992 "exp_gen", block->index);
3993 print_bitmap_set (dump_file, PHI_GEN (block),
3994 "phi_gen", block->index);
3995 print_bitmap_set (dump_file, TMP_GEN (block),
3996 "tmp_gen", block->index);
3997 print_bitmap_set (dump_file, AVAIL_OUT (block),
3998 "avail_out", block->index);
4001 /* Put the dominator children of BLOCK on the worklist of blocks
4002 to compute available sets for. */
4003 for (son = first_dom_son (CDI_DOMINATORS, block);
4004 son;
4005 son = next_dom_son (CDI_DOMINATORS, son))
4006 worklist[sp++] = son;
4009 free (worklist);
4013 /* Local state for the eliminate domwalk. */
4014 static vec<gimple *> el_to_remove;
4015 static vec<gimple *> el_to_fixup;
4016 static unsigned int el_todo;
4017 static vec<tree> el_avail;
4018 static vec<tree> el_avail_stack;
4020 /* Return a leader for OP that is available at the current point of the
4021 eliminate domwalk. */
4023 static tree
4024 eliminate_avail (tree op)
4026 tree valnum = VN_INFO (op)->valnum;
4027 if (TREE_CODE (valnum) == SSA_NAME)
4029 if (SSA_NAME_IS_DEFAULT_DEF (valnum))
4030 return valnum;
4031 if (el_avail.length () > SSA_NAME_VERSION (valnum))
4032 return el_avail[SSA_NAME_VERSION (valnum)];
4034 else if (is_gimple_min_invariant (valnum))
4035 return valnum;
4036 return NULL_TREE;
4039 /* At the current point of the eliminate domwalk make OP available. */
4041 static void
4042 eliminate_push_avail (tree op)
4044 tree valnum = VN_INFO (op)->valnum;
4045 if (TREE_CODE (valnum) == SSA_NAME)
4047 if (el_avail.length () <= SSA_NAME_VERSION (valnum))
4048 el_avail.safe_grow_cleared (SSA_NAME_VERSION (valnum) + 1);
4049 tree pushop = op;
4050 if (el_avail[SSA_NAME_VERSION (valnum)])
4051 pushop = el_avail[SSA_NAME_VERSION (valnum)];
4052 el_avail_stack.safe_push (pushop);
4053 el_avail[SSA_NAME_VERSION (valnum)] = op;
4057 /* Insert the expression recorded by SCCVN for VAL at *GSI. Returns
4058 the leader for the expression if insertion was successful. */
4060 static tree
4061 eliminate_insert (gimple_stmt_iterator *gsi, tree val)
4063 gimple *stmt = gimple_seq_first_stmt (VN_INFO (val)->expr);
4064 if (!is_gimple_assign (stmt)
4065 || (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt))
4066 && gimple_assign_rhs_code (stmt) != VIEW_CONVERT_EXPR
4067 && gimple_assign_rhs_code (stmt) != BIT_FIELD_REF))
4068 return NULL_TREE;
4070 tree op = gimple_assign_rhs1 (stmt);
4071 if (gimple_assign_rhs_code (stmt) == VIEW_CONVERT_EXPR
4072 || gimple_assign_rhs_code (stmt) == BIT_FIELD_REF)
4073 op = TREE_OPERAND (op, 0);
4074 tree leader = TREE_CODE (op) == SSA_NAME ? eliminate_avail (op) : op;
4075 if (!leader)
4076 return NULL_TREE;
4078 gimple_seq stmts = NULL;
4079 tree res;
4080 if (gimple_assign_rhs_code (stmt) == BIT_FIELD_REF)
4081 res = gimple_build (&stmts, BIT_FIELD_REF,
4082 TREE_TYPE (val), leader,
4083 TREE_OPERAND (gimple_assign_rhs1 (stmt), 1),
4084 TREE_OPERAND (gimple_assign_rhs1 (stmt), 2));
4085 else
4086 res = gimple_build (&stmts, gimple_assign_rhs_code (stmt),
4087 TREE_TYPE (val), leader);
4088 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
4089 VN_INFO_GET (res)->valnum = val;
4091 if (TREE_CODE (leader) == SSA_NAME)
4092 gimple_set_plf (SSA_NAME_DEF_STMT (leader), NECESSARY, true);
4094 pre_stats.insertions++;
4095 if (dump_file && (dump_flags & TDF_DETAILS))
4097 fprintf (dump_file, "Inserted ");
4098 print_gimple_stmt (dump_file, SSA_NAME_DEF_STMT (res), 0, 0);
4101 return res;
4104 class eliminate_dom_walker : public dom_walker
4106 public:
4107 eliminate_dom_walker (cdi_direction direction, bool do_pre_)
4108 : dom_walker (direction), do_pre (do_pre_) {}
4110 virtual edge before_dom_children (basic_block);
4111 virtual void after_dom_children (basic_block);
4113 bool do_pre;
4116 /* Perform elimination for the basic-block B during the domwalk. */
4118 edge
4119 eliminate_dom_walker::before_dom_children (basic_block b)
4121 /* Mark new bb. */
4122 el_avail_stack.safe_push (NULL_TREE);
4124 /* ??? If we do nothing for unreachable blocks then this will confuse
4125 tailmerging. Eventually we can reduce its reliance on SCCVN now
4126 that we fully copy/constant-propagate (most) things. */
4128 for (gphi_iterator gsi = gsi_start_phis (b); !gsi_end_p (gsi);)
4130 gphi *phi = gsi.phi ();
4131 tree res = PHI_RESULT (phi);
4133 if (virtual_operand_p (res))
4135 gsi_next (&gsi);
4136 continue;
4139 tree sprime = eliminate_avail (res);
4140 if (sprime
4141 && sprime != res)
4143 if (dump_file && (dump_flags & TDF_DETAILS))
4145 fprintf (dump_file, "Replaced redundant PHI node defining ");
4146 print_generic_expr (dump_file, res, 0);
4147 fprintf (dump_file, " with ");
4148 print_generic_expr (dump_file, sprime, 0);
4149 fprintf (dump_file, "\n");
4152 /* If we inserted this PHI node ourself, it's not an elimination. */
4153 if (inserted_exprs
4154 && bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (res)))
4155 pre_stats.phis--;
4156 else
4157 pre_stats.eliminations++;
4159 /* If we will propagate into all uses don't bother to do
4160 anything. */
4161 if (may_propagate_copy (res, sprime))
4163 /* Mark the PHI for removal. */
4164 el_to_remove.safe_push (phi);
4165 gsi_next (&gsi);
4166 continue;
4169 remove_phi_node (&gsi, false);
4171 if (inserted_exprs
4172 && !bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (res))
4173 && TREE_CODE (sprime) == SSA_NAME)
4174 gimple_set_plf (SSA_NAME_DEF_STMT (sprime), NECESSARY, true);
4176 if (!useless_type_conversion_p (TREE_TYPE (res), TREE_TYPE (sprime)))
4177 sprime = fold_convert (TREE_TYPE (res), sprime);
4178 gimple *stmt = gimple_build_assign (res, sprime);
4179 /* ??? It cannot yet be necessary (DOM walk). */
4180 gimple_set_plf (stmt, NECESSARY, gimple_plf (phi, NECESSARY));
4182 gimple_stmt_iterator gsi2 = gsi_after_labels (b);
4183 gsi_insert_before (&gsi2, stmt, GSI_NEW_STMT);
4184 continue;
4187 eliminate_push_avail (res);
4188 gsi_next (&gsi);
4191 for (gimple_stmt_iterator gsi = gsi_start_bb (b);
4192 !gsi_end_p (gsi);
4193 gsi_next (&gsi))
4195 tree sprime = NULL_TREE;
4196 gimple *stmt = gsi_stmt (gsi);
4197 tree lhs = gimple_get_lhs (stmt);
4198 if (lhs && TREE_CODE (lhs) == SSA_NAME
4199 && !gimple_has_volatile_ops (stmt)
4200 /* See PR43491. Do not replace a global register variable when
4201 it is a the RHS of an assignment. Do replace local register
4202 variables since gcc does not guarantee a local variable will
4203 be allocated in register.
4204 ??? The fix isn't effective here. This should instead
4205 be ensured by not value-numbering them the same but treating
4206 them like volatiles? */
4207 && !(gimple_assign_single_p (stmt)
4208 && (TREE_CODE (gimple_assign_rhs1 (stmt)) == VAR_DECL
4209 && DECL_HARD_REGISTER (gimple_assign_rhs1 (stmt))
4210 && is_global_var (gimple_assign_rhs1 (stmt)))))
4212 sprime = eliminate_avail (lhs);
4213 if (!sprime)
4215 /* If there is no existing usable leader but SCCVN thinks
4216 it has an expression it wants to use as replacement,
4217 insert that. */
4218 tree val = VN_INFO (lhs)->valnum;
4219 if (val != VN_TOP
4220 && TREE_CODE (val) == SSA_NAME
4221 && VN_INFO (val)->needs_insertion
4222 && VN_INFO (val)->expr != NULL
4223 && (sprime = eliminate_insert (&gsi, val)) != NULL_TREE)
4224 eliminate_push_avail (sprime);
4227 /* If this now constitutes a copy duplicate points-to
4228 and range info appropriately. This is especially
4229 important for inserted code. See tree-ssa-copy.c
4230 for similar code. */
4231 if (sprime
4232 && TREE_CODE (sprime) == SSA_NAME)
4234 basic_block sprime_b = gimple_bb (SSA_NAME_DEF_STMT (sprime));
4235 if (POINTER_TYPE_P (TREE_TYPE (lhs))
4236 && VN_INFO_PTR_INFO (lhs)
4237 && ! VN_INFO_PTR_INFO (sprime))
4239 duplicate_ssa_name_ptr_info (sprime,
4240 VN_INFO_PTR_INFO (lhs));
4241 if (b != sprime_b)
4242 mark_ptr_info_alignment_unknown
4243 (SSA_NAME_PTR_INFO (sprime));
4245 else if (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
4246 && VN_INFO_RANGE_INFO (lhs)
4247 && ! VN_INFO_RANGE_INFO (sprime)
4248 && b == sprime_b)
4249 duplicate_ssa_name_range_info (sprime,
4250 VN_INFO_RANGE_TYPE (lhs),
4251 VN_INFO_RANGE_INFO (lhs));
4254 /* Inhibit the use of an inserted PHI on a loop header when
4255 the address of the memory reference is a simple induction
4256 variable. In other cases the vectorizer won't do anything
4257 anyway (either it's loop invariant or a complicated
4258 expression). */
4259 if (sprime
4260 && TREE_CODE (sprime) == SSA_NAME
4261 && do_pre
4262 && flag_tree_loop_vectorize
4263 && loop_outer (b->loop_father)
4264 && has_zero_uses (sprime)
4265 && bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (sprime))
4266 && gimple_assign_load_p (stmt))
4268 gimple *def_stmt = SSA_NAME_DEF_STMT (sprime);
4269 basic_block def_bb = gimple_bb (def_stmt);
4270 if (gimple_code (def_stmt) == GIMPLE_PHI
4271 && def_bb->loop_father->header == def_bb)
4273 loop_p loop = def_bb->loop_father;
4274 ssa_op_iter iter;
4275 tree op;
4276 bool found = false;
4277 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
4279 affine_iv iv;
4280 def_bb = gimple_bb (SSA_NAME_DEF_STMT (op));
4281 if (def_bb
4282 && flow_bb_inside_loop_p (loop, def_bb)
4283 && simple_iv (loop, loop, op, &iv, true))
4285 found = true;
4286 break;
4289 if (found)
4291 if (dump_file && (dump_flags & TDF_DETAILS))
4293 fprintf (dump_file, "Not replacing ");
4294 print_gimple_expr (dump_file, stmt, 0, 0);
4295 fprintf (dump_file, " with ");
4296 print_generic_expr (dump_file, sprime, 0);
4297 fprintf (dump_file, " which would add a loop"
4298 " carried dependence to loop %d\n",
4299 loop->num);
4301 /* Don't keep sprime available. */
4302 sprime = NULL_TREE;
4307 if (sprime)
4309 /* If we can propagate the value computed for LHS into
4310 all uses don't bother doing anything with this stmt. */
4311 if (may_propagate_copy (lhs, sprime))
4313 /* Mark it for removal. */
4314 el_to_remove.safe_push (stmt);
4316 /* ??? Don't count copy/constant propagations. */
4317 if (gimple_assign_single_p (stmt)
4318 && (TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME
4319 || gimple_assign_rhs1 (stmt) == sprime))
4320 continue;
4322 if (dump_file && (dump_flags & TDF_DETAILS))
4324 fprintf (dump_file, "Replaced ");
4325 print_gimple_expr (dump_file, stmt, 0, 0);
4326 fprintf (dump_file, " with ");
4327 print_generic_expr (dump_file, sprime, 0);
4328 fprintf (dump_file, " in all uses of ");
4329 print_gimple_stmt (dump_file, stmt, 0, 0);
4332 pre_stats.eliminations++;
4333 continue;
4336 /* If this is an assignment from our leader (which
4337 happens in the case the value-number is a constant)
4338 then there is nothing to do. */
4339 if (gimple_assign_single_p (stmt)
4340 && sprime == gimple_assign_rhs1 (stmt))
4341 continue;
4343 /* Else replace its RHS. */
4344 bool can_make_abnormal_goto
4345 = is_gimple_call (stmt)
4346 && stmt_can_make_abnormal_goto (stmt);
4348 if (dump_file && (dump_flags & TDF_DETAILS))
4350 fprintf (dump_file, "Replaced ");
4351 print_gimple_expr (dump_file, stmt, 0, 0);
4352 fprintf (dump_file, " with ");
4353 print_generic_expr (dump_file, sprime, 0);
4354 fprintf (dump_file, " in ");
4355 print_gimple_stmt (dump_file, stmt, 0, 0);
4358 if (TREE_CODE (sprime) == SSA_NAME)
4359 gimple_set_plf (SSA_NAME_DEF_STMT (sprime),
4360 NECESSARY, true);
4362 pre_stats.eliminations++;
4363 gimple *orig_stmt = stmt;
4364 if (!useless_type_conversion_p (TREE_TYPE (lhs),
4365 TREE_TYPE (sprime)))
4366 sprime = fold_convert (TREE_TYPE (lhs), sprime);
4367 tree vdef = gimple_vdef (stmt);
4368 tree vuse = gimple_vuse (stmt);
4369 propagate_tree_value_into_stmt (&gsi, sprime);
4370 stmt = gsi_stmt (gsi);
4371 update_stmt (stmt);
4372 if (vdef != gimple_vdef (stmt))
4373 VN_INFO (vdef)->valnum = vuse;
4375 /* If we removed EH side-effects from the statement, clean
4376 its EH information. */
4377 if (maybe_clean_or_replace_eh_stmt (orig_stmt, stmt))
4379 bitmap_set_bit (need_eh_cleanup,
4380 gimple_bb (stmt)->index);
4381 if (dump_file && (dump_flags & TDF_DETAILS))
4382 fprintf (dump_file, " Removed EH side-effects.\n");
4385 /* Likewise for AB side-effects. */
4386 if (can_make_abnormal_goto
4387 && !stmt_can_make_abnormal_goto (stmt))
4389 bitmap_set_bit (need_ab_cleanup,
4390 gimple_bb (stmt)->index);
4391 if (dump_file && (dump_flags & TDF_DETAILS))
4392 fprintf (dump_file, " Removed AB side-effects.\n");
4395 continue;
4399 /* If the statement is a scalar store, see if the expression
4400 has the same value number as its rhs. If so, the store is
4401 dead. */
4402 if (gimple_assign_single_p (stmt)
4403 && !gimple_has_volatile_ops (stmt)
4404 && !is_gimple_reg (gimple_assign_lhs (stmt))
4405 && (TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME
4406 || is_gimple_min_invariant (gimple_assign_rhs1 (stmt))))
4408 tree val;
4409 tree rhs = gimple_assign_rhs1 (stmt);
4410 val = vn_reference_lookup (gimple_assign_lhs (stmt),
4411 gimple_vuse (stmt), VN_WALK, NULL, false);
4412 if (TREE_CODE (rhs) == SSA_NAME)
4413 rhs = VN_INFO (rhs)->valnum;
4414 if (val
4415 && operand_equal_p (val, rhs, 0))
4417 if (dump_file && (dump_flags & TDF_DETAILS))
4419 fprintf (dump_file, "Deleted redundant store ");
4420 print_gimple_stmt (dump_file, stmt, 0, 0);
4423 /* Queue stmt for removal. */
4424 el_to_remove.safe_push (stmt);
4425 continue;
4429 /* If this is a control statement value numbering left edges
4430 unexecuted on force the condition in a way consistent with
4431 that. */
4432 if (gcond *cond = dyn_cast <gcond *> (stmt))
4434 if ((EDGE_SUCC (b, 0)->flags & EDGE_EXECUTABLE)
4435 ^ (EDGE_SUCC (b, 1)->flags & EDGE_EXECUTABLE))
4437 if (dump_file && (dump_flags & TDF_DETAILS))
4439 fprintf (dump_file, "Removing unexecutable edge from ");
4440 print_gimple_stmt (dump_file, stmt, 0, 0);
4442 if (((EDGE_SUCC (b, 0)->flags & EDGE_TRUE_VALUE) != 0)
4443 == ((EDGE_SUCC (b, 0)->flags & EDGE_EXECUTABLE) != 0))
4444 gimple_cond_make_true (cond);
4445 else
4446 gimple_cond_make_false (cond);
4447 update_stmt (cond);
4448 el_todo |= TODO_cleanup_cfg;
4449 continue;
4453 bool can_make_abnormal_goto = stmt_can_make_abnormal_goto (stmt);
4454 bool was_noreturn = (is_gimple_call (stmt)
4455 && gimple_call_noreturn_p (stmt));
4456 tree vdef = gimple_vdef (stmt);
4457 tree vuse = gimple_vuse (stmt);
4459 /* If we didn't replace the whole stmt (or propagate the result
4460 into all uses), replace all uses on this stmt with their
4461 leaders. */
4462 use_operand_p use_p;
4463 ssa_op_iter iter;
4464 FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_USE)
4466 tree use = USE_FROM_PTR (use_p);
4467 /* ??? The call code above leaves stmt operands un-updated. */
4468 if (TREE_CODE (use) != SSA_NAME)
4469 continue;
4470 tree sprime = eliminate_avail (use);
4471 if (sprime && sprime != use
4472 && may_propagate_copy (use, sprime)
4473 /* We substitute into debug stmts to avoid excessive
4474 debug temporaries created by removed stmts, but we need
4475 to avoid doing so for inserted sprimes as we never want
4476 to create debug temporaries for them. */
4477 && (!inserted_exprs
4478 || TREE_CODE (sprime) != SSA_NAME
4479 || !is_gimple_debug (stmt)
4480 || !bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (sprime))))
4482 propagate_value (use_p, sprime);
4483 gimple_set_modified (stmt, true);
4484 if (TREE_CODE (sprime) == SSA_NAME
4485 && !is_gimple_debug (stmt))
4486 gimple_set_plf (SSA_NAME_DEF_STMT (sprime),
4487 NECESSARY, true);
4491 /* Visit indirect calls and turn them into direct calls if
4492 possible using the devirtualization machinery. */
4493 if (gcall *call_stmt = dyn_cast <gcall *> (stmt))
4495 tree fn = gimple_call_fn (call_stmt);
4496 if (fn
4497 && flag_devirtualize
4498 && virtual_method_call_p (fn))
4500 tree otr_type = obj_type_ref_class (fn);
4501 tree instance;
4502 ipa_polymorphic_call_context context (current_function_decl, fn, stmt, &instance);
4503 bool final;
4505 context.get_dynamic_type (instance, OBJ_TYPE_REF_OBJECT (fn), otr_type, stmt);
4507 vec <cgraph_node *>targets
4508 = possible_polymorphic_call_targets (obj_type_ref_class (fn),
4509 tree_to_uhwi
4510 (OBJ_TYPE_REF_TOKEN (fn)),
4511 context,
4512 &final);
4513 if (dump_file)
4514 dump_possible_polymorphic_call_targets (dump_file,
4515 obj_type_ref_class (fn),
4516 tree_to_uhwi
4517 (OBJ_TYPE_REF_TOKEN (fn)),
4518 context);
4519 if (final && targets.length () <= 1 && dbg_cnt (devirt))
4521 tree fn;
4522 if (targets.length () == 1)
4523 fn = targets[0]->decl;
4524 else
4525 fn = builtin_decl_implicit (BUILT_IN_UNREACHABLE);
4526 if (dump_enabled_p ())
4528 location_t loc = gimple_location_safe (stmt);
4529 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, loc,
4530 "converting indirect call to "
4531 "function %s\n",
4532 lang_hooks.decl_printable_name (fn, 2));
4534 gimple_call_set_fndecl (call_stmt, fn);
4535 maybe_remove_unused_call_args (cfun, call_stmt);
4536 gimple_set_modified (stmt, true);
4541 if (gimple_modified_p (stmt))
4543 /* If a formerly non-invariant ADDR_EXPR is turned into an
4544 invariant one it was on a separate stmt. */
4545 if (gimple_assign_single_p (stmt)
4546 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ADDR_EXPR)
4547 recompute_tree_invariant_for_addr_expr (gimple_assign_rhs1 (stmt));
4548 gimple *old_stmt = stmt;
4549 if (is_gimple_call (stmt))
4551 /* ??? Only fold calls inplace for now, this may create new
4552 SSA names which in turn will confuse free_scc_vn SSA name
4553 release code. */
4554 fold_stmt_inplace (&gsi);
4555 /* When changing a call into a noreturn call, cfg cleanup
4556 is needed to fix up the noreturn call. */
4557 if (!was_noreturn && gimple_call_noreturn_p (stmt))
4558 el_to_fixup.safe_push (stmt);
4560 else
4562 fold_stmt (&gsi);
4563 stmt = gsi_stmt (gsi);
4564 if ((gimple_code (stmt) == GIMPLE_COND
4565 && (gimple_cond_true_p (as_a <gcond *> (stmt))
4566 || gimple_cond_false_p (as_a <gcond *> (stmt))))
4567 || (gimple_code (stmt) == GIMPLE_SWITCH
4568 && TREE_CODE (gimple_switch_index (
4569 as_a <gswitch *> (stmt)))
4570 == INTEGER_CST))
4571 el_todo |= TODO_cleanup_cfg;
4573 /* If we removed EH side-effects from the statement, clean
4574 its EH information. */
4575 if (maybe_clean_or_replace_eh_stmt (old_stmt, stmt))
4577 bitmap_set_bit (need_eh_cleanup,
4578 gimple_bb (stmt)->index);
4579 if (dump_file && (dump_flags & TDF_DETAILS))
4580 fprintf (dump_file, " Removed EH side-effects.\n");
4582 /* Likewise for AB side-effects. */
4583 if (can_make_abnormal_goto
4584 && !stmt_can_make_abnormal_goto (stmt))
4586 bitmap_set_bit (need_ab_cleanup,
4587 gimple_bb (stmt)->index);
4588 if (dump_file && (dump_flags & TDF_DETAILS))
4589 fprintf (dump_file, " Removed AB side-effects.\n");
4591 update_stmt (stmt);
4592 if (vdef != gimple_vdef (stmt))
4593 VN_INFO (vdef)->valnum = vuse;
4596 /* Make new values available - for fully redundant LHS we
4597 continue with the next stmt above and skip this. */
4598 def_operand_p defp;
4599 FOR_EACH_SSA_DEF_OPERAND (defp, stmt, iter, SSA_OP_DEF)
4600 eliminate_push_avail (DEF_FROM_PTR (defp));
4603 /* Replace destination PHI arguments. */
4604 edge_iterator ei;
4605 edge e;
4606 FOR_EACH_EDGE (e, ei, b->succs)
4608 for (gphi_iterator gsi = gsi_start_phis (e->dest);
4609 !gsi_end_p (gsi);
4610 gsi_next (&gsi))
4612 gphi *phi = gsi.phi ();
4613 use_operand_p use_p = PHI_ARG_DEF_PTR_FROM_EDGE (phi, e);
4614 tree arg = USE_FROM_PTR (use_p);
4615 if (TREE_CODE (arg) != SSA_NAME
4616 || virtual_operand_p (arg))
4617 continue;
4618 tree sprime = eliminate_avail (arg);
4619 if (sprime && may_propagate_copy (arg, sprime))
4621 propagate_value (use_p, sprime);
4622 if (TREE_CODE (sprime) == SSA_NAME)
4623 gimple_set_plf (SSA_NAME_DEF_STMT (sprime), NECESSARY, true);
4627 return NULL;
4630 /* Make no longer available leaders no longer available. */
4632 void
4633 eliminate_dom_walker::after_dom_children (basic_block)
4635 tree entry;
4636 while ((entry = el_avail_stack.pop ()) != NULL_TREE)
4638 tree valnum = VN_INFO (entry)->valnum;
4639 tree old = el_avail[SSA_NAME_VERSION (valnum)];
4640 if (old == entry)
4641 el_avail[SSA_NAME_VERSION (valnum)] = NULL_TREE;
4642 else
4643 el_avail[SSA_NAME_VERSION (valnum)] = entry;
4647 /* Eliminate fully redundant computations. */
4649 static unsigned int
4650 eliminate (bool do_pre)
4652 gimple_stmt_iterator gsi;
4653 gimple *stmt;
4655 need_eh_cleanup = BITMAP_ALLOC (NULL);
4656 need_ab_cleanup = BITMAP_ALLOC (NULL);
4658 el_to_remove.create (0);
4659 el_to_fixup.create (0);
4660 el_todo = 0;
4661 el_avail.create (num_ssa_names);
4662 el_avail_stack.create (0);
4664 eliminate_dom_walker (CDI_DOMINATORS,
4665 do_pre).walk (cfun->cfg->x_entry_block_ptr);
4667 el_avail.release ();
4668 el_avail_stack.release ();
4670 /* We cannot remove stmts during BB walk, especially not release SSA
4671 names there as this confuses the VN machinery. The stmts ending
4672 up in el_to_remove are either stores or simple copies.
4673 Remove stmts in reverse order to make debug stmt creation possible. */
4674 while (!el_to_remove.is_empty ())
4676 stmt = el_to_remove.pop ();
4678 if (dump_file && (dump_flags & TDF_DETAILS))
4680 fprintf (dump_file, "Removing dead stmt ");
4681 print_gimple_stmt (dump_file, stmt, 0, 0);
4684 tree lhs;
4685 if (gimple_code (stmt) == GIMPLE_PHI)
4686 lhs = gimple_phi_result (stmt);
4687 else
4688 lhs = gimple_get_lhs (stmt);
4690 if (inserted_exprs
4691 && TREE_CODE (lhs) == SSA_NAME)
4692 bitmap_clear_bit (inserted_exprs, SSA_NAME_VERSION (lhs));
4694 gsi = gsi_for_stmt (stmt);
4695 if (gimple_code (stmt) == GIMPLE_PHI)
4696 remove_phi_node (&gsi, true);
4697 else
4699 basic_block bb = gimple_bb (stmt);
4700 unlink_stmt_vdef (stmt);
4701 if (gsi_remove (&gsi, true))
4702 bitmap_set_bit (need_eh_cleanup, bb->index);
4703 if (is_gimple_call (stmt) && stmt_can_make_abnormal_goto (stmt))
4704 bitmap_set_bit (need_ab_cleanup, bb->index);
4705 release_defs (stmt);
4708 /* Removing a stmt may expose a forwarder block. */
4709 el_todo |= TODO_cleanup_cfg;
4711 el_to_remove.release ();
4713 /* Fixup stmts that became noreturn calls. This may require splitting
4714 blocks and thus isn't possible during the dominator walk. Do this
4715 in reverse order so we don't inadvertedly remove a stmt we want to
4716 fixup by visiting a dominating now noreturn call first. */
4717 while (!el_to_fixup.is_empty ())
4719 stmt = el_to_fixup.pop ();
4721 if (dump_file && (dump_flags & TDF_DETAILS))
4723 fprintf (dump_file, "Fixing up noreturn call ");
4724 print_gimple_stmt (dump_file, stmt, 0, 0);
4727 if (fixup_noreturn_call (stmt))
4728 el_todo |= TODO_cleanup_cfg;
4730 el_to_fixup.release ();
4732 return el_todo;
4735 /* Perform CFG cleanups made necessary by elimination. */
4737 static unsigned
4738 fini_eliminate (void)
4740 bool do_eh_cleanup = !bitmap_empty_p (need_eh_cleanup);
4741 bool do_ab_cleanup = !bitmap_empty_p (need_ab_cleanup);
4743 if (do_eh_cleanup)
4744 gimple_purge_all_dead_eh_edges (need_eh_cleanup);
4746 if (do_ab_cleanup)
4747 gimple_purge_all_dead_abnormal_call_edges (need_ab_cleanup);
4749 BITMAP_FREE (need_eh_cleanup);
4750 BITMAP_FREE (need_ab_cleanup);
4752 if (do_eh_cleanup || do_ab_cleanup)
4753 return TODO_cleanup_cfg;
4754 return 0;
4757 /* Borrow a bit of tree-ssa-dce.c for the moment.
4758 XXX: In 4.1, we should be able to just run a DCE pass after PRE, though
4759 this may be a bit faster, and we may want critical edges kept split. */
4761 /* If OP's defining statement has not already been determined to be necessary,
4762 mark that statement necessary. Return the stmt, if it is newly
4763 necessary. */
4765 static inline gimple *
4766 mark_operand_necessary (tree op)
4768 gimple *stmt;
4770 gcc_assert (op);
4772 if (TREE_CODE (op) != SSA_NAME)
4773 return NULL;
4775 stmt = SSA_NAME_DEF_STMT (op);
4776 gcc_assert (stmt);
4778 if (gimple_plf (stmt, NECESSARY)
4779 || gimple_nop_p (stmt))
4780 return NULL;
4782 gimple_set_plf (stmt, NECESSARY, true);
4783 return stmt;
4786 /* Because we don't follow exactly the standard PRE algorithm, and decide not
4787 to insert PHI nodes sometimes, and because value numbering of casts isn't
4788 perfect, we sometimes end up inserting dead code. This simple DCE-like
4789 pass removes any insertions we made that weren't actually used. */
4791 static void
4792 remove_dead_inserted_code (void)
4794 bitmap worklist;
4795 unsigned i;
4796 bitmap_iterator bi;
4797 gimple *t;
4799 worklist = BITMAP_ALLOC (NULL);
4800 EXECUTE_IF_SET_IN_BITMAP (inserted_exprs, 0, i, bi)
4802 t = SSA_NAME_DEF_STMT (ssa_name (i));
4803 if (gimple_plf (t, NECESSARY))
4804 bitmap_set_bit (worklist, i);
4806 while (!bitmap_empty_p (worklist))
4808 i = bitmap_first_set_bit (worklist);
4809 bitmap_clear_bit (worklist, i);
4810 t = SSA_NAME_DEF_STMT (ssa_name (i));
4812 /* PHI nodes are somewhat special in that each PHI alternative has
4813 data and control dependencies. All the statements feeding the
4814 PHI node's arguments are always necessary. */
4815 if (gimple_code (t) == GIMPLE_PHI)
4817 unsigned k;
4819 for (k = 0; k < gimple_phi_num_args (t); k++)
4821 tree arg = PHI_ARG_DEF (t, k);
4822 if (TREE_CODE (arg) == SSA_NAME)
4824 gimple *n = mark_operand_necessary (arg);
4825 if (n)
4826 bitmap_set_bit (worklist, SSA_NAME_VERSION (arg));
4830 else
4832 /* Propagate through the operands. Examine all the USE, VUSE and
4833 VDEF operands in this statement. Mark all the statements
4834 which feed this statement's uses as necessary. */
4835 ssa_op_iter iter;
4836 tree use;
4838 /* The operands of VDEF expressions are also needed as they
4839 represent potential definitions that may reach this
4840 statement (VDEF operands allow us to follow def-def
4841 links). */
4843 FOR_EACH_SSA_TREE_OPERAND (use, t, iter, SSA_OP_ALL_USES)
4845 gimple *n = mark_operand_necessary (use);
4846 if (n)
4847 bitmap_set_bit (worklist, SSA_NAME_VERSION (use));
4852 EXECUTE_IF_SET_IN_BITMAP (inserted_exprs, 0, i, bi)
4854 t = SSA_NAME_DEF_STMT (ssa_name (i));
4855 if (!gimple_plf (t, NECESSARY))
4857 gimple_stmt_iterator gsi;
4859 if (dump_file && (dump_flags & TDF_DETAILS))
4861 fprintf (dump_file, "Removing unnecessary insertion:");
4862 print_gimple_stmt (dump_file, t, 0, 0);
4865 gsi = gsi_for_stmt (t);
4866 if (gimple_code (t) == GIMPLE_PHI)
4867 remove_phi_node (&gsi, true);
4868 else
4870 gsi_remove (&gsi, true);
4871 release_defs (t);
4875 BITMAP_FREE (worklist);
4879 /* Initialize data structures used by PRE. */
4881 static void
4882 init_pre (void)
4884 basic_block bb;
4886 next_expression_id = 1;
4887 expressions.create (0);
4888 expressions.safe_push (NULL);
4889 value_expressions.create (get_max_value_id () + 1);
4890 value_expressions.safe_grow_cleared (get_max_value_id () + 1);
4891 name_to_id.create (0);
4893 inserted_exprs = BITMAP_ALLOC (NULL);
4895 connect_infinite_loops_to_exit ();
4896 memset (&pre_stats, 0, sizeof (pre_stats));
4898 alloc_aux_for_blocks (sizeof (struct bb_bitmap_sets));
4900 calculate_dominance_info (CDI_DOMINATORS);
4902 bitmap_obstack_initialize (&grand_bitmap_obstack);
4903 phi_translate_table = new hash_table<expr_pred_trans_d> (5110);
4904 expression_to_id = new hash_table<pre_expr_d> (num_ssa_names * 3);
4905 FOR_ALL_BB_FN (bb, cfun)
4907 EXP_GEN (bb) = bitmap_set_new ();
4908 PHI_GEN (bb) = bitmap_set_new ();
4909 TMP_GEN (bb) = bitmap_set_new ();
4910 AVAIL_OUT (bb) = bitmap_set_new ();
4915 /* Deallocate data structures used by PRE. */
4917 static void
4918 fini_pre ()
4920 value_expressions.release ();
4921 BITMAP_FREE (inserted_exprs);
4922 bitmap_obstack_release (&grand_bitmap_obstack);
4923 bitmap_set_pool.release ();
4924 pre_expr_pool.release ();
4925 delete phi_translate_table;
4926 phi_translate_table = NULL;
4927 delete expression_to_id;
4928 expression_to_id = NULL;
4929 name_to_id.release ();
4931 free_aux_for_blocks ();
4934 namespace {
4936 const pass_data pass_data_pre =
4938 GIMPLE_PASS, /* type */
4939 "pre", /* name */
4940 OPTGROUP_NONE, /* optinfo_flags */
4941 TV_TREE_PRE, /* tv_id */
4942 /* PROP_no_crit_edges is ensured by placing pass_split_crit_edges before
4943 pass_pre. */
4944 ( PROP_no_crit_edges | PROP_cfg | PROP_ssa ), /* properties_required */
4945 0, /* properties_provided */
4946 PROP_no_crit_edges, /* properties_destroyed */
4947 TODO_rebuild_alias, /* todo_flags_start */
4948 0, /* todo_flags_finish */
4951 class pass_pre : public gimple_opt_pass
4953 public:
4954 pass_pre (gcc::context *ctxt)
4955 : gimple_opt_pass (pass_data_pre, ctxt)
4958 /* opt_pass methods: */
4959 virtual bool gate (function *)
4960 { return flag_tree_pre != 0 || flag_code_hoisting != 0; }
4961 virtual unsigned int execute (function *);
4963 }; // class pass_pre
4965 unsigned int
4966 pass_pre::execute (function *fun)
4968 unsigned int todo = 0;
4970 do_partial_partial =
4971 flag_tree_partial_pre && optimize_function_for_speed_p (fun);
4973 /* This has to happen before SCCVN runs because
4974 loop_optimizer_init may create new phis, etc. */
4975 loop_optimizer_init (LOOPS_NORMAL);
4977 if (!run_scc_vn (VN_WALK))
4979 loop_optimizer_finalize ();
4980 return 0;
4983 init_pre ();
4984 scev_initialize ();
4986 /* Collect and value number expressions computed in each basic block. */
4987 compute_avail ();
4989 /* Insert can get quite slow on an incredibly large number of basic
4990 blocks due to some quadratic behavior. Until this behavior is
4991 fixed, don't run it when he have an incredibly large number of
4992 bb's. If we aren't going to run insert, there is no point in
4993 computing ANTIC, either, even though it's plenty fast. */
4994 if (n_basic_blocks_for_fn (fun) < 4000)
4996 compute_antic ();
4997 insert ();
5000 /* Make sure to remove fake edges before committing our inserts.
5001 This makes sure we don't end up with extra critical edges that
5002 we would need to split. */
5003 remove_fake_exit_edges ();
5004 gsi_commit_edge_inserts ();
5006 /* Eliminate folds statements which might (should not...) end up
5007 not keeping virtual operands up-to-date. */
5008 gcc_assert (!need_ssa_update_p (fun));
5010 /* Remove all the redundant expressions. */
5011 todo |= eliminate (true);
5013 statistics_counter_event (fun, "Insertions", pre_stats.insertions);
5014 statistics_counter_event (fun, "PA inserted", pre_stats.pa_insert);
5015 statistics_counter_event (fun, "HOIST inserted", pre_stats.hoist_insert);
5016 statistics_counter_event (fun, "New PHIs", pre_stats.phis);
5017 statistics_counter_event (fun, "Eliminated", pre_stats.eliminations);
5019 clear_expression_ids ();
5020 remove_dead_inserted_code ();
5022 scev_finalize ();
5023 fini_pre ();
5024 todo |= fini_eliminate ();
5025 loop_optimizer_finalize ();
5027 /* Restore SSA info before tail-merging as that resets it as well. */
5028 scc_vn_restore_ssa_info ();
5030 /* TODO: tail_merge_optimize may merge all predecessors of a block, in which
5031 case we can merge the block with the remaining predecessor of the block.
5032 It should either:
5033 - call merge_blocks after each tail merge iteration
5034 - call merge_blocks after all tail merge iterations
5035 - mark TODO_cleanup_cfg when necessary
5036 - share the cfg cleanup with fini_pre. */
5037 todo |= tail_merge_optimize (todo);
5039 free_scc_vn ();
5041 /* Tail merging invalidates the virtual SSA web, together with
5042 cfg-cleanup opportunities exposed by PRE this will wreck the
5043 SSA updating machinery. So make sure to run update-ssa
5044 manually, before eventually scheduling cfg-cleanup as part of
5045 the todo. */
5046 update_ssa (TODO_update_ssa_only_virtuals);
5048 return todo;
5051 } // anon namespace
5053 gimple_opt_pass *
5054 make_pass_pre (gcc::context *ctxt)
5056 return new pass_pre (ctxt);
5059 namespace {
5061 const pass_data pass_data_fre =
5063 GIMPLE_PASS, /* type */
5064 "fre", /* name */
5065 OPTGROUP_NONE, /* optinfo_flags */
5066 TV_TREE_FRE, /* tv_id */
5067 ( PROP_cfg | PROP_ssa ), /* properties_required */
5068 0, /* properties_provided */
5069 0, /* properties_destroyed */
5070 0, /* todo_flags_start */
5071 0, /* todo_flags_finish */
5074 class pass_fre : public gimple_opt_pass
5076 public:
5077 pass_fre (gcc::context *ctxt)
5078 : gimple_opt_pass (pass_data_fre, ctxt)
5081 /* opt_pass methods: */
5082 opt_pass * clone () { return new pass_fre (m_ctxt); }
5083 virtual bool gate (function *) { return flag_tree_fre != 0; }
5084 virtual unsigned int execute (function *);
5086 }; // class pass_fre
5088 unsigned int
5089 pass_fre::execute (function *fun)
5091 unsigned int todo = 0;
5093 if (!run_scc_vn (VN_WALKREWRITE))
5094 return 0;
5096 memset (&pre_stats, 0, sizeof (pre_stats));
5098 /* Remove all the redundant expressions. */
5099 todo |= eliminate (false);
5101 todo |= fini_eliminate ();
5103 scc_vn_restore_ssa_info ();
5104 free_scc_vn ();
5106 statistics_counter_event (fun, "Insertions", pre_stats.insertions);
5107 statistics_counter_event (fun, "Eliminated", pre_stats.eliminations);
5109 return todo;
5112 } // anon namespace
5114 gimple_opt_pass *
5115 make_pass_fre (gcc::context *ctxt)
5117 return new pass_fre (ctxt);