2014-07-29 Ed Smith-Rowland <3dw4rd@verizon.net>
[official-gcc.git] / gcc / tree-ssa-pre.c
blob8b4d2badb6f20c98a0bb61d81f72934985ae1301
1 /* SSA-PRE for trees.
2 Copyright (C) 2001-2014 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 "tm.h"
26 #include "tree.h"
27 #include "basic-block.h"
28 #include "gimple-pretty-print.h"
29 #include "tree-inline.h"
30 #include "inchash.h"
31 #include "hash-table.h"
32 #include "tree-ssa-alias.h"
33 #include "internal-fn.h"
34 #include "gimple-fold.h"
35 #include "tree-eh.h"
36 #include "gimple-expr.h"
37 #include "is-a.h"
38 #include "gimple.h"
39 #include "gimplify.h"
40 #include "gimple-iterator.h"
41 #include "gimplify-me.h"
42 #include "gimple-ssa.h"
43 #include "tree-cfg.h"
44 #include "tree-phinodes.h"
45 #include "ssa-iterators.h"
46 #include "stringpool.h"
47 #include "tree-ssanames.h"
48 #include "tree-ssa-loop.h"
49 #include "tree-into-ssa.h"
50 #include "expr.h"
51 #include "tree-dfa.h"
52 #include "tree-ssa.h"
53 #include "tree-iterator.h"
54 #include "alloc-pool.h"
55 #include "obstack.h"
56 #include "tree-pass.h"
57 #include "flags.h"
58 #include "langhooks.h"
59 #include "cfgloop.h"
60 #include "tree-ssa-sccvn.h"
61 #include "tree-scalar-evolution.h"
62 #include "params.h"
63 #include "dbgcnt.h"
64 #include "domwalk.h"
65 #include "ipa-prop.h"
66 #include "tree-ssa-propagate.h"
68 /* TODO:
70 1. Avail sets can be shared by making an avail_find_leader that
71 walks up the dominator tree and looks in those avail sets.
72 This might affect code optimality, it's unclear right now.
73 2. Strength reduction can be performed by anticipating expressions
74 we can repair later on.
75 3. We can do back-substitution or smarter value numbering to catch
76 commutative expressions split up over multiple statements.
79 /* For ease of terminology, "expression node" in the below refers to
80 every expression node but GIMPLE_ASSIGN, because GIMPLE_ASSIGNs
81 represent the actual statement containing the expressions we care about,
82 and we cache the value number by putting it in the expression. */
84 /* Basic algorithm
86 First we walk the statements to generate the AVAIL sets, the
87 EXP_GEN sets, and the tmp_gen sets. EXP_GEN sets represent the
88 generation of values/expressions by a given block. We use them
89 when computing the ANTIC sets. The AVAIL sets consist of
90 SSA_NAME's that represent values, so we know what values are
91 available in what blocks. AVAIL is a forward dataflow problem. In
92 SSA, values are never killed, so we don't need a kill set, or a
93 fixpoint iteration, in order to calculate the AVAIL sets. In
94 traditional parlance, AVAIL sets tell us the downsafety of the
95 expressions/values.
97 Next, we generate the ANTIC sets. These sets represent the
98 anticipatable expressions. ANTIC is a backwards dataflow
99 problem. An expression is anticipatable in a given block if it could
100 be generated in that block. This means that if we had to perform
101 an insertion in that block, of the value of that expression, we
102 could. Calculating the ANTIC sets requires phi translation of
103 expressions, because the flow goes backwards through phis. We must
104 iterate to a fixpoint of the ANTIC sets, because we have a kill
105 set. Even in SSA form, values are not live over the entire
106 function, only from their definition point onwards. So we have to
107 remove values from the ANTIC set once we go past the definition
108 point of the leaders that make them up.
109 compute_antic/compute_antic_aux performs this computation.
111 Third, we perform insertions to make partially redundant
112 expressions fully redundant.
114 An expression is partially redundant (excluding partial
115 anticipation) if:
117 1. It is AVAIL in some, but not all, of the predecessors of a
118 given block.
119 2. It is ANTIC in all the predecessors.
121 In order to make it fully redundant, we insert the expression into
122 the predecessors where it is not available, but is ANTIC.
124 For the partial anticipation case, we only perform insertion if it
125 is partially anticipated in some block, and fully available in all
126 of the predecessors.
128 insert/insert_aux/do_regular_insertion/do_partial_partial_insertion
129 performs these steps.
131 Fourth, we eliminate fully redundant expressions.
132 This is a simple statement walk that replaces redundant
133 calculations with the now available values. */
135 /* Representations of value numbers:
137 Value numbers are represented by a representative SSA_NAME. We
138 will create fake SSA_NAME's in situations where we need a
139 representative but do not have one (because it is a complex
140 expression). In order to facilitate storing the value numbers in
141 bitmaps, and keep the number of wasted SSA_NAME's down, we also
142 associate a value_id with each value number, and create full blown
143 ssa_name's only where we actually need them (IE in operands of
144 existing expressions).
146 Theoretically you could replace all the value_id's with
147 SSA_NAME_VERSION, but this would allocate a large number of
148 SSA_NAME's (which are each > 30 bytes) just to get a 4 byte number.
149 It would also require an additional indirection at each point we
150 use the value id. */
152 /* Representation of expressions on value numbers:
154 Expressions consisting of value numbers are represented the same
155 way as our VN internally represents them, with an additional
156 "pre_expr" wrapping around them in order to facilitate storing all
157 of the expressions in the same sets. */
159 /* Representation of sets:
161 The dataflow sets do not need to be sorted in any particular order
162 for the majority of their lifetime, are simply represented as two
163 bitmaps, one that keeps track of values present in the set, and one
164 that keeps track of expressions present in the set.
166 When we need them in topological order, we produce it on demand by
167 transforming the bitmap into an array and sorting it into topo
168 order. */
170 /* Type of expression, used to know which member of the PRE_EXPR union
171 is valid. */
173 enum pre_expr_kind
175 NAME,
176 NARY,
177 REFERENCE,
178 CONSTANT
181 typedef union pre_expr_union_d
183 tree name;
184 tree constant;
185 vn_nary_op_t nary;
186 vn_reference_t reference;
187 } pre_expr_union;
189 typedef struct pre_expr_d : typed_noop_remove <pre_expr_d>
191 enum pre_expr_kind kind;
192 unsigned int id;
193 pre_expr_union u;
195 /* hash_table support. */
196 typedef pre_expr_d value_type;
197 typedef pre_expr_d compare_type;
198 static inline hashval_t hash (const pre_expr_d *);
199 static inline int equal (const pre_expr_d *, const pre_expr_d *);
200 } *pre_expr;
202 #define PRE_EXPR_NAME(e) (e)->u.name
203 #define PRE_EXPR_NARY(e) (e)->u.nary
204 #define PRE_EXPR_REFERENCE(e) (e)->u.reference
205 #define PRE_EXPR_CONSTANT(e) (e)->u.constant
207 /* Compare E1 and E1 for equality. */
209 inline int
210 pre_expr_d::equal (const value_type *e1, const compare_type *e2)
212 if (e1->kind != e2->kind)
213 return false;
215 switch (e1->kind)
217 case CONSTANT:
218 return vn_constant_eq_with_type (PRE_EXPR_CONSTANT (e1),
219 PRE_EXPR_CONSTANT (e2));
220 case NAME:
221 return PRE_EXPR_NAME (e1) == PRE_EXPR_NAME (e2);
222 case NARY:
223 return vn_nary_op_eq (PRE_EXPR_NARY (e1), PRE_EXPR_NARY (e2));
224 case REFERENCE:
225 return vn_reference_eq (PRE_EXPR_REFERENCE (e1),
226 PRE_EXPR_REFERENCE (e2));
227 default:
228 gcc_unreachable ();
232 /* Hash E. */
234 inline hashval_t
235 pre_expr_d::hash (const value_type *e)
237 switch (e->kind)
239 case CONSTANT:
240 return vn_hash_constant_with_type (PRE_EXPR_CONSTANT (e));
241 case NAME:
242 return SSA_NAME_VERSION (PRE_EXPR_NAME (e));
243 case NARY:
244 return PRE_EXPR_NARY (e)->hashcode;
245 case REFERENCE:
246 return PRE_EXPR_REFERENCE (e)->hashcode;
247 default:
248 gcc_unreachable ();
252 /* Next global expression id number. */
253 static unsigned int next_expression_id;
255 /* Mapping from expression to id number we can use in bitmap sets. */
256 static vec<pre_expr> expressions;
257 static hash_table<pre_expr_d> *expression_to_id;
258 static vec<unsigned> name_to_id;
260 /* Allocate an expression id for EXPR. */
262 static inline unsigned int
263 alloc_expression_id (pre_expr expr)
265 struct pre_expr_d **slot;
266 /* Make sure we won't overflow. */
267 gcc_assert (next_expression_id + 1 > next_expression_id);
268 expr->id = next_expression_id++;
269 expressions.safe_push (expr);
270 if (expr->kind == NAME)
272 unsigned version = SSA_NAME_VERSION (PRE_EXPR_NAME (expr));
273 /* vec::safe_grow_cleared allocates no headroom. Avoid frequent
274 re-allocations by using vec::reserve upfront. There is no
275 vec::quick_grow_cleared unfortunately. */
276 unsigned old_len = name_to_id.length ();
277 name_to_id.reserve (num_ssa_names - old_len);
278 name_to_id.safe_grow_cleared (num_ssa_names);
279 gcc_assert (name_to_id[version] == 0);
280 name_to_id[version] = expr->id;
282 else
284 slot = expression_to_id->find_slot (expr, INSERT);
285 gcc_assert (!*slot);
286 *slot = expr;
288 return next_expression_id - 1;
291 /* Return the expression id for tree EXPR. */
293 static inline unsigned int
294 get_expression_id (const pre_expr expr)
296 return expr->id;
299 static inline unsigned int
300 lookup_expression_id (const pre_expr expr)
302 struct pre_expr_d **slot;
304 if (expr->kind == NAME)
306 unsigned version = SSA_NAME_VERSION (PRE_EXPR_NAME (expr));
307 if (name_to_id.length () <= version)
308 return 0;
309 return name_to_id[version];
311 else
313 slot = expression_to_id->find_slot (expr, NO_INSERT);
314 if (!slot)
315 return 0;
316 return ((pre_expr)*slot)->id;
320 /* Return the existing expression id for EXPR, or create one if one
321 does not exist yet. */
323 static inline unsigned int
324 get_or_alloc_expression_id (pre_expr expr)
326 unsigned int id = lookup_expression_id (expr);
327 if (id == 0)
328 return alloc_expression_id (expr);
329 return expr->id = id;
332 /* Return the expression that has expression id ID */
334 static inline pre_expr
335 expression_for_id (unsigned int id)
337 return expressions[id];
340 /* Free the expression id field in all of our expressions,
341 and then destroy the expressions array. */
343 static void
344 clear_expression_ids (void)
346 expressions.release ();
349 static alloc_pool pre_expr_pool;
351 /* Given an SSA_NAME NAME, get or create a pre_expr to represent it. */
353 static pre_expr
354 get_or_alloc_expr_for_name (tree name)
356 struct pre_expr_d expr;
357 pre_expr result;
358 unsigned int result_id;
360 expr.kind = NAME;
361 expr.id = 0;
362 PRE_EXPR_NAME (&expr) = name;
363 result_id = lookup_expression_id (&expr);
364 if (result_id != 0)
365 return expression_for_id (result_id);
367 result = (pre_expr) pool_alloc (pre_expr_pool);
368 result->kind = NAME;
369 PRE_EXPR_NAME (result) = name;
370 alloc_expression_id (result);
371 return result;
374 /* An unordered bitmap set. One bitmap tracks values, the other,
375 expressions. */
376 typedef struct bitmap_set
378 bitmap_head expressions;
379 bitmap_head values;
380 } *bitmap_set_t;
382 #define FOR_EACH_EXPR_ID_IN_SET(set, id, bi) \
383 EXECUTE_IF_SET_IN_BITMAP (&(set)->expressions, 0, (id), (bi))
385 #define FOR_EACH_VALUE_ID_IN_SET(set, id, bi) \
386 EXECUTE_IF_SET_IN_BITMAP (&(set)->values, 0, (id), (bi))
388 /* Mapping from value id to expressions with that value_id. */
389 static vec<bitmap> value_expressions;
391 /* Sets that we need to keep track of. */
392 typedef struct bb_bitmap_sets
394 /* The EXP_GEN set, which represents expressions/values generated in
395 a basic block. */
396 bitmap_set_t exp_gen;
398 /* The PHI_GEN set, which represents PHI results generated in a
399 basic block. */
400 bitmap_set_t phi_gen;
402 /* The TMP_GEN set, which represents results/temporaries generated
403 in a basic block. IE the LHS of an expression. */
404 bitmap_set_t tmp_gen;
406 /* The AVAIL_OUT set, which represents which values are available in
407 a given basic block. */
408 bitmap_set_t avail_out;
410 /* The ANTIC_IN set, which represents which values are anticipatable
411 in a given basic block. */
412 bitmap_set_t antic_in;
414 /* The PA_IN set, which represents which values are
415 partially anticipatable in a given basic block. */
416 bitmap_set_t pa_in;
418 /* The NEW_SETS set, which is used during insertion to augment the
419 AVAIL_OUT set of blocks with the new insertions performed during
420 the current iteration. */
421 bitmap_set_t new_sets;
423 /* A cache for value_dies_in_block_x. */
424 bitmap expr_dies;
426 /* True if we have visited this block during ANTIC calculation. */
427 unsigned int visited : 1;
429 /* True we have deferred processing this block during ANTIC
430 calculation until its successor is processed. */
431 unsigned int deferred : 1;
433 /* True when the block contains a call that might not return. */
434 unsigned int contains_may_not_return_call : 1;
435 } *bb_value_sets_t;
437 #define EXP_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->exp_gen
438 #define PHI_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->phi_gen
439 #define TMP_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->tmp_gen
440 #define AVAIL_OUT(BB) ((bb_value_sets_t) ((BB)->aux))->avail_out
441 #define ANTIC_IN(BB) ((bb_value_sets_t) ((BB)->aux))->antic_in
442 #define PA_IN(BB) ((bb_value_sets_t) ((BB)->aux))->pa_in
443 #define NEW_SETS(BB) ((bb_value_sets_t) ((BB)->aux))->new_sets
444 #define EXPR_DIES(BB) ((bb_value_sets_t) ((BB)->aux))->expr_dies
445 #define BB_VISITED(BB) ((bb_value_sets_t) ((BB)->aux))->visited
446 #define BB_DEFERRED(BB) ((bb_value_sets_t) ((BB)->aux))->deferred
447 #define BB_MAY_NOTRETURN(BB) ((bb_value_sets_t) ((BB)->aux))->contains_may_not_return_call
450 /* Basic block list in postorder. */
451 static int *postorder;
452 static int postorder_num;
454 /* This structure is used to keep track of statistics on what
455 optimization PRE was able to perform. */
456 static struct
458 /* The number of RHS computations eliminated by PRE. */
459 int eliminations;
461 /* The number of new expressions/temporaries generated by PRE. */
462 int insertions;
464 /* The number of inserts found due to partial anticipation */
465 int pa_insert;
467 /* The number of new PHI nodes added by PRE. */
468 int phis;
469 } pre_stats;
471 static bool do_partial_partial;
472 static pre_expr bitmap_find_leader (bitmap_set_t, unsigned int);
473 static void bitmap_value_insert_into_set (bitmap_set_t, pre_expr);
474 static void bitmap_value_replace_in_set (bitmap_set_t, pre_expr);
475 static void bitmap_set_copy (bitmap_set_t, bitmap_set_t);
476 static bool bitmap_set_contains_value (bitmap_set_t, unsigned int);
477 static void bitmap_insert_into_set (bitmap_set_t, pre_expr);
478 static void bitmap_insert_into_set_1 (bitmap_set_t, pre_expr,
479 unsigned int, bool);
480 static bitmap_set_t bitmap_set_new (void);
481 static tree create_expression_by_pieces (basic_block, pre_expr, gimple_seq *,
482 tree);
483 static tree find_or_generate_expression (basic_block, tree, gimple_seq *);
484 static unsigned int get_expr_value_id (pre_expr);
486 /* We can add and remove elements and entries to and from sets
487 and hash tables, so we use alloc pools for them. */
489 static alloc_pool bitmap_set_pool;
490 static bitmap_obstack grand_bitmap_obstack;
492 /* Set of blocks with statements that have had their EH properties changed. */
493 static bitmap need_eh_cleanup;
495 /* Set of blocks with statements that have had their AB properties changed. */
496 static bitmap need_ab_cleanup;
498 /* A three tuple {e, pred, v} used to cache phi translations in the
499 phi_translate_table. */
501 typedef struct expr_pred_trans_d : typed_free_remove<expr_pred_trans_d>
503 /* The expression. */
504 pre_expr e;
506 /* The predecessor block along which we translated the expression. */
507 basic_block pred;
509 /* The value that resulted from the translation. */
510 pre_expr v;
512 /* The hashcode for the expression, pred pair. This is cached for
513 speed reasons. */
514 hashval_t hashcode;
516 /* hash_table support. */
517 typedef expr_pred_trans_d value_type;
518 typedef expr_pred_trans_d compare_type;
519 static inline hashval_t hash (const value_type *);
520 static inline int equal (const value_type *, const compare_type *);
521 } *expr_pred_trans_t;
522 typedef const struct expr_pred_trans_d *const_expr_pred_trans_t;
524 inline hashval_t
525 expr_pred_trans_d::hash (const expr_pred_trans_d *e)
527 return e->hashcode;
530 inline int
531 expr_pred_trans_d::equal (const value_type *ve1,
532 const compare_type *ve2)
534 basic_block b1 = ve1->pred;
535 basic_block b2 = ve2->pred;
537 /* If they are not translations for the same basic block, they can't
538 be equal. */
539 if (b1 != b2)
540 return false;
541 return pre_expr_d::equal (ve1->e, ve2->e);
544 /* The phi_translate_table caches phi translations for a given
545 expression and predecessor. */
546 static hash_table<expr_pred_trans_d> *phi_translate_table;
548 /* Add the tuple mapping from {expression E, basic block PRED} to
549 the phi translation table and return whether it pre-existed. */
551 static inline bool
552 phi_trans_add (expr_pred_trans_t *entry, pre_expr e, basic_block pred)
554 expr_pred_trans_t *slot;
555 expr_pred_trans_d tem;
556 hashval_t hash = iterative_hash_hashval_t (pre_expr_d::hash (e),
557 pred->index);
558 tem.e = e;
559 tem.pred = pred;
560 tem.hashcode = hash;
561 slot = phi_translate_table->find_slot_with_hash (&tem, hash, INSERT);
562 if (*slot)
564 *entry = *slot;
565 return true;
568 *entry = *slot = XNEW (struct expr_pred_trans_d);
569 (*entry)->e = e;
570 (*entry)->pred = pred;
571 (*entry)->hashcode = hash;
572 return false;
576 /* Add expression E to the expression set of value id V. */
578 static void
579 add_to_value (unsigned int v, pre_expr e)
581 bitmap set;
583 gcc_checking_assert (get_expr_value_id (e) == v);
585 if (v >= value_expressions.length ())
587 value_expressions.safe_grow_cleared (v + 1);
590 set = value_expressions[v];
591 if (!set)
593 set = BITMAP_ALLOC (&grand_bitmap_obstack);
594 value_expressions[v] = set;
597 bitmap_set_bit (set, get_or_alloc_expression_id (e));
600 /* Create a new bitmap set and return it. */
602 static bitmap_set_t
603 bitmap_set_new (void)
605 bitmap_set_t ret = (bitmap_set_t) pool_alloc (bitmap_set_pool);
606 bitmap_initialize (&ret->expressions, &grand_bitmap_obstack);
607 bitmap_initialize (&ret->values, &grand_bitmap_obstack);
608 return ret;
611 /* Return the value id for a PRE expression EXPR. */
613 static unsigned int
614 get_expr_value_id (pre_expr expr)
616 unsigned int id;
617 switch (expr->kind)
619 case CONSTANT:
620 id = get_constant_value_id (PRE_EXPR_CONSTANT (expr));
621 break;
622 case NAME:
623 id = VN_INFO (PRE_EXPR_NAME (expr))->value_id;
624 break;
625 case NARY:
626 id = PRE_EXPR_NARY (expr)->value_id;
627 break;
628 case REFERENCE:
629 id = PRE_EXPR_REFERENCE (expr)->value_id;
630 break;
631 default:
632 gcc_unreachable ();
634 /* ??? We cannot assert that expr has a value-id (it can be 0), because
635 we assign value-ids only to expressions that have a result
636 in set_hashtable_value_ids. */
637 return id;
640 /* Return a SCCVN valnum (SSA name or constant) for the PRE value-id VAL. */
642 static tree
643 sccvn_valnum_from_value_id (unsigned int val)
645 bitmap_iterator bi;
646 unsigned int i;
647 bitmap exprset = value_expressions[val];
648 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
650 pre_expr vexpr = expression_for_id (i);
651 if (vexpr->kind == NAME)
652 return VN_INFO (PRE_EXPR_NAME (vexpr))->valnum;
653 else if (vexpr->kind == CONSTANT)
654 return PRE_EXPR_CONSTANT (vexpr);
656 return NULL_TREE;
659 /* Remove an expression EXPR from a bitmapped set. */
661 static void
662 bitmap_remove_from_set (bitmap_set_t set, pre_expr expr)
664 unsigned int val = get_expr_value_id (expr);
665 if (!value_id_constant_p (val))
667 bitmap_clear_bit (&set->values, val);
668 bitmap_clear_bit (&set->expressions, get_expression_id (expr));
672 static void
673 bitmap_insert_into_set_1 (bitmap_set_t set, pre_expr expr,
674 unsigned int val, bool allow_constants)
676 if (allow_constants || !value_id_constant_p (val))
678 /* We specifically expect this and only this function to be able to
679 insert constants into a set. */
680 bitmap_set_bit (&set->values, val);
681 bitmap_set_bit (&set->expressions, get_or_alloc_expression_id (expr));
685 /* Insert an expression EXPR into a bitmapped set. */
687 static void
688 bitmap_insert_into_set (bitmap_set_t set, pre_expr expr)
690 bitmap_insert_into_set_1 (set, expr, get_expr_value_id (expr), false);
693 /* Copy a bitmapped set ORIG, into bitmapped set DEST. */
695 static void
696 bitmap_set_copy (bitmap_set_t dest, bitmap_set_t orig)
698 bitmap_copy (&dest->expressions, &orig->expressions);
699 bitmap_copy (&dest->values, &orig->values);
703 /* Free memory used up by SET. */
704 static void
705 bitmap_set_free (bitmap_set_t set)
707 bitmap_clear (&set->expressions);
708 bitmap_clear (&set->values);
712 /* Generate an topological-ordered array of bitmap set SET. */
714 static vec<pre_expr>
715 sorted_array_from_bitmap_set (bitmap_set_t set)
717 unsigned int i, j;
718 bitmap_iterator bi, bj;
719 vec<pre_expr> result;
721 /* Pre-allocate roughly enough space for the array. */
722 result.create (bitmap_count_bits (&set->values));
724 FOR_EACH_VALUE_ID_IN_SET (set, i, bi)
726 /* The number of expressions having a given value is usually
727 relatively small. Thus, rather than making a vector of all
728 the expressions and sorting it by value-id, we walk the values
729 and check in the reverse mapping that tells us what expressions
730 have a given value, to filter those in our set. As a result,
731 the expressions are inserted in value-id order, which means
732 topological order.
734 If this is somehow a significant lose for some cases, we can
735 choose which set to walk based on the set size. */
736 bitmap exprset = value_expressions[i];
737 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, j, bj)
739 if (bitmap_bit_p (&set->expressions, j))
740 result.safe_push (expression_for_id (j));
744 return result;
747 /* Perform bitmapped set operation DEST &= ORIG. */
749 static void
750 bitmap_set_and (bitmap_set_t dest, bitmap_set_t orig)
752 bitmap_iterator bi;
753 unsigned int i;
755 if (dest != orig)
757 bitmap_head temp;
758 bitmap_initialize (&temp, &grand_bitmap_obstack);
760 bitmap_and_into (&dest->values, &orig->values);
761 bitmap_copy (&temp, &dest->expressions);
762 EXECUTE_IF_SET_IN_BITMAP (&temp, 0, i, bi)
764 pre_expr expr = expression_for_id (i);
765 unsigned int value_id = get_expr_value_id (expr);
766 if (!bitmap_bit_p (&dest->values, value_id))
767 bitmap_clear_bit (&dest->expressions, i);
769 bitmap_clear (&temp);
773 /* Subtract all values and expressions contained in ORIG from DEST. */
775 static bitmap_set_t
776 bitmap_set_subtract (bitmap_set_t dest, bitmap_set_t orig)
778 bitmap_set_t result = bitmap_set_new ();
779 bitmap_iterator bi;
780 unsigned int i;
782 bitmap_and_compl (&result->expressions, &dest->expressions,
783 &orig->expressions);
785 FOR_EACH_EXPR_ID_IN_SET (result, i, bi)
787 pre_expr expr = expression_for_id (i);
788 unsigned int value_id = get_expr_value_id (expr);
789 bitmap_set_bit (&result->values, value_id);
792 return result;
795 /* Subtract all the values in bitmap set B from bitmap set A. */
797 static void
798 bitmap_set_subtract_values (bitmap_set_t a, bitmap_set_t b)
800 unsigned int i;
801 bitmap_iterator bi;
802 bitmap_head temp;
804 bitmap_initialize (&temp, &grand_bitmap_obstack);
806 bitmap_copy (&temp, &a->expressions);
807 EXECUTE_IF_SET_IN_BITMAP (&temp, 0, i, bi)
809 pre_expr expr = expression_for_id (i);
810 if (bitmap_set_contains_value (b, get_expr_value_id (expr)))
811 bitmap_remove_from_set (a, expr);
813 bitmap_clear (&temp);
817 /* Return true if bitmapped set SET contains the value VALUE_ID. */
819 static bool
820 bitmap_set_contains_value (bitmap_set_t set, unsigned int value_id)
822 if (value_id_constant_p (value_id))
823 return true;
825 if (!set || bitmap_empty_p (&set->expressions))
826 return false;
828 return bitmap_bit_p (&set->values, value_id);
831 static inline bool
832 bitmap_set_contains_expr (bitmap_set_t set, const pre_expr expr)
834 return bitmap_bit_p (&set->expressions, get_expression_id (expr));
837 /* Replace an instance of value LOOKFOR with expression EXPR in SET. */
839 static void
840 bitmap_set_replace_value (bitmap_set_t set, unsigned int lookfor,
841 const pre_expr expr)
843 bitmap exprset;
844 unsigned int i;
845 bitmap_iterator bi;
847 if (value_id_constant_p (lookfor))
848 return;
850 if (!bitmap_set_contains_value (set, lookfor))
851 return;
853 /* The number of expressions having a given value is usually
854 significantly less than the total number of expressions in SET.
855 Thus, rather than check, for each expression in SET, whether it
856 has the value LOOKFOR, we walk the reverse mapping that tells us
857 what expressions have a given value, and see if any of those
858 expressions are in our set. For large testcases, this is about
859 5-10x faster than walking the bitmap. If this is somehow a
860 significant lose for some cases, we can choose which set to walk
861 based on the set size. */
862 exprset = value_expressions[lookfor];
863 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
865 if (bitmap_clear_bit (&set->expressions, i))
867 bitmap_set_bit (&set->expressions, get_expression_id (expr));
868 return;
872 gcc_unreachable ();
875 /* Return true if two bitmap sets are equal. */
877 static bool
878 bitmap_set_equal (bitmap_set_t a, bitmap_set_t b)
880 return bitmap_equal_p (&a->values, &b->values);
883 /* Replace an instance of EXPR's VALUE with EXPR in SET if it exists,
884 and add it otherwise. */
886 static void
887 bitmap_value_replace_in_set (bitmap_set_t set, pre_expr expr)
889 unsigned int val = get_expr_value_id (expr);
891 if (bitmap_set_contains_value (set, val))
892 bitmap_set_replace_value (set, val, expr);
893 else
894 bitmap_insert_into_set (set, expr);
897 /* Insert EXPR into SET if EXPR's value is not already present in
898 SET. */
900 static void
901 bitmap_value_insert_into_set (bitmap_set_t set, pre_expr expr)
903 unsigned int val = get_expr_value_id (expr);
905 gcc_checking_assert (expr->id == get_or_alloc_expression_id (expr));
907 /* Constant values are always considered to be part of the set. */
908 if (value_id_constant_p (val))
909 return;
911 /* If the value membership changed, add the expression. */
912 if (bitmap_set_bit (&set->values, val))
913 bitmap_set_bit (&set->expressions, expr->id);
916 /* Print out EXPR to outfile. */
918 static void
919 print_pre_expr (FILE *outfile, const pre_expr expr)
921 switch (expr->kind)
923 case CONSTANT:
924 print_generic_expr (outfile, PRE_EXPR_CONSTANT (expr), 0);
925 break;
926 case NAME:
927 print_generic_expr (outfile, PRE_EXPR_NAME (expr), 0);
928 break;
929 case NARY:
931 unsigned int i;
932 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
933 fprintf (outfile, "{%s,", get_tree_code_name (nary->opcode));
934 for (i = 0; i < nary->length; i++)
936 print_generic_expr (outfile, nary->op[i], 0);
937 if (i != (unsigned) nary->length - 1)
938 fprintf (outfile, ",");
940 fprintf (outfile, "}");
942 break;
944 case REFERENCE:
946 vn_reference_op_t vro;
947 unsigned int i;
948 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
949 fprintf (outfile, "{");
950 for (i = 0;
951 ref->operands.iterate (i, &vro);
952 i++)
954 bool closebrace = false;
955 if (vro->opcode != SSA_NAME
956 && TREE_CODE_CLASS (vro->opcode) != tcc_declaration)
958 fprintf (outfile, "%s", get_tree_code_name (vro->opcode));
959 if (vro->op0)
961 fprintf (outfile, "<");
962 closebrace = true;
965 if (vro->op0)
967 print_generic_expr (outfile, vro->op0, 0);
968 if (vro->op1)
970 fprintf (outfile, ",");
971 print_generic_expr (outfile, vro->op1, 0);
973 if (vro->op2)
975 fprintf (outfile, ",");
976 print_generic_expr (outfile, vro->op2, 0);
979 if (closebrace)
980 fprintf (outfile, ">");
981 if (i != ref->operands.length () - 1)
982 fprintf (outfile, ",");
984 fprintf (outfile, "}");
985 if (ref->vuse)
987 fprintf (outfile, "@");
988 print_generic_expr (outfile, ref->vuse, 0);
991 break;
994 void debug_pre_expr (pre_expr);
996 /* Like print_pre_expr but always prints to stderr. */
997 DEBUG_FUNCTION void
998 debug_pre_expr (pre_expr e)
1000 print_pre_expr (stderr, e);
1001 fprintf (stderr, "\n");
1004 /* Print out SET to OUTFILE. */
1006 static void
1007 print_bitmap_set (FILE *outfile, bitmap_set_t set,
1008 const char *setname, int blockindex)
1010 fprintf (outfile, "%s[%d] := { ", setname, blockindex);
1011 if (set)
1013 bool first = true;
1014 unsigned i;
1015 bitmap_iterator bi;
1017 FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
1019 const pre_expr expr = expression_for_id (i);
1021 if (!first)
1022 fprintf (outfile, ", ");
1023 first = false;
1024 print_pre_expr (outfile, expr);
1026 fprintf (outfile, " (%04d)", get_expr_value_id (expr));
1029 fprintf (outfile, " }\n");
1032 void debug_bitmap_set (bitmap_set_t);
1034 DEBUG_FUNCTION void
1035 debug_bitmap_set (bitmap_set_t set)
1037 print_bitmap_set (stderr, set, "debug", 0);
1040 void debug_bitmap_sets_for (basic_block);
1042 DEBUG_FUNCTION void
1043 debug_bitmap_sets_for (basic_block bb)
1045 print_bitmap_set (stderr, AVAIL_OUT (bb), "avail_out", bb->index);
1046 print_bitmap_set (stderr, EXP_GEN (bb), "exp_gen", bb->index);
1047 print_bitmap_set (stderr, PHI_GEN (bb), "phi_gen", bb->index);
1048 print_bitmap_set (stderr, TMP_GEN (bb), "tmp_gen", bb->index);
1049 print_bitmap_set (stderr, ANTIC_IN (bb), "antic_in", bb->index);
1050 if (do_partial_partial)
1051 print_bitmap_set (stderr, PA_IN (bb), "pa_in", bb->index);
1052 print_bitmap_set (stderr, NEW_SETS (bb), "new_sets", bb->index);
1055 /* Print out the expressions that have VAL to OUTFILE. */
1057 static void
1058 print_value_expressions (FILE *outfile, unsigned int val)
1060 bitmap set = value_expressions[val];
1061 if (set)
1063 bitmap_set x;
1064 char s[10];
1065 sprintf (s, "%04d", val);
1066 x.expressions = *set;
1067 print_bitmap_set (outfile, &x, s, 0);
1072 DEBUG_FUNCTION void
1073 debug_value_expressions (unsigned int val)
1075 print_value_expressions (stderr, val);
1078 /* Given a CONSTANT, allocate a new CONSTANT type PRE_EXPR to
1079 represent it. */
1081 static pre_expr
1082 get_or_alloc_expr_for_constant (tree constant)
1084 unsigned int result_id;
1085 unsigned int value_id;
1086 struct pre_expr_d expr;
1087 pre_expr newexpr;
1089 expr.kind = CONSTANT;
1090 PRE_EXPR_CONSTANT (&expr) = constant;
1091 result_id = lookup_expression_id (&expr);
1092 if (result_id != 0)
1093 return expression_for_id (result_id);
1095 newexpr = (pre_expr) pool_alloc (pre_expr_pool);
1096 newexpr->kind = CONSTANT;
1097 PRE_EXPR_CONSTANT (newexpr) = constant;
1098 alloc_expression_id (newexpr);
1099 value_id = get_or_alloc_constant_value_id (constant);
1100 add_to_value (value_id, newexpr);
1101 return newexpr;
1104 /* Given a value id V, find the actual tree representing the constant
1105 value if there is one, and return it. Return NULL if we can't find
1106 a constant. */
1108 static tree
1109 get_constant_for_value_id (unsigned int v)
1111 if (value_id_constant_p (v))
1113 unsigned int i;
1114 bitmap_iterator bi;
1115 bitmap exprset = value_expressions[v];
1117 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
1119 pre_expr expr = expression_for_id (i);
1120 if (expr->kind == CONSTANT)
1121 return PRE_EXPR_CONSTANT (expr);
1124 return NULL;
1127 /* Get or allocate a pre_expr for a piece of GIMPLE, and return it.
1128 Currently only supports constants and SSA_NAMES. */
1129 static pre_expr
1130 get_or_alloc_expr_for (tree t)
1132 if (TREE_CODE (t) == SSA_NAME)
1133 return get_or_alloc_expr_for_name (t);
1134 else if (is_gimple_min_invariant (t))
1135 return get_or_alloc_expr_for_constant (t);
1136 else
1138 /* More complex expressions can result from SCCVN expression
1139 simplification that inserts values for them. As they all
1140 do not have VOPs the get handled by the nary ops struct. */
1141 vn_nary_op_t result;
1142 unsigned int result_id;
1143 vn_nary_op_lookup (t, &result);
1144 if (result != NULL)
1146 pre_expr e = (pre_expr) pool_alloc (pre_expr_pool);
1147 e->kind = NARY;
1148 PRE_EXPR_NARY (e) = result;
1149 result_id = lookup_expression_id (e);
1150 if (result_id != 0)
1152 pool_free (pre_expr_pool, e);
1153 e = expression_for_id (result_id);
1154 return e;
1156 alloc_expression_id (e);
1157 return e;
1160 return NULL;
1163 /* Return the folded version of T if T, when folded, is a gimple
1164 min_invariant. Otherwise, return T. */
1166 static pre_expr
1167 fully_constant_expression (pre_expr e)
1169 switch (e->kind)
1171 case CONSTANT:
1172 return e;
1173 case NARY:
1175 vn_nary_op_t nary = PRE_EXPR_NARY (e);
1176 switch (TREE_CODE_CLASS (nary->opcode))
1178 case tcc_binary:
1179 case tcc_comparison:
1181 /* We have to go from trees to pre exprs to value ids to
1182 constants. */
1183 tree naryop0 = nary->op[0];
1184 tree naryop1 = nary->op[1];
1185 tree result;
1186 if (!is_gimple_min_invariant (naryop0))
1188 pre_expr rep0 = get_or_alloc_expr_for (naryop0);
1189 unsigned int vrep0 = get_expr_value_id (rep0);
1190 tree const0 = get_constant_for_value_id (vrep0);
1191 if (const0)
1192 naryop0 = fold_convert (TREE_TYPE (naryop0), const0);
1194 if (!is_gimple_min_invariant (naryop1))
1196 pre_expr rep1 = get_or_alloc_expr_for (naryop1);
1197 unsigned int vrep1 = get_expr_value_id (rep1);
1198 tree const1 = get_constant_for_value_id (vrep1);
1199 if (const1)
1200 naryop1 = fold_convert (TREE_TYPE (naryop1), const1);
1202 result = fold_binary (nary->opcode, nary->type,
1203 naryop0, naryop1);
1204 if (result && is_gimple_min_invariant (result))
1205 return get_or_alloc_expr_for_constant (result);
1206 /* We might have simplified the expression to a
1207 SSA_NAME for example from x_1 * 1. But we cannot
1208 insert a PHI for x_1 unconditionally as x_1 might
1209 not be available readily. */
1210 return e;
1212 case tcc_reference:
1213 if (nary->opcode != REALPART_EXPR
1214 && nary->opcode != IMAGPART_EXPR
1215 && nary->opcode != VIEW_CONVERT_EXPR)
1216 return e;
1217 /* Fallthrough. */
1218 case tcc_unary:
1220 /* We have to go from trees to pre exprs to value ids to
1221 constants. */
1222 tree naryop0 = nary->op[0];
1223 tree const0, result;
1224 if (is_gimple_min_invariant (naryop0))
1225 const0 = naryop0;
1226 else
1228 pre_expr rep0 = get_or_alloc_expr_for (naryop0);
1229 unsigned int vrep0 = get_expr_value_id (rep0);
1230 const0 = get_constant_for_value_id (vrep0);
1232 result = NULL;
1233 if (const0)
1235 tree type1 = TREE_TYPE (nary->op[0]);
1236 const0 = fold_convert (type1, const0);
1237 result = fold_unary (nary->opcode, nary->type, const0);
1239 if (result && is_gimple_min_invariant (result))
1240 return get_or_alloc_expr_for_constant (result);
1241 return e;
1243 default:
1244 return e;
1247 case REFERENCE:
1249 vn_reference_t ref = PRE_EXPR_REFERENCE (e);
1250 tree folded;
1251 if ((folded = fully_constant_vn_reference_p (ref)))
1252 return get_or_alloc_expr_for_constant (folded);
1253 return e;
1255 default:
1256 return e;
1258 return e;
1261 /* Translate the VUSE backwards through phi nodes in PHIBLOCK, so that
1262 it has the value it would have in BLOCK. Set *SAME_VALID to true
1263 in case the new vuse doesn't change the value id of the OPERANDS. */
1265 static tree
1266 translate_vuse_through_block (vec<vn_reference_op_s> operands,
1267 alias_set_type set, tree type, tree vuse,
1268 basic_block phiblock,
1269 basic_block block, bool *same_valid)
1271 gimple phi = SSA_NAME_DEF_STMT (vuse);
1272 ao_ref ref;
1273 edge e = NULL;
1274 bool use_oracle;
1276 *same_valid = true;
1278 if (gimple_bb (phi) != phiblock)
1279 return vuse;
1281 use_oracle = ao_ref_init_from_vn_reference (&ref, set, type, operands);
1283 /* Use the alias-oracle to find either the PHI node in this block,
1284 the first VUSE used in this block that is equivalent to vuse or
1285 the first VUSE which definition in this block kills the value. */
1286 if (gimple_code (phi) == GIMPLE_PHI)
1287 e = find_edge (block, phiblock);
1288 else if (use_oracle)
1289 while (!stmt_may_clobber_ref_p_1 (phi, &ref))
1291 vuse = gimple_vuse (phi);
1292 phi = SSA_NAME_DEF_STMT (vuse);
1293 if (gimple_bb (phi) != phiblock)
1294 return vuse;
1295 if (gimple_code (phi) == GIMPLE_PHI)
1297 e = find_edge (block, phiblock);
1298 break;
1301 else
1302 return NULL_TREE;
1304 if (e)
1306 if (use_oracle)
1308 bitmap visited = NULL;
1309 unsigned int cnt;
1310 /* Try to find a vuse that dominates this phi node by skipping
1311 non-clobbering statements. */
1312 vuse = get_continuation_for_phi (phi, &ref, &cnt, &visited, false,
1313 NULL, NULL);
1314 if (visited)
1315 BITMAP_FREE (visited);
1317 else
1318 vuse = NULL_TREE;
1319 if (!vuse)
1321 /* If we didn't find any, the value ID can't stay the same,
1322 but return the translated vuse. */
1323 *same_valid = false;
1324 vuse = PHI_ARG_DEF (phi, e->dest_idx);
1326 /* ??? We would like to return vuse here as this is the canonical
1327 upmost vdef that this reference is associated with. But during
1328 insertion of the references into the hash tables we only ever
1329 directly insert with their direct gimple_vuse, hence returning
1330 something else would make us not find the other expression. */
1331 return PHI_ARG_DEF (phi, e->dest_idx);
1334 return NULL_TREE;
1337 /* Like bitmap_find_leader, but checks for the value existing in SET1 *or*
1338 SET2. This is used to avoid making a set consisting of the union
1339 of PA_IN and ANTIC_IN during insert. */
1341 static inline pre_expr
1342 find_leader_in_sets (unsigned int val, bitmap_set_t set1, bitmap_set_t set2)
1344 pre_expr result;
1346 result = bitmap_find_leader (set1, val);
1347 if (!result && set2)
1348 result = bitmap_find_leader (set2, val);
1349 return result;
1352 /* Get the tree type for our PRE expression e. */
1354 static tree
1355 get_expr_type (const pre_expr e)
1357 switch (e->kind)
1359 case NAME:
1360 return TREE_TYPE (PRE_EXPR_NAME (e));
1361 case CONSTANT:
1362 return TREE_TYPE (PRE_EXPR_CONSTANT (e));
1363 case REFERENCE:
1364 return PRE_EXPR_REFERENCE (e)->type;
1365 case NARY:
1366 return PRE_EXPR_NARY (e)->type;
1368 gcc_unreachable ();
1371 /* Get a representative SSA_NAME for a given expression.
1372 Since all of our sub-expressions are treated as values, we require
1373 them to be SSA_NAME's for simplicity.
1374 Prior versions of GVNPRE used to use "value handles" here, so that
1375 an expression would be VH.11 + VH.10 instead of d_3 + e_6. In
1376 either case, the operands are really values (IE we do not expect
1377 them to be usable without finding leaders). */
1379 static tree
1380 get_representative_for (const pre_expr e)
1382 tree name;
1383 unsigned int value_id = get_expr_value_id (e);
1385 switch (e->kind)
1387 case NAME:
1388 return PRE_EXPR_NAME (e);
1389 case CONSTANT:
1390 return PRE_EXPR_CONSTANT (e);
1391 case NARY:
1392 case REFERENCE:
1394 /* Go through all of the expressions representing this value
1395 and pick out an SSA_NAME. */
1396 unsigned int i;
1397 bitmap_iterator bi;
1398 bitmap exprs = value_expressions[value_id];
1399 EXECUTE_IF_SET_IN_BITMAP (exprs, 0, i, bi)
1401 pre_expr rep = expression_for_id (i);
1402 if (rep->kind == NAME)
1403 return PRE_EXPR_NAME (rep);
1404 else if (rep->kind == CONSTANT)
1405 return PRE_EXPR_CONSTANT (rep);
1408 break;
1411 /* If we reached here we couldn't find an SSA_NAME. This can
1412 happen when we've discovered a value that has never appeared in
1413 the program as set to an SSA_NAME, as the result of phi translation.
1414 Create one here.
1415 ??? We should be able to re-use this when we insert the statement
1416 to compute it. */
1417 name = make_temp_ssa_name (get_expr_type (e), gimple_build_nop (), "pretmp");
1418 VN_INFO_GET (name)->value_id = value_id;
1419 VN_INFO (name)->valnum = name;
1420 /* ??? For now mark this SSA name for release by SCCVN. */
1421 VN_INFO (name)->needs_insertion = true;
1422 add_to_value (value_id, get_or_alloc_expr_for_name (name));
1423 if (dump_file && (dump_flags & TDF_DETAILS))
1425 fprintf (dump_file, "Created SSA_NAME representative ");
1426 print_generic_expr (dump_file, name, 0);
1427 fprintf (dump_file, " for expression:");
1428 print_pre_expr (dump_file, e);
1429 fprintf (dump_file, " (%04d)\n", value_id);
1432 return name;
1437 static pre_expr
1438 phi_translate (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1439 basic_block pred, basic_block phiblock);
1441 /* Translate EXPR using phis in PHIBLOCK, so that it has the values of
1442 the phis in PRED. Return NULL if we can't find a leader for each part
1443 of the translated expression. */
1445 static pre_expr
1446 phi_translate_1 (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1447 basic_block pred, basic_block phiblock)
1449 switch (expr->kind)
1451 case NARY:
1453 unsigned int i;
1454 bool changed = false;
1455 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1456 vn_nary_op_t newnary = XALLOCAVAR (struct vn_nary_op_s,
1457 sizeof_vn_nary_op (nary->length));
1458 memcpy (newnary, nary, sizeof_vn_nary_op (nary->length));
1460 for (i = 0; i < newnary->length; i++)
1462 if (TREE_CODE (newnary->op[i]) != SSA_NAME)
1463 continue;
1464 else
1466 pre_expr leader, result;
1467 unsigned int op_val_id = VN_INFO (newnary->op[i])->value_id;
1468 leader = find_leader_in_sets (op_val_id, set1, set2);
1469 result = phi_translate (leader, set1, set2, pred, phiblock);
1470 if (result && result != leader)
1472 tree name = get_representative_for (result);
1473 if (!name)
1474 return NULL;
1475 newnary->op[i] = name;
1477 else if (!result)
1478 return NULL;
1480 changed |= newnary->op[i] != nary->op[i];
1483 if (changed)
1485 pre_expr constant;
1486 unsigned int new_val_id;
1488 tree result = vn_nary_op_lookup_pieces (newnary->length,
1489 newnary->opcode,
1490 newnary->type,
1491 &newnary->op[0],
1492 &nary);
1493 if (result && is_gimple_min_invariant (result))
1494 return get_or_alloc_expr_for_constant (result);
1496 expr = (pre_expr) pool_alloc (pre_expr_pool);
1497 expr->kind = NARY;
1498 expr->id = 0;
1499 if (nary)
1501 PRE_EXPR_NARY (expr) = nary;
1502 constant = fully_constant_expression (expr);
1503 if (constant != expr)
1504 return constant;
1506 new_val_id = nary->value_id;
1507 get_or_alloc_expression_id (expr);
1509 else
1511 new_val_id = get_next_value_id ();
1512 value_expressions.safe_grow_cleared (get_max_value_id () + 1);
1513 nary = vn_nary_op_insert_pieces (newnary->length,
1514 newnary->opcode,
1515 newnary->type,
1516 &newnary->op[0],
1517 result, new_val_id);
1518 PRE_EXPR_NARY (expr) = nary;
1519 constant = fully_constant_expression (expr);
1520 if (constant != expr)
1521 return constant;
1522 get_or_alloc_expression_id (expr);
1524 add_to_value (new_val_id, expr);
1526 return expr;
1528 break;
1530 case REFERENCE:
1532 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1533 vec<vn_reference_op_s> operands = ref->operands;
1534 tree vuse = ref->vuse;
1535 tree newvuse = vuse;
1536 vec<vn_reference_op_s> newoperands = vNULL;
1537 bool changed = false, same_valid = true;
1538 unsigned int i, j, n;
1539 vn_reference_op_t operand;
1540 vn_reference_t newref;
1542 for (i = 0, j = 0;
1543 operands.iterate (i, &operand); i++, j++)
1545 pre_expr opresult;
1546 pre_expr leader;
1547 tree op[3];
1548 tree type = operand->type;
1549 vn_reference_op_s newop = *operand;
1550 op[0] = operand->op0;
1551 op[1] = operand->op1;
1552 op[2] = operand->op2;
1553 for (n = 0; n < 3; ++n)
1555 unsigned int op_val_id;
1556 if (!op[n])
1557 continue;
1558 if (TREE_CODE (op[n]) != SSA_NAME)
1560 /* We can't possibly insert these. */
1561 if (n != 0
1562 && !is_gimple_min_invariant (op[n]))
1563 break;
1564 continue;
1566 op_val_id = VN_INFO (op[n])->value_id;
1567 leader = find_leader_in_sets (op_val_id, set1, set2);
1568 if (!leader)
1569 break;
1570 opresult = phi_translate (leader, set1, set2, pred, phiblock);
1571 if (!opresult)
1572 break;
1573 if (opresult != leader)
1575 tree name = get_representative_for (opresult);
1576 if (!name)
1577 break;
1578 changed |= name != op[n];
1579 op[n] = name;
1582 if (n != 3)
1584 newoperands.release ();
1585 return NULL;
1587 if (!newoperands.exists ())
1588 newoperands = operands.copy ();
1589 /* We may have changed from an SSA_NAME to a constant */
1590 if (newop.opcode == SSA_NAME && TREE_CODE (op[0]) != SSA_NAME)
1591 newop.opcode = TREE_CODE (op[0]);
1592 newop.type = type;
1593 newop.op0 = op[0];
1594 newop.op1 = op[1];
1595 newop.op2 = op[2];
1596 /* If it transforms a non-constant ARRAY_REF into a constant
1597 one, adjust the constant offset. */
1598 if (newop.opcode == ARRAY_REF
1599 && newop.off == -1
1600 && TREE_CODE (op[0]) == INTEGER_CST
1601 && TREE_CODE (op[1]) == INTEGER_CST
1602 && TREE_CODE (op[2]) == INTEGER_CST)
1604 offset_int off = ((wi::to_offset (op[0])
1605 - wi::to_offset (op[1]))
1606 * wi::to_offset (op[2]));
1607 if (wi::fits_shwi_p (off))
1608 newop.off = off.to_shwi ();
1610 newoperands[j] = newop;
1611 /* If it transforms from an SSA_NAME to an address, fold with
1612 a preceding indirect reference. */
1613 if (j > 0 && op[0] && TREE_CODE (op[0]) == ADDR_EXPR
1614 && newoperands[j - 1].opcode == MEM_REF)
1615 vn_reference_fold_indirect (&newoperands, &j);
1617 if (i != operands.length ())
1619 newoperands.release ();
1620 return NULL;
1623 if (vuse)
1625 newvuse = translate_vuse_through_block (newoperands,
1626 ref->set, ref->type,
1627 vuse, phiblock, pred,
1628 &same_valid);
1629 if (newvuse == NULL_TREE)
1631 newoperands.release ();
1632 return NULL;
1636 if (changed || newvuse != vuse)
1638 unsigned int new_val_id;
1639 pre_expr constant;
1641 tree result = vn_reference_lookup_pieces (newvuse, ref->set,
1642 ref->type,
1643 newoperands,
1644 &newref, VN_WALK);
1645 if (result)
1646 newoperands.release ();
1648 /* We can always insert constants, so if we have a partial
1649 redundant constant load of another type try to translate it
1650 to a constant of appropriate type. */
1651 if (result && is_gimple_min_invariant (result))
1653 tree tem = result;
1654 if (!useless_type_conversion_p (ref->type, TREE_TYPE (result)))
1656 tem = fold_unary (VIEW_CONVERT_EXPR, ref->type, result);
1657 if (tem && !is_gimple_min_invariant (tem))
1658 tem = NULL_TREE;
1660 if (tem)
1661 return get_or_alloc_expr_for_constant (tem);
1664 /* If we'd have to convert things we would need to validate
1665 if we can insert the translated expression. So fail
1666 here for now - we cannot insert an alias with a different
1667 type in the VN tables either, as that would assert. */
1668 if (result
1669 && !useless_type_conversion_p (ref->type, TREE_TYPE (result)))
1670 return NULL;
1671 else if (!result && newref
1672 && !useless_type_conversion_p (ref->type, newref->type))
1674 newoperands.release ();
1675 return NULL;
1678 expr = (pre_expr) pool_alloc (pre_expr_pool);
1679 expr->kind = REFERENCE;
1680 expr->id = 0;
1682 if (newref)
1684 PRE_EXPR_REFERENCE (expr) = newref;
1685 constant = fully_constant_expression (expr);
1686 if (constant != expr)
1687 return constant;
1689 new_val_id = newref->value_id;
1690 get_or_alloc_expression_id (expr);
1692 else
1694 if (changed || !same_valid)
1696 new_val_id = get_next_value_id ();
1697 value_expressions.safe_grow_cleared
1698 (get_max_value_id () + 1);
1700 else
1701 new_val_id = ref->value_id;
1702 newref = vn_reference_insert_pieces (newvuse, ref->set,
1703 ref->type,
1704 newoperands,
1705 result, new_val_id);
1706 newoperands.create (0);
1707 PRE_EXPR_REFERENCE (expr) = newref;
1708 constant = fully_constant_expression (expr);
1709 if (constant != expr)
1710 return constant;
1711 get_or_alloc_expression_id (expr);
1713 add_to_value (new_val_id, expr);
1715 newoperands.release ();
1716 return expr;
1718 break;
1720 case NAME:
1722 tree name = PRE_EXPR_NAME (expr);
1723 gimple def_stmt = SSA_NAME_DEF_STMT (name);
1724 /* If the SSA name is defined by a PHI node in this block,
1725 translate it. */
1726 if (gimple_code (def_stmt) == GIMPLE_PHI
1727 && gimple_bb (def_stmt) == phiblock)
1729 edge e = find_edge (pred, gimple_bb (def_stmt));
1730 tree def = PHI_ARG_DEF (def_stmt, e->dest_idx);
1732 /* Handle constant. */
1733 if (is_gimple_min_invariant (def))
1734 return get_or_alloc_expr_for_constant (def);
1736 return get_or_alloc_expr_for_name (def);
1738 /* Otherwise return it unchanged - it will get cleaned if its
1739 value is not available in PREDs AVAIL_OUT set of expressions. */
1740 return expr;
1743 default:
1744 gcc_unreachable ();
1748 /* Wrapper around phi_translate_1 providing caching functionality. */
1750 static pre_expr
1751 phi_translate (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1752 basic_block pred, basic_block phiblock)
1754 expr_pred_trans_t slot = NULL;
1755 pre_expr phitrans;
1757 if (!expr)
1758 return NULL;
1760 /* Constants contain no values that need translation. */
1761 if (expr->kind == CONSTANT)
1762 return expr;
1764 if (value_id_constant_p (get_expr_value_id (expr)))
1765 return expr;
1767 /* Don't add translations of NAMEs as those are cheap to translate. */
1768 if (expr->kind != NAME)
1770 if (phi_trans_add (&slot, expr, pred))
1771 return slot->v;
1772 /* Store NULL for the value we want to return in the case of
1773 recursing. */
1774 slot->v = NULL;
1777 /* Translate. */
1778 phitrans = phi_translate_1 (expr, set1, set2, pred, phiblock);
1780 if (slot)
1782 if (phitrans)
1783 slot->v = phitrans;
1784 else
1785 /* Remove failed translations again, they cause insert
1786 iteration to not pick up new opportunities reliably. */
1787 phi_translate_table->remove_elt_with_hash (slot, slot->hashcode);
1790 return phitrans;
1794 /* For each expression in SET, translate the values through phi nodes
1795 in PHIBLOCK using edge PHIBLOCK->PRED, and store the resulting
1796 expressions in DEST. */
1798 static void
1799 phi_translate_set (bitmap_set_t dest, bitmap_set_t set, basic_block pred,
1800 basic_block phiblock)
1802 vec<pre_expr> exprs;
1803 pre_expr expr;
1804 int i;
1806 if (gimple_seq_empty_p (phi_nodes (phiblock)))
1808 bitmap_set_copy (dest, set);
1809 return;
1812 exprs = sorted_array_from_bitmap_set (set);
1813 FOR_EACH_VEC_ELT (exprs, i, expr)
1815 pre_expr translated;
1816 translated = phi_translate (expr, set, NULL, pred, phiblock);
1817 if (!translated)
1818 continue;
1820 /* We might end up with multiple expressions from SET being
1821 translated to the same value. In this case we do not want
1822 to retain the NARY or REFERENCE expression but prefer a NAME
1823 which would be the leader. */
1824 if (translated->kind == NAME)
1825 bitmap_value_replace_in_set (dest, translated);
1826 else
1827 bitmap_value_insert_into_set (dest, translated);
1829 exprs.release ();
1832 /* Find the leader for a value (i.e., the name representing that
1833 value) in a given set, and return it. Return NULL if no leader
1834 is found. */
1836 static pre_expr
1837 bitmap_find_leader (bitmap_set_t set, unsigned int val)
1839 if (value_id_constant_p (val))
1841 unsigned int i;
1842 bitmap_iterator bi;
1843 bitmap exprset = value_expressions[val];
1845 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
1847 pre_expr expr = expression_for_id (i);
1848 if (expr->kind == CONSTANT)
1849 return expr;
1852 if (bitmap_set_contains_value (set, val))
1854 /* Rather than walk the entire bitmap of expressions, and see
1855 whether any of them has the value we are looking for, we look
1856 at the reverse mapping, which tells us the set of expressions
1857 that have a given value (IE value->expressions with that
1858 value) and see if any of those expressions are in our set.
1859 The number of expressions per value is usually significantly
1860 less than the number of expressions in the set. In fact, for
1861 large testcases, doing it this way is roughly 5-10x faster
1862 than walking the bitmap.
1863 If this is somehow a significant lose for some cases, we can
1864 choose which set to walk based on which set is smaller. */
1865 unsigned int i;
1866 bitmap_iterator bi;
1867 bitmap exprset = value_expressions[val];
1869 EXECUTE_IF_AND_IN_BITMAP (exprset, &set->expressions, 0, i, bi)
1870 return expression_for_id (i);
1872 return NULL;
1875 /* Determine if EXPR, a memory expression, is ANTIC_IN at the top of
1876 BLOCK by seeing if it is not killed in the block. Note that we are
1877 only determining whether there is a store that kills it. Because
1878 of the order in which clean iterates over values, we are guaranteed
1879 that altered operands will have caused us to be eliminated from the
1880 ANTIC_IN set already. */
1882 static bool
1883 value_dies_in_block_x (pre_expr expr, basic_block block)
1885 tree vuse = PRE_EXPR_REFERENCE (expr)->vuse;
1886 vn_reference_t refx = PRE_EXPR_REFERENCE (expr);
1887 gimple def;
1888 gimple_stmt_iterator gsi;
1889 unsigned id = get_expression_id (expr);
1890 bool res = false;
1891 ao_ref ref;
1893 if (!vuse)
1894 return false;
1896 /* Lookup a previously calculated result. */
1897 if (EXPR_DIES (block)
1898 && bitmap_bit_p (EXPR_DIES (block), id * 2))
1899 return bitmap_bit_p (EXPR_DIES (block), id * 2 + 1);
1901 /* A memory expression {e, VUSE} dies in the block if there is a
1902 statement that may clobber e. If, starting statement walk from the
1903 top of the basic block, a statement uses VUSE there can be no kill
1904 inbetween that use and the original statement that loaded {e, VUSE},
1905 so we can stop walking. */
1906 ref.base = NULL_TREE;
1907 for (gsi = gsi_start_bb (block); !gsi_end_p (gsi); gsi_next (&gsi))
1909 tree def_vuse, def_vdef;
1910 def = gsi_stmt (gsi);
1911 def_vuse = gimple_vuse (def);
1912 def_vdef = gimple_vdef (def);
1914 /* Not a memory statement. */
1915 if (!def_vuse)
1916 continue;
1918 /* Not a may-def. */
1919 if (!def_vdef)
1921 /* A load with the same VUSE, we're done. */
1922 if (def_vuse == vuse)
1923 break;
1925 continue;
1928 /* Init ref only if we really need it. */
1929 if (ref.base == NULL_TREE
1930 && !ao_ref_init_from_vn_reference (&ref, refx->set, refx->type,
1931 refx->operands))
1933 res = true;
1934 break;
1936 /* If the statement may clobber expr, it dies. */
1937 if (stmt_may_clobber_ref_p_1 (def, &ref))
1939 res = true;
1940 break;
1944 /* Remember the result. */
1945 if (!EXPR_DIES (block))
1946 EXPR_DIES (block) = BITMAP_ALLOC (&grand_bitmap_obstack);
1947 bitmap_set_bit (EXPR_DIES (block), id * 2);
1948 if (res)
1949 bitmap_set_bit (EXPR_DIES (block), id * 2 + 1);
1951 return res;
1955 /* Determine if OP is valid in SET1 U SET2, which it is when the union
1956 contains its value-id. */
1958 static bool
1959 op_valid_in_sets (bitmap_set_t set1, bitmap_set_t set2, tree op)
1961 if (op && TREE_CODE (op) == SSA_NAME)
1963 unsigned int value_id = VN_INFO (op)->value_id;
1964 if (!(bitmap_set_contains_value (set1, value_id)
1965 || (set2 && bitmap_set_contains_value (set2, value_id))))
1966 return false;
1968 return true;
1971 /* Determine if the expression EXPR is valid in SET1 U SET2.
1972 ONLY SET2 CAN BE NULL.
1973 This means that we have a leader for each part of the expression
1974 (if it consists of values), or the expression is an SSA_NAME.
1975 For loads/calls, we also see if the vuse is killed in this block. */
1977 static bool
1978 valid_in_sets (bitmap_set_t set1, bitmap_set_t set2, pre_expr expr,
1979 basic_block block)
1981 switch (expr->kind)
1983 case NAME:
1984 return bitmap_find_leader (AVAIL_OUT (block),
1985 get_expr_value_id (expr)) != NULL;
1986 case NARY:
1988 unsigned int i;
1989 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1990 for (i = 0; i < nary->length; i++)
1991 if (!op_valid_in_sets (set1, set2, nary->op[i]))
1992 return false;
1993 return true;
1995 break;
1996 case REFERENCE:
1998 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1999 vn_reference_op_t vro;
2000 unsigned int i;
2002 FOR_EACH_VEC_ELT (ref->operands, i, vro)
2004 if (!op_valid_in_sets (set1, set2, vro->op0)
2005 || !op_valid_in_sets (set1, set2, vro->op1)
2006 || !op_valid_in_sets (set1, set2, vro->op2))
2007 return false;
2009 return true;
2011 default:
2012 gcc_unreachable ();
2016 /* Clean the set of expressions that are no longer valid in SET1 or
2017 SET2. This means expressions that are made up of values we have no
2018 leaders for in SET1 or SET2. This version is used for partial
2019 anticipation, which means it is not valid in either ANTIC_IN or
2020 PA_IN. */
2022 static void
2023 dependent_clean (bitmap_set_t set1, bitmap_set_t set2, basic_block block)
2025 vec<pre_expr> exprs = sorted_array_from_bitmap_set (set1);
2026 pre_expr expr;
2027 int i;
2029 FOR_EACH_VEC_ELT (exprs, i, expr)
2031 if (!valid_in_sets (set1, set2, expr, block))
2032 bitmap_remove_from_set (set1, expr);
2034 exprs.release ();
2037 /* Clean the set of expressions that are no longer valid in SET. This
2038 means expressions that are made up of values we have no leaders for
2039 in SET. */
2041 static void
2042 clean (bitmap_set_t set, basic_block block)
2044 vec<pre_expr> exprs = sorted_array_from_bitmap_set (set);
2045 pre_expr expr;
2046 int i;
2048 FOR_EACH_VEC_ELT (exprs, i, expr)
2050 if (!valid_in_sets (set, NULL, expr, block))
2051 bitmap_remove_from_set (set, expr);
2053 exprs.release ();
2056 /* Clean the set of expressions that are no longer valid in SET because
2057 they are clobbered in BLOCK or because they trap and may not be executed. */
2059 static void
2060 prune_clobbered_mems (bitmap_set_t set, basic_block block)
2062 bitmap_iterator bi;
2063 unsigned i;
2065 FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
2067 pre_expr expr = expression_for_id (i);
2068 if (expr->kind == REFERENCE)
2070 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
2071 if (ref->vuse)
2073 gimple def_stmt = SSA_NAME_DEF_STMT (ref->vuse);
2074 if (!gimple_nop_p (def_stmt)
2075 && ((gimple_bb (def_stmt) != block
2076 && !dominated_by_p (CDI_DOMINATORS,
2077 block, gimple_bb (def_stmt)))
2078 || (gimple_bb (def_stmt) == block
2079 && value_dies_in_block_x (expr, block))))
2080 bitmap_remove_from_set (set, expr);
2083 else if (expr->kind == NARY)
2085 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
2086 /* If the NARY may trap make sure the block does not contain
2087 a possible exit point.
2088 ??? This is overly conservative if we translate AVAIL_OUT
2089 as the available expression might be after the exit point. */
2090 if (BB_MAY_NOTRETURN (block)
2091 && vn_nary_may_trap (nary))
2092 bitmap_remove_from_set (set, expr);
2097 static sbitmap has_abnormal_preds;
2099 /* List of blocks that may have changed during ANTIC computation and
2100 thus need to be iterated over. */
2102 static sbitmap changed_blocks;
2104 /* Decide whether to defer a block for a later iteration, or PHI
2105 translate SOURCE to DEST using phis in PHIBLOCK. Return false if we
2106 should defer the block, and true if we processed it. */
2108 static bool
2109 defer_or_phi_translate_block (bitmap_set_t dest, bitmap_set_t source,
2110 basic_block block, basic_block phiblock)
2112 if (!BB_VISITED (phiblock))
2114 bitmap_set_bit (changed_blocks, block->index);
2115 BB_VISITED (block) = 0;
2116 BB_DEFERRED (block) = 1;
2117 return false;
2119 else
2120 phi_translate_set (dest, source, block, phiblock);
2121 return true;
2124 /* Compute the ANTIC set for BLOCK.
2126 If succs(BLOCK) > 1 then
2127 ANTIC_OUT[BLOCK] = intersection of ANTIC_IN[b] for all succ(BLOCK)
2128 else if succs(BLOCK) == 1 then
2129 ANTIC_OUT[BLOCK] = phi_translate (ANTIC_IN[succ(BLOCK)])
2131 ANTIC_IN[BLOCK] = clean(ANTIC_OUT[BLOCK] U EXP_GEN[BLOCK] - TMP_GEN[BLOCK])
2134 static bool
2135 compute_antic_aux (basic_block block, bool block_has_abnormal_pred_edge)
2137 bool changed = false;
2138 bitmap_set_t S, old, ANTIC_OUT;
2139 bitmap_iterator bi;
2140 unsigned int bii;
2141 edge e;
2142 edge_iterator ei;
2144 old = ANTIC_OUT = S = NULL;
2145 BB_VISITED (block) = 1;
2147 /* If any edges from predecessors are abnormal, antic_in is empty,
2148 so do nothing. */
2149 if (block_has_abnormal_pred_edge)
2150 goto maybe_dump_sets;
2152 old = ANTIC_IN (block);
2153 ANTIC_OUT = bitmap_set_new ();
2155 /* If the block has no successors, ANTIC_OUT is empty. */
2156 if (EDGE_COUNT (block->succs) == 0)
2158 /* If we have one successor, we could have some phi nodes to
2159 translate through. */
2160 else if (single_succ_p (block))
2162 basic_block succ_bb = single_succ (block);
2164 /* We trade iterations of the dataflow equations for having to
2165 phi translate the maximal set, which is incredibly slow
2166 (since the maximal set often has 300+ members, even when you
2167 have a small number of blocks).
2168 Basically, we defer the computation of ANTIC for this block
2169 until we have processed it's successor, which will inevitably
2170 have a *much* smaller set of values to phi translate once
2171 clean has been run on it.
2172 The cost of doing this is that we technically perform more
2173 iterations, however, they are lower cost iterations.
2175 Timings for PRE on tramp3d-v4:
2176 without maximal set fix: 11 seconds
2177 with maximal set fix/without deferring: 26 seconds
2178 with maximal set fix/with deferring: 11 seconds
2181 if (!defer_or_phi_translate_block (ANTIC_OUT, ANTIC_IN (succ_bb),
2182 block, succ_bb))
2184 changed = true;
2185 goto maybe_dump_sets;
2188 /* If we have multiple successors, we take the intersection of all of
2189 them. Note that in the case of loop exit phi nodes, we may have
2190 phis to translate through. */
2191 else
2193 size_t i;
2194 basic_block bprime, first = NULL;
2196 auto_vec<basic_block> worklist (EDGE_COUNT (block->succs));
2197 FOR_EACH_EDGE (e, ei, block->succs)
2199 if (!first
2200 && BB_VISITED (e->dest))
2201 first = e->dest;
2202 else if (BB_VISITED (e->dest))
2203 worklist.quick_push (e->dest);
2206 /* Of multiple successors we have to have visited one already. */
2207 if (!first)
2209 bitmap_set_bit (changed_blocks, block->index);
2210 BB_VISITED (block) = 0;
2211 BB_DEFERRED (block) = 1;
2212 changed = true;
2213 goto maybe_dump_sets;
2216 if (!gimple_seq_empty_p (phi_nodes (first)))
2217 phi_translate_set (ANTIC_OUT, ANTIC_IN (first), block, first);
2218 else
2219 bitmap_set_copy (ANTIC_OUT, ANTIC_IN (first));
2221 FOR_EACH_VEC_ELT (worklist, i, bprime)
2223 if (!gimple_seq_empty_p (phi_nodes (bprime)))
2225 bitmap_set_t tmp = bitmap_set_new ();
2226 phi_translate_set (tmp, ANTIC_IN (bprime), block, bprime);
2227 bitmap_set_and (ANTIC_OUT, tmp);
2228 bitmap_set_free (tmp);
2230 else
2231 bitmap_set_and (ANTIC_OUT, ANTIC_IN (bprime));
2235 /* Prune expressions that are clobbered in block and thus become
2236 invalid if translated from ANTIC_OUT to ANTIC_IN. */
2237 prune_clobbered_mems (ANTIC_OUT, block);
2239 /* Generate ANTIC_OUT - TMP_GEN. */
2240 S = bitmap_set_subtract (ANTIC_OUT, TMP_GEN (block));
2242 /* Start ANTIC_IN with EXP_GEN - TMP_GEN. */
2243 ANTIC_IN (block) = bitmap_set_subtract (EXP_GEN (block),
2244 TMP_GEN (block));
2246 /* Then union in the ANTIC_OUT - TMP_GEN values,
2247 to get ANTIC_OUT U EXP_GEN - TMP_GEN */
2248 FOR_EACH_EXPR_ID_IN_SET (S, bii, bi)
2249 bitmap_value_insert_into_set (ANTIC_IN (block),
2250 expression_for_id (bii));
2252 clean (ANTIC_IN (block), block);
2254 if (!bitmap_set_equal (old, ANTIC_IN (block)))
2256 changed = true;
2257 bitmap_set_bit (changed_blocks, block->index);
2258 FOR_EACH_EDGE (e, ei, block->preds)
2259 bitmap_set_bit (changed_blocks, e->src->index);
2261 else
2262 bitmap_clear_bit (changed_blocks, block->index);
2264 maybe_dump_sets:
2265 if (dump_file && (dump_flags & TDF_DETAILS))
2267 if (!BB_DEFERRED (block) || BB_VISITED (block))
2269 if (ANTIC_OUT)
2270 print_bitmap_set (dump_file, ANTIC_OUT, "ANTIC_OUT", block->index);
2272 print_bitmap_set (dump_file, ANTIC_IN (block), "ANTIC_IN",
2273 block->index);
2275 if (S)
2276 print_bitmap_set (dump_file, S, "S", block->index);
2278 else
2280 fprintf (dump_file,
2281 "Block %d was deferred for a future iteration.\n",
2282 block->index);
2285 if (old)
2286 bitmap_set_free (old);
2287 if (S)
2288 bitmap_set_free (S);
2289 if (ANTIC_OUT)
2290 bitmap_set_free (ANTIC_OUT);
2291 return changed;
2294 /* Compute PARTIAL_ANTIC for BLOCK.
2296 If succs(BLOCK) > 1 then
2297 PA_OUT[BLOCK] = value wise union of PA_IN[b] + all ANTIC_IN not
2298 in ANTIC_OUT for all succ(BLOCK)
2299 else if succs(BLOCK) == 1 then
2300 PA_OUT[BLOCK] = phi_translate (PA_IN[succ(BLOCK)])
2302 PA_IN[BLOCK] = dependent_clean(PA_OUT[BLOCK] - TMP_GEN[BLOCK]
2303 - ANTIC_IN[BLOCK])
2306 static bool
2307 compute_partial_antic_aux (basic_block block,
2308 bool block_has_abnormal_pred_edge)
2310 bool changed = false;
2311 bitmap_set_t old_PA_IN;
2312 bitmap_set_t PA_OUT;
2313 edge e;
2314 edge_iterator ei;
2315 unsigned long max_pa = PARAM_VALUE (PARAM_MAX_PARTIAL_ANTIC_LENGTH);
2317 old_PA_IN = PA_OUT = NULL;
2319 /* If any edges from predecessors are abnormal, antic_in is empty,
2320 so do nothing. */
2321 if (block_has_abnormal_pred_edge)
2322 goto maybe_dump_sets;
2324 /* If there are too many partially anticipatable values in the
2325 block, phi_translate_set can take an exponential time: stop
2326 before the translation starts. */
2327 if (max_pa
2328 && single_succ_p (block)
2329 && bitmap_count_bits (&PA_IN (single_succ (block))->values) > max_pa)
2330 goto maybe_dump_sets;
2332 old_PA_IN = PA_IN (block);
2333 PA_OUT = bitmap_set_new ();
2335 /* If the block has no successors, ANTIC_OUT is empty. */
2336 if (EDGE_COUNT (block->succs) == 0)
2338 /* If we have one successor, we could have some phi nodes to
2339 translate through. Note that we can't phi translate across DFS
2340 back edges in partial antic, because it uses a union operation on
2341 the successors. For recurrences like IV's, we will end up
2342 generating a new value in the set on each go around (i + 3 (VH.1)
2343 VH.1 + 1 (VH.2), VH.2 + 1 (VH.3), etc), forever. */
2344 else if (single_succ_p (block))
2346 basic_block succ = single_succ (block);
2347 if (!(single_succ_edge (block)->flags & EDGE_DFS_BACK))
2348 phi_translate_set (PA_OUT, PA_IN (succ), block, succ);
2350 /* If we have multiple successors, we take the union of all of
2351 them. */
2352 else
2354 size_t i;
2355 basic_block bprime;
2357 auto_vec<basic_block> worklist (EDGE_COUNT (block->succs));
2358 FOR_EACH_EDGE (e, ei, block->succs)
2360 if (e->flags & EDGE_DFS_BACK)
2361 continue;
2362 worklist.quick_push (e->dest);
2364 if (worklist.length () > 0)
2366 FOR_EACH_VEC_ELT (worklist, i, bprime)
2368 unsigned int i;
2369 bitmap_iterator bi;
2371 FOR_EACH_EXPR_ID_IN_SET (ANTIC_IN (bprime), i, bi)
2372 bitmap_value_insert_into_set (PA_OUT,
2373 expression_for_id (i));
2374 if (!gimple_seq_empty_p (phi_nodes (bprime)))
2376 bitmap_set_t pa_in = bitmap_set_new ();
2377 phi_translate_set (pa_in, PA_IN (bprime), block, bprime);
2378 FOR_EACH_EXPR_ID_IN_SET (pa_in, i, bi)
2379 bitmap_value_insert_into_set (PA_OUT,
2380 expression_for_id (i));
2381 bitmap_set_free (pa_in);
2383 else
2384 FOR_EACH_EXPR_ID_IN_SET (PA_IN (bprime), i, bi)
2385 bitmap_value_insert_into_set (PA_OUT,
2386 expression_for_id (i));
2391 /* Prune expressions that are clobbered in block and thus become
2392 invalid if translated from PA_OUT to PA_IN. */
2393 prune_clobbered_mems (PA_OUT, block);
2395 /* PA_IN starts with PA_OUT - TMP_GEN.
2396 Then we subtract things from ANTIC_IN. */
2397 PA_IN (block) = bitmap_set_subtract (PA_OUT, TMP_GEN (block));
2399 /* For partial antic, we want to put back in the phi results, since
2400 we will properly avoid making them partially antic over backedges. */
2401 bitmap_ior_into (&PA_IN (block)->values, &PHI_GEN (block)->values);
2402 bitmap_ior_into (&PA_IN (block)->expressions, &PHI_GEN (block)->expressions);
2404 /* PA_IN[block] = PA_IN[block] - ANTIC_IN[block] */
2405 bitmap_set_subtract_values (PA_IN (block), ANTIC_IN (block));
2407 dependent_clean (PA_IN (block), ANTIC_IN (block), block);
2409 if (!bitmap_set_equal (old_PA_IN, PA_IN (block)))
2411 changed = true;
2412 bitmap_set_bit (changed_blocks, block->index);
2413 FOR_EACH_EDGE (e, ei, block->preds)
2414 bitmap_set_bit (changed_blocks, e->src->index);
2416 else
2417 bitmap_clear_bit (changed_blocks, block->index);
2419 maybe_dump_sets:
2420 if (dump_file && (dump_flags & TDF_DETAILS))
2422 if (PA_OUT)
2423 print_bitmap_set (dump_file, PA_OUT, "PA_OUT", block->index);
2425 print_bitmap_set (dump_file, PA_IN (block), "PA_IN", block->index);
2427 if (old_PA_IN)
2428 bitmap_set_free (old_PA_IN);
2429 if (PA_OUT)
2430 bitmap_set_free (PA_OUT);
2431 return changed;
2434 /* Compute ANTIC and partial ANTIC sets. */
2436 static void
2437 compute_antic (void)
2439 bool changed = true;
2440 int num_iterations = 0;
2441 basic_block block;
2442 int i;
2444 /* If any predecessor edges are abnormal, we punt, so antic_in is empty.
2445 We pre-build the map of blocks with incoming abnormal edges here. */
2446 has_abnormal_preds = sbitmap_alloc (last_basic_block_for_fn (cfun));
2447 bitmap_clear (has_abnormal_preds);
2449 FOR_ALL_BB_FN (block, cfun)
2451 edge_iterator ei;
2452 edge e;
2454 FOR_EACH_EDGE (e, ei, block->preds)
2456 e->flags &= ~EDGE_DFS_BACK;
2457 if (e->flags & EDGE_ABNORMAL)
2459 bitmap_set_bit (has_abnormal_preds, block->index);
2460 break;
2464 BB_VISITED (block) = 0;
2465 BB_DEFERRED (block) = 0;
2467 /* While we are here, give empty ANTIC_IN sets to each block. */
2468 ANTIC_IN (block) = bitmap_set_new ();
2469 PA_IN (block) = bitmap_set_new ();
2472 /* At the exit block we anticipate nothing. */
2473 BB_VISITED (EXIT_BLOCK_PTR_FOR_FN (cfun)) = 1;
2475 changed_blocks = sbitmap_alloc (last_basic_block_for_fn (cfun) + 1);
2476 bitmap_ones (changed_blocks);
2477 while (changed)
2479 if (dump_file && (dump_flags & TDF_DETAILS))
2480 fprintf (dump_file, "Starting iteration %d\n", num_iterations);
2481 /* ??? We need to clear our PHI translation cache here as the
2482 ANTIC sets shrink and we restrict valid translations to
2483 those having operands with leaders in ANTIC. Same below
2484 for PA ANTIC computation. */
2485 num_iterations++;
2486 changed = false;
2487 for (i = postorder_num - 1; i >= 0; i--)
2489 if (bitmap_bit_p (changed_blocks, postorder[i]))
2491 basic_block block = BASIC_BLOCK_FOR_FN (cfun, postorder[i]);
2492 changed |= compute_antic_aux (block,
2493 bitmap_bit_p (has_abnormal_preds,
2494 block->index));
2497 /* Theoretically possible, but *highly* unlikely. */
2498 gcc_checking_assert (num_iterations < 500);
2501 statistics_histogram_event (cfun, "compute_antic iterations",
2502 num_iterations);
2504 if (do_partial_partial)
2506 bitmap_ones (changed_blocks);
2507 mark_dfs_back_edges ();
2508 num_iterations = 0;
2509 changed = true;
2510 while (changed)
2512 if (dump_file && (dump_flags & TDF_DETAILS))
2513 fprintf (dump_file, "Starting iteration %d\n", num_iterations);
2514 num_iterations++;
2515 changed = false;
2516 for (i = postorder_num - 1 ; i >= 0; i--)
2518 if (bitmap_bit_p (changed_blocks, postorder[i]))
2520 basic_block block = BASIC_BLOCK_FOR_FN (cfun, postorder[i]);
2521 changed
2522 |= compute_partial_antic_aux (block,
2523 bitmap_bit_p (has_abnormal_preds,
2524 block->index));
2527 /* Theoretically possible, but *highly* unlikely. */
2528 gcc_checking_assert (num_iterations < 500);
2530 statistics_histogram_event (cfun, "compute_partial_antic iterations",
2531 num_iterations);
2533 sbitmap_free (has_abnormal_preds);
2534 sbitmap_free (changed_blocks);
2538 /* Inserted expressions are placed onto this worklist, which is used
2539 for performing quick dead code elimination of insertions we made
2540 that didn't turn out to be necessary. */
2541 static bitmap inserted_exprs;
2543 /* The actual worker for create_component_ref_by_pieces. */
2545 static tree
2546 create_component_ref_by_pieces_1 (basic_block block, vn_reference_t ref,
2547 unsigned int *operand, gimple_seq *stmts)
2549 vn_reference_op_t currop = &ref->operands[*operand];
2550 tree genop;
2551 ++*operand;
2552 switch (currop->opcode)
2554 case CALL_EXPR:
2556 tree folded, sc = NULL_TREE;
2557 unsigned int nargs = 0;
2558 tree fn, *args;
2559 if (TREE_CODE (currop->op0) == FUNCTION_DECL)
2560 fn = currop->op0;
2561 else
2562 fn = find_or_generate_expression (block, currop->op0, stmts);
2563 if (!fn)
2564 return NULL_TREE;
2565 if (currop->op1)
2567 sc = find_or_generate_expression (block, currop->op1, stmts);
2568 if (!sc)
2569 return NULL_TREE;
2571 args = XNEWVEC (tree, ref->operands.length () - 1);
2572 while (*operand < ref->operands.length ())
2574 args[nargs] = create_component_ref_by_pieces_1 (block, ref,
2575 operand, stmts);
2576 if (!args[nargs])
2577 return NULL_TREE;
2578 nargs++;
2580 folded = build_call_array (currop->type,
2581 (TREE_CODE (fn) == FUNCTION_DECL
2582 ? build_fold_addr_expr (fn) : fn),
2583 nargs, args);
2584 free (args);
2585 if (sc)
2586 CALL_EXPR_STATIC_CHAIN (folded) = sc;
2587 return folded;
2590 case MEM_REF:
2592 tree baseop = create_component_ref_by_pieces_1 (block, ref, operand,
2593 stmts);
2594 if (!baseop)
2595 return NULL_TREE;
2596 tree offset = currop->op0;
2597 if (TREE_CODE (baseop) == ADDR_EXPR
2598 && handled_component_p (TREE_OPERAND (baseop, 0)))
2600 HOST_WIDE_INT off;
2601 tree base;
2602 base = get_addr_base_and_unit_offset (TREE_OPERAND (baseop, 0),
2603 &off);
2604 gcc_assert (base);
2605 offset = int_const_binop (PLUS_EXPR, offset,
2606 build_int_cst (TREE_TYPE (offset),
2607 off));
2608 baseop = build_fold_addr_expr (base);
2610 return fold_build2 (MEM_REF, currop->type, baseop, offset);
2613 case TARGET_MEM_REF:
2615 tree genop0 = NULL_TREE, genop1 = NULL_TREE;
2616 vn_reference_op_t nextop = &ref->operands[++*operand];
2617 tree baseop = create_component_ref_by_pieces_1 (block, ref, operand,
2618 stmts);
2619 if (!baseop)
2620 return NULL_TREE;
2621 if (currop->op0)
2623 genop0 = find_or_generate_expression (block, currop->op0, stmts);
2624 if (!genop0)
2625 return NULL_TREE;
2627 if (nextop->op0)
2629 genop1 = find_or_generate_expression (block, nextop->op0, stmts);
2630 if (!genop1)
2631 return NULL_TREE;
2633 return build5 (TARGET_MEM_REF, currop->type,
2634 baseop, currop->op2, genop0, currop->op1, genop1);
2637 case ADDR_EXPR:
2638 if (currop->op0)
2640 gcc_assert (is_gimple_min_invariant (currop->op0));
2641 return currop->op0;
2643 /* Fallthrough. */
2644 case REALPART_EXPR:
2645 case IMAGPART_EXPR:
2646 case VIEW_CONVERT_EXPR:
2648 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2649 stmts);
2650 if (!genop0)
2651 return NULL_TREE;
2652 return fold_build1 (currop->opcode, currop->type, genop0);
2655 case WITH_SIZE_EXPR:
2657 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2658 stmts);
2659 if (!genop0)
2660 return NULL_TREE;
2661 tree genop1 = find_or_generate_expression (block, currop->op0, stmts);
2662 if (!genop1)
2663 return NULL_TREE;
2664 return fold_build2 (currop->opcode, currop->type, genop0, genop1);
2667 case BIT_FIELD_REF:
2669 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2670 stmts);
2671 if (!genop0)
2672 return NULL_TREE;
2673 tree op1 = currop->op0;
2674 tree op2 = currop->op1;
2675 return fold_build3 (BIT_FIELD_REF, currop->type, genop0, op1, op2);
2678 /* For array ref vn_reference_op's, operand 1 of the array ref
2679 is op0 of the reference op and operand 3 of the array ref is
2680 op1. */
2681 case ARRAY_RANGE_REF:
2682 case ARRAY_REF:
2684 tree genop0;
2685 tree genop1 = currop->op0;
2686 tree genop2 = currop->op1;
2687 tree genop3 = currop->op2;
2688 genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2689 stmts);
2690 if (!genop0)
2691 return NULL_TREE;
2692 genop1 = find_or_generate_expression (block, genop1, stmts);
2693 if (!genop1)
2694 return NULL_TREE;
2695 if (genop2)
2697 tree domain_type = TYPE_DOMAIN (TREE_TYPE (genop0));
2698 /* Drop zero minimum index if redundant. */
2699 if (integer_zerop (genop2)
2700 && (!domain_type
2701 || integer_zerop (TYPE_MIN_VALUE (domain_type))))
2702 genop2 = NULL_TREE;
2703 else
2705 genop2 = find_or_generate_expression (block, genop2, stmts);
2706 if (!genop2)
2707 return NULL_TREE;
2710 if (genop3)
2712 tree elmt_type = TREE_TYPE (TREE_TYPE (genop0));
2713 /* We can't always put a size in units of the element alignment
2714 here as the element alignment may be not visible. See
2715 PR43783. Simply drop the element size for constant
2716 sizes. */
2717 if (tree_int_cst_equal (genop3, TYPE_SIZE_UNIT (elmt_type)))
2718 genop3 = NULL_TREE;
2719 else
2721 genop3 = size_binop (EXACT_DIV_EXPR, genop3,
2722 size_int (TYPE_ALIGN_UNIT (elmt_type)));
2723 genop3 = find_or_generate_expression (block, genop3, stmts);
2724 if (!genop3)
2725 return NULL_TREE;
2728 return build4 (currop->opcode, currop->type, genop0, genop1,
2729 genop2, genop3);
2731 case COMPONENT_REF:
2733 tree op0;
2734 tree op1;
2735 tree genop2 = currop->op1;
2736 op0 = create_component_ref_by_pieces_1 (block, ref, operand, stmts);
2737 if (!op0)
2738 return NULL_TREE;
2739 /* op1 should be a FIELD_DECL, which are represented by themselves. */
2740 op1 = currop->op0;
2741 if (genop2)
2743 genop2 = find_or_generate_expression (block, genop2, stmts);
2744 if (!genop2)
2745 return NULL_TREE;
2747 return fold_build3 (COMPONENT_REF, TREE_TYPE (op1), op0, op1, genop2);
2750 case SSA_NAME:
2752 genop = find_or_generate_expression (block, currop->op0, stmts);
2753 return genop;
2755 case STRING_CST:
2756 case INTEGER_CST:
2757 case COMPLEX_CST:
2758 case VECTOR_CST:
2759 case REAL_CST:
2760 case CONSTRUCTOR:
2761 case VAR_DECL:
2762 case PARM_DECL:
2763 case CONST_DECL:
2764 case RESULT_DECL:
2765 case FUNCTION_DECL:
2766 return currop->op0;
2768 default:
2769 gcc_unreachable ();
2773 /* For COMPONENT_REF's and ARRAY_REF's, we can't have any intermediates for the
2774 COMPONENT_REF or MEM_REF or ARRAY_REF portion, because we'd end up with
2775 trying to rename aggregates into ssa form directly, which is a no no.
2777 Thus, this routine doesn't create temporaries, it just builds a
2778 single access expression for the array, calling
2779 find_or_generate_expression to build the innermost pieces.
2781 This function is a subroutine of create_expression_by_pieces, and
2782 should not be called on it's own unless you really know what you
2783 are doing. */
2785 static tree
2786 create_component_ref_by_pieces (basic_block block, vn_reference_t ref,
2787 gimple_seq *stmts)
2789 unsigned int op = 0;
2790 return create_component_ref_by_pieces_1 (block, ref, &op, stmts);
2793 /* Find a simple leader for an expression, or generate one using
2794 create_expression_by_pieces from a NARY expression for the value.
2795 BLOCK is the basic_block we are looking for leaders in.
2796 OP is the tree expression to find a leader for or generate.
2797 Returns the leader or NULL_TREE on failure. */
2799 static tree
2800 find_or_generate_expression (basic_block block, tree op, gimple_seq *stmts)
2802 pre_expr expr = get_or_alloc_expr_for (op);
2803 unsigned int lookfor = get_expr_value_id (expr);
2804 pre_expr leader = bitmap_find_leader (AVAIL_OUT (block), lookfor);
2805 if (leader)
2807 if (leader->kind == NAME)
2808 return PRE_EXPR_NAME (leader);
2809 else if (leader->kind == CONSTANT)
2810 return PRE_EXPR_CONSTANT (leader);
2812 /* Defer. */
2813 return NULL_TREE;
2816 /* It must be a complex expression, so generate it recursively. Note
2817 that this is only necessary to handle gcc.dg/tree-ssa/ssa-pre28.c
2818 where the insert algorithm fails to insert a required expression. */
2819 bitmap exprset = value_expressions[lookfor];
2820 bitmap_iterator bi;
2821 unsigned int i;
2822 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
2824 pre_expr temp = expression_for_id (i);
2825 /* We cannot insert random REFERENCE expressions at arbitrary
2826 places. We can insert NARYs which eventually re-materializes
2827 its operand values. */
2828 if (temp->kind == NARY)
2829 return create_expression_by_pieces (block, temp, stmts,
2830 get_expr_type (expr));
2833 /* Defer. */
2834 return NULL_TREE;
2837 #define NECESSARY GF_PLF_1
2839 /* Create an expression in pieces, so that we can handle very complex
2840 expressions that may be ANTIC, but not necessary GIMPLE.
2841 BLOCK is the basic block the expression will be inserted into,
2842 EXPR is the expression to insert (in value form)
2843 STMTS is a statement list to append the necessary insertions into.
2845 This function will die if we hit some value that shouldn't be
2846 ANTIC but is (IE there is no leader for it, or its components).
2847 The function returns NULL_TREE in case a different antic expression
2848 has to be inserted first.
2849 This function may also generate expressions that are themselves
2850 partially or fully redundant. Those that are will be either made
2851 fully redundant during the next iteration of insert (for partially
2852 redundant ones), or eliminated by eliminate (for fully redundant
2853 ones). */
2855 static tree
2856 create_expression_by_pieces (basic_block block, pre_expr expr,
2857 gimple_seq *stmts, tree type)
2859 tree name;
2860 tree folded;
2861 gimple_seq forced_stmts = NULL;
2862 unsigned int value_id;
2863 gimple_stmt_iterator gsi;
2864 tree exprtype = type ? type : get_expr_type (expr);
2865 pre_expr nameexpr;
2866 gimple newstmt;
2868 switch (expr->kind)
2870 /* We may hit the NAME/CONSTANT case if we have to convert types
2871 that value numbering saw through. */
2872 case NAME:
2873 folded = PRE_EXPR_NAME (expr);
2874 break;
2875 case CONSTANT:
2876 folded = PRE_EXPR_CONSTANT (expr);
2877 break;
2878 case REFERENCE:
2880 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
2881 folded = create_component_ref_by_pieces (block, ref, stmts);
2882 if (!folded)
2883 return NULL_TREE;
2885 break;
2886 case NARY:
2888 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
2889 tree *genop = XALLOCAVEC (tree, nary->length);
2890 unsigned i;
2891 for (i = 0; i < nary->length; ++i)
2893 genop[i] = find_or_generate_expression (block, nary->op[i], stmts);
2894 if (!genop[i])
2895 return NULL_TREE;
2896 /* Ensure genop[] is properly typed for POINTER_PLUS_EXPR. It
2897 may have conversions stripped. */
2898 if (nary->opcode == POINTER_PLUS_EXPR)
2900 if (i == 0)
2901 genop[i] = fold_convert (nary->type, genop[i]);
2902 else if (i == 1)
2903 genop[i] = convert_to_ptrofftype (genop[i]);
2905 else
2906 genop[i] = fold_convert (TREE_TYPE (nary->op[i]), genop[i]);
2908 if (nary->opcode == CONSTRUCTOR)
2910 vec<constructor_elt, va_gc> *elts = NULL;
2911 for (i = 0; i < nary->length; ++i)
2912 CONSTRUCTOR_APPEND_ELT (elts, NULL_TREE, genop[i]);
2913 folded = build_constructor (nary->type, elts);
2915 else
2917 switch (nary->length)
2919 case 1:
2920 folded = fold_build1 (nary->opcode, nary->type,
2921 genop[0]);
2922 break;
2923 case 2:
2924 folded = fold_build2 (nary->opcode, nary->type,
2925 genop[0], genop[1]);
2926 break;
2927 case 3:
2928 folded = fold_build3 (nary->opcode, nary->type,
2929 genop[0], genop[1], genop[2]);
2930 break;
2931 default:
2932 gcc_unreachable ();
2936 break;
2937 default:
2938 gcc_unreachable ();
2941 if (!useless_type_conversion_p (exprtype, TREE_TYPE (folded)))
2942 folded = fold_convert (exprtype, folded);
2944 /* Force the generated expression to be a sequence of GIMPLE
2945 statements.
2946 We have to call unshare_expr because force_gimple_operand may
2947 modify the tree we pass to it. */
2948 folded = force_gimple_operand (unshare_expr (folded), &forced_stmts,
2949 false, NULL);
2951 /* If we have any intermediate expressions to the value sets, add them
2952 to the value sets and chain them in the instruction stream. */
2953 if (forced_stmts)
2955 gsi = gsi_start (forced_stmts);
2956 for (; !gsi_end_p (gsi); gsi_next (&gsi))
2958 gimple stmt = gsi_stmt (gsi);
2959 tree forcedname = gimple_get_lhs (stmt);
2960 pre_expr nameexpr;
2962 if (TREE_CODE (forcedname) == SSA_NAME)
2964 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (forcedname));
2965 VN_INFO_GET (forcedname)->valnum = forcedname;
2966 VN_INFO (forcedname)->value_id = get_next_value_id ();
2967 nameexpr = get_or_alloc_expr_for_name (forcedname);
2968 add_to_value (VN_INFO (forcedname)->value_id, nameexpr);
2969 bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
2970 bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
2973 gimple_seq_add_seq (stmts, forced_stmts);
2976 name = make_temp_ssa_name (exprtype, NULL, "pretmp");
2977 newstmt = gimple_build_assign (name, folded);
2978 gimple_set_plf (newstmt, NECESSARY, false);
2980 gimple_seq_add_stmt (stmts, newstmt);
2981 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (name));
2983 /* Fold the last statement. */
2984 gsi = gsi_last (*stmts);
2985 if (fold_stmt_inplace (&gsi))
2986 update_stmt (gsi_stmt (gsi));
2988 /* Add a value number to the temporary.
2989 The value may already exist in either NEW_SETS, or AVAIL_OUT, because
2990 we are creating the expression by pieces, and this particular piece of
2991 the expression may have been represented. There is no harm in replacing
2992 here. */
2993 value_id = get_expr_value_id (expr);
2994 VN_INFO_GET (name)->value_id = value_id;
2995 VN_INFO (name)->valnum = sccvn_valnum_from_value_id (value_id);
2996 if (VN_INFO (name)->valnum == NULL_TREE)
2997 VN_INFO (name)->valnum = name;
2998 gcc_assert (VN_INFO (name)->valnum != NULL_TREE);
2999 nameexpr = get_or_alloc_expr_for_name (name);
3000 add_to_value (value_id, nameexpr);
3001 if (NEW_SETS (block))
3002 bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
3003 bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
3005 pre_stats.insertions++;
3006 if (dump_file && (dump_flags & TDF_DETAILS))
3008 fprintf (dump_file, "Inserted ");
3009 print_gimple_stmt (dump_file, newstmt, 0, 0);
3010 fprintf (dump_file, " in predecessor %d (%04d)\n",
3011 block->index, value_id);
3014 return name;
3018 /* Insert the to-be-made-available values of expression EXPRNUM for each
3019 predecessor, stored in AVAIL, into the predecessors of BLOCK, and
3020 merge the result with a phi node, given the same value number as
3021 NODE. Return true if we have inserted new stuff. */
3023 static bool
3024 insert_into_preds_of_block (basic_block block, unsigned int exprnum,
3025 vec<pre_expr> avail)
3027 pre_expr expr = expression_for_id (exprnum);
3028 pre_expr newphi;
3029 unsigned int val = get_expr_value_id (expr);
3030 edge pred;
3031 bool insertions = false;
3032 bool nophi = false;
3033 basic_block bprime;
3034 pre_expr eprime;
3035 edge_iterator ei;
3036 tree type = get_expr_type (expr);
3037 tree temp;
3038 gimple phi;
3040 /* Make sure we aren't creating an induction variable. */
3041 if (bb_loop_depth (block) > 0 && EDGE_COUNT (block->preds) == 2)
3043 bool firstinsideloop = false;
3044 bool secondinsideloop = false;
3045 firstinsideloop = flow_bb_inside_loop_p (block->loop_father,
3046 EDGE_PRED (block, 0)->src);
3047 secondinsideloop = flow_bb_inside_loop_p (block->loop_father,
3048 EDGE_PRED (block, 1)->src);
3049 /* Induction variables only have one edge inside the loop. */
3050 if ((firstinsideloop ^ secondinsideloop)
3051 && expr->kind != REFERENCE)
3053 if (dump_file && (dump_flags & TDF_DETAILS))
3054 fprintf (dump_file, "Skipping insertion of phi for partial redundancy: Looks like an induction variable\n");
3055 nophi = true;
3059 /* Make the necessary insertions. */
3060 FOR_EACH_EDGE (pred, ei, block->preds)
3062 gimple_seq stmts = NULL;
3063 tree builtexpr;
3064 bprime = pred->src;
3065 eprime = avail[pred->dest_idx];
3067 if (eprime->kind != NAME && eprime->kind != CONSTANT)
3069 builtexpr = create_expression_by_pieces (bprime, eprime,
3070 &stmts, type);
3071 gcc_assert (!(pred->flags & EDGE_ABNORMAL));
3072 gsi_insert_seq_on_edge (pred, stmts);
3073 if (!builtexpr)
3075 /* We cannot insert a PHI node if we failed to insert
3076 on one edge. */
3077 nophi = true;
3078 continue;
3080 avail[pred->dest_idx] = get_or_alloc_expr_for_name (builtexpr);
3081 insertions = true;
3083 else if (eprime->kind == CONSTANT)
3085 /* Constants may not have the right type, fold_convert
3086 should give us back a constant with the right type. */
3087 tree constant = PRE_EXPR_CONSTANT (eprime);
3088 if (!useless_type_conversion_p (type, TREE_TYPE (constant)))
3090 tree builtexpr = fold_convert (type, constant);
3091 if (!is_gimple_min_invariant (builtexpr))
3093 tree forcedexpr = force_gimple_operand (builtexpr,
3094 &stmts, true,
3095 NULL);
3096 if (!is_gimple_min_invariant (forcedexpr))
3098 if (forcedexpr != builtexpr)
3100 VN_INFO_GET (forcedexpr)->valnum = PRE_EXPR_CONSTANT (eprime);
3101 VN_INFO (forcedexpr)->value_id = get_expr_value_id (eprime);
3103 if (stmts)
3105 gimple_stmt_iterator gsi;
3106 gsi = gsi_start (stmts);
3107 for (; !gsi_end_p (gsi); gsi_next (&gsi))
3109 gimple stmt = gsi_stmt (gsi);
3110 tree lhs = gimple_get_lhs (stmt);
3111 if (TREE_CODE (lhs) == SSA_NAME)
3112 bitmap_set_bit (inserted_exprs,
3113 SSA_NAME_VERSION (lhs));
3114 gimple_set_plf (stmt, NECESSARY, false);
3116 gsi_insert_seq_on_edge (pred, stmts);
3118 avail[pred->dest_idx]
3119 = get_or_alloc_expr_for_name (forcedexpr);
3122 else
3123 avail[pred->dest_idx]
3124 = get_or_alloc_expr_for_constant (builtexpr);
3127 else if (eprime->kind == NAME)
3129 /* We may have to do a conversion because our value
3130 numbering can look through types in certain cases, but
3131 our IL requires all operands of a phi node have the same
3132 type. */
3133 tree name = PRE_EXPR_NAME (eprime);
3134 if (!useless_type_conversion_p (type, TREE_TYPE (name)))
3136 tree builtexpr;
3137 tree forcedexpr;
3138 builtexpr = fold_convert (type, name);
3139 forcedexpr = force_gimple_operand (builtexpr,
3140 &stmts, true,
3141 NULL);
3143 if (forcedexpr != name)
3145 VN_INFO_GET (forcedexpr)->valnum = VN_INFO (name)->valnum;
3146 VN_INFO (forcedexpr)->value_id = VN_INFO (name)->value_id;
3149 if (stmts)
3151 gimple_stmt_iterator gsi;
3152 gsi = gsi_start (stmts);
3153 for (; !gsi_end_p (gsi); gsi_next (&gsi))
3155 gimple stmt = gsi_stmt (gsi);
3156 tree lhs = gimple_get_lhs (stmt);
3157 if (TREE_CODE (lhs) == SSA_NAME)
3158 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (lhs));
3159 gimple_set_plf (stmt, NECESSARY, false);
3161 gsi_insert_seq_on_edge (pred, stmts);
3163 avail[pred->dest_idx] = get_or_alloc_expr_for_name (forcedexpr);
3167 /* If we didn't want a phi node, and we made insertions, we still have
3168 inserted new stuff, and thus return true. If we didn't want a phi node,
3169 and didn't make insertions, we haven't added anything new, so return
3170 false. */
3171 if (nophi && insertions)
3172 return true;
3173 else if (nophi && !insertions)
3174 return false;
3176 /* Now build a phi for the new variable. */
3177 temp = make_temp_ssa_name (type, NULL, "prephitmp");
3178 phi = create_phi_node (temp, block);
3180 gimple_set_plf (phi, NECESSARY, false);
3181 VN_INFO_GET (temp)->value_id = val;
3182 VN_INFO (temp)->valnum = sccvn_valnum_from_value_id (val);
3183 if (VN_INFO (temp)->valnum == NULL_TREE)
3184 VN_INFO (temp)->valnum = temp;
3185 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (temp));
3186 FOR_EACH_EDGE (pred, ei, block->preds)
3188 pre_expr ae = avail[pred->dest_idx];
3189 gcc_assert (get_expr_type (ae) == type
3190 || useless_type_conversion_p (type, get_expr_type (ae)));
3191 if (ae->kind == CONSTANT)
3192 add_phi_arg (phi, unshare_expr (PRE_EXPR_CONSTANT (ae)),
3193 pred, UNKNOWN_LOCATION);
3194 else
3195 add_phi_arg (phi, PRE_EXPR_NAME (ae), pred, UNKNOWN_LOCATION);
3198 newphi = get_or_alloc_expr_for_name (temp);
3199 add_to_value (val, newphi);
3201 /* The value should *not* exist in PHI_GEN, or else we wouldn't be doing
3202 this insertion, since we test for the existence of this value in PHI_GEN
3203 before proceeding with the partial redundancy checks in insert_aux.
3205 The value may exist in AVAIL_OUT, in particular, it could be represented
3206 by the expression we are trying to eliminate, in which case we want the
3207 replacement to occur. If it's not existing in AVAIL_OUT, we want it
3208 inserted there.
3210 Similarly, to the PHI_GEN case, the value should not exist in NEW_SETS of
3211 this block, because if it did, it would have existed in our dominator's
3212 AVAIL_OUT, and would have been skipped due to the full redundancy check.
3215 bitmap_insert_into_set (PHI_GEN (block), newphi);
3216 bitmap_value_replace_in_set (AVAIL_OUT (block),
3217 newphi);
3218 bitmap_insert_into_set (NEW_SETS (block),
3219 newphi);
3221 if (dump_file && (dump_flags & TDF_DETAILS))
3223 fprintf (dump_file, "Created phi ");
3224 print_gimple_stmt (dump_file, phi, 0, 0);
3225 fprintf (dump_file, " in block %d (%04d)\n", block->index, val);
3227 pre_stats.phis++;
3228 return true;
3233 /* Perform insertion of partially redundant values.
3234 For BLOCK, do the following:
3235 1. Propagate the NEW_SETS of the dominator into the current block.
3236 If the block has multiple predecessors,
3237 2a. Iterate over the ANTIC expressions for the block to see if
3238 any of them are partially redundant.
3239 2b. If so, insert them into the necessary predecessors to make
3240 the expression fully redundant.
3241 2c. Insert a new PHI merging the values of the predecessors.
3242 2d. Insert the new PHI, and the new expressions, into the
3243 NEW_SETS set.
3244 3. Recursively call ourselves on the dominator children of BLOCK.
3246 Steps 1, 2a, and 3 are done by insert_aux. 2b, 2c and 2d are done by
3247 do_regular_insertion and do_partial_insertion.
3251 static bool
3252 do_regular_insertion (basic_block block, basic_block dom)
3254 bool new_stuff = false;
3255 vec<pre_expr> exprs;
3256 pre_expr expr;
3257 vec<pre_expr> avail = vNULL;
3258 int i;
3260 exprs = sorted_array_from_bitmap_set (ANTIC_IN (block));
3261 avail.safe_grow (EDGE_COUNT (block->preds));
3263 FOR_EACH_VEC_ELT (exprs, i, expr)
3265 if (expr->kind == NARY
3266 || expr->kind == REFERENCE)
3268 unsigned int val;
3269 bool by_some = false;
3270 bool cant_insert = false;
3271 bool all_same = true;
3272 pre_expr first_s = NULL;
3273 edge pred;
3274 basic_block bprime;
3275 pre_expr eprime = NULL;
3276 edge_iterator ei;
3277 pre_expr edoubleprime = NULL;
3278 bool do_insertion = false;
3280 val = get_expr_value_id (expr);
3281 if (bitmap_set_contains_value (PHI_GEN (block), val))
3282 continue;
3283 if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3285 if (dump_file && (dump_flags & TDF_DETAILS))
3287 fprintf (dump_file, "Found fully redundant value: ");
3288 print_pre_expr (dump_file, expr);
3289 fprintf (dump_file, "\n");
3291 continue;
3294 FOR_EACH_EDGE (pred, ei, block->preds)
3296 unsigned int vprime;
3298 /* We should never run insertion for the exit block
3299 and so not come across fake pred edges. */
3300 gcc_assert (!(pred->flags & EDGE_FAKE));
3301 bprime = pred->src;
3302 eprime = phi_translate (expr, ANTIC_IN (block), NULL,
3303 bprime, block);
3305 /* eprime will generally only be NULL if the
3306 value of the expression, translated
3307 through the PHI for this predecessor, is
3308 undefined. If that is the case, we can't
3309 make the expression fully redundant,
3310 because its value is undefined along a
3311 predecessor path. We can thus break out
3312 early because it doesn't matter what the
3313 rest of the results are. */
3314 if (eprime == NULL)
3316 avail[pred->dest_idx] = NULL;
3317 cant_insert = true;
3318 break;
3321 eprime = fully_constant_expression (eprime);
3322 vprime = get_expr_value_id (eprime);
3323 edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime),
3324 vprime);
3325 if (edoubleprime == NULL)
3327 avail[pred->dest_idx] = eprime;
3328 all_same = false;
3330 else
3332 avail[pred->dest_idx] = edoubleprime;
3333 by_some = true;
3334 /* We want to perform insertions to remove a redundancy on
3335 a path in the CFG we want to optimize for speed. */
3336 if (optimize_edge_for_speed_p (pred))
3337 do_insertion = true;
3338 if (first_s == NULL)
3339 first_s = edoubleprime;
3340 else if (!pre_expr_d::equal (first_s, edoubleprime))
3341 all_same = false;
3344 /* If we can insert it, it's not the same value
3345 already existing along every predecessor, and
3346 it's defined by some predecessor, it is
3347 partially redundant. */
3348 if (!cant_insert && !all_same && by_some)
3350 if (!do_insertion)
3352 if (dump_file && (dump_flags & TDF_DETAILS))
3354 fprintf (dump_file, "Skipping partial redundancy for "
3355 "expression ");
3356 print_pre_expr (dump_file, expr);
3357 fprintf (dump_file, " (%04d), no redundancy on to be "
3358 "optimized for speed edge\n", val);
3361 else if (dbg_cnt (treepre_insert))
3363 if (dump_file && (dump_flags & TDF_DETAILS))
3365 fprintf (dump_file, "Found partial redundancy for "
3366 "expression ");
3367 print_pre_expr (dump_file, expr);
3368 fprintf (dump_file, " (%04d)\n",
3369 get_expr_value_id (expr));
3371 if (insert_into_preds_of_block (block,
3372 get_expression_id (expr),
3373 avail))
3374 new_stuff = true;
3377 /* If all edges produce the same value and that value is
3378 an invariant, then the PHI has the same value on all
3379 edges. Note this. */
3380 else if (!cant_insert && all_same)
3382 gcc_assert (edoubleprime->kind == CONSTANT
3383 || edoubleprime->kind == NAME);
3385 tree temp = make_temp_ssa_name (get_expr_type (expr),
3386 NULL, "pretmp");
3387 gimple assign = gimple_build_assign (temp,
3388 edoubleprime->kind == CONSTANT ? PRE_EXPR_CONSTANT (edoubleprime) : PRE_EXPR_NAME (edoubleprime));
3389 gimple_stmt_iterator gsi = gsi_after_labels (block);
3390 gsi_insert_before (&gsi, assign, GSI_NEW_STMT);
3392 gimple_set_plf (assign, NECESSARY, false);
3393 VN_INFO_GET (temp)->value_id = val;
3394 VN_INFO (temp)->valnum = sccvn_valnum_from_value_id (val);
3395 if (VN_INFO (temp)->valnum == NULL_TREE)
3396 VN_INFO (temp)->valnum = temp;
3397 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (temp));
3398 pre_expr newe = get_or_alloc_expr_for_name (temp);
3399 add_to_value (val, newe);
3400 bitmap_value_replace_in_set (AVAIL_OUT (block), newe);
3401 bitmap_insert_into_set (NEW_SETS (block), newe);
3406 exprs.release ();
3407 return new_stuff;
3411 /* Perform insertion for partially anticipatable expressions. There
3412 is only one case we will perform insertion for these. This case is
3413 if the expression is partially anticipatable, and fully available.
3414 In this case, we know that putting it earlier will enable us to
3415 remove the later computation. */
3418 static bool
3419 do_partial_partial_insertion (basic_block block, basic_block dom)
3421 bool new_stuff = false;
3422 vec<pre_expr> exprs;
3423 pre_expr expr;
3424 auto_vec<pre_expr> avail;
3425 int i;
3427 exprs = sorted_array_from_bitmap_set (PA_IN (block));
3428 avail.safe_grow (EDGE_COUNT (block->preds));
3430 FOR_EACH_VEC_ELT (exprs, i, expr)
3432 if (expr->kind == NARY
3433 || expr->kind == REFERENCE)
3435 unsigned int val;
3436 bool by_all = true;
3437 bool cant_insert = false;
3438 edge pred;
3439 basic_block bprime;
3440 pre_expr eprime = NULL;
3441 edge_iterator ei;
3443 val = get_expr_value_id (expr);
3444 if (bitmap_set_contains_value (PHI_GEN (block), val))
3445 continue;
3446 if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3447 continue;
3449 FOR_EACH_EDGE (pred, ei, block->preds)
3451 unsigned int vprime;
3452 pre_expr edoubleprime;
3454 /* We should never run insertion for the exit block
3455 and so not come across fake pred edges. */
3456 gcc_assert (!(pred->flags & EDGE_FAKE));
3457 bprime = pred->src;
3458 eprime = phi_translate (expr, ANTIC_IN (block),
3459 PA_IN (block),
3460 bprime, block);
3462 /* eprime will generally only be NULL if the
3463 value of the expression, translated
3464 through the PHI for this predecessor, is
3465 undefined. If that is the case, we can't
3466 make the expression fully redundant,
3467 because its value is undefined along a
3468 predecessor path. We can thus break out
3469 early because it doesn't matter what the
3470 rest of the results are. */
3471 if (eprime == NULL)
3473 avail[pred->dest_idx] = NULL;
3474 cant_insert = true;
3475 break;
3478 eprime = fully_constant_expression (eprime);
3479 vprime = get_expr_value_id (eprime);
3480 edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime), vprime);
3481 avail[pred->dest_idx] = edoubleprime;
3482 if (edoubleprime == NULL)
3484 by_all = false;
3485 break;
3489 /* If we can insert it, it's not the same value
3490 already existing along every predecessor, and
3491 it's defined by some predecessor, it is
3492 partially redundant. */
3493 if (!cant_insert && by_all)
3495 edge succ;
3496 bool do_insertion = false;
3498 /* Insert only if we can remove a later expression on a path
3499 that we want to optimize for speed.
3500 The phi node that we will be inserting in BLOCK is not free,
3501 and inserting it for the sake of !optimize_for_speed successor
3502 may cause regressions on the speed path. */
3503 FOR_EACH_EDGE (succ, ei, block->succs)
3505 if (bitmap_set_contains_value (PA_IN (succ->dest), val)
3506 || bitmap_set_contains_value (ANTIC_IN (succ->dest), val))
3508 if (optimize_edge_for_speed_p (succ))
3509 do_insertion = true;
3513 if (!do_insertion)
3515 if (dump_file && (dump_flags & TDF_DETAILS))
3517 fprintf (dump_file, "Skipping partial partial redundancy "
3518 "for expression ");
3519 print_pre_expr (dump_file, expr);
3520 fprintf (dump_file, " (%04d), not (partially) anticipated "
3521 "on any to be optimized for speed edges\n", val);
3524 else if (dbg_cnt (treepre_insert))
3526 pre_stats.pa_insert++;
3527 if (dump_file && (dump_flags & TDF_DETAILS))
3529 fprintf (dump_file, "Found partial partial redundancy "
3530 "for expression ");
3531 print_pre_expr (dump_file, expr);
3532 fprintf (dump_file, " (%04d)\n",
3533 get_expr_value_id (expr));
3535 if (insert_into_preds_of_block (block,
3536 get_expression_id (expr),
3537 avail))
3538 new_stuff = true;
3544 exprs.release ();
3545 return new_stuff;
3548 static bool
3549 insert_aux (basic_block block)
3551 basic_block son;
3552 bool new_stuff = false;
3554 if (block)
3556 basic_block dom;
3557 dom = get_immediate_dominator (CDI_DOMINATORS, block);
3558 if (dom)
3560 unsigned i;
3561 bitmap_iterator bi;
3562 bitmap_set_t newset = NEW_SETS (dom);
3563 if (newset)
3565 /* Note that we need to value_replace both NEW_SETS, and
3566 AVAIL_OUT. For both the case of NEW_SETS, the value may be
3567 represented by some non-simple expression here that we want
3568 to replace it with. */
3569 FOR_EACH_EXPR_ID_IN_SET (newset, i, bi)
3571 pre_expr expr = expression_for_id (i);
3572 bitmap_value_replace_in_set (NEW_SETS (block), expr);
3573 bitmap_value_replace_in_set (AVAIL_OUT (block), expr);
3576 if (!single_pred_p (block))
3578 new_stuff |= do_regular_insertion (block, dom);
3579 if (do_partial_partial)
3580 new_stuff |= do_partial_partial_insertion (block, dom);
3584 for (son = first_dom_son (CDI_DOMINATORS, block);
3585 son;
3586 son = next_dom_son (CDI_DOMINATORS, son))
3588 new_stuff |= insert_aux (son);
3591 return new_stuff;
3594 /* Perform insertion of partially redundant values. */
3596 static void
3597 insert (void)
3599 bool new_stuff = true;
3600 basic_block bb;
3601 int num_iterations = 0;
3603 FOR_ALL_BB_FN (bb, cfun)
3604 NEW_SETS (bb) = bitmap_set_new ();
3606 while (new_stuff)
3608 num_iterations++;
3609 if (dump_file && dump_flags & TDF_DETAILS)
3610 fprintf (dump_file, "Starting insert iteration %d\n", num_iterations);
3611 new_stuff = insert_aux (ENTRY_BLOCK_PTR_FOR_FN (cfun));
3613 /* Clear the NEW sets before the next iteration. We have already
3614 fully propagated its contents. */
3615 if (new_stuff)
3616 FOR_ALL_BB_FN (bb, cfun)
3617 bitmap_set_free (NEW_SETS (bb));
3619 statistics_histogram_event (cfun, "insert iterations", num_iterations);
3623 /* Compute the AVAIL set for all basic blocks.
3625 This function performs value numbering of the statements in each basic
3626 block. The AVAIL sets are built from information we glean while doing
3627 this value numbering, since the AVAIL sets contain only one entry per
3628 value.
3630 AVAIL_IN[BLOCK] = AVAIL_OUT[dom(BLOCK)].
3631 AVAIL_OUT[BLOCK] = AVAIL_IN[BLOCK] U PHI_GEN[BLOCK] U TMP_GEN[BLOCK]. */
3633 static void
3634 compute_avail (void)
3637 basic_block block, son;
3638 basic_block *worklist;
3639 size_t sp = 0;
3640 unsigned i;
3642 /* We pretend that default definitions are defined in the entry block.
3643 This includes function arguments and the static chain decl. */
3644 for (i = 1; i < num_ssa_names; ++i)
3646 tree name = ssa_name (i);
3647 pre_expr e;
3648 if (!name
3649 || !SSA_NAME_IS_DEFAULT_DEF (name)
3650 || has_zero_uses (name)
3651 || virtual_operand_p (name))
3652 continue;
3654 e = get_or_alloc_expr_for_name (name);
3655 add_to_value (get_expr_value_id (e), e);
3656 bitmap_insert_into_set (TMP_GEN (ENTRY_BLOCK_PTR_FOR_FN (cfun)), e);
3657 bitmap_value_insert_into_set (AVAIL_OUT (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
3661 if (dump_file && (dump_flags & TDF_DETAILS))
3663 print_bitmap_set (dump_file, TMP_GEN (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
3664 "tmp_gen", ENTRY_BLOCK);
3665 print_bitmap_set (dump_file, AVAIL_OUT (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
3666 "avail_out", ENTRY_BLOCK);
3669 /* Allocate the worklist. */
3670 worklist = XNEWVEC (basic_block, n_basic_blocks_for_fn (cfun));
3672 /* Seed the algorithm by putting the dominator children of the entry
3673 block on the worklist. */
3674 for (son = first_dom_son (CDI_DOMINATORS, ENTRY_BLOCK_PTR_FOR_FN (cfun));
3675 son;
3676 son = next_dom_son (CDI_DOMINATORS, son))
3677 worklist[sp++] = son;
3679 /* Loop until the worklist is empty. */
3680 while (sp)
3682 gimple_stmt_iterator gsi;
3683 gimple stmt;
3684 basic_block dom;
3686 /* Pick a block from the worklist. */
3687 block = worklist[--sp];
3689 /* Initially, the set of available values in BLOCK is that of
3690 its immediate dominator. */
3691 dom = get_immediate_dominator (CDI_DOMINATORS, block);
3692 if (dom)
3693 bitmap_set_copy (AVAIL_OUT (block), AVAIL_OUT (dom));
3695 /* Generate values for PHI nodes. */
3696 for (gsi = gsi_start_phis (block); !gsi_end_p (gsi); gsi_next (&gsi))
3698 tree result = gimple_phi_result (gsi_stmt (gsi));
3700 /* We have no need for virtual phis, as they don't represent
3701 actual computations. */
3702 if (virtual_operand_p (result))
3703 continue;
3705 pre_expr e = get_or_alloc_expr_for_name (result);
3706 add_to_value (get_expr_value_id (e), e);
3707 bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3708 bitmap_insert_into_set (PHI_GEN (block), e);
3711 BB_MAY_NOTRETURN (block) = 0;
3713 /* Now compute value numbers and populate value sets with all
3714 the expressions computed in BLOCK. */
3715 for (gsi = gsi_start_bb (block); !gsi_end_p (gsi); gsi_next (&gsi))
3717 ssa_op_iter iter;
3718 tree op;
3720 stmt = gsi_stmt (gsi);
3722 /* Cache whether the basic-block has any non-visible side-effect
3723 or control flow.
3724 If this isn't a call or it is the last stmt in the
3725 basic-block then the CFG represents things correctly. */
3726 if (is_gimple_call (stmt) && !stmt_ends_bb_p (stmt))
3728 /* Non-looping const functions always return normally.
3729 Otherwise the call might not return or have side-effects
3730 that forbids hoisting possibly trapping expressions
3731 before it. */
3732 int flags = gimple_call_flags (stmt);
3733 if (!(flags & ECF_CONST)
3734 || (flags & ECF_LOOPING_CONST_OR_PURE))
3735 BB_MAY_NOTRETURN (block) = 1;
3738 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_DEF)
3740 pre_expr e = get_or_alloc_expr_for_name (op);
3742 add_to_value (get_expr_value_id (e), e);
3743 bitmap_insert_into_set (TMP_GEN (block), e);
3744 bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3747 if (gimple_has_side_effects (stmt)
3748 || stmt_could_throw_p (stmt)
3749 || is_gimple_debug (stmt))
3750 continue;
3752 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
3754 if (ssa_undefined_value_p (op))
3755 continue;
3756 pre_expr e = get_or_alloc_expr_for_name (op);
3757 bitmap_value_insert_into_set (EXP_GEN (block), e);
3760 switch (gimple_code (stmt))
3762 case GIMPLE_RETURN:
3763 continue;
3765 case GIMPLE_CALL:
3767 vn_reference_t ref;
3768 pre_expr result = NULL;
3769 auto_vec<vn_reference_op_s> ops;
3771 /* We can value number only calls to real functions. */
3772 if (gimple_call_internal_p (stmt))
3773 continue;
3775 copy_reference_ops_from_call (stmt, &ops);
3776 vn_reference_lookup_pieces (gimple_vuse (stmt), 0,
3777 gimple_expr_type (stmt),
3778 ops, &ref, VN_NOWALK);
3779 if (!ref)
3780 continue;
3782 /* If the value of the call is not invalidated in
3783 this block until it is computed, add the expression
3784 to EXP_GEN. */
3785 if (!gimple_vuse (stmt)
3786 || gimple_code
3787 (SSA_NAME_DEF_STMT (gimple_vuse (stmt))) == GIMPLE_PHI
3788 || gimple_bb (SSA_NAME_DEF_STMT
3789 (gimple_vuse (stmt))) != block)
3791 result = (pre_expr) pool_alloc (pre_expr_pool);
3792 result->kind = REFERENCE;
3793 result->id = 0;
3794 PRE_EXPR_REFERENCE (result) = ref;
3796 get_or_alloc_expression_id (result);
3797 add_to_value (get_expr_value_id (result), result);
3798 bitmap_value_insert_into_set (EXP_GEN (block), result);
3800 continue;
3803 case GIMPLE_ASSIGN:
3805 pre_expr result = NULL;
3806 switch (vn_get_stmt_kind (stmt))
3808 case VN_NARY:
3810 enum tree_code code = gimple_assign_rhs_code (stmt);
3811 vn_nary_op_t nary;
3813 /* COND_EXPR and VEC_COND_EXPR are awkward in
3814 that they contain an embedded complex expression.
3815 Don't even try to shove those through PRE. */
3816 if (code == COND_EXPR
3817 || code == VEC_COND_EXPR)
3818 continue;
3820 vn_nary_op_lookup_stmt (stmt, &nary);
3821 if (!nary)
3822 continue;
3824 /* If the NARY traps and there was a preceding
3825 point in the block that might not return avoid
3826 adding the nary to EXP_GEN. */
3827 if (BB_MAY_NOTRETURN (block)
3828 && vn_nary_may_trap (nary))
3829 continue;
3831 result = (pre_expr) pool_alloc (pre_expr_pool);
3832 result->kind = NARY;
3833 result->id = 0;
3834 PRE_EXPR_NARY (result) = nary;
3835 break;
3838 case VN_REFERENCE:
3840 vn_reference_t ref;
3841 vn_reference_lookup (gimple_assign_rhs1 (stmt),
3842 gimple_vuse (stmt),
3843 VN_WALK, &ref);
3844 if (!ref)
3845 continue;
3847 /* If the value of the reference is not invalidated in
3848 this block until it is computed, add the expression
3849 to EXP_GEN. */
3850 if (gimple_vuse (stmt))
3852 gimple def_stmt;
3853 bool ok = true;
3854 def_stmt = SSA_NAME_DEF_STMT (gimple_vuse (stmt));
3855 while (!gimple_nop_p (def_stmt)
3856 && gimple_code (def_stmt) != GIMPLE_PHI
3857 && gimple_bb (def_stmt) == block)
3859 if (stmt_may_clobber_ref_p
3860 (def_stmt, gimple_assign_rhs1 (stmt)))
3862 ok = false;
3863 break;
3865 def_stmt
3866 = SSA_NAME_DEF_STMT (gimple_vuse (def_stmt));
3868 if (!ok)
3869 continue;
3872 result = (pre_expr) pool_alloc (pre_expr_pool);
3873 result->kind = REFERENCE;
3874 result->id = 0;
3875 PRE_EXPR_REFERENCE (result) = ref;
3876 break;
3879 default:
3880 continue;
3883 get_or_alloc_expression_id (result);
3884 add_to_value (get_expr_value_id (result), result);
3885 bitmap_value_insert_into_set (EXP_GEN (block), result);
3886 continue;
3888 default:
3889 break;
3893 if (dump_file && (dump_flags & TDF_DETAILS))
3895 print_bitmap_set (dump_file, EXP_GEN (block),
3896 "exp_gen", block->index);
3897 print_bitmap_set (dump_file, PHI_GEN (block),
3898 "phi_gen", block->index);
3899 print_bitmap_set (dump_file, TMP_GEN (block),
3900 "tmp_gen", block->index);
3901 print_bitmap_set (dump_file, AVAIL_OUT (block),
3902 "avail_out", block->index);
3905 /* Put the dominator children of BLOCK on the worklist of blocks
3906 to compute available sets for. */
3907 for (son = first_dom_son (CDI_DOMINATORS, block);
3908 son;
3909 son = next_dom_son (CDI_DOMINATORS, son))
3910 worklist[sp++] = son;
3913 free (worklist);
3917 /* Local state for the eliminate domwalk. */
3918 static vec<gimple> el_to_remove;
3919 static unsigned int el_todo;
3920 static vec<tree> el_avail;
3921 static vec<tree> el_avail_stack;
3923 /* Return a leader for OP that is available at the current point of the
3924 eliminate domwalk. */
3926 static tree
3927 eliminate_avail (tree op)
3929 tree valnum = VN_INFO (op)->valnum;
3930 if (TREE_CODE (valnum) == SSA_NAME)
3932 if (SSA_NAME_IS_DEFAULT_DEF (valnum))
3933 return valnum;
3934 if (el_avail.length () > SSA_NAME_VERSION (valnum))
3935 return el_avail[SSA_NAME_VERSION (valnum)];
3937 else if (is_gimple_min_invariant (valnum))
3938 return valnum;
3939 return NULL_TREE;
3942 /* At the current point of the eliminate domwalk make OP available. */
3944 static void
3945 eliminate_push_avail (tree op)
3947 tree valnum = VN_INFO (op)->valnum;
3948 if (TREE_CODE (valnum) == SSA_NAME)
3950 if (el_avail.length () <= SSA_NAME_VERSION (valnum))
3951 el_avail.safe_grow_cleared (SSA_NAME_VERSION (valnum) + 1);
3952 el_avail[SSA_NAME_VERSION (valnum)] = op;
3953 el_avail_stack.safe_push (op);
3957 /* Insert the expression recorded by SCCVN for VAL at *GSI. Returns
3958 the leader for the expression if insertion was successful. */
3960 static tree
3961 eliminate_insert (gimple_stmt_iterator *gsi, tree val)
3963 tree expr = vn_get_expr_for (val);
3964 if (!CONVERT_EXPR_P (expr)
3965 && TREE_CODE (expr) != VIEW_CONVERT_EXPR)
3966 return NULL_TREE;
3968 tree op = TREE_OPERAND (expr, 0);
3969 tree leader = TREE_CODE (op) == SSA_NAME ? eliminate_avail (op) : op;
3970 if (!leader)
3971 return NULL_TREE;
3973 tree res = make_temp_ssa_name (TREE_TYPE (val), NULL, "pretmp");
3974 gimple tem = gimple_build_assign (res,
3975 fold_build1 (TREE_CODE (expr),
3976 TREE_TYPE (expr), leader));
3977 gsi_insert_before (gsi, tem, GSI_SAME_STMT);
3978 VN_INFO_GET (res)->valnum = val;
3980 if (TREE_CODE (leader) == SSA_NAME)
3981 gimple_set_plf (SSA_NAME_DEF_STMT (leader), NECESSARY, true);
3983 pre_stats.insertions++;
3984 if (dump_file && (dump_flags & TDF_DETAILS))
3986 fprintf (dump_file, "Inserted ");
3987 print_gimple_stmt (dump_file, tem, 0, 0);
3990 return res;
3993 class eliminate_dom_walker : public dom_walker
3995 public:
3996 eliminate_dom_walker (cdi_direction direction, bool do_pre_)
3997 : dom_walker (direction), do_pre (do_pre_) {}
3999 virtual void before_dom_children (basic_block);
4000 virtual void after_dom_children (basic_block);
4002 bool do_pre;
4005 /* Perform elimination for the basic-block B during the domwalk. */
4007 void
4008 eliminate_dom_walker::before_dom_children (basic_block b)
4010 gimple_stmt_iterator gsi;
4011 gimple stmt;
4013 /* Mark new bb. */
4014 el_avail_stack.safe_push (NULL_TREE);
4016 /* ??? If we do nothing for unreachable blocks then this will confuse
4017 tailmerging. Eventually we can reduce its reliance on SCCVN now
4018 that we fully copy/constant-propagate (most) things. */
4020 for (gsi = gsi_start_phis (b); !gsi_end_p (gsi);)
4022 gimple phi = gsi_stmt (gsi);
4023 tree res = PHI_RESULT (phi);
4025 if (virtual_operand_p (res))
4027 gsi_next (&gsi);
4028 continue;
4031 tree sprime = eliminate_avail (res);
4032 if (sprime
4033 && sprime != res)
4035 if (dump_file && (dump_flags & TDF_DETAILS))
4037 fprintf (dump_file, "Replaced redundant PHI node defining ");
4038 print_generic_expr (dump_file, res, 0);
4039 fprintf (dump_file, " with ");
4040 print_generic_expr (dump_file, sprime, 0);
4041 fprintf (dump_file, "\n");
4044 /* If we inserted this PHI node ourself, it's not an elimination. */
4045 if (inserted_exprs
4046 && bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (res)))
4047 pre_stats.phis--;
4048 else
4049 pre_stats.eliminations++;
4051 /* If we will propagate into all uses don't bother to do
4052 anything. */
4053 if (may_propagate_copy (res, sprime))
4055 /* Mark the PHI for removal. */
4056 el_to_remove.safe_push (phi);
4057 gsi_next (&gsi);
4058 continue;
4061 remove_phi_node (&gsi, false);
4063 if (inserted_exprs
4064 && !bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (res))
4065 && TREE_CODE (sprime) == SSA_NAME)
4066 gimple_set_plf (SSA_NAME_DEF_STMT (sprime), NECESSARY, true);
4068 if (!useless_type_conversion_p (TREE_TYPE (res), TREE_TYPE (sprime)))
4069 sprime = fold_convert (TREE_TYPE (res), sprime);
4070 gimple stmt = gimple_build_assign (res, sprime);
4071 /* ??? It cannot yet be necessary (DOM walk). */
4072 gimple_set_plf (stmt, NECESSARY, gimple_plf (phi, NECESSARY));
4074 gimple_stmt_iterator gsi2 = gsi_after_labels (b);
4075 gsi_insert_before (&gsi2, stmt, GSI_NEW_STMT);
4076 continue;
4079 eliminate_push_avail (res);
4080 gsi_next (&gsi);
4083 for (gsi = gsi_start_bb (b); !gsi_end_p (gsi); gsi_next (&gsi))
4085 tree sprime = NULL_TREE;
4086 stmt = gsi_stmt (gsi);
4087 tree lhs = gimple_get_lhs (stmt);
4088 if (lhs && TREE_CODE (lhs) == SSA_NAME
4089 && !gimple_has_volatile_ops (stmt)
4090 /* See PR43491. Do not replace a global register variable when
4091 it is a the RHS of an assignment. Do replace local register
4092 variables since gcc does not guarantee a local variable will
4093 be allocated in register.
4094 ??? The fix isn't effective here. This should instead
4095 be ensured by not value-numbering them the same but treating
4096 them like volatiles? */
4097 && !(gimple_assign_single_p (stmt)
4098 && (TREE_CODE (gimple_assign_rhs1 (stmt)) == VAR_DECL
4099 && DECL_HARD_REGISTER (gimple_assign_rhs1 (stmt))
4100 && is_global_var (gimple_assign_rhs1 (stmt)))))
4102 sprime = eliminate_avail (lhs);
4103 if (!sprime)
4105 /* If there is no existing usable leader but SCCVN thinks
4106 it has an expression it wants to use as replacement,
4107 insert that. */
4108 tree val = VN_INFO (lhs)->valnum;
4109 if (val != VN_TOP
4110 && TREE_CODE (val) == SSA_NAME
4111 && VN_INFO (val)->needs_insertion
4112 && VN_INFO (val)->expr != NULL_TREE
4113 && (sprime = eliminate_insert (&gsi, val)) != NULL_TREE)
4114 eliminate_push_avail (sprime);
4117 /* If this now constitutes a copy duplicate points-to
4118 and range info appropriately. This is especially
4119 important for inserted code. See tree-ssa-copy.c
4120 for similar code. */
4121 if (sprime
4122 && TREE_CODE (sprime) == SSA_NAME)
4124 basic_block sprime_b = gimple_bb (SSA_NAME_DEF_STMT (sprime));
4125 if (POINTER_TYPE_P (TREE_TYPE (lhs))
4126 && SSA_NAME_PTR_INFO (lhs)
4127 && !SSA_NAME_PTR_INFO (sprime))
4129 duplicate_ssa_name_ptr_info (sprime,
4130 SSA_NAME_PTR_INFO (lhs));
4131 if (b != sprime_b)
4132 mark_ptr_info_alignment_unknown
4133 (SSA_NAME_PTR_INFO (sprime));
4135 else if (!POINTER_TYPE_P (TREE_TYPE (lhs))
4136 && SSA_NAME_RANGE_INFO (lhs)
4137 && !SSA_NAME_RANGE_INFO (sprime)
4138 && b == sprime_b)
4139 duplicate_ssa_name_range_info (sprime,
4140 SSA_NAME_RANGE_TYPE (lhs),
4141 SSA_NAME_RANGE_INFO (lhs));
4144 /* Inhibit the use of an inserted PHI on a loop header when
4145 the address of the memory reference is a simple induction
4146 variable. In other cases the vectorizer won't do anything
4147 anyway (either it's loop invariant or a complicated
4148 expression). */
4149 if (sprime
4150 && TREE_CODE (sprime) == SSA_NAME
4151 && do_pre
4152 && flag_tree_loop_vectorize
4153 && loop_outer (b->loop_father)
4154 && has_zero_uses (sprime)
4155 && bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (sprime))
4156 && gimple_assign_load_p (stmt))
4158 gimple def_stmt = SSA_NAME_DEF_STMT (sprime);
4159 basic_block def_bb = gimple_bb (def_stmt);
4160 if (gimple_code (def_stmt) == GIMPLE_PHI
4161 && b->loop_father->header == def_bb)
4163 ssa_op_iter iter;
4164 tree op;
4165 bool found = false;
4166 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
4168 affine_iv iv;
4169 def_bb = gimple_bb (SSA_NAME_DEF_STMT (op));
4170 if (def_bb
4171 && flow_bb_inside_loop_p (b->loop_father, def_bb)
4172 && simple_iv (b->loop_father,
4173 b->loop_father, op, &iv, true))
4175 found = true;
4176 break;
4179 if (found)
4181 if (dump_file && (dump_flags & TDF_DETAILS))
4183 fprintf (dump_file, "Not replacing ");
4184 print_gimple_expr (dump_file, stmt, 0, 0);
4185 fprintf (dump_file, " with ");
4186 print_generic_expr (dump_file, sprime, 0);
4187 fprintf (dump_file, " which would add a loop"
4188 " carried dependence to loop %d\n",
4189 b->loop_father->num);
4191 /* Don't keep sprime available. */
4192 sprime = NULL_TREE;
4197 if (sprime)
4199 /* If we can propagate the value computed for LHS into
4200 all uses don't bother doing anything with this stmt. */
4201 if (may_propagate_copy (lhs, sprime))
4203 /* Mark it for removal. */
4204 el_to_remove.safe_push (stmt);
4206 /* ??? Don't count copy/constant propagations. */
4207 if (gimple_assign_single_p (stmt)
4208 && (TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME
4209 || gimple_assign_rhs1 (stmt) == sprime))
4210 continue;
4212 if (dump_file && (dump_flags & TDF_DETAILS))
4214 fprintf (dump_file, "Replaced ");
4215 print_gimple_expr (dump_file, stmt, 0, 0);
4216 fprintf (dump_file, " with ");
4217 print_generic_expr (dump_file, sprime, 0);
4218 fprintf (dump_file, " in all uses of ");
4219 print_gimple_stmt (dump_file, stmt, 0, 0);
4222 pre_stats.eliminations++;
4223 continue;
4226 /* If this is an assignment from our leader (which
4227 happens in the case the value-number is a constant)
4228 then there is nothing to do. */
4229 if (gimple_assign_single_p (stmt)
4230 && sprime == gimple_assign_rhs1 (stmt))
4231 continue;
4233 /* Else replace its RHS. */
4234 bool can_make_abnormal_goto
4235 = is_gimple_call (stmt)
4236 && stmt_can_make_abnormal_goto (stmt);
4238 if (dump_file && (dump_flags & TDF_DETAILS))
4240 fprintf (dump_file, "Replaced ");
4241 print_gimple_expr (dump_file, stmt, 0, 0);
4242 fprintf (dump_file, " with ");
4243 print_generic_expr (dump_file, sprime, 0);
4244 fprintf (dump_file, " in ");
4245 print_gimple_stmt (dump_file, stmt, 0, 0);
4248 if (TREE_CODE (sprime) == SSA_NAME)
4249 gimple_set_plf (SSA_NAME_DEF_STMT (sprime),
4250 NECESSARY, true);
4252 pre_stats.eliminations++;
4253 gimple orig_stmt = stmt;
4254 if (!useless_type_conversion_p (TREE_TYPE (lhs),
4255 TREE_TYPE (sprime)))
4256 sprime = fold_convert (TREE_TYPE (lhs), sprime);
4257 tree vdef = gimple_vdef (stmt);
4258 tree vuse = gimple_vuse (stmt);
4259 propagate_tree_value_into_stmt (&gsi, sprime);
4260 stmt = gsi_stmt (gsi);
4261 update_stmt (stmt);
4262 if (vdef != gimple_vdef (stmt))
4263 VN_INFO (vdef)->valnum = vuse;
4265 /* If we removed EH side-effects from the statement, clean
4266 its EH information. */
4267 if (maybe_clean_or_replace_eh_stmt (orig_stmt, stmt))
4269 bitmap_set_bit (need_eh_cleanup,
4270 gimple_bb (stmt)->index);
4271 if (dump_file && (dump_flags & TDF_DETAILS))
4272 fprintf (dump_file, " Removed EH side-effects.\n");
4275 /* Likewise for AB side-effects. */
4276 if (can_make_abnormal_goto
4277 && !stmt_can_make_abnormal_goto (stmt))
4279 bitmap_set_bit (need_ab_cleanup,
4280 gimple_bb (stmt)->index);
4281 if (dump_file && (dump_flags & TDF_DETAILS))
4282 fprintf (dump_file, " Removed AB side-effects.\n");
4285 continue;
4289 /* If the statement is a scalar store, see if the expression
4290 has the same value number as its rhs. If so, the store is
4291 dead. */
4292 if (gimple_assign_single_p (stmt)
4293 && !gimple_has_volatile_ops (stmt)
4294 && !is_gimple_reg (gimple_assign_lhs (stmt))
4295 && (TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME
4296 || is_gimple_min_invariant (gimple_assign_rhs1 (stmt))))
4298 tree val;
4299 tree rhs = gimple_assign_rhs1 (stmt);
4300 val = vn_reference_lookup (gimple_assign_lhs (stmt),
4301 gimple_vuse (stmt), VN_WALK, NULL);
4302 if (TREE_CODE (rhs) == SSA_NAME)
4303 rhs = VN_INFO (rhs)->valnum;
4304 if (val
4305 && operand_equal_p (val, rhs, 0))
4307 if (dump_file && (dump_flags & TDF_DETAILS))
4309 fprintf (dump_file, "Deleted redundant store ");
4310 print_gimple_stmt (dump_file, stmt, 0, 0);
4313 /* Queue stmt for removal. */
4314 el_to_remove.safe_push (stmt);
4315 continue;
4319 bool can_make_abnormal_goto = stmt_can_make_abnormal_goto (stmt);
4320 bool was_noreturn = (is_gimple_call (stmt)
4321 && gimple_call_noreturn_p (stmt));
4322 tree vdef = gimple_vdef (stmt);
4323 tree vuse = gimple_vuse (stmt);
4325 /* If we didn't replace the whole stmt (or propagate the result
4326 into all uses), replace all uses on this stmt with their
4327 leaders. */
4328 use_operand_p use_p;
4329 ssa_op_iter iter;
4330 FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_USE)
4332 tree use = USE_FROM_PTR (use_p);
4333 /* ??? The call code above leaves stmt operands un-updated. */
4334 if (TREE_CODE (use) != SSA_NAME)
4335 continue;
4336 tree sprime = eliminate_avail (use);
4337 if (sprime && sprime != use
4338 && may_propagate_copy (use, sprime)
4339 /* We substitute into debug stmts to avoid excessive
4340 debug temporaries created by removed stmts, but we need
4341 to avoid doing so for inserted sprimes as we never want
4342 to create debug temporaries for them. */
4343 && (!inserted_exprs
4344 || TREE_CODE (sprime) != SSA_NAME
4345 || !is_gimple_debug (stmt)
4346 || !bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (sprime))))
4348 propagate_value (use_p, sprime);
4349 gimple_set_modified (stmt, true);
4350 if (TREE_CODE (sprime) == SSA_NAME
4351 && !is_gimple_debug (stmt))
4352 gimple_set_plf (SSA_NAME_DEF_STMT (sprime),
4353 NECESSARY, true);
4357 /* Visit indirect calls and turn them into direct calls if
4358 possible using the devirtualization machinery. */
4359 if (is_gimple_call (stmt))
4361 tree fn = gimple_call_fn (stmt);
4362 if (fn
4363 && TREE_CODE (fn) == OBJ_TYPE_REF
4364 && TREE_CODE (OBJ_TYPE_REF_EXPR (fn)) == SSA_NAME)
4366 fn = ipa_intraprocedural_devirtualization (stmt);
4367 if (fn && dbg_cnt (devirt))
4369 if (dump_enabled_p ())
4371 location_t loc = gimple_location_safe (stmt);
4372 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, loc,
4373 "converting indirect call to "
4374 "function %s\n",
4375 cgraph_node::get (fn)->name ());
4377 gimple_call_set_fndecl (stmt, fn);
4378 gimple_set_modified (stmt, true);
4383 if (gimple_modified_p (stmt))
4385 /* If a formerly non-invariant ADDR_EXPR is turned into an
4386 invariant one it was on a separate stmt. */
4387 if (gimple_assign_single_p (stmt)
4388 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ADDR_EXPR)
4389 recompute_tree_invariant_for_addr_expr (gimple_assign_rhs1 (stmt));
4390 gimple old_stmt = stmt;
4391 if (is_gimple_call (stmt))
4393 /* ??? Only fold calls inplace for now, this may create new
4394 SSA names which in turn will confuse free_scc_vn SSA name
4395 release code. */
4396 fold_stmt_inplace (&gsi);
4397 /* When changing a call into a noreturn call, cfg cleanup
4398 is needed to fix up the noreturn call. */
4399 if (!was_noreturn && gimple_call_noreturn_p (stmt))
4400 el_todo |= TODO_cleanup_cfg;
4402 else
4404 fold_stmt (&gsi);
4405 stmt = gsi_stmt (gsi);
4406 if ((gimple_code (stmt) == GIMPLE_COND
4407 && (gimple_cond_true_p (stmt)
4408 || gimple_cond_false_p (stmt)))
4409 || (gimple_code (stmt) == GIMPLE_SWITCH
4410 && TREE_CODE (gimple_switch_index (stmt)) == INTEGER_CST))
4411 el_todo |= TODO_cleanup_cfg;
4413 /* If we removed EH side-effects from the statement, clean
4414 its EH information. */
4415 if (maybe_clean_or_replace_eh_stmt (old_stmt, stmt))
4417 bitmap_set_bit (need_eh_cleanup,
4418 gimple_bb (stmt)->index);
4419 if (dump_file && (dump_flags & TDF_DETAILS))
4420 fprintf (dump_file, " Removed EH side-effects.\n");
4422 /* Likewise for AB side-effects. */
4423 if (can_make_abnormal_goto
4424 && !stmt_can_make_abnormal_goto (stmt))
4426 bitmap_set_bit (need_ab_cleanup,
4427 gimple_bb (stmt)->index);
4428 if (dump_file && (dump_flags & TDF_DETAILS))
4429 fprintf (dump_file, " Removed AB side-effects.\n");
4431 update_stmt (stmt);
4432 if (vdef != gimple_vdef (stmt))
4433 VN_INFO (vdef)->valnum = vuse;
4436 /* Make new values available - for fully redundant LHS we
4437 continue with the next stmt above and skip this. */
4438 def_operand_p defp;
4439 FOR_EACH_SSA_DEF_OPERAND (defp, stmt, iter, SSA_OP_DEF)
4440 eliminate_push_avail (DEF_FROM_PTR (defp));
4443 /* Replace destination PHI arguments. */
4444 edge_iterator ei;
4445 edge e;
4446 FOR_EACH_EDGE (e, ei, b->succs)
4448 for (gsi = gsi_start_phis (e->dest); !gsi_end_p (gsi); gsi_next (&gsi))
4450 gimple phi = gsi_stmt (gsi);
4451 use_operand_p use_p = PHI_ARG_DEF_PTR_FROM_EDGE (phi, e);
4452 tree arg = USE_FROM_PTR (use_p);
4453 if (TREE_CODE (arg) != SSA_NAME
4454 || virtual_operand_p (arg))
4455 continue;
4456 tree sprime = eliminate_avail (arg);
4457 if (sprime && may_propagate_copy (arg, sprime))
4459 propagate_value (use_p, sprime);
4460 if (TREE_CODE (sprime) == SSA_NAME)
4461 gimple_set_plf (SSA_NAME_DEF_STMT (sprime), NECESSARY, true);
4467 /* Make no longer available leaders no longer available. */
4469 void
4470 eliminate_dom_walker::after_dom_children (basic_block)
4472 tree entry;
4473 while ((entry = el_avail_stack.pop ()) != NULL_TREE)
4474 el_avail[SSA_NAME_VERSION (VN_INFO (entry)->valnum)] = NULL_TREE;
4477 /* Eliminate fully redundant computations. */
4479 static unsigned int
4480 eliminate (bool do_pre)
4482 gimple_stmt_iterator gsi;
4483 gimple stmt;
4485 need_eh_cleanup = BITMAP_ALLOC (NULL);
4486 need_ab_cleanup = BITMAP_ALLOC (NULL);
4488 el_to_remove.create (0);
4489 el_todo = 0;
4490 el_avail.create (0);
4491 el_avail_stack.create (0);
4493 eliminate_dom_walker (CDI_DOMINATORS,
4494 do_pre).walk (cfun->cfg->x_entry_block_ptr);
4496 el_avail.release ();
4497 el_avail_stack.release ();
4499 /* We cannot remove stmts during BB walk, especially not release SSA
4500 names there as this confuses the VN machinery. The stmts ending
4501 up in el_to_remove are either stores or simple copies.
4502 Remove stmts in reverse order to make debug stmt creation possible. */
4503 while (!el_to_remove.is_empty ())
4505 stmt = el_to_remove.pop ();
4507 if (dump_file && (dump_flags & TDF_DETAILS))
4509 fprintf (dump_file, "Removing dead stmt ");
4510 print_gimple_stmt (dump_file, stmt, 0, 0);
4513 tree lhs;
4514 if (gimple_code (stmt) == GIMPLE_PHI)
4515 lhs = gimple_phi_result (stmt);
4516 else
4517 lhs = gimple_get_lhs (stmt);
4519 if (inserted_exprs
4520 && TREE_CODE (lhs) == SSA_NAME)
4521 bitmap_clear_bit (inserted_exprs, SSA_NAME_VERSION (lhs));
4523 gsi = gsi_for_stmt (stmt);
4524 if (gimple_code (stmt) == GIMPLE_PHI)
4525 remove_phi_node (&gsi, true);
4526 else
4528 basic_block bb = gimple_bb (stmt);
4529 unlink_stmt_vdef (stmt);
4530 if (gsi_remove (&gsi, true))
4531 bitmap_set_bit (need_eh_cleanup, bb->index);
4532 release_defs (stmt);
4535 /* Removing a stmt may expose a forwarder block. */
4536 el_todo |= TODO_cleanup_cfg;
4538 el_to_remove.release ();
4540 return el_todo;
4543 /* Perform CFG cleanups made necessary by elimination. */
4545 static unsigned
4546 fini_eliminate (void)
4548 bool do_eh_cleanup = !bitmap_empty_p (need_eh_cleanup);
4549 bool do_ab_cleanup = !bitmap_empty_p (need_ab_cleanup);
4551 if (do_eh_cleanup)
4552 gimple_purge_all_dead_eh_edges (need_eh_cleanup);
4554 if (do_ab_cleanup)
4555 gimple_purge_all_dead_abnormal_call_edges (need_ab_cleanup);
4557 BITMAP_FREE (need_eh_cleanup);
4558 BITMAP_FREE (need_ab_cleanup);
4560 if (do_eh_cleanup || do_ab_cleanup)
4561 return TODO_cleanup_cfg;
4562 return 0;
4565 /* Borrow a bit of tree-ssa-dce.c for the moment.
4566 XXX: In 4.1, we should be able to just run a DCE pass after PRE, though
4567 this may be a bit faster, and we may want critical edges kept split. */
4569 /* If OP's defining statement has not already been determined to be necessary,
4570 mark that statement necessary. Return the stmt, if it is newly
4571 necessary. */
4573 static inline gimple
4574 mark_operand_necessary (tree op)
4576 gimple stmt;
4578 gcc_assert (op);
4580 if (TREE_CODE (op) != SSA_NAME)
4581 return NULL;
4583 stmt = SSA_NAME_DEF_STMT (op);
4584 gcc_assert (stmt);
4586 if (gimple_plf (stmt, NECESSARY)
4587 || gimple_nop_p (stmt))
4588 return NULL;
4590 gimple_set_plf (stmt, NECESSARY, true);
4591 return stmt;
4594 /* Because we don't follow exactly the standard PRE algorithm, and decide not
4595 to insert PHI nodes sometimes, and because value numbering of casts isn't
4596 perfect, we sometimes end up inserting dead code. This simple DCE-like
4597 pass removes any insertions we made that weren't actually used. */
4599 static void
4600 remove_dead_inserted_code (void)
4602 bitmap worklist;
4603 unsigned i;
4604 bitmap_iterator bi;
4605 gimple t;
4607 worklist = BITMAP_ALLOC (NULL);
4608 EXECUTE_IF_SET_IN_BITMAP (inserted_exprs, 0, i, bi)
4610 t = SSA_NAME_DEF_STMT (ssa_name (i));
4611 if (gimple_plf (t, NECESSARY))
4612 bitmap_set_bit (worklist, i);
4614 while (!bitmap_empty_p (worklist))
4616 i = bitmap_first_set_bit (worklist);
4617 bitmap_clear_bit (worklist, i);
4618 t = SSA_NAME_DEF_STMT (ssa_name (i));
4620 /* PHI nodes are somewhat special in that each PHI alternative has
4621 data and control dependencies. All the statements feeding the
4622 PHI node's arguments are always necessary. */
4623 if (gimple_code (t) == GIMPLE_PHI)
4625 unsigned k;
4627 for (k = 0; k < gimple_phi_num_args (t); k++)
4629 tree arg = PHI_ARG_DEF (t, k);
4630 if (TREE_CODE (arg) == SSA_NAME)
4632 gimple n = mark_operand_necessary (arg);
4633 if (n)
4634 bitmap_set_bit (worklist, SSA_NAME_VERSION (arg));
4638 else
4640 /* Propagate through the operands. Examine all the USE, VUSE and
4641 VDEF operands in this statement. Mark all the statements
4642 which feed this statement's uses as necessary. */
4643 ssa_op_iter iter;
4644 tree use;
4646 /* The operands of VDEF expressions are also needed as they
4647 represent potential definitions that may reach this
4648 statement (VDEF operands allow us to follow def-def
4649 links). */
4651 FOR_EACH_SSA_TREE_OPERAND (use, t, iter, SSA_OP_ALL_USES)
4653 gimple n = mark_operand_necessary (use);
4654 if (n)
4655 bitmap_set_bit (worklist, SSA_NAME_VERSION (use));
4660 EXECUTE_IF_SET_IN_BITMAP (inserted_exprs, 0, i, bi)
4662 t = SSA_NAME_DEF_STMT (ssa_name (i));
4663 if (!gimple_plf (t, NECESSARY))
4665 gimple_stmt_iterator gsi;
4667 if (dump_file && (dump_flags & TDF_DETAILS))
4669 fprintf (dump_file, "Removing unnecessary insertion:");
4670 print_gimple_stmt (dump_file, t, 0, 0);
4673 gsi = gsi_for_stmt (t);
4674 if (gimple_code (t) == GIMPLE_PHI)
4675 remove_phi_node (&gsi, true);
4676 else
4678 gsi_remove (&gsi, true);
4679 release_defs (t);
4683 BITMAP_FREE (worklist);
4687 /* Initialize data structures used by PRE. */
4689 static void
4690 init_pre (void)
4692 basic_block bb;
4694 next_expression_id = 1;
4695 expressions.create (0);
4696 expressions.safe_push (NULL);
4697 value_expressions.create (get_max_value_id () + 1);
4698 value_expressions.safe_grow_cleared (get_max_value_id () + 1);
4699 name_to_id.create (0);
4701 inserted_exprs = BITMAP_ALLOC (NULL);
4703 connect_infinite_loops_to_exit ();
4704 memset (&pre_stats, 0, sizeof (pre_stats));
4706 postorder = XNEWVEC (int, n_basic_blocks_for_fn (cfun));
4707 postorder_num = inverted_post_order_compute (postorder);
4709 alloc_aux_for_blocks (sizeof (struct bb_bitmap_sets));
4711 calculate_dominance_info (CDI_POST_DOMINATORS);
4712 calculate_dominance_info (CDI_DOMINATORS);
4714 bitmap_obstack_initialize (&grand_bitmap_obstack);
4715 phi_translate_table = new hash_table<expr_pred_trans_d> (5110);
4716 expression_to_id = new hash_table<pre_expr_d> (num_ssa_names * 3);
4717 bitmap_set_pool = create_alloc_pool ("Bitmap sets",
4718 sizeof (struct bitmap_set), 30);
4719 pre_expr_pool = create_alloc_pool ("pre_expr nodes",
4720 sizeof (struct pre_expr_d), 30);
4721 FOR_ALL_BB_FN (bb, cfun)
4723 EXP_GEN (bb) = bitmap_set_new ();
4724 PHI_GEN (bb) = bitmap_set_new ();
4725 TMP_GEN (bb) = bitmap_set_new ();
4726 AVAIL_OUT (bb) = bitmap_set_new ();
4731 /* Deallocate data structures used by PRE. */
4733 static void
4734 fini_pre ()
4736 free (postorder);
4737 value_expressions.release ();
4738 BITMAP_FREE (inserted_exprs);
4739 bitmap_obstack_release (&grand_bitmap_obstack);
4740 free_alloc_pool (bitmap_set_pool);
4741 free_alloc_pool (pre_expr_pool);
4742 delete phi_translate_table;
4743 phi_translate_table = NULL;
4744 delete expression_to_id;
4745 expression_to_id = NULL;
4746 name_to_id.release ();
4748 free_aux_for_blocks ();
4750 free_dominance_info (CDI_POST_DOMINATORS);
4753 namespace {
4755 const pass_data pass_data_pre =
4757 GIMPLE_PASS, /* type */
4758 "pre", /* name */
4759 OPTGROUP_NONE, /* optinfo_flags */
4760 TV_TREE_PRE, /* tv_id */
4761 /* PROP_no_crit_edges is ensured by placing pass_split_crit_edges before
4762 pass_pre. */
4763 ( PROP_no_crit_edges | PROP_cfg | PROP_ssa ), /* properties_required */
4764 0, /* properties_provided */
4765 PROP_no_crit_edges, /* properties_destroyed */
4766 TODO_rebuild_alias, /* todo_flags_start */
4767 0, /* todo_flags_finish */
4770 class pass_pre : public gimple_opt_pass
4772 public:
4773 pass_pre (gcc::context *ctxt)
4774 : gimple_opt_pass (pass_data_pre, ctxt)
4777 /* opt_pass methods: */
4778 virtual bool gate (function *) { return flag_tree_pre != 0; }
4779 virtual unsigned int execute (function *);
4781 }; // class pass_pre
4783 unsigned int
4784 pass_pre::execute (function *fun)
4786 unsigned int todo = 0;
4788 do_partial_partial =
4789 flag_tree_partial_pre && optimize_function_for_speed_p (fun);
4791 /* This has to happen before SCCVN runs because
4792 loop_optimizer_init may create new phis, etc. */
4793 loop_optimizer_init (LOOPS_NORMAL);
4795 if (!run_scc_vn (VN_WALK))
4797 loop_optimizer_finalize ();
4798 return 0;
4801 init_pre ();
4802 scev_initialize ();
4804 /* Collect and value number expressions computed in each basic block. */
4805 compute_avail ();
4807 /* Insert can get quite slow on an incredibly large number of basic
4808 blocks due to some quadratic behavior. Until this behavior is
4809 fixed, don't run it when he have an incredibly large number of
4810 bb's. If we aren't going to run insert, there is no point in
4811 computing ANTIC, either, even though it's plenty fast. */
4812 if (n_basic_blocks_for_fn (fun) < 4000)
4814 compute_antic ();
4815 insert ();
4818 /* Make sure to remove fake edges before committing our inserts.
4819 This makes sure we don't end up with extra critical edges that
4820 we would need to split. */
4821 remove_fake_exit_edges ();
4822 gsi_commit_edge_inserts ();
4824 /* Remove all the redundant expressions. */
4825 todo |= eliminate (true);
4827 statistics_counter_event (fun, "Insertions", pre_stats.insertions);
4828 statistics_counter_event (fun, "PA inserted", pre_stats.pa_insert);
4829 statistics_counter_event (fun, "New PHIs", pre_stats.phis);
4830 statistics_counter_event (fun, "Eliminated", pre_stats.eliminations);
4832 clear_expression_ids ();
4833 remove_dead_inserted_code ();
4835 scev_finalize ();
4836 fini_pre ();
4837 todo |= fini_eliminate ();
4838 loop_optimizer_finalize ();
4840 /* TODO: tail_merge_optimize may merge all predecessors of a block, in which
4841 case we can merge the block with the remaining predecessor of the block.
4842 It should either:
4843 - call merge_blocks after each tail merge iteration
4844 - call merge_blocks after all tail merge iterations
4845 - mark TODO_cleanup_cfg when necessary
4846 - share the cfg cleanup with fini_pre. */
4847 todo |= tail_merge_optimize (todo);
4849 free_scc_vn ();
4851 /* Tail merging invalidates the virtual SSA web, together with
4852 cfg-cleanup opportunities exposed by PRE this will wreck the
4853 SSA updating machinery. So make sure to run update-ssa
4854 manually, before eventually scheduling cfg-cleanup as part of
4855 the todo. */
4856 update_ssa (TODO_update_ssa_only_virtuals);
4858 return todo;
4861 } // anon namespace
4863 gimple_opt_pass *
4864 make_pass_pre (gcc::context *ctxt)
4866 return new pass_pre (ctxt);
4869 namespace {
4871 const pass_data pass_data_fre =
4873 GIMPLE_PASS, /* type */
4874 "fre", /* name */
4875 OPTGROUP_NONE, /* optinfo_flags */
4876 TV_TREE_FRE, /* tv_id */
4877 ( PROP_cfg | PROP_ssa ), /* properties_required */
4878 0, /* properties_provided */
4879 0, /* properties_destroyed */
4880 0, /* todo_flags_start */
4881 0, /* todo_flags_finish */
4884 class pass_fre : public gimple_opt_pass
4886 public:
4887 pass_fre (gcc::context *ctxt)
4888 : gimple_opt_pass (pass_data_fre, ctxt)
4891 /* opt_pass methods: */
4892 opt_pass * clone () { return new pass_fre (m_ctxt); }
4893 virtual bool gate (function *) { return flag_tree_fre != 0; }
4894 virtual unsigned int execute (function *);
4896 }; // class pass_fre
4898 unsigned int
4899 pass_fre::execute (function *fun)
4901 unsigned int todo = 0;
4903 if (!run_scc_vn (VN_WALKREWRITE))
4904 return 0;
4906 memset (&pre_stats, 0, sizeof (pre_stats));
4908 /* Remove all the redundant expressions. */
4909 todo |= eliminate (false);
4911 todo |= fini_eliminate ();
4913 free_scc_vn ();
4915 statistics_counter_event (fun, "Insertions", pre_stats.insertions);
4916 statistics_counter_event (fun, "Eliminated", pre_stats.eliminations);
4918 return todo;
4921 } // anon namespace
4923 gimple_opt_pass *
4924 make_pass_fre (gcc::context *ctxt)
4926 return new pass_fre (ctxt);