2013-10-22 Jan-Benedict Glaw <jbglaw@lug-owl.de>
[official-gcc.git] / gcc / tree-ssa-pre.c
blob4774f39ae7cbe2144692d006cc8ff6f62a80c191
1 /* SSA-PRE for trees.
2 Copyright (C) 2001-2013 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 "tree-ssa.h"
31 #include "gimple.h"
32 #include "hash-table.h"
33 #include "tree-iterator.h"
34 #include "alloc-pool.h"
35 #include "obstack.h"
36 #include "tree-pass.h"
37 #include "flags.h"
38 #include "bitmap.h"
39 #include "langhooks.h"
40 #include "cfgloop.h"
41 #include "tree-ssa-sccvn.h"
42 #include "tree-scalar-evolution.h"
43 #include "params.h"
44 #include "dbgcnt.h"
45 #include "domwalk.h"
46 #include "ipa-prop.h"
47 #include "tree-ssa-propagate.h"
49 /* TODO:
51 1. Avail sets can be shared by making an avail_find_leader that
52 walks up the dominator tree and looks in those avail sets.
53 This might affect code optimality, it's unclear right now.
54 2. Strength reduction can be performed by anticipating expressions
55 we can repair later on.
56 3. We can do back-substitution or smarter value numbering to catch
57 commutative expressions split up over multiple statements.
60 /* For ease of terminology, "expression node" in the below refers to
61 every expression node but GIMPLE_ASSIGN, because GIMPLE_ASSIGNs
62 represent the actual statement containing the expressions we care about,
63 and we cache the value number by putting it in the expression. */
65 /* Basic algorithm
67 First we walk the statements to generate the AVAIL sets, the
68 EXP_GEN sets, and the tmp_gen sets. EXP_GEN sets represent the
69 generation of values/expressions by a given block. We use them
70 when computing the ANTIC sets. The AVAIL sets consist of
71 SSA_NAME's that represent values, so we know what values are
72 available in what blocks. AVAIL is a forward dataflow problem. In
73 SSA, values are never killed, so we don't need a kill set, or a
74 fixpoint iteration, in order to calculate the AVAIL sets. In
75 traditional parlance, AVAIL sets tell us the downsafety of the
76 expressions/values.
78 Next, we generate the ANTIC sets. These sets represent the
79 anticipatable expressions. ANTIC is a backwards dataflow
80 problem. An expression is anticipatable in a given block if it could
81 be generated in that block. This means that if we had to perform
82 an insertion in that block, of the value of that expression, we
83 could. Calculating the ANTIC sets requires phi translation of
84 expressions, because the flow goes backwards through phis. We must
85 iterate to a fixpoint of the ANTIC sets, because we have a kill
86 set. Even in SSA form, values are not live over the entire
87 function, only from their definition point onwards. So we have to
88 remove values from the ANTIC set once we go past the definition
89 point of the leaders that make them up.
90 compute_antic/compute_antic_aux performs this computation.
92 Third, we perform insertions to make partially redundant
93 expressions fully redundant.
95 An expression is partially redundant (excluding partial
96 anticipation) if:
98 1. It is AVAIL in some, but not all, of the predecessors of a
99 given block.
100 2. It is ANTIC in all the predecessors.
102 In order to make it fully redundant, we insert the expression into
103 the predecessors where it is not available, but is ANTIC.
105 For the partial anticipation case, we only perform insertion if it
106 is partially anticipated in some block, and fully available in all
107 of the predecessors.
109 insert/insert_aux/do_regular_insertion/do_partial_partial_insertion
110 performs these steps.
112 Fourth, we eliminate fully redundant expressions.
113 This is a simple statement walk that replaces redundant
114 calculations with the now available values. */
116 /* Representations of value numbers:
118 Value numbers are represented by a representative SSA_NAME. We
119 will create fake SSA_NAME's in situations where we need a
120 representative but do not have one (because it is a complex
121 expression). In order to facilitate storing the value numbers in
122 bitmaps, and keep the number of wasted SSA_NAME's down, we also
123 associate a value_id with each value number, and create full blown
124 ssa_name's only where we actually need them (IE in operands of
125 existing expressions).
127 Theoretically you could replace all the value_id's with
128 SSA_NAME_VERSION, but this would allocate a large number of
129 SSA_NAME's (which are each > 30 bytes) just to get a 4 byte number.
130 It would also require an additional indirection at each point we
131 use the value id. */
133 /* Representation of expressions on value numbers:
135 Expressions consisting of value numbers are represented the same
136 way as our VN internally represents them, with an additional
137 "pre_expr" wrapping around them in order to facilitate storing all
138 of the expressions in the same sets. */
140 /* Representation of sets:
142 The dataflow sets do not need to be sorted in any particular order
143 for the majority of their lifetime, are simply represented as two
144 bitmaps, one that keeps track of values present in the set, and one
145 that keeps track of expressions present in the set.
147 When we need them in topological order, we produce it on demand by
148 transforming the bitmap into an array and sorting it into topo
149 order. */
151 /* Type of expression, used to know which member of the PRE_EXPR union
152 is valid. */
154 enum pre_expr_kind
156 NAME,
157 NARY,
158 REFERENCE,
159 CONSTANT
162 typedef union pre_expr_union_d
164 tree name;
165 tree constant;
166 vn_nary_op_t nary;
167 vn_reference_t reference;
168 } pre_expr_union;
170 typedef struct pre_expr_d : typed_noop_remove <pre_expr_d>
172 enum pre_expr_kind kind;
173 unsigned int id;
174 pre_expr_union u;
176 /* hash_table support. */
177 typedef pre_expr_d value_type;
178 typedef pre_expr_d compare_type;
179 static inline hashval_t hash (const pre_expr_d *);
180 static inline int equal (const pre_expr_d *, const pre_expr_d *);
181 } *pre_expr;
183 #define PRE_EXPR_NAME(e) (e)->u.name
184 #define PRE_EXPR_NARY(e) (e)->u.nary
185 #define PRE_EXPR_REFERENCE(e) (e)->u.reference
186 #define PRE_EXPR_CONSTANT(e) (e)->u.constant
188 /* Compare E1 and E1 for equality. */
190 inline int
191 pre_expr_d::equal (const value_type *e1, const compare_type *e2)
193 if (e1->kind != e2->kind)
194 return false;
196 switch (e1->kind)
198 case CONSTANT:
199 return vn_constant_eq_with_type (PRE_EXPR_CONSTANT (e1),
200 PRE_EXPR_CONSTANT (e2));
201 case NAME:
202 return PRE_EXPR_NAME (e1) == PRE_EXPR_NAME (e2);
203 case NARY:
204 return vn_nary_op_eq (PRE_EXPR_NARY (e1), PRE_EXPR_NARY (e2));
205 case REFERENCE:
206 return vn_reference_eq (PRE_EXPR_REFERENCE (e1),
207 PRE_EXPR_REFERENCE (e2));
208 default:
209 gcc_unreachable ();
213 /* Hash E. */
215 inline hashval_t
216 pre_expr_d::hash (const value_type *e)
218 switch (e->kind)
220 case CONSTANT:
221 return vn_hash_constant_with_type (PRE_EXPR_CONSTANT (e));
222 case NAME:
223 return SSA_NAME_VERSION (PRE_EXPR_NAME (e));
224 case NARY:
225 return PRE_EXPR_NARY (e)->hashcode;
226 case REFERENCE:
227 return PRE_EXPR_REFERENCE (e)->hashcode;
228 default:
229 gcc_unreachable ();
233 /* Next global expression id number. */
234 static unsigned int next_expression_id;
236 /* Mapping from expression to id number we can use in bitmap sets. */
237 static vec<pre_expr> expressions;
238 static hash_table <pre_expr_d> expression_to_id;
239 static vec<unsigned> name_to_id;
241 /* Allocate an expression id for EXPR. */
243 static inline unsigned int
244 alloc_expression_id (pre_expr expr)
246 struct pre_expr_d **slot;
247 /* Make sure we won't overflow. */
248 gcc_assert (next_expression_id + 1 > next_expression_id);
249 expr->id = next_expression_id++;
250 expressions.safe_push (expr);
251 if (expr->kind == NAME)
253 unsigned version = SSA_NAME_VERSION (PRE_EXPR_NAME (expr));
254 /* vec::safe_grow_cleared allocates no headroom. Avoid frequent
255 re-allocations by using vec::reserve upfront. There is no
256 vec::quick_grow_cleared unfortunately. */
257 unsigned old_len = name_to_id.length ();
258 name_to_id.reserve (num_ssa_names - old_len);
259 name_to_id.safe_grow_cleared (num_ssa_names);
260 gcc_assert (name_to_id[version] == 0);
261 name_to_id[version] = expr->id;
263 else
265 slot = expression_to_id.find_slot (expr, INSERT);
266 gcc_assert (!*slot);
267 *slot = expr;
269 return next_expression_id - 1;
272 /* Return the expression id for tree EXPR. */
274 static inline unsigned int
275 get_expression_id (const pre_expr expr)
277 return expr->id;
280 static inline unsigned int
281 lookup_expression_id (const pre_expr expr)
283 struct pre_expr_d **slot;
285 if (expr->kind == NAME)
287 unsigned version = SSA_NAME_VERSION (PRE_EXPR_NAME (expr));
288 if (name_to_id.length () <= version)
289 return 0;
290 return name_to_id[version];
292 else
294 slot = expression_to_id.find_slot (expr, NO_INSERT);
295 if (!slot)
296 return 0;
297 return ((pre_expr)*slot)->id;
301 /* Return the existing expression id for EXPR, or create one if one
302 does not exist yet. */
304 static inline unsigned int
305 get_or_alloc_expression_id (pre_expr expr)
307 unsigned int id = lookup_expression_id (expr);
308 if (id == 0)
309 return alloc_expression_id (expr);
310 return expr->id = id;
313 /* Return the expression that has expression id ID */
315 static inline pre_expr
316 expression_for_id (unsigned int id)
318 return expressions[id];
321 /* Free the expression id field in all of our expressions,
322 and then destroy the expressions array. */
324 static void
325 clear_expression_ids (void)
327 expressions.release ();
330 static alloc_pool pre_expr_pool;
332 /* Given an SSA_NAME NAME, get or create a pre_expr to represent it. */
334 static pre_expr
335 get_or_alloc_expr_for_name (tree name)
337 struct pre_expr_d expr;
338 pre_expr result;
339 unsigned int result_id;
341 expr.kind = NAME;
342 expr.id = 0;
343 PRE_EXPR_NAME (&expr) = name;
344 result_id = lookup_expression_id (&expr);
345 if (result_id != 0)
346 return expression_for_id (result_id);
348 result = (pre_expr) pool_alloc (pre_expr_pool);
349 result->kind = NAME;
350 PRE_EXPR_NAME (result) = name;
351 alloc_expression_id (result);
352 return result;
355 /* An unordered bitmap set. One bitmap tracks values, the other,
356 expressions. */
357 typedef struct bitmap_set
359 bitmap_head expressions;
360 bitmap_head values;
361 } *bitmap_set_t;
363 #define FOR_EACH_EXPR_ID_IN_SET(set, id, bi) \
364 EXECUTE_IF_SET_IN_BITMAP (&(set)->expressions, 0, (id), (bi))
366 #define FOR_EACH_VALUE_ID_IN_SET(set, id, bi) \
367 EXECUTE_IF_SET_IN_BITMAP (&(set)->values, 0, (id), (bi))
369 /* Mapping from value id to expressions with that value_id. */
370 static vec<bitmap> value_expressions;
372 /* Sets that we need to keep track of. */
373 typedef struct bb_bitmap_sets
375 /* The EXP_GEN set, which represents expressions/values generated in
376 a basic block. */
377 bitmap_set_t exp_gen;
379 /* The PHI_GEN set, which represents PHI results generated in a
380 basic block. */
381 bitmap_set_t phi_gen;
383 /* The TMP_GEN set, which represents results/temporaries generated
384 in a basic block. IE the LHS of an expression. */
385 bitmap_set_t tmp_gen;
387 /* The AVAIL_OUT set, which represents which values are available in
388 a given basic block. */
389 bitmap_set_t avail_out;
391 /* The ANTIC_IN set, which represents which values are anticipatable
392 in a given basic block. */
393 bitmap_set_t antic_in;
395 /* The PA_IN set, which represents which values are
396 partially anticipatable in a given basic block. */
397 bitmap_set_t pa_in;
399 /* The NEW_SETS set, which is used during insertion to augment the
400 AVAIL_OUT set of blocks with the new insertions performed during
401 the current iteration. */
402 bitmap_set_t new_sets;
404 /* A cache for value_dies_in_block_x. */
405 bitmap expr_dies;
407 /* True if we have visited this block during ANTIC calculation. */
408 unsigned int visited : 1;
410 /* True we have deferred processing this block during ANTIC
411 calculation until its successor is processed. */
412 unsigned int deferred : 1;
414 /* True when the block contains a call that might not return. */
415 unsigned int contains_may_not_return_call : 1;
416 } *bb_value_sets_t;
418 #define EXP_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->exp_gen
419 #define PHI_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->phi_gen
420 #define TMP_GEN(BB) ((bb_value_sets_t) ((BB)->aux))->tmp_gen
421 #define AVAIL_OUT(BB) ((bb_value_sets_t) ((BB)->aux))->avail_out
422 #define ANTIC_IN(BB) ((bb_value_sets_t) ((BB)->aux))->antic_in
423 #define PA_IN(BB) ((bb_value_sets_t) ((BB)->aux))->pa_in
424 #define NEW_SETS(BB) ((bb_value_sets_t) ((BB)->aux))->new_sets
425 #define EXPR_DIES(BB) ((bb_value_sets_t) ((BB)->aux))->expr_dies
426 #define BB_VISITED(BB) ((bb_value_sets_t) ((BB)->aux))->visited
427 #define BB_DEFERRED(BB) ((bb_value_sets_t) ((BB)->aux))->deferred
428 #define BB_MAY_NOTRETURN(BB) ((bb_value_sets_t) ((BB)->aux))->contains_may_not_return_call
431 /* Basic block list in postorder. */
432 static int *postorder;
433 static int postorder_num;
435 /* This structure is used to keep track of statistics on what
436 optimization PRE was able to perform. */
437 static struct
439 /* The number of RHS computations eliminated by PRE. */
440 int eliminations;
442 /* The number of new expressions/temporaries generated by PRE. */
443 int insertions;
445 /* The number of inserts found due to partial anticipation */
446 int pa_insert;
448 /* The number of new PHI nodes added by PRE. */
449 int phis;
450 } pre_stats;
452 static bool do_partial_partial;
453 static pre_expr bitmap_find_leader (bitmap_set_t, unsigned int);
454 static void bitmap_value_insert_into_set (bitmap_set_t, pre_expr);
455 static void bitmap_value_replace_in_set (bitmap_set_t, pre_expr);
456 static void bitmap_set_copy (bitmap_set_t, bitmap_set_t);
457 static bool bitmap_set_contains_value (bitmap_set_t, unsigned int);
458 static void bitmap_insert_into_set (bitmap_set_t, pre_expr);
459 static void bitmap_insert_into_set_1 (bitmap_set_t, pre_expr,
460 unsigned int, bool);
461 static bitmap_set_t bitmap_set_new (void);
462 static tree create_expression_by_pieces (basic_block, pre_expr, gimple_seq *,
463 tree);
464 static tree find_or_generate_expression (basic_block, tree, gimple_seq *);
465 static unsigned int get_expr_value_id (pre_expr);
467 /* We can add and remove elements and entries to and from sets
468 and hash tables, so we use alloc pools for them. */
470 static alloc_pool bitmap_set_pool;
471 static bitmap_obstack grand_bitmap_obstack;
473 /* Set of blocks with statements that have had their EH properties changed. */
474 static bitmap need_eh_cleanup;
476 /* Set of blocks with statements that have had their AB properties changed. */
477 static bitmap need_ab_cleanup;
479 /* A three tuple {e, pred, v} used to cache phi translations in the
480 phi_translate_table. */
482 typedef struct expr_pred_trans_d : typed_free_remove<expr_pred_trans_d>
484 /* The expression. */
485 pre_expr e;
487 /* The predecessor block along which we translated the expression. */
488 basic_block pred;
490 /* The value that resulted from the translation. */
491 pre_expr v;
493 /* The hashcode for the expression, pred pair. This is cached for
494 speed reasons. */
495 hashval_t hashcode;
497 /* hash_table support. */
498 typedef expr_pred_trans_d value_type;
499 typedef expr_pred_trans_d compare_type;
500 static inline hashval_t hash (const value_type *);
501 static inline int equal (const value_type *, const compare_type *);
502 } *expr_pred_trans_t;
503 typedef const struct expr_pred_trans_d *const_expr_pred_trans_t;
505 inline hashval_t
506 expr_pred_trans_d::hash (const expr_pred_trans_d *e)
508 return e->hashcode;
511 inline int
512 expr_pred_trans_d::equal (const value_type *ve1,
513 const compare_type *ve2)
515 basic_block b1 = ve1->pred;
516 basic_block b2 = ve2->pred;
518 /* If they are not translations for the same basic block, they can't
519 be equal. */
520 if (b1 != b2)
521 return false;
522 return pre_expr_d::equal (ve1->e, ve2->e);
525 /* The phi_translate_table caches phi translations for a given
526 expression and predecessor. */
527 static hash_table <expr_pred_trans_d> phi_translate_table;
529 /* Add the tuple mapping from {expression E, basic block PRED} to
530 the phi translation table and return whether it pre-existed. */
532 static inline bool
533 phi_trans_add (expr_pred_trans_t *entry, pre_expr e, basic_block pred)
535 expr_pred_trans_t *slot;
536 expr_pred_trans_d tem;
537 hashval_t hash = iterative_hash_hashval_t (pre_expr_d::hash (e),
538 pred->index);
539 tem.e = e;
540 tem.pred = pred;
541 tem.hashcode = hash;
542 slot = phi_translate_table.find_slot_with_hash (&tem, hash, INSERT);
543 if (*slot)
545 *entry = *slot;
546 return true;
549 *entry = *slot = XNEW (struct expr_pred_trans_d);
550 (*entry)->e = e;
551 (*entry)->pred = pred;
552 (*entry)->hashcode = hash;
553 return false;
557 /* Add expression E to the expression set of value id V. */
559 static void
560 add_to_value (unsigned int v, pre_expr e)
562 bitmap set;
564 gcc_checking_assert (get_expr_value_id (e) == v);
566 if (v >= value_expressions.length ())
568 value_expressions.safe_grow_cleared (v + 1);
571 set = value_expressions[v];
572 if (!set)
574 set = BITMAP_ALLOC (&grand_bitmap_obstack);
575 value_expressions[v] = set;
578 bitmap_set_bit (set, get_or_alloc_expression_id (e));
581 /* Create a new bitmap set and return it. */
583 static bitmap_set_t
584 bitmap_set_new (void)
586 bitmap_set_t ret = (bitmap_set_t) pool_alloc (bitmap_set_pool);
587 bitmap_initialize (&ret->expressions, &grand_bitmap_obstack);
588 bitmap_initialize (&ret->values, &grand_bitmap_obstack);
589 return ret;
592 /* Return the value id for a PRE expression EXPR. */
594 static unsigned int
595 get_expr_value_id (pre_expr expr)
597 unsigned int id;
598 switch (expr->kind)
600 case CONSTANT:
601 id = get_constant_value_id (PRE_EXPR_CONSTANT (expr));
602 break;
603 case NAME:
604 id = VN_INFO (PRE_EXPR_NAME (expr))->value_id;
605 break;
606 case NARY:
607 id = PRE_EXPR_NARY (expr)->value_id;
608 break;
609 case REFERENCE:
610 id = PRE_EXPR_REFERENCE (expr)->value_id;
611 break;
612 default:
613 gcc_unreachable ();
615 /* ??? We cannot assert that expr has a value-id (it can be 0), because
616 we assign value-ids only to expressions that have a result
617 in set_hashtable_value_ids. */
618 return id;
621 /* Return a SCCVN valnum (SSA name or constant) for the PRE value-id VAL. */
623 static tree
624 sccvn_valnum_from_value_id (unsigned int val)
626 bitmap_iterator bi;
627 unsigned int i;
628 bitmap exprset = value_expressions[val];
629 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
631 pre_expr vexpr = expression_for_id (i);
632 if (vexpr->kind == NAME)
633 return VN_INFO (PRE_EXPR_NAME (vexpr))->valnum;
634 else if (vexpr->kind == CONSTANT)
635 return PRE_EXPR_CONSTANT (vexpr);
637 return NULL_TREE;
640 /* Remove an expression EXPR from a bitmapped set. */
642 static void
643 bitmap_remove_from_set (bitmap_set_t set, pre_expr expr)
645 unsigned int val = get_expr_value_id (expr);
646 if (!value_id_constant_p (val))
648 bitmap_clear_bit (&set->values, val);
649 bitmap_clear_bit (&set->expressions, get_expression_id (expr));
653 static void
654 bitmap_insert_into_set_1 (bitmap_set_t set, pre_expr expr,
655 unsigned int val, bool allow_constants)
657 if (allow_constants || !value_id_constant_p (val))
659 /* We specifically expect this and only this function to be able to
660 insert constants into a set. */
661 bitmap_set_bit (&set->values, val);
662 bitmap_set_bit (&set->expressions, get_or_alloc_expression_id (expr));
666 /* Insert an expression EXPR into a bitmapped set. */
668 static void
669 bitmap_insert_into_set (bitmap_set_t set, pre_expr expr)
671 bitmap_insert_into_set_1 (set, expr, get_expr_value_id (expr), false);
674 /* Copy a bitmapped set ORIG, into bitmapped set DEST. */
676 static void
677 bitmap_set_copy (bitmap_set_t dest, bitmap_set_t orig)
679 bitmap_copy (&dest->expressions, &orig->expressions);
680 bitmap_copy (&dest->values, &orig->values);
684 /* Free memory used up by SET. */
685 static void
686 bitmap_set_free (bitmap_set_t set)
688 bitmap_clear (&set->expressions);
689 bitmap_clear (&set->values);
693 /* Generate an topological-ordered array of bitmap set SET. */
695 static vec<pre_expr>
696 sorted_array_from_bitmap_set (bitmap_set_t set)
698 unsigned int i, j;
699 bitmap_iterator bi, bj;
700 vec<pre_expr> result;
702 /* Pre-allocate roughly enough space for the array. */
703 result.create (bitmap_count_bits (&set->values));
705 FOR_EACH_VALUE_ID_IN_SET (set, i, bi)
707 /* The number of expressions having a given value is usually
708 relatively small. Thus, rather than making a vector of all
709 the expressions and sorting it by value-id, we walk the values
710 and check in the reverse mapping that tells us what expressions
711 have a given value, to filter those in our set. As a result,
712 the expressions are inserted in value-id order, which means
713 topological order.
715 If this is somehow a significant lose for some cases, we can
716 choose which set to walk based on the set size. */
717 bitmap exprset = value_expressions[i];
718 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, j, bj)
720 if (bitmap_bit_p (&set->expressions, j))
721 result.safe_push (expression_for_id (j));
725 return result;
728 /* Perform bitmapped set operation DEST &= ORIG. */
730 static void
731 bitmap_set_and (bitmap_set_t dest, bitmap_set_t orig)
733 bitmap_iterator bi;
734 unsigned int i;
736 if (dest != orig)
738 bitmap_head temp;
739 bitmap_initialize (&temp, &grand_bitmap_obstack);
741 bitmap_and_into (&dest->values, &orig->values);
742 bitmap_copy (&temp, &dest->expressions);
743 EXECUTE_IF_SET_IN_BITMAP (&temp, 0, i, bi)
745 pre_expr expr = expression_for_id (i);
746 unsigned int value_id = get_expr_value_id (expr);
747 if (!bitmap_bit_p (&dest->values, value_id))
748 bitmap_clear_bit (&dest->expressions, i);
750 bitmap_clear (&temp);
754 /* Subtract all values and expressions contained in ORIG from DEST. */
756 static bitmap_set_t
757 bitmap_set_subtract (bitmap_set_t dest, bitmap_set_t orig)
759 bitmap_set_t result = bitmap_set_new ();
760 bitmap_iterator bi;
761 unsigned int i;
763 bitmap_and_compl (&result->expressions, &dest->expressions,
764 &orig->expressions);
766 FOR_EACH_EXPR_ID_IN_SET (result, i, bi)
768 pre_expr expr = expression_for_id (i);
769 unsigned int value_id = get_expr_value_id (expr);
770 bitmap_set_bit (&result->values, value_id);
773 return result;
776 /* Subtract all the values in bitmap set B from bitmap set A. */
778 static void
779 bitmap_set_subtract_values (bitmap_set_t a, bitmap_set_t b)
781 unsigned int i;
782 bitmap_iterator bi;
783 bitmap_head temp;
785 bitmap_initialize (&temp, &grand_bitmap_obstack);
787 bitmap_copy (&temp, &a->expressions);
788 EXECUTE_IF_SET_IN_BITMAP (&temp, 0, i, bi)
790 pre_expr expr = expression_for_id (i);
791 if (bitmap_set_contains_value (b, get_expr_value_id (expr)))
792 bitmap_remove_from_set (a, expr);
794 bitmap_clear (&temp);
798 /* Return true if bitmapped set SET contains the value VALUE_ID. */
800 static bool
801 bitmap_set_contains_value (bitmap_set_t set, unsigned int value_id)
803 if (value_id_constant_p (value_id))
804 return true;
806 if (!set || bitmap_empty_p (&set->expressions))
807 return false;
809 return bitmap_bit_p (&set->values, value_id);
812 static inline bool
813 bitmap_set_contains_expr (bitmap_set_t set, const pre_expr expr)
815 return bitmap_bit_p (&set->expressions, get_expression_id (expr));
818 /* Replace an instance of value LOOKFOR with expression EXPR in SET. */
820 static void
821 bitmap_set_replace_value (bitmap_set_t set, unsigned int lookfor,
822 const pre_expr expr)
824 bitmap exprset;
825 unsigned int i;
826 bitmap_iterator bi;
828 if (value_id_constant_p (lookfor))
829 return;
831 if (!bitmap_set_contains_value (set, lookfor))
832 return;
834 /* The number of expressions having a given value is usually
835 significantly less than the total number of expressions in SET.
836 Thus, rather than check, for each expression in SET, whether it
837 has the value LOOKFOR, we walk the reverse mapping that tells us
838 what expressions have a given value, and see if any of those
839 expressions are in our set. For large testcases, this is about
840 5-10x faster than walking the bitmap. If this is somehow a
841 significant lose for some cases, we can choose which set to walk
842 based on the set size. */
843 exprset = value_expressions[lookfor];
844 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
846 if (bitmap_clear_bit (&set->expressions, i))
848 bitmap_set_bit (&set->expressions, get_expression_id (expr));
849 return;
853 gcc_unreachable ();
856 /* Return true if two bitmap sets are equal. */
858 static bool
859 bitmap_set_equal (bitmap_set_t a, bitmap_set_t b)
861 return bitmap_equal_p (&a->values, &b->values);
864 /* Replace an instance of EXPR's VALUE with EXPR in SET if it exists,
865 and add it otherwise. */
867 static void
868 bitmap_value_replace_in_set (bitmap_set_t set, pre_expr expr)
870 unsigned int val = get_expr_value_id (expr);
872 if (bitmap_set_contains_value (set, val))
873 bitmap_set_replace_value (set, val, expr);
874 else
875 bitmap_insert_into_set (set, expr);
878 /* Insert EXPR into SET if EXPR's value is not already present in
879 SET. */
881 static void
882 bitmap_value_insert_into_set (bitmap_set_t set, pre_expr expr)
884 unsigned int val = get_expr_value_id (expr);
886 gcc_checking_assert (expr->id == get_or_alloc_expression_id (expr));
888 /* Constant values are always considered to be part of the set. */
889 if (value_id_constant_p (val))
890 return;
892 /* If the value membership changed, add the expression. */
893 if (bitmap_set_bit (&set->values, val))
894 bitmap_set_bit (&set->expressions, expr->id);
897 /* Print out EXPR to outfile. */
899 static void
900 print_pre_expr (FILE *outfile, const pre_expr expr)
902 switch (expr->kind)
904 case CONSTANT:
905 print_generic_expr (outfile, PRE_EXPR_CONSTANT (expr), 0);
906 break;
907 case NAME:
908 print_generic_expr (outfile, PRE_EXPR_NAME (expr), 0);
909 break;
910 case NARY:
912 unsigned int i;
913 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
914 fprintf (outfile, "{%s,", get_tree_code_name (nary->opcode));
915 for (i = 0; i < nary->length; i++)
917 print_generic_expr (outfile, nary->op[i], 0);
918 if (i != (unsigned) nary->length - 1)
919 fprintf (outfile, ",");
921 fprintf (outfile, "}");
923 break;
925 case REFERENCE:
927 vn_reference_op_t vro;
928 unsigned int i;
929 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
930 fprintf (outfile, "{");
931 for (i = 0;
932 ref->operands.iterate (i, &vro);
933 i++)
935 bool closebrace = false;
936 if (vro->opcode != SSA_NAME
937 && TREE_CODE_CLASS (vro->opcode) != tcc_declaration)
939 fprintf (outfile, "%s", get_tree_code_name (vro->opcode));
940 if (vro->op0)
942 fprintf (outfile, "<");
943 closebrace = true;
946 if (vro->op0)
948 print_generic_expr (outfile, vro->op0, 0);
949 if (vro->op1)
951 fprintf (outfile, ",");
952 print_generic_expr (outfile, vro->op1, 0);
954 if (vro->op2)
956 fprintf (outfile, ",");
957 print_generic_expr (outfile, vro->op2, 0);
960 if (closebrace)
961 fprintf (outfile, ">");
962 if (i != ref->operands.length () - 1)
963 fprintf (outfile, ",");
965 fprintf (outfile, "}");
966 if (ref->vuse)
968 fprintf (outfile, "@");
969 print_generic_expr (outfile, ref->vuse, 0);
972 break;
975 void debug_pre_expr (pre_expr);
977 /* Like print_pre_expr but always prints to stderr. */
978 DEBUG_FUNCTION void
979 debug_pre_expr (pre_expr e)
981 print_pre_expr (stderr, e);
982 fprintf (stderr, "\n");
985 /* Print out SET to OUTFILE. */
987 static void
988 print_bitmap_set (FILE *outfile, bitmap_set_t set,
989 const char *setname, int blockindex)
991 fprintf (outfile, "%s[%d] := { ", setname, blockindex);
992 if (set)
994 bool first = true;
995 unsigned i;
996 bitmap_iterator bi;
998 FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
1000 const pre_expr expr = expression_for_id (i);
1002 if (!first)
1003 fprintf (outfile, ", ");
1004 first = false;
1005 print_pre_expr (outfile, expr);
1007 fprintf (outfile, " (%04d)", get_expr_value_id (expr));
1010 fprintf (outfile, " }\n");
1013 void debug_bitmap_set (bitmap_set_t);
1015 DEBUG_FUNCTION void
1016 debug_bitmap_set (bitmap_set_t set)
1018 print_bitmap_set (stderr, set, "debug", 0);
1021 void debug_bitmap_sets_for (basic_block);
1023 DEBUG_FUNCTION void
1024 debug_bitmap_sets_for (basic_block bb)
1026 print_bitmap_set (stderr, AVAIL_OUT (bb), "avail_out", bb->index);
1027 print_bitmap_set (stderr, EXP_GEN (bb), "exp_gen", bb->index);
1028 print_bitmap_set (stderr, PHI_GEN (bb), "phi_gen", bb->index);
1029 print_bitmap_set (stderr, TMP_GEN (bb), "tmp_gen", bb->index);
1030 print_bitmap_set (stderr, ANTIC_IN (bb), "antic_in", bb->index);
1031 if (do_partial_partial)
1032 print_bitmap_set (stderr, PA_IN (bb), "pa_in", bb->index);
1033 print_bitmap_set (stderr, NEW_SETS (bb), "new_sets", bb->index);
1036 /* Print out the expressions that have VAL to OUTFILE. */
1038 static void
1039 print_value_expressions (FILE *outfile, unsigned int val)
1041 bitmap set = value_expressions[val];
1042 if (set)
1044 bitmap_set x;
1045 char s[10];
1046 sprintf (s, "%04d", val);
1047 x.expressions = *set;
1048 print_bitmap_set (outfile, &x, s, 0);
1053 DEBUG_FUNCTION void
1054 debug_value_expressions (unsigned int val)
1056 print_value_expressions (stderr, val);
1059 /* Given a CONSTANT, allocate a new CONSTANT type PRE_EXPR to
1060 represent it. */
1062 static pre_expr
1063 get_or_alloc_expr_for_constant (tree constant)
1065 unsigned int result_id;
1066 unsigned int value_id;
1067 struct pre_expr_d expr;
1068 pre_expr newexpr;
1070 expr.kind = CONSTANT;
1071 PRE_EXPR_CONSTANT (&expr) = constant;
1072 result_id = lookup_expression_id (&expr);
1073 if (result_id != 0)
1074 return expression_for_id (result_id);
1076 newexpr = (pre_expr) pool_alloc (pre_expr_pool);
1077 newexpr->kind = CONSTANT;
1078 PRE_EXPR_CONSTANT (newexpr) = constant;
1079 alloc_expression_id (newexpr);
1080 value_id = get_or_alloc_constant_value_id (constant);
1081 add_to_value (value_id, newexpr);
1082 return newexpr;
1085 /* Given a value id V, find the actual tree representing the constant
1086 value if there is one, and return it. Return NULL if we can't find
1087 a constant. */
1089 static tree
1090 get_constant_for_value_id (unsigned int v)
1092 if (value_id_constant_p (v))
1094 unsigned int i;
1095 bitmap_iterator bi;
1096 bitmap exprset = value_expressions[v];
1098 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
1100 pre_expr expr = expression_for_id (i);
1101 if (expr->kind == CONSTANT)
1102 return PRE_EXPR_CONSTANT (expr);
1105 return NULL;
1108 /* Get or allocate a pre_expr for a piece of GIMPLE, and return it.
1109 Currently only supports constants and SSA_NAMES. */
1110 static pre_expr
1111 get_or_alloc_expr_for (tree t)
1113 if (TREE_CODE (t) == SSA_NAME)
1114 return get_or_alloc_expr_for_name (t);
1115 else if (is_gimple_min_invariant (t))
1116 return get_or_alloc_expr_for_constant (t);
1117 else
1119 /* More complex expressions can result from SCCVN expression
1120 simplification that inserts values for them. As they all
1121 do not have VOPs the get handled by the nary ops struct. */
1122 vn_nary_op_t result;
1123 unsigned int result_id;
1124 vn_nary_op_lookup (t, &result);
1125 if (result != NULL)
1127 pre_expr e = (pre_expr) pool_alloc (pre_expr_pool);
1128 e->kind = NARY;
1129 PRE_EXPR_NARY (e) = result;
1130 result_id = lookup_expression_id (e);
1131 if (result_id != 0)
1133 pool_free (pre_expr_pool, e);
1134 e = expression_for_id (result_id);
1135 return e;
1137 alloc_expression_id (e);
1138 return e;
1141 return NULL;
1144 /* Return the folded version of T if T, when folded, is a gimple
1145 min_invariant. Otherwise, return T. */
1147 static pre_expr
1148 fully_constant_expression (pre_expr e)
1150 switch (e->kind)
1152 case CONSTANT:
1153 return e;
1154 case NARY:
1156 vn_nary_op_t nary = PRE_EXPR_NARY (e);
1157 switch (TREE_CODE_CLASS (nary->opcode))
1159 case tcc_binary:
1160 case tcc_comparison:
1162 /* We have to go from trees to pre exprs to value ids to
1163 constants. */
1164 tree naryop0 = nary->op[0];
1165 tree naryop1 = nary->op[1];
1166 tree result;
1167 if (!is_gimple_min_invariant (naryop0))
1169 pre_expr rep0 = get_or_alloc_expr_for (naryop0);
1170 unsigned int vrep0 = get_expr_value_id (rep0);
1171 tree const0 = get_constant_for_value_id (vrep0);
1172 if (const0)
1173 naryop0 = fold_convert (TREE_TYPE (naryop0), const0);
1175 if (!is_gimple_min_invariant (naryop1))
1177 pre_expr rep1 = get_or_alloc_expr_for (naryop1);
1178 unsigned int vrep1 = get_expr_value_id (rep1);
1179 tree const1 = get_constant_for_value_id (vrep1);
1180 if (const1)
1181 naryop1 = fold_convert (TREE_TYPE (naryop1), const1);
1183 result = fold_binary (nary->opcode, nary->type,
1184 naryop0, naryop1);
1185 if (result && is_gimple_min_invariant (result))
1186 return get_or_alloc_expr_for_constant (result);
1187 /* We might have simplified the expression to a
1188 SSA_NAME for example from x_1 * 1. But we cannot
1189 insert a PHI for x_1 unconditionally as x_1 might
1190 not be available readily. */
1191 return e;
1193 case tcc_reference:
1194 if (nary->opcode != REALPART_EXPR
1195 && nary->opcode != IMAGPART_EXPR
1196 && nary->opcode != VIEW_CONVERT_EXPR)
1197 return e;
1198 /* Fallthrough. */
1199 case tcc_unary:
1201 /* We have to go from trees to pre exprs to value ids to
1202 constants. */
1203 tree naryop0 = nary->op[0];
1204 tree const0, result;
1205 if (is_gimple_min_invariant (naryop0))
1206 const0 = naryop0;
1207 else
1209 pre_expr rep0 = get_or_alloc_expr_for (naryop0);
1210 unsigned int vrep0 = get_expr_value_id (rep0);
1211 const0 = get_constant_for_value_id (vrep0);
1213 result = NULL;
1214 if (const0)
1216 tree type1 = TREE_TYPE (nary->op[0]);
1217 const0 = fold_convert (type1, const0);
1218 result = fold_unary (nary->opcode, nary->type, const0);
1220 if (result && is_gimple_min_invariant (result))
1221 return get_or_alloc_expr_for_constant (result);
1222 return e;
1224 default:
1225 return e;
1228 case REFERENCE:
1230 vn_reference_t ref = PRE_EXPR_REFERENCE (e);
1231 tree folded;
1232 if ((folded = fully_constant_vn_reference_p (ref)))
1233 return get_or_alloc_expr_for_constant (folded);
1234 return e;
1236 default:
1237 return e;
1239 return e;
1242 /* Translate the VUSE backwards through phi nodes in PHIBLOCK, so that
1243 it has the value it would have in BLOCK. Set *SAME_VALID to true
1244 in case the new vuse doesn't change the value id of the OPERANDS. */
1246 static tree
1247 translate_vuse_through_block (vec<vn_reference_op_s> operands,
1248 alias_set_type set, tree type, tree vuse,
1249 basic_block phiblock,
1250 basic_block block, bool *same_valid)
1252 gimple phi = SSA_NAME_DEF_STMT (vuse);
1253 ao_ref ref;
1254 edge e = NULL;
1255 bool use_oracle;
1257 *same_valid = true;
1259 if (gimple_bb (phi) != phiblock)
1260 return vuse;
1262 use_oracle = ao_ref_init_from_vn_reference (&ref, set, type, operands);
1264 /* Use the alias-oracle to find either the PHI node in this block,
1265 the first VUSE used in this block that is equivalent to vuse or
1266 the first VUSE which definition in this block kills the value. */
1267 if (gimple_code (phi) == GIMPLE_PHI)
1268 e = find_edge (block, phiblock);
1269 else if (use_oracle)
1270 while (!stmt_may_clobber_ref_p_1 (phi, &ref))
1272 vuse = gimple_vuse (phi);
1273 phi = SSA_NAME_DEF_STMT (vuse);
1274 if (gimple_bb (phi) != phiblock)
1275 return vuse;
1276 if (gimple_code (phi) == GIMPLE_PHI)
1278 e = find_edge (block, phiblock);
1279 break;
1282 else
1283 return NULL_TREE;
1285 if (e)
1287 if (use_oracle)
1289 bitmap visited = NULL;
1290 unsigned int cnt;
1291 /* Try to find a vuse that dominates this phi node by skipping
1292 non-clobbering statements. */
1293 vuse = get_continuation_for_phi (phi, &ref, &cnt, &visited, false);
1294 if (visited)
1295 BITMAP_FREE (visited);
1297 else
1298 vuse = NULL_TREE;
1299 if (!vuse)
1301 /* If we didn't find any, the value ID can't stay the same,
1302 but return the translated vuse. */
1303 *same_valid = false;
1304 vuse = PHI_ARG_DEF (phi, e->dest_idx);
1306 /* ??? We would like to return vuse here as this is the canonical
1307 upmost vdef that this reference is associated with. But during
1308 insertion of the references into the hash tables we only ever
1309 directly insert with their direct gimple_vuse, hence returning
1310 something else would make us not find the other expression. */
1311 return PHI_ARG_DEF (phi, e->dest_idx);
1314 return NULL_TREE;
1317 /* Like bitmap_find_leader, but checks for the value existing in SET1 *or*
1318 SET2. This is used to avoid making a set consisting of the union
1319 of PA_IN and ANTIC_IN during insert. */
1321 static inline pre_expr
1322 find_leader_in_sets (unsigned int val, bitmap_set_t set1, bitmap_set_t set2)
1324 pre_expr result;
1326 result = bitmap_find_leader (set1, val);
1327 if (!result && set2)
1328 result = bitmap_find_leader (set2, val);
1329 return result;
1332 /* Get the tree type for our PRE expression e. */
1334 static tree
1335 get_expr_type (const pre_expr e)
1337 switch (e->kind)
1339 case NAME:
1340 return TREE_TYPE (PRE_EXPR_NAME (e));
1341 case CONSTANT:
1342 return TREE_TYPE (PRE_EXPR_CONSTANT (e));
1343 case REFERENCE:
1344 return PRE_EXPR_REFERENCE (e)->type;
1345 case NARY:
1346 return PRE_EXPR_NARY (e)->type;
1348 gcc_unreachable ();
1351 /* Get a representative SSA_NAME for a given expression.
1352 Since all of our sub-expressions are treated as values, we require
1353 them to be SSA_NAME's for simplicity.
1354 Prior versions of GVNPRE used to use "value handles" here, so that
1355 an expression would be VH.11 + VH.10 instead of d_3 + e_6. In
1356 either case, the operands are really values (IE we do not expect
1357 them to be usable without finding leaders). */
1359 static tree
1360 get_representative_for (const pre_expr e)
1362 tree name;
1363 unsigned int value_id = get_expr_value_id (e);
1365 switch (e->kind)
1367 case NAME:
1368 return PRE_EXPR_NAME (e);
1369 case CONSTANT:
1370 return PRE_EXPR_CONSTANT (e);
1371 case NARY:
1372 case REFERENCE:
1374 /* Go through all of the expressions representing this value
1375 and pick out an SSA_NAME. */
1376 unsigned int i;
1377 bitmap_iterator bi;
1378 bitmap exprs = value_expressions[value_id];
1379 EXECUTE_IF_SET_IN_BITMAP (exprs, 0, i, bi)
1381 pre_expr rep = expression_for_id (i);
1382 if (rep->kind == NAME)
1383 return PRE_EXPR_NAME (rep);
1384 else if (rep->kind == CONSTANT)
1385 return PRE_EXPR_CONSTANT (rep);
1388 break;
1391 /* If we reached here we couldn't find an SSA_NAME. This can
1392 happen when we've discovered a value that has never appeared in
1393 the program as set to an SSA_NAME, as the result of phi translation.
1394 Create one here.
1395 ??? We should be able to re-use this when we insert the statement
1396 to compute it. */
1397 name = make_temp_ssa_name (get_expr_type (e), gimple_build_nop (), "pretmp");
1398 VN_INFO_GET (name)->value_id = value_id;
1399 VN_INFO (name)->valnum = name;
1400 /* ??? For now mark this SSA name for release by SCCVN. */
1401 VN_INFO (name)->needs_insertion = true;
1402 add_to_value (value_id, get_or_alloc_expr_for_name (name));
1403 if (dump_file && (dump_flags & TDF_DETAILS))
1405 fprintf (dump_file, "Created SSA_NAME representative ");
1406 print_generic_expr (dump_file, name, 0);
1407 fprintf (dump_file, " for expression:");
1408 print_pre_expr (dump_file, e);
1409 fprintf (dump_file, " (%04d)\n", value_id);
1412 return name;
1417 static pre_expr
1418 phi_translate (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1419 basic_block pred, basic_block phiblock);
1421 /* Translate EXPR using phis in PHIBLOCK, so that it has the values of
1422 the phis in PRED. Return NULL if we can't find a leader for each part
1423 of the translated expression. */
1425 static pre_expr
1426 phi_translate_1 (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1427 basic_block pred, basic_block phiblock)
1429 switch (expr->kind)
1431 case NARY:
1433 unsigned int i;
1434 bool changed = false;
1435 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1436 vn_nary_op_t newnary = XALLOCAVAR (struct vn_nary_op_s,
1437 sizeof_vn_nary_op (nary->length));
1438 memcpy (newnary, nary, sizeof_vn_nary_op (nary->length));
1440 for (i = 0; i < newnary->length; i++)
1442 if (TREE_CODE (newnary->op[i]) != SSA_NAME)
1443 continue;
1444 else
1446 pre_expr leader, result;
1447 unsigned int op_val_id = VN_INFO (newnary->op[i])->value_id;
1448 leader = find_leader_in_sets (op_val_id, set1, set2);
1449 result = phi_translate (leader, set1, set2, pred, phiblock);
1450 if (result && result != leader)
1452 tree name = get_representative_for (result);
1453 if (!name)
1454 return NULL;
1455 newnary->op[i] = name;
1457 else if (!result)
1458 return NULL;
1460 changed |= newnary->op[i] != nary->op[i];
1463 if (changed)
1465 pre_expr constant;
1466 unsigned int new_val_id;
1468 tree result = vn_nary_op_lookup_pieces (newnary->length,
1469 newnary->opcode,
1470 newnary->type,
1471 &newnary->op[0],
1472 &nary);
1473 if (result && is_gimple_min_invariant (result))
1474 return get_or_alloc_expr_for_constant (result);
1476 expr = (pre_expr) pool_alloc (pre_expr_pool);
1477 expr->kind = NARY;
1478 expr->id = 0;
1479 if (nary)
1481 PRE_EXPR_NARY (expr) = nary;
1482 constant = fully_constant_expression (expr);
1483 if (constant != expr)
1484 return constant;
1486 new_val_id = nary->value_id;
1487 get_or_alloc_expression_id (expr);
1489 else
1491 new_val_id = get_next_value_id ();
1492 value_expressions.safe_grow_cleared (get_max_value_id () + 1);
1493 nary = vn_nary_op_insert_pieces (newnary->length,
1494 newnary->opcode,
1495 newnary->type,
1496 &newnary->op[0],
1497 result, new_val_id);
1498 PRE_EXPR_NARY (expr) = nary;
1499 constant = fully_constant_expression (expr);
1500 if (constant != expr)
1501 return constant;
1502 get_or_alloc_expression_id (expr);
1504 add_to_value (new_val_id, expr);
1506 return expr;
1508 break;
1510 case REFERENCE:
1512 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1513 vec<vn_reference_op_s> operands = ref->operands;
1514 tree vuse = ref->vuse;
1515 tree newvuse = vuse;
1516 vec<vn_reference_op_s> newoperands = vNULL;
1517 bool changed = false, same_valid = true;
1518 unsigned int i, j, n;
1519 vn_reference_op_t operand;
1520 vn_reference_t newref;
1522 for (i = 0, j = 0;
1523 operands.iterate (i, &operand); i++, j++)
1525 pre_expr opresult;
1526 pre_expr leader;
1527 tree op[3];
1528 tree type = operand->type;
1529 vn_reference_op_s newop = *operand;
1530 op[0] = operand->op0;
1531 op[1] = operand->op1;
1532 op[2] = operand->op2;
1533 for (n = 0; n < 3; ++n)
1535 unsigned int op_val_id;
1536 if (!op[n])
1537 continue;
1538 if (TREE_CODE (op[n]) != SSA_NAME)
1540 /* We can't possibly insert these. */
1541 if (n != 0
1542 && !is_gimple_min_invariant (op[n]))
1543 break;
1544 continue;
1546 op_val_id = VN_INFO (op[n])->value_id;
1547 leader = find_leader_in_sets (op_val_id, set1, set2);
1548 if (!leader)
1549 break;
1550 opresult = phi_translate (leader, set1, set2, pred, phiblock);
1551 if (!opresult)
1552 break;
1553 if (opresult != leader)
1555 tree name = get_representative_for (opresult);
1556 if (!name)
1557 break;
1558 changed |= name != op[n];
1559 op[n] = name;
1562 if (n != 3)
1564 newoperands.release ();
1565 return NULL;
1567 if (!newoperands.exists ())
1568 newoperands = operands.copy ();
1569 /* We may have changed from an SSA_NAME to a constant */
1570 if (newop.opcode == SSA_NAME && TREE_CODE (op[0]) != SSA_NAME)
1571 newop.opcode = TREE_CODE (op[0]);
1572 newop.type = type;
1573 newop.op0 = op[0];
1574 newop.op1 = op[1];
1575 newop.op2 = op[2];
1576 /* If it transforms a non-constant ARRAY_REF into a constant
1577 one, adjust the constant offset. */
1578 if (newop.opcode == ARRAY_REF
1579 && newop.off == -1
1580 && TREE_CODE (op[0]) == INTEGER_CST
1581 && TREE_CODE (op[1]) == INTEGER_CST
1582 && TREE_CODE (op[2]) == INTEGER_CST)
1584 double_int off = tree_to_double_int (op[0]);
1585 off += -tree_to_double_int (op[1]);
1586 off *= tree_to_double_int (op[2]);
1587 if (off.fits_shwi ())
1588 newop.off = off.low;
1590 newoperands[j] = newop;
1591 /* If it transforms from an SSA_NAME to an address, fold with
1592 a preceding indirect reference. */
1593 if (j > 0 && op[0] && TREE_CODE (op[0]) == ADDR_EXPR
1594 && newoperands[j - 1].opcode == MEM_REF)
1595 vn_reference_fold_indirect (&newoperands, &j);
1597 if (i != operands.length ())
1599 newoperands.release ();
1600 return NULL;
1603 if (vuse)
1605 newvuse = translate_vuse_through_block (newoperands,
1606 ref->set, ref->type,
1607 vuse, phiblock, pred,
1608 &same_valid);
1609 if (newvuse == NULL_TREE)
1611 newoperands.release ();
1612 return NULL;
1616 if (changed || newvuse != vuse)
1618 unsigned int new_val_id;
1619 pre_expr constant;
1621 tree result = vn_reference_lookup_pieces (newvuse, ref->set,
1622 ref->type,
1623 newoperands,
1624 &newref, VN_WALK);
1625 if (result)
1626 newoperands.release ();
1628 /* We can always insert constants, so if we have a partial
1629 redundant constant load of another type try to translate it
1630 to a constant of appropriate type. */
1631 if (result && is_gimple_min_invariant (result))
1633 tree tem = result;
1634 if (!useless_type_conversion_p (ref->type, TREE_TYPE (result)))
1636 tem = fold_unary (VIEW_CONVERT_EXPR, ref->type, result);
1637 if (tem && !is_gimple_min_invariant (tem))
1638 tem = NULL_TREE;
1640 if (tem)
1641 return get_or_alloc_expr_for_constant (tem);
1644 /* If we'd have to convert things we would need to validate
1645 if we can insert the translated expression. So fail
1646 here for now - we cannot insert an alias with a different
1647 type in the VN tables either, as that would assert. */
1648 if (result
1649 && !useless_type_conversion_p (ref->type, TREE_TYPE (result)))
1650 return NULL;
1651 else if (!result && newref
1652 && !useless_type_conversion_p (ref->type, newref->type))
1654 newoperands.release ();
1655 return NULL;
1658 expr = (pre_expr) pool_alloc (pre_expr_pool);
1659 expr->kind = REFERENCE;
1660 expr->id = 0;
1662 if (newref)
1664 PRE_EXPR_REFERENCE (expr) = newref;
1665 constant = fully_constant_expression (expr);
1666 if (constant != expr)
1667 return constant;
1669 new_val_id = newref->value_id;
1670 get_or_alloc_expression_id (expr);
1672 else
1674 if (changed || !same_valid)
1676 new_val_id = get_next_value_id ();
1677 value_expressions.safe_grow_cleared
1678 (get_max_value_id () + 1);
1680 else
1681 new_val_id = ref->value_id;
1682 newref = vn_reference_insert_pieces (newvuse, ref->set,
1683 ref->type,
1684 newoperands,
1685 result, new_val_id);
1686 newoperands.create (0);
1687 PRE_EXPR_REFERENCE (expr) = newref;
1688 constant = fully_constant_expression (expr);
1689 if (constant != expr)
1690 return constant;
1691 get_or_alloc_expression_id (expr);
1693 add_to_value (new_val_id, expr);
1695 newoperands.release ();
1696 return expr;
1698 break;
1700 case NAME:
1702 tree name = PRE_EXPR_NAME (expr);
1703 gimple def_stmt = SSA_NAME_DEF_STMT (name);
1704 /* If the SSA name is defined by a PHI node in this block,
1705 translate it. */
1706 if (gimple_code (def_stmt) == GIMPLE_PHI
1707 && gimple_bb (def_stmt) == phiblock)
1709 edge e = find_edge (pred, gimple_bb (def_stmt));
1710 tree def = PHI_ARG_DEF (def_stmt, e->dest_idx);
1712 /* Handle constant. */
1713 if (is_gimple_min_invariant (def))
1714 return get_or_alloc_expr_for_constant (def);
1716 return get_or_alloc_expr_for_name (def);
1718 /* Otherwise return it unchanged - it will get cleaned if its
1719 value is not available in PREDs AVAIL_OUT set of expressions. */
1720 return expr;
1723 default:
1724 gcc_unreachable ();
1728 /* Wrapper around phi_translate_1 providing caching functionality. */
1730 static pre_expr
1731 phi_translate (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1732 basic_block pred, basic_block phiblock)
1734 expr_pred_trans_t slot = NULL;
1735 pre_expr phitrans;
1737 if (!expr)
1738 return NULL;
1740 /* Constants contain no values that need translation. */
1741 if (expr->kind == CONSTANT)
1742 return expr;
1744 if (value_id_constant_p (get_expr_value_id (expr)))
1745 return expr;
1747 /* Don't add translations of NAMEs as those are cheap to translate. */
1748 if (expr->kind != NAME)
1750 if (phi_trans_add (&slot, expr, pred))
1751 return slot->v;
1752 /* Store NULL for the value we want to return in the case of
1753 recursing. */
1754 slot->v = NULL;
1757 /* Translate. */
1758 phitrans = phi_translate_1 (expr, set1, set2, pred, phiblock);
1760 if (slot)
1762 if (phitrans)
1763 slot->v = phitrans;
1764 else
1765 /* Remove failed translations again, they cause insert
1766 iteration to not pick up new opportunities reliably. */
1767 phi_translate_table.remove_elt_with_hash (slot, slot->hashcode);
1770 return phitrans;
1774 /* For each expression in SET, translate the values through phi nodes
1775 in PHIBLOCK using edge PHIBLOCK->PRED, and store the resulting
1776 expressions in DEST. */
1778 static void
1779 phi_translate_set (bitmap_set_t dest, bitmap_set_t set, basic_block pred,
1780 basic_block phiblock)
1782 vec<pre_expr> exprs;
1783 pre_expr expr;
1784 int i;
1786 if (gimple_seq_empty_p (phi_nodes (phiblock)))
1788 bitmap_set_copy (dest, set);
1789 return;
1792 exprs = sorted_array_from_bitmap_set (set);
1793 FOR_EACH_VEC_ELT (exprs, i, expr)
1795 pre_expr translated;
1796 translated = phi_translate (expr, set, NULL, pred, phiblock);
1797 if (!translated)
1798 continue;
1800 /* We might end up with multiple expressions from SET being
1801 translated to the same value. In this case we do not want
1802 to retain the NARY or REFERENCE expression but prefer a NAME
1803 which would be the leader. */
1804 if (translated->kind == NAME)
1805 bitmap_value_replace_in_set (dest, translated);
1806 else
1807 bitmap_value_insert_into_set (dest, translated);
1809 exprs.release ();
1812 /* Find the leader for a value (i.e., the name representing that
1813 value) in a given set, and return it. Return NULL if no leader
1814 is found. */
1816 static pre_expr
1817 bitmap_find_leader (bitmap_set_t set, unsigned int val)
1819 if (value_id_constant_p (val))
1821 unsigned int i;
1822 bitmap_iterator bi;
1823 bitmap exprset = value_expressions[val];
1825 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
1827 pre_expr expr = expression_for_id (i);
1828 if (expr->kind == CONSTANT)
1829 return expr;
1832 if (bitmap_set_contains_value (set, val))
1834 /* Rather than walk the entire bitmap of expressions, and see
1835 whether any of them has the value we are looking for, we look
1836 at the reverse mapping, which tells us the set of expressions
1837 that have a given value (IE value->expressions with that
1838 value) and see if any of those expressions are in our set.
1839 The number of expressions per value is usually significantly
1840 less than the number of expressions in the set. In fact, for
1841 large testcases, doing it this way is roughly 5-10x faster
1842 than walking the bitmap.
1843 If this is somehow a significant lose for some cases, we can
1844 choose which set to walk based on which set is smaller. */
1845 unsigned int i;
1846 bitmap_iterator bi;
1847 bitmap exprset = value_expressions[val];
1849 EXECUTE_IF_AND_IN_BITMAP (exprset, &set->expressions, 0, i, bi)
1850 return expression_for_id (i);
1852 return NULL;
1855 /* Determine if EXPR, a memory expression, is ANTIC_IN at the top of
1856 BLOCK by seeing if it is not killed in the block. Note that we are
1857 only determining whether there is a store that kills it. Because
1858 of the order in which clean iterates over values, we are guaranteed
1859 that altered operands will have caused us to be eliminated from the
1860 ANTIC_IN set already. */
1862 static bool
1863 value_dies_in_block_x (pre_expr expr, basic_block block)
1865 tree vuse = PRE_EXPR_REFERENCE (expr)->vuse;
1866 vn_reference_t refx = PRE_EXPR_REFERENCE (expr);
1867 gimple def;
1868 gimple_stmt_iterator gsi;
1869 unsigned id = get_expression_id (expr);
1870 bool res = false;
1871 ao_ref ref;
1873 if (!vuse)
1874 return false;
1876 /* Lookup a previously calculated result. */
1877 if (EXPR_DIES (block)
1878 && bitmap_bit_p (EXPR_DIES (block), id * 2))
1879 return bitmap_bit_p (EXPR_DIES (block), id * 2 + 1);
1881 /* A memory expression {e, VUSE} dies in the block if there is a
1882 statement that may clobber e. If, starting statement walk from the
1883 top of the basic block, a statement uses VUSE there can be no kill
1884 inbetween that use and the original statement that loaded {e, VUSE},
1885 so we can stop walking. */
1886 ref.base = NULL_TREE;
1887 for (gsi = gsi_start_bb (block); !gsi_end_p (gsi); gsi_next (&gsi))
1889 tree def_vuse, def_vdef;
1890 def = gsi_stmt (gsi);
1891 def_vuse = gimple_vuse (def);
1892 def_vdef = gimple_vdef (def);
1894 /* Not a memory statement. */
1895 if (!def_vuse)
1896 continue;
1898 /* Not a may-def. */
1899 if (!def_vdef)
1901 /* A load with the same VUSE, we're done. */
1902 if (def_vuse == vuse)
1903 break;
1905 continue;
1908 /* Init ref only if we really need it. */
1909 if (ref.base == NULL_TREE
1910 && !ao_ref_init_from_vn_reference (&ref, refx->set, refx->type,
1911 refx->operands))
1913 res = true;
1914 break;
1916 /* If the statement may clobber expr, it dies. */
1917 if (stmt_may_clobber_ref_p_1 (def, &ref))
1919 res = true;
1920 break;
1924 /* Remember the result. */
1925 if (!EXPR_DIES (block))
1926 EXPR_DIES (block) = BITMAP_ALLOC (&grand_bitmap_obstack);
1927 bitmap_set_bit (EXPR_DIES (block), id * 2);
1928 if (res)
1929 bitmap_set_bit (EXPR_DIES (block), id * 2 + 1);
1931 return res;
1935 /* Determine if OP is valid in SET1 U SET2, which it is when the union
1936 contains its value-id. */
1938 static bool
1939 op_valid_in_sets (bitmap_set_t set1, bitmap_set_t set2, tree op)
1941 if (op && TREE_CODE (op) == SSA_NAME)
1943 unsigned int value_id = VN_INFO (op)->value_id;
1944 if (!(bitmap_set_contains_value (set1, value_id)
1945 || (set2 && bitmap_set_contains_value (set2, value_id))))
1946 return false;
1948 return true;
1951 /* Determine if the expression EXPR is valid in SET1 U SET2.
1952 ONLY SET2 CAN BE NULL.
1953 This means that we have a leader for each part of the expression
1954 (if it consists of values), or the expression is an SSA_NAME.
1955 For loads/calls, we also see if the vuse is killed in this block. */
1957 static bool
1958 valid_in_sets (bitmap_set_t set1, bitmap_set_t set2, pre_expr expr,
1959 basic_block block)
1961 switch (expr->kind)
1963 case NAME:
1964 return bitmap_find_leader (AVAIL_OUT (block),
1965 get_expr_value_id (expr)) != NULL;
1966 case NARY:
1968 unsigned int i;
1969 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1970 for (i = 0; i < nary->length; i++)
1971 if (!op_valid_in_sets (set1, set2, nary->op[i]))
1972 return false;
1973 return true;
1975 break;
1976 case REFERENCE:
1978 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1979 vn_reference_op_t vro;
1980 unsigned int i;
1982 FOR_EACH_VEC_ELT (ref->operands, i, vro)
1984 if (!op_valid_in_sets (set1, set2, vro->op0)
1985 || !op_valid_in_sets (set1, set2, vro->op1)
1986 || !op_valid_in_sets (set1, set2, vro->op2))
1987 return false;
1989 return true;
1991 default:
1992 gcc_unreachable ();
1996 /* Clean the set of expressions that are no longer valid in SET1 or
1997 SET2. This means expressions that are made up of values we have no
1998 leaders for in SET1 or SET2. This version is used for partial
1999 anticipation, which means it is not valid in either ANTIC_IN or
2000 PA_IN. */
2002 static void
2003 dependent_clean (bitmap_set_t set1, bitmap_set_t set2, basic_block block)
2005 vec<pre_expr> exprs = sorted_array_from_bitmap_set (set1);
2006 pre_expr expr;
2007 int i;
2009 FOR_EACH_VEC_ELT (exprs, i, expr)
2011 if (!valid_in_sets (set1, set2, expr, block))
2012 bitmap_remove_from_set (set1, expr);
2014 exprs.release ();
2017 /* Clean the set of expressions that are no longer valid in SET. This
2018 means expressions that are made up of values we have no leaders for
2019 in SET. */
2021 static void
2022 clean (bitmap_set_t set, basic_block block)
2024 vec<pre_expr> exprs = sorted_array_from_bitmap_set (set);
2025 pre_expr expr;
2026 int i;
2028 FOR_EACH_VEC_ELT (exprs, i, expr)
2030 if (!valid_in_sets (set, NULL, expr, block))
2031 bitmap_remove_from_set (set, expr);
2033 exprs.release ();
2036 /* Clean the set of expressions that are no longer valid in SET because
2037 they are clobbered in BLOCK or because they trap and may not be executed. */
2039 static void
2040 prune_clobbered_mems (bitmap_set_t set, basic_block block)
2042 bitmap_iterator bi;
2043 unsigned i;
2045 FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
2047 pre_expr expr = expression_for_id (i);
2048 if (expr->kind == REFERENCE)
2050 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
2051 if (ref->vuse)
2053 gimple def_stmt = SSA_NAME_DEF_STMT (ref->vuse);
2054 if (!gimple_nop_p (def_stmt)
2055 && ((gimple_bb (def_stmt) != block
2056 && !dominated_by_p (CDI_DOMINATORS,
2057 block, gimple_bb (def_stmt)))
2058 || (gimple_bb (def_stmt) == block
2059 && value_dies_in_block_x (expr, block))))
2060 bitmap_remove_from_set (set, expr);
2063 else if (expr->kind == NARY)
2065 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
2066 /* If the NARY may trap make sure the block does not contain
2067 a possible exit point.
2068 ??? This is overly conservative if we translate AVAIL_OUT
2069 as the available expression might be after the exit point. */
2070 if (BB_MAY_NOTRETURN (block)
2071 && vn_nary_may_trap (nary))
2072 bitmap_remove_from_set (set, expr);
2077 static sbitmap has_abnormal_preds;
2079 /* List of blocks that may have changed during ANTIC computation and
2080 thus need to be iterated over. */
2082 static sbitmap changed_blocks;
2084 /* Decide whether to defer a block for a later iteration, or PHI
2085 translate SOURCE to DEST using phis in PHIBLOCK. Return false if we
2086 should defer the block, and true if we processed it. */
2088 static bool
2089 defer_or_phi_translate_block (bitmap_set_t dest, bitmap_set_t source,
2090 basic_block block, basic_block phiblock)
2092 if (!BB_VISITED (phiblock))
2094 bitmap_set_bit (changed_blocks, block->index);
2095 BB_VISITED (block) = 0;
2096 BB_DEFERRED (block) = 1;
2097 return false;
2099 else
2100 phi_translate_set (dest, source, block, phiblock);
2101 return true;
2104 /* Compute the ANTIC set for BLOCK.
2106 If succs(BLOCK) > 1 then
2107 ANTIC_OUT[BLOCK] = intersection of ANTIC_IN[b] for all succ(BLOCK)
2108 else if succs(BLOCK) == 1 then
2109 ANTIC_OUT[BLOCK] = phi_translate (ANTIC_IN[succ(BLOCK)])
2111 ANTIC_IN[BLOCK] = clean(ANTIC_OUT[BLOCK] U EXP_GEN[BLOCK] - TMP_GEN[BLOCK])
2114 static bool
2115 compute_antic_aux (basic_block block, bool block_has_abnormal_pred_edge)
2117 bool changed = false;
2118 bitmap_set_t S, old, ANTIC_OUT;
2119 bitmap_iterator bi;
2120 unsigned int bii;
2121 edge e;
2122 edge_iterator ei;
2124 old = ANTIC_OUT = S = NULL;
2125 BB_VISITED (block) = 1;
2127 /* If any edges from predecessors are abnormal, antic_in is empty,
2128 so do nothing. */
2129 if (block_has_abnormal_pred_edge)
2130 goto maybe_dump_sets;
2132 old = ANTIC_IN (block);
2133 ANTIC_OUT = bitmap_set_new ();
2135 /* If the block has no successors, ANTIC_OUT is empty. */
2136 if (EDGE_COUNT (block->succs) == 0)
2138 /* If we have one successor, we could have some phi nodes to
2139 translate through. */
2140 else if (single_succ_p (block))
2142 basic_block succ_bb = single_succ (block);
2144 /* We trade iterations of the dataflow equations for having to
2145 phi translate the maximal set, which is incredibly slow
2146 (since the maximal set often has 300+ members, even when you
2147 have a small number of blocks).
2148 Basically, we defer the computation of ANTIC for this block
2149 until we have processed it's successor, which will inevitably
2150 have a *much* smaller set of values to phi translate once
2151 clean has been run on it.
2152 The cost of doing this is that we technically perform more
2153 iterations, however, they are lower cost iterations.
2155 Timings for PRE on tramp3d-v4:
2156 without maximal set fix: 11 seconds
2157 with maximal set fix/without deferring: 26 seconds
2158 with maximal set fix/with deferring: 11 seconds
2161 if (!defer_or_phi_translate_block (ANTIC_OUT, ANTIC_IN (succ_bb),
2162 block, succ_bb))
2164 changed = true;
2165 goto maybe_dump_sets;
2168 /* If we have multiple successors, we take the intersection of all of
2169 them. Note that in the case of loop exit phi nodes, we may have
2170 phis to translate through. */
2171 else
2173 vec<basic_block> worklist;
2174 size_t i;
2175 basic_block bprime, first = NULL;
2177 worklist.create (EDGE_COUNT (block->succs));
2178 FOR_EACH_EDGE (e, ei, block->succs)
2180 if (!first
2181 && BB_VISITED (e->dest))
2182 first = e->dest;
2183 else if (BB_VISITED (e->dest))
2184 worklist.quick_push (e->dest);
2187 /* Of multiple successors we have to have visited one already. */
2188 if (!first)
2190 bitmap_set_bit (changed_blocks, block->index);
2191 BB_VISITED (block) = 0;
2192 BB_DEFERRED (block) = 1;
2193 changed = true;
2194 worklist.release ();
2195 goto maybe_dump_sets;
2198 if (!gimple_seq_empty_p (phi_nodes (first)))
2199 phi_translate_set (ANTIC_OUT, ANTIC_IN (first), block, first);
2200 else
2201 bitmap_set_copy (ANTIC_OUT, ANTIC_IN (first));
2203 FOR_EACH_VEC_ELT (worklist, i, bprime)
2205 if (!gimple_seq_empty_p (phi_nodes (bprime)))
2207 bitmap_set_t tmp = bitmap_set_new ();
2208 phi_translate_set (tmp, ANTIC_IN (bprime), block, bprime);
2209 bitmap_set_and (ANTIC_OUT, tmp);
2210 bitmap_set_free (tmp);
2212 else
2213 bitmap_set_and (ANTIC_OUT, ANTIC_IN (bprime));
2215 worklist.release ();
2218 /* Prune expressions that are clobbered in block and thus become
2219 invalid if translated from ANTIC_OUT to ANTIC_IN. */
2220 prune_clobbered_mems (ANTIC_OUT, block);
2222 /* Generate ANTIC_OUT - TMP_GEN. */
2223 S = bitmap_set_subtract (ANTIC_OUT, TMP_GEN (block));
2225 /* Start ANTIC_IN with EXP_GEN - TMP_GEN. */
2226 ANTIC_IN (block) = bitmap_set_subtract (EXP_GEN (block),
2227 TMP_GEN (block));
2229 /* Then union in the ANTIC_OUT - TMP_GEN values,
2230 to get ANTIC_OUT U EXP_GEN - TMP_GEN */
2231 FOR_EACH_EXPR_ID_IN_SET (S, bii, bi)
2232 bitmap_value_insert_into_set (ANTIC_IN (block),
2233 expression_for_id (bii));
2235 clean (ANTIC_IN (block), block);
2237 if (!bitmap_set_equal (old, ANTIC_IN (block)))
2239 changed = true;
2240 bitmap_set_bit (changed_blocks, block->index);
2241 FOR_EACH_EDGE (e, ei, block->preds)
2242 bitmap_set_bit (changed_blocks, e->src->index);
2244 else
2245 bitmap_clear_bit (changed_blocks, block->index);
2247 maybe_dump_sets:
2248 if (dump_file && (dump_flags & TDF_DETAILS))
2250 if (!BB_DEFERRED (block) || BB_VISITED (block))
2252 if (ANTIC_OUT)
2253 print_bitmap_set (dump_file, ANTIC_OUT, "ANTIC_OUT", block->index);
2255 print_bitmap_set (dump_file, ANTIC_IN (block), "ANTIC_IN",
2256 block->index);
2258 if (S)
2259 print_bitmap_set (dump_file, S, "S", block->index);
2261 else
2263 fprintf (dump_file,
2264 "Block %d was deferred for a future iteration.\n",
2265 block->index);
2268 if (old)
2269 bitmap_set_free (old);
2270 if (S)
2271 bitmap_set_free (S);
2272 if (ANTIC_OUT)
2273 bitmap_set_free (ANTIC_OUT);
2274 return changed;
2277 /* Compute PARTIAL_ANTIC for BLOCK.
2279 If succs(BLOCK) > 1 then
2280 PA_OUT[BLOCK] = value wise union of PA_IN[b] + all ANTIC_IN not
2281 in ANTIC_OUT for all succ(BLOCK)
2282 else if succs(BLOCK) == 1 then
2283 PA_OUT[BLOCK] = phi_translate (PA_IN[succ(BLOCK)])
2285 PA_IN[BLOCK] = dependent_clean(PA_OUT[BLOCK] - TMP_GEN[BLOCK]
2286 - ANTIC_IN[BLOCK])
2289 static bool
2290 compute_partial_antic_aux (basic_block block,
2291 bool block_has_abnormal_pred_edge)
2293 bool changed = false;
2294 bitmap_set_t old_PA_IN;
2295 bitmap_set_t PA_OUT;
2296 edge e;
2297 edge_iterator ei;
2298 unsigned long max_pa = PARAM_VALUE (PARAM_MAX_PARTIAL_ANTIC_LENGTH);
2300 old_PA_IN = PA_OUT = NULL;
2302 /* If any edges from predecessors are abnormal, antic_in is empty,
2303 so do nothing. */
2304 if (block_has_abnormal_pred_edge)
2305 goto maybe_dump_sets;
2307 /* If there are too many partially anticipatable values in the
2308 block, phi_translate_set can take an exponential time: stop
2309 before the translation starts. */
2310 if (max_pa
2311 && single_succ_p (block)
2312 && bitmap_count_bits (&PA_IN (single_succ (block))->values) > max_pa)
2313 goto maybe_dump_sets;
2315 old_PA_IN = PA_IN (block);
2316 PA_OUT = bitmap_set_new ();
2318 /* If the block has no successors, ANTIC_OUT is empty. */
2319 if (EDGE_COUNT (block->succs) == 0)
2321 /* If we have one successor, we could have some phi nodes to
2322 translate through. Note that we can't phi translate across DFS
2323 back edges in partial antic, because it uses a union operation on
2324 the successors. For recurrences like IV's, we will end up
2325 generating a new value in the set on each go around (i + 3 (VH.1)
2326 VH.1 + 1 (VH.2), VH.2 + 1 (VH.3), etc), forever. */
2327 else if (single_succ_p (block))
2329 basic_block succ = single_succ (block);
2330 if (!(single_succ_edge (block)->flags & EDGE_DFS_BACK))
2331 phi_translate_set (PA_OUT, PA_IN (succ), block, succ);
2333 /* If we have multiple successors, we take the union of all of
2334 them. */
2335 else
2337 vec<basic_block> worklist;
2338 size_t i;
2339 basic_block bprime;
2341 worklist.create (EDGE_COUNT (block->succs));
2342 FOR_EACH_EDGE (e, ei, block->succs)
2344 if (e->flags & EDGE_DFS_BACK)
2345 continue;
2346 worklist.quick_push (e->dest);
2348 if (worklist.length () > 0)
2350 FOR_EACH_VEC_ELT (worklist, i, bprime)
2352 unsigned int i;
2353 bitmap_iterator bi;
2355 FOR_EACH_EXPR_ID_IN_SET (ANTIC_IN (bprime), i, bi)
2356 bitmap_value_insert_into_set (PA_OUT,
2357 expression_for_id (i));
2358 if (!gimple_seq_empty_p (phi_nodes (bprime)))
2360 bitmap_set_t pa_in = bitmap_set_new ();
2361 phi_translate_set (pa_in, PA_IN (bprime), block, bprime);
2362 FOR_EACH_EXPR_ID_IN_SET (pa_in, i, bi)
2363 bitmap_value_insert_into_set (PA_OUT,
2364 expression_for_id (i));
2365 bitmap_set_free (pa_in);
2367 else
2368 FOR_EACH_EXPR_ID_IN_SET (PA_IN (bprime), i, bi)
2369 bitmap_value_insert_into_set (PA_OUT,
2370 expression_for_id (i));
2373 worklist.release ();
2376 /* Prune expressions that are clobbered in block and thus become
2377 invalid if translated from PA_OUT to PA_IN. */
2378 prune_clobbered_mems (PA_OUT, block);
2380 /* PA_IN starts with PA_OUT - TMP_GEN.
2381 Then we subtract things from ANTIC_IN. */
2382 PA_IN (block) = bitmap_set_subtract (PA_OUT, TMP_GEN (block));
2384 /* For partial antic, we want to put back in the phi results, since
2385 we will properly avoid making them partially antic over backedges. */
2386 bitmap_ior_into (&PA_IN (block)->values, &PHI_GEN (block)->values);
2387 bitmap_ior_into (&PA_IN (block)->expressions, &PHI_GEN (block)->expressions);
2389 /* PA_IN[block] = PA_IN[block] - ANTIC_IN[block] */
2390 bitmap_set_subtract_values (PA_IN (block), ANTIC_IN (block));
2392 dependent_clean (PA_IN (block), ANTIC_IN (block), block);
2394 if (!bitmap_set_equal (old_PA_IN, PA_IN (block)))
2396 changed = true;
2397 bitmap_set_bit (changed_blocks, block->index);
2398 FOR_EACH_EDGE (e, ei, block->preds)
2399 bitmap_set_bit (changed_blocks, e->src->index);
2401 else
2402 bitmap_clear_bit (changed_blocks, block->index);
2404 maybe_dump_sets:
2405 if (dump_file && (dump_flags & TDF_DETAILS))
2407 if (PA_OUT)
2408 print_bitmap_set (dump_file, PA_OUT, "PA_OUT", block->index);
2410 print_bitmap_set (dump_file, PA_IN (block), "PA_IN", block->index);
2412 if (old_PA_IN)
2413 bitmap_set_free (old_PA_IN);
2414 if (PA_OUT)
2415 bitmap_set_free (PA_OUT);
2416 return changed;
2419 /* Compute ANTIC and partial ANTIC sets. */
2421 static void
2422 compute_antic (void)
2424 bool changed = true;
2425 int num_iterations = 0;
2426 basic_block block;
2427 int i;
2429 /* If any predecessor edges are abnormal, we punt, so antic_in is empty.
2430 We pre-build the map of blocks with incoming abnormal edges here. */
2431 has_abnormal_preds = sbitmap_alloc (last_basic_block);
2432 bitmap_clear (has_abnormal_preds);
2434 FOR_ALL_BB (block)
2436 edge_iterator ei;
2437 edge e;
2439 FOR_EACH_EDGE (e, ei, block->preds)
2441 e->flags &= ~EDGE_DFS_BACK;
2442 if (e->flags & EDGE_ABNORMAL)
2444 bitmap_set_bit (has_abnormal_preds, block->index);
2445 break;
2449 BB_VISITED (block) = 0;
2450 BB_DEFERRED (block) = 0;
2452 /* While we are here, give empty ANTIC_IN sets to each block. */
2453 ANTIC_IN (block) = bitmap_set_new ();
2454 PA_IN (block) = bitmap_set_new ();
2457 /* At the exit block we anticipate nothing. */
2458 BB_VISITED (EXIT_BLOCK_PTR) = 1;
2460 changed_blocks = sbitmap_alloc (last_basic_block + 1);
2461 bitmap_ones (changed_blocks);
2462 while (changed)
2464 if (dump_file && (dump_flags & TDF_DETAILS))
2465 fprintf (dump_file, "Starting iteration %d\n", num_iterations);
2466 /* ??? We need to clear our PHI translation cache here as the
2467 ANTIC sets shrink and we restrict valid translations to
2468 those having operands with leaders in ANTIC. Same below
2469 for PA ANTIC computation. */
2470 num_iterations++;
2471 changed = false;
2472 for (i = postorder_num - 1; i >= 0; i--)
2474 if (bitmap_bit_p (changed_blocks, postorder[i]))
2476 basic_block block = BASIC_BLOCK (postorder[i]);
2477 changed |= compute_antic_aux (block,
2478 bitmap_bit_p (has_abnormal_preds,
2479 block->index));
2482 /* Theoretically possible, but *highly* unlikely. */
2483 gcc_checking_assert (num_iterations < 500);
2486 statistics_histogram_event (cfun, "compute_antic iterations",
2487 num_iterations);
2489 if (do_partial_partial)
2491 bitmap_ones (changed_blocks);
2492 mark_dfs_back_edges ();
2493 num_iterations = 0;
2494 changed = true;
2495 while (changed)
2497 if (dump_file && (dump_flags & TDF_DETAILS))
2498 fprintf (dump_file, "Starting iteration %d\n", num_iterations);
2499 num_iterations++;
2500 changed = false;
2501 for (i = postorder_num - 1 ; i >= 0; i--)
2503 if (bitmap_bit_p (changed_blocks, postorder[i]))
2505 basic_block block = BASIC_BLOCK (postorder[i]);
2506 changed
2507 |= compute_partial_antic_aux (block,
2508 bitmap_bit_p (has_abnormal_preds,
2509 block->index));
2512 /* Theoretically possible, but *highly* unlikely. */
2513 gcc_checking_assert (num_iterations < 500);
2515 statistics_histogram_event (cfun, "compute_partial_antic iterations",
2516 num_iterations);
2518 sbitmap_free (has_abnormal_preds);
2519 sbitmap_free (changed_blocks);
2523 /* Inserted expressions are placed onto this worklist, which is used
2524 for performing quick dead code elimination of insertions we made
2525 that didn't turn out to be necessary. */
2526 static bitmap inserted_exprs;
2528 /* The actual worker for create_component_ref_by_pieces. */
2530 static tree
2531 create_component_ref_by_pieces_1 (basic_block block, vn_reference_t ref,
2532 unsigned int *operand, gimple_seq *stmts)
2534 vn_reference_op_t currop = &ref->operands[*operand];
2535 tree genop;
2536 ++*operand;
2537 switch (currop->opcode)
2539 case CALL_EXPR:
2541 tree folded, sc = NULL_TREE;
2542 unsigned int nargs = 0;
2543 tree fn, *args;
2544 if (TREE_CODE (currop->op0) == FUNCTION_DECL)
2545 fn = currop->op0;
2546 else
2547 fn = find_or_generate_expression (block, currop->op0, stmts);
2548 if (!fn)
2549 return NULL_TREE;
2550 if (currop->op1)
2552 sc = find_or_generate_expression (block, currop->op1, stmts);
2553 if (!sc)
2554 return NULL_TREE;
2556 args = XNEWVEC (tree, ref->operands.length () - 1);
2557 while (*operand < ref->operands.length ())
2559 args[nargs] = create_component_ref_by_pieces_1 (block, ref,
2560 operand, stmts);
2561 if (!args[nargs])
2562 return NULL_TREE;
2563 nargs++;
2565 folded = build_call_array (currop->type,
2566 (TREE_CODE (fn) == FUNCTION_DECL
2567 ? build_fold_addr_expr (fn) : fn),
2568 nargs, args);
2569 free (args);
2570 if (sc)
2571 CALL_EXPR_STATIC_CHAIN (folded) = sc;
2572 return folded;
2575 case MEM_REF:
2577 tree baseop = create_component_ref_by_pieces_1 (block, ref, operand,
2578 stmts);
2579 if (!baseop)
2580 return NULL_TREE;
2581 tree offset = currop->op0;
2582 if (TREE_CODE (baseop) == ADDR_EXPR
2583 && handled_component_p (TREE_OPERAND (baseop, 0)))
2585 HOST_WIDE_INT off;
2586 tree base;
2587 base = get_addr_base_and_unit_offset (TREE_OPERAND (baseop, 0),
2588 &off);
2589 gcc_assert (base);
2590 offset = int_const_binop (PLUS_EXPR, offset,
2591 build_int_cst (TREE_TYPE (offset),
2592 off));
2593 baseop = build_fold_addr_expr (base);
2595 return fold_build2 (MEM_REF, currop->type, baseop, offset);
2598 case TARGET_MEM_REF:
2600 tree genop0 = NULL_TREE, genop1 = NULL_TREE;
2601 vn_reference_op_t nextop = &ref->operands[++*operand];
2602 tree baseop = create_component_ref_by_pieces_1 (block, ref, operand,
2603 stmts);
2604 if (!baseop)
2605 return NULL_TREE;
2606 if (currop->op0)
2608 genop0 = find_or_generate_expression (block, currop->op0, stmts);
2609 if (!genop0)
2610 return NULL_TREE;
2612 if (nextop->op0)
2614 genop1 = find_or_generate_expression (block, nextop->op0, stmts);
2615 if (!genop1)
2616 return NULL_TREE;
2618 return build5 (TARGET_MEM_REF, currop->type,
2619 baseop, currop->op2, genop0, currop->op1, genop1);
2622 case ADDR_EXPR:
2623 if (currop->op0)
2625 gcc_assert (is_gimple_min_invariant (currop->op0));
2626 return currop->op0;
2628 /* Fallthrough. */
2629 case REALPART_EXPR:
2630 case IMAGPART_EXPR:
2631 case VIEW_CONVERT_EXPR:
2633 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2634 stmts);
2635 if (!genop0)
2636 return NULL_TREE;
2637 return fold_build1 (currop->opcode, currop->type, genop0);
2640 case WITH_SIZE_EXPR:
2642 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2643 stmts);
2644 if (!genop0)
2645 return NULL_TREE;
2646 tree genop1 = find_or_generate_expression (block, currop->op0, stmts);
2647 if (!genop1)
2648 return NULL_TREE;
2649 return fold_build2 (currop->opcode, currop->type, genop0, genop1);
2652 case BIT_FIELD_REF:
2654 tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2655 stmts);
2656 if (!genop0)
2657 return NULL_TREE;
2658 tree op1 = currop->op0;
2659 tree op2 = currop->op1;
2660 return fold_build3 (BIT_FIELD_REF, currop->type, genop0, op1, op2);
2663 /* For array ref vn_reference_op's, operand 1 of the array ref
2664 is op0 of the reference op and operand 3 of the array ref is
2665 op1. */
2666 case ARRAY_RANGE_REF:
2667 case ARRAY_REF:
2669 tree genop0;
2670 tree genop1 = currop->op0;
2671 tree genop2 = currop->op1;
2672 tree genop3 = currop->op2;
2673 genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2674 stmts);
2675 if (!genop0)
2676 return NULL_TREE;
2677 genop1 = find_or_generate_expression (block, genop1, stmts);
2678 if (!genop1)
2679 return NULL_TREE;
2680 if (genop2)
2682 tree domain_type = TYPE_DOMAIN (TREE_TYPE (genop0));
2683 /* Drop zero minimum index if redundant. */
2684 if (integer_zerop (genop2)
2685 && (!domain_type
2686 || integer_zerop (TYPE_MIN_VALUE (domain_type))))
2687 genop2 = NULL_TREE;
2688 else
2690 genop2 = find_or_generate_expression (block, genop2, stmts);
2691 if (!genop2)
2692 return NULL_TREE;
2695 if (genop3)
2697 tree elmt_type = TREE_TYPE (TREE_TYPE (genop0));
2698 /* We can't always put a size in units of the element alignment
2699 here as the element alignment may be not visible. See
2700 PR43783. Simply drop the element size for constant
2701 sizes. */
2702 if (tree_int_cst_equal (genop3, TYPE_SIZE_UNIT (elmt_type)))
2703 genop3 = NULL_TREE;
2704 else
2706 genop3 = size_binop (EXACT_DIV_EXPR, genop3,
2707 size_int (TYPE_ALIGN_UNIT (elmt_type)));
2708 genop3 = find_or_generate_expression (block, genop3, stmts);
2709 if (!genop3)
2710 return NULL_TREE;
2713 return build4 (currop->opcode, currop->type, genop0, genop1,
2714 genop2, genop3);
2716 case COMPONENT_REF:
2718 tree op0;
2719 tree op1;
2720 tree genop2 = currop->op1;
2721 op0 = create_component_ref_by_pieces_1 (block, ref, operand, stmts);
2722 if (!op0)
2723 return NULL_TREE;
2724 /* op1 should be a FIELD_DECL, which are represented by themselves. */
2725 op1 = currop->op0;
2726 if (genop2)
2728 genop2 = find_or_generate_expression (block, genop2, stmts);
2729 if (!genop2)
2730 return NULL_TREE;
2732 return fold_build3 (COMPONENT_REF, TREE_TYPE (op1), op0, op1, genop2);
2735 case SSA_NAME:
2737 genop = find_or_generate_expression (block, currop->op0, stmts);
2738 return genop;
2740 case STRING_CST:
2741 case INTEGER_CST:
2742 case COMPLEX_CST:
2743 case VECTOR_CST:
2744 case REAL_CST:
2745 case CONSTRUCTOR:
2746 case VAR_DECL:
2747 case PARM_DECL:
2748 case CONST_DECL:
2749 case RESULT_DECL:
2750 case FUNCTION_DECL:
2751 return currop->op0;
2753 default:
2754 gcc_unreachable ();
2758 /* For COMPONENT_REF's and ARRAY_REF's, we can't have any intermediates for the
2759 COMPONENT_REF or MEM_REF or ARRAY_REF portion, because we'd end up with
2760 trying to rename aggregates into ssa form directly, which is a no no.
2762 Thus, this routine doesn't create temporaries, it just builds a
2763 single access expression for the array, calling
2764 find_or_generate_expression to build the innermost pieces.
2766 This function is a subroutine of create_expression_by_pieces, and
2767 should not be called on it's own unless you really know what you
2768 are doing. */
2770 static tree
2771 create_component_ref_by_pieces (basic_block block, vn_reference_t ref,
2772 gimple_seq *stmts)
2774 unsigned int op = 0;
2775 return create_component_ref_by_pieces_1 (block, ref, &op, stmts);
2778 /* Find a simple leader for an expression, or generate one using
2779 create_expression_by_pieces from a NARY expression for the value.
2780 BLOCK is the basic_block we are looking for leaders in.
2781 OP is the tree expression to find a leader for or generate.
2782 Returns the leader or NULL_TREE on failure. */
2784 static tree
2785 find_or_generate_expression (basic_block block, tree op, gimple_seq *stmts)
2787 pre_expr expr = get_or_alloc_expr_for (op);
2788 unsigned int lookfor = get_expr_value_id (expr);
2789 pre_expr leader = bitmap_find_leader (AVAIL_OUT (block), lookfor);
2790 if (leader)
2792 if (leader->kind == NAME)
2793 return PRE_EXPR_NAME (leader);
2794 else if (leader->kind == CONSTANT)
2795 return PRE_EXPR_CONSTANT (leader);
2797 /* Defer. */
2798 return NULL_TREE;
2801 /* It must be a complex expression, so generate it recursively. Note
2802 that this is only necessary to handle gcc.dg/tree-ssa/ssa-pre28.c
2803 where the insert algorithm fails to insert a required expression. */
2804 bitmap exprset = value_expressions[lookfor];
2805 bitmap_iterator bi;
2806 unsigned int i;
2807 EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
2809 pre_expr temp = expression_for_id (i);
2810 /* We cannot insert random REFERENCE expressions at arbitrary
2811 places. We can insert NARYs which eventually re-materializes
2812 its operand values. */
2813 if (temp->kind == NARY)
2814 return create_expression_by_pieces (block, temp, stmts,
2815 get_expr_type (expr));
2818 /* Defer. */
2819 return NULL_TREE;
2822 #define NECESSARY GF_PLF_1
2824 /* Create an expression in pieces, so that we can handle very complex
2825 expressions that may be ANTIC, but not necessary GIMPLE.
2826 BLOCK is the basic block the expression will be inserted into,
2827 EXPR is the expression to insert (in value form)
2828 STMTS is a statement list to append the necessary insertions into.
2830 This function will die if we hit some value that shouldn't be
2831 ANTIC but is (IE there is no leader for it, or its components).
2832 The function returns NULL_TREE in case a different antic expression
2833 has to be inserted first.
2834 This function may also generate expressions that are themselves
2835 partially or fully redundant. Those that are will be either made
2836 fully redundant during the next iteration of insert (for partially
2837 redundant ones), or eliminated by eliminate (for fully redundant
2838 ones). */
2840 static tree
2841 create_expression_by_pieces (basic_block block, pre_expr expr,
2842 gimple_seq *stmts, tree type)
2844 tree name;
2845 tree folded;
2846 gimple_seq forced_stmts = NULL;
2847 unsigned int value_id;
2848 gimple_stmt_iterator gsi;
2849 tree exprtype = type ? type : get_expr_type (expr);
2850 pre_expr nameexpr;
2851 gimple newstmt;
2853 switch (expr->kind)
2855 /* We may hit the NAME/CONSTANT case if we have to convert types
2856 that value numbering saw through. */
2857 case NAME:
2858 folded = PRE_EXPR_NAME (expr);
2859 break;
2860 case CONSTANT:
2861 folded = PRE_EXPR_CONSTANT (expr);
2862 break;
2863 case REFERENCE:
2865 vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
2866 folded = create_component_ref_by_pieces (block, ref, stmts);
2867 if (!folded)
2868 return NULL_TREE;
2870 break;
2871 case NARY:
2873 vn_nary_op_t nary = PRE_EXPR_NARY (expr);
2874 tree *genop = XALLOCAVEC (tree, nary->length);
2875 unsigned i;
2876 for (i = 0; i < nary->length; ++i)
2878 genop[i] = find_or_generate_expression (block, nary->op[i], stmts);
2879 if (!genop[i])
2880 return NULL_TREE;
2881 /* Ensure genop[] is properly typed for POINTER_PLUS_EXPR. It
2882 may have conversions stripped. */
2883 if (nary->opcode == POINTER_PLUS_EXPR)
2885 if (i == 0)
2886 genop[i] = fold_convert (nary->type, genop[i]);
2887 else if (i == 1)
2888 genop[i] = convert_to_ptrofftype (genop[i]);
2890 else
2891 genop[i] = fold_convert (TREE_TYPE (nary->op[i]), genop[i]);
2893 if (nary->opcode == CONSTRUCTOR)
2895 vec<constructor_elt, va_gc> *elts = NULL;
2896 for (i = 0; i < nary->length; ++i)
2897 CONSTRUCTOR_APPEND_ELT (elts, NULL_TREE, genop[i]);
2898 folded = build_constructor (nary->type, elts);
2900 else
2902 switch (nary->length)
2904 case 1:
2905 folded = fold_build1 (nary->opcode, nary->type,
2906 genop[0]);
2907 break;
2908 case 2:
2909 folded = fold_build2 (nary->opcode, nary->type,
2910 genop[0], genop[1]);
2911 break;
2912 case 3:
2913 folded = fold_build3 (nary->opcode, nary->type,
2914 genop[0], genop[1], genop[2]);
2915 break;
2916 default:
2917 gcc_unreachable ();
2921 break;
2922 default:
2923 gcc_unreachable ();
2926 if (!useless_type_conversion_p (exprtype, TREE_TYPE (folded)))
2927 folded = fold_convert (exprtype, folded);
2929 /* Force the generated expression to be a sequence of GIMPLE
2930 statements.
2931 We have to call unshare_expr because force_gimple_operand may
2932 modify the tree we pass to it. */
2933 folded = force_gimple_operand (unshare_expr (folded), &forced_stmts,
2934 false, NULL);
2936 /* If we have any intermediate expressions to the value sets, add them
2937 to the value sets and chain them in the instruction stream. */
2938 if (forced_stmts)
2940 gsi = gsi_start (forced_stmts);
2941 for (; !gsi_end_p (gsi); gsi_next (&gsi))
2943 gimple stmt = gsi_stmt (gsi);
2944 tree forcedname = gimple_get_lhs (stmt);
2945 pre_expr nameexpr;
2947 if (TREE_CODE (forcedname) == SSA_NAME)
2949 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (forcedname));
2950 VN_INFO_GET (forcedname)->valnum = forcedname;
2951 VN_INFO (forcedname)->value_id = get_next_value_id ();
2952 nameexpr = get_or_alloc_expr_for_name (forcedname);
2953 add_to_value (VN_INFO (forcedname)->value_id, nameexpr);
2954 bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
2955 bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
2958 gimple_seq_add_seq (stmts, forced_stmts);
2961 name = make_temp_ssa_name (exprtype, NULL, "pretmp");
2962 newstmt = gimple_build_assign (name, folded);
2963 gimple_set_plf (newstmt, NECESSARY, false);
2965 gimple_seq_add_stmt (stmts, newstmt);
2966 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (name));
2968 /* Fold the last statement. */
2969 gsi = gsi_last (*stmts);
2970 if (fold_stmt_inplace (&gsi))
2971 update_stmt (gsi_stmt (gsi));
2973 /* Add a value number to the temporary.
2974 The value may already exist in either NEW_SETS, or AVAIL_OUT, because
2975 we are creating the expression by pieces, and this particular piece of
2976 the expression may have been represented. There is no harm in replacing
2977 here. */
2978 value_id = get_expr_value_id (expr);
2979 VN_INFO_GET (name)->value_id = value_id;
2980 VN_INFO (name)->valnum = sccvn_valnum_from_value_id (value_id);
2981 if (VN_INFO (name)->valnum == NULL_TREE)
2982 VN_INFO (name)->valnum = name;
2983 gcc_assert (VN_INFO (name)->valnum != NULL_TREE);
2984 nameexpr = get_or_alloc_expr_for_name (name);
2985 add_to_value (value_id, nameexpr);
2986 if (NEW_SETS (block))
2987 bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
2988 bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
2990 pre_stats.insertions++;
2991 if (dump_file && (dump_flags & TDF_DETAILS))
2993 fprintf (dump_file, "Inserted ");
2994 print_gimple_stmt (dump_file, newstmt, 0, 0);
2995 fprintf (dump_file, " in predecessor %d (%04d)\n",
2996 block->index, value_id);
2999 return name;
3003 /* Returns true if we want to inhibit the insertions of PHI nodes
3004 for the given EXPR for basic block BB (a member of a loop).
3005 We want to do this, when we fear that the induction variable we
3006 create might inhibit vectorization. */
3008 static bool
3009 inhibit_phi_insertion (basic_block bb, pre_expr expr)
3011 vn_reference_t vr = PRE_EXPR_REFERENCE (expr);
3012 vec<vn_reference_op_s> ops = vr->operands;
3013 vn_reference_op_t op;
3014 unsigned i;
3016 /* If we aren't going to vectorize we don't inhibit anything. */
3017 if (!flag_tree_loop_vectorize)
3018 return false;
3020 /* Otherwise we inhibit the insertion when the address of the
3021 memory reference is a simple induction variable. In other
3022 cases the vectorizer won't do anything anyway (either it's
3023 loop invariant or a complicated expression). */
3024 FOR_EACH_VEC_ELT (ops, i, op)
3026 switch (op->opcode)
3028 case CALL_EXPR:
3029 /* Calls are not a problem. */
3030 return false;
3032 case ARRAY_REF:
3033 case ARRAY_RANGE_REF:
3034 if (TREE_CODE (op->op0) != SSA_NAME)
3035 break;
3036 /* Fallthru. */
3037 case SSA_NAME:
3039 basic_block defbb = gimple_bb (SSA_NAME_DEF_STMT (op->op0));
3040 affine_iv iv;
3041 /* Default defs are loop invariant. */
3042 if (!defbb)
3043 break;
3044 /* Defined outside this loop, also loop invariant. */
3045 if (!flow_bb_inside_loop_p (bb->loop_father, defbb))
3046 break;
3047 /* If it's a simple induction variable inhibit insertion,
3048 the vectorizer might be interested in this one. */
3049 if (simple_iv (bb->loop_father, bb->loop_father,
3050 op->op0, &iv, true))
3051 return true;
3052 /* No simple IV, vectorizer can't do anything, hence no
3053 reason to inhibit the transformation for this operand. */
3054 break;
3056 default:
3057 break;
3060 return false;
3063 /* Insert the to-be-made-available values of expression EXPRNUM for each
3064 predecessor, stored in AVAIL, into the predecessors of BLOCK, and
3065 merge the result with a phi node, given the same value number as
3066 NODE. Return true if we have inserted new stuff. */
3068 static bool
3069 insert_into_preds_of_block (basic_block block, unsigned int exprnum,
3070 vec<pre_expr> avail)
3072 pre_expr expr = expression_for_id (exprnum);
3073 pre_expr newphi;
3074 unsigned int val = get_expr_value_id (expr);
3075 edge pred;
3076 bool insertions = false;
3077 bool nophi = false;
3078 basic_block bprime;
3079 pre_expr eprime;
3080 edge_iterator ei;
3081 tree type = get_expr_type (expr);
3082 tree temp;
3083 gimple phi;
3085 /* Make sure we aren't creating an induction variable. */
3086 if (bb_loop_depth (block) > 0 && EDGE_COUNT (block->preds) == 2)
3088 bool firstinsideloop = false;
3089 bool secondinsideloop = false;
3090 firstinsideloop = flow_bb_inside_loop_p (block->loop_father,
3091 EDGE_PRED (block, 0)->src);
3092 secondinsideloop = flow_bb_inside_loop_p (block->loop_father,
3093 EDGE_PRED (block, 1)->src);
3094 /* Induction variables only have one edge inside the loop. */
3095 if ((firstinsideloop ^ secondinsideloop)
3096 && (expr->kind != REFERENCE
3097 || inhibit_phi_insertion (block, expr)))
3099 if (dump_file && (dump_flags & TDF_DETAILS))
3100 fprintf (dump_file, "Skipping insertion of phi for partial redundancy: Looks like an induction variable\n");
3101 nophi = true;
3105 /* Make the necessary insertions. */
3106 FOR_EACH_EDGE (pred, ei, block->preds)
3108 gimple_seq stmts = NULL;
3109 tree builtexpr;
3110 bprime = pred->src;
3111 eprime = avail[pred->dest_idx];
3113 if (eprime->kind != NAME && eprime->kind != CONSTANT)
3115 builtexpr = create_expression_by_pieces (bprime, eprime,
3116 &stmts, type);
3117 gcc_assert (!(pred->flags & EDGE_ABNORMAL));
3118 gsi_insert_seq_on_edge (pred, stmts);
3119 if (!builtexpr)
3121 /* We cannot insert a PHI node if we failed to insert
3122 on one edge. */
3123 nophi = true;
3124 continue;
3126 avail[pred->dest_idx] = get_or_alloc_expr_for_name (builtexpr);
3127 insertions = true;
3129 else if (eprime->kind == CONSTANT)
3131 /* Constants may not have the right type, fold_convert
3132 should give us back a constant with the right type. */
3133 tree constant = PRE_EXPR_CONSTANT (eprime);
3134 if (!useless_type_conversion_p (type, TREE_TYPE (constant)))
3136 tree builtexpr = fold_convert (type, constant);
3137 if (!is_gimple_min_invariant (builtexpr))
3139 tree forcedexpr = force_gimple_operand (builtexpr,
3140 &stmts, true,
3141 NULL);
3142 if (!is_gimple_min_invariant (forcedexpr))
3144 if (forcedexpr != builtexpr)
3146 VN_INFO_GET (forcedexpr)->valnum = PRE_EXPR_CONSTANT (eprime);
3147 VN_INFO (forcedexpr)->value_id = get_expr_value_id (eprime);
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,
3159 SSA_NAME_VERSION (lhs));
3160 gimple_set_plf (stmt, NECESSARY, false);
3162 gsi_insert_seq_on_edge (pred, stmts);
3164 avail[pred->dest_idx]
3165 = get_or_alloc_expr_for_name (forcedexpr);
3168 else
3169 avail[pred->dest_idx]
3170 = get_or_alloc_expr_for_constant (builtexpr);
3173 else if (eprime->kind == NAME)
3175 /* We may have to do a conversion because our value
3176 numbering can look through types in certain cases, but
3177 our IL requires all operands of a phi node have the same
3178 type. */
3179 tree name = PRE_EXPR_NAME (eprime);
3180 if (!useless_type_conversion_p (type, TREE_TYPE (name)))
3182 tree builtexpr;
3183 tree forcedexpr;
3184 builtexpr = fold_convert (type, name);
3185 forcedexpr = force_gimple_operand (builtexpr,
3186 &stmts, true,
3187 NULL);
3189 if (forcedexpr != name)
3191 VN_INFO_GET (forcedexpr)->valnum = VN_INFO (name)->valnum;
3192 VN_INFO (forcedexpr)->value_id = VN_INFO (name)->value_id;
3195 if (stmts)
3197 gimple_stmt_iterator gsi;
3198 gsi = gsi_start (stmts);
3199 for (; !gsi_end_p (gsi); gsi_next (&gsi))
3201 gimple stmt = gsi_stmt (gsi);
3202 tree lhs = gimple_get_lhs (stmt);
3203 if (TREE_CODE (lhs) == SSA_NAME)
3204 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (lhs));
3205 gimple_set_plf (stmt, NECESSARY, false);
3207 gsi_insert_seq_on_edge (pred, stmts);
3209 avail[pred->dest_idx] = get_or_alloc_expr_for_name (forcedexpr);
3213 /* If we didn't want a phi node, and we made insertions, we still have
3214 inserted new stuff, and thus return true. If we didn't want a phi node,
3215 and didn't make insertions, we haven't added anything new, so return
3216 false. */
3217 if (nophi && insertions)
3218 return true;
3219 else if (nophi && !insertions)
3220 return false;
3222 /* Now build a phi for the new variable. */
3223 temp = make_temp_ssa_name (type, NULL, "prephitmp");
3224 phi = create_phi_node (temp, block);
3226 gimple_set_plf (phi, NECESSARY, false);
3227 VN_INFO_GET (temp)->value_id = val;
3228 VN_INFO (temp)->valnum = sccvn_valnum_from_value_id (val);
3229 if (VN_INFO (temp)->valnum == NULL_TREE)
3230 VN_INFO (temp)->valnum = temp;
3231 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (temp));
3232 FOR_EACH_EDGE (pred, ei, block->preds)
3234 pre_expr ae = avail[pred->dest_idx];
3235 gcc_assert (get_expr_type (ae) == type
3236 || useless_type_conversion_p (type, get_expr_type (ae)));
3237 if (ae->kind == CONSTANT)
3238 add_phi_arg (phi, unshare_expr (PRE_EXPR_CONSTANT (ae)),
3239 pred, UNKNOWN_LOCATION);
3240 else
3241 add_phi_arg (phi, PRE_EXPR_NAME (ae), pred, UNKNOWN_LOCATION);
3244 newphi = get_or_alloc_expr_for_name (temp);
3245 add_to_value (val, newphi);
3247 /* The value should *not* exist in PHI_GEN, or else we wouldn't be doing
3248 this insertion, since we test for the existence of this value in PHI_GEN
3249 before proceeding with the partial redundancy checks in insert_aux.
3251 The value may exist in AVAIL_OUT, in particular, it could be represented
3252 by the expression we are trying to eliminate, in which case we want the
3253 replacement to occur. If it's not existing in AVAIL_OUT, we want it
3254 inserted there.
3256 Similarly, to the PHI_GEN case, the value should not exist in NEW_SETS of
3257 this block, because if it did, it would have existed in our dominator's
3258 AVAIL_OUT, and would have been skipped due to the full redundancy check.
3261 bitmap_insert_into_set (PHI_GEN (block), newphi);
3262 bitmap_value_replace_in_set (AVAIL_OUT (block),
3263 newphi);
3264 bitmap_insert_into_set (NEW_SETS (block),
3265 newphi);
3267 if (dump_file && (dump_flags & TDF_DETAILS))
3269 fprintf (dump_file, "Created phi ");
3270 print_gimple_stmt (dump_file, phi, 0, 0);
3271 fprintf (dump_file, " in block %d (%04d)\n", block->index, val);
3273 pre_stats.phis++;
3274 return true;
3279 /* Perform insertion of partially redundant values.
3280 For BLOCK, do the following:
3281 1. Propagate the NEW_SETS of the dominator into the current block.
3282 If the block has multiple predecessors,
3283 2a. Iterate over the ANTIC expressions for the block to see if
3284 any of them are partially redundant.
3285 2b. If so, insert them into the necessary predecessors to make
3286 the expression fully redundant.
3287 2c. Insert a new PHI merging the values of the predecessors.
3288 2d. Insert the new PHI, and the new expressions, into the
3289 NEW_SETS set.
3290 3. Recursively call ourselves on the dominator children of BLOCK.
3292 Steps 1, 2a, and 3 are done by insert_aux. 2b, 2c and 2d are done by
3293 do_regular_insertion and do_partial_insertion.
3297 static bool
3298 do_regular_insertion (basic_block block, basic_block dom)
3300 bool new_stuff = false;
3301 vec<pre_expr> exprs;
3302 pre_expr expr;
3303 vec<pre_expr> avail = vNULL;
3304 int i;
3306 exprs = sorted_array_from_bitmap_set (ANTIC_IN (block));
3307 avail.safe_grow (EDGE_COUNT (block->preds));
3309 FOR_EACH_VEC_ELT (exprs, i, expr)
3311 if (expr->kind == NARY
3312 || expr->kind == REFERENCE)
3314 unsigned int val;
3315 bool by_some = false;
3316 bool cant_insert = false;
3317 bool all_same = true;
3318 pre_expr first_s = NULL;
3319 edge pred;
3320 basic_block bprime;
3321 pre_expr eprime = NULL;
3322 edge_iterator ei;
3323 pre_expr edoubleprime = NULL;
3324 bool do_insertion = false;
3326 val = get_expr_value_id (expr);
3327 if (bitmap_set_contains_value (PHI_GEN (block), val))
3328 continue;
3329 if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3331 if (dump_file && (dump_flags & TDF_DETAILS))
3333 fprintf (dump_file, "Found fully redundant value: ");
3334 print_pre_expr (dump_file, expr);
3335 fprintf (dump_file, "\n");
3337 continue;
3340 FOR_EACH_EDGE (pred, ei, block->preds)
3342 unsigned int vprime;
3344 /* We should never run insertion for the exit block
3345 and so not come across fake pred edges. */
3346 gcc_assert (!(pred->flags & EDGE_FAKE));
3347 bprime = pred->src;
3348 eprime = phi_translate (expr, ANTIC_IN (block), NULL,
3349 bprime, block);
3351 /* eprime will generally only be NULL if the
3352 value of the expression, translated
3353 through the PHI for this predecessor, is
3354 undefined. If that is the case, we can't
3355 make the expression fully redundant,
3356 because its value is undefined along a
3357 predecessor path. We can thus break out
3358 early because it doesn't matter what the
3359 rest of the results are. */
3360 if (eprime == NULL)
3362 avail[pred->dest_idx] = NULL;
3363 cant_insert = true;
3364 break;
3367 eprime = fully_constant_expression (eprime);
3368 vprime = get_expr_value_id (eprime);
3369 edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime),
3370 vprime);
3371 if (edoubleprime == NULL)
3373 avail[pred->dest_idx] = eprime;
3374 all_same = false;
3376 else
3378 avail[pred->dest_idx] = edoubleprime;
3379 by_some = true;
3380 /* We want to perform insertions to remove a redundancy on
3381 a path in the CFG we want to optimize for speed. */
3382 if (optimize_edge_for_speed_p (pred))
3383 do_insertion = true;
3384 if (first_s == NULL)
3385 first_s = edoubleprime;
3386 else if (!pre_expr_d::equal (first_s, edoubleprime))
3387 all_same = false;
3390 /* If we can insert it, it's not the same value
3391 already existing along every predecessor, and
3392 it's defined by some predecessor, it is
3393 partially redundant. */
3394 if (!cant_insert && !all_same && by_some)
3396 if (!do_insertion)
3398 if (dump_file && (dump_flags & TDF_DETAILS))
3400 fprintf (dump_file, "Skipping partial redundancy for "
3401 "expression ");
3402 print_pre_expr (dump_file, expr);
3403 fprintf (dump_file, " (%04d), no redundancy on to be "
3404 "optimized for speed edge\n", val);
3407 else if (dbg_cnt (treepre_insert))
3409 if (dump_file && (dump_flags & TDF_DETAILS))
3411 fprintf (dump_file, "Found partial redundancy for "
3412 "expression ");
3413 print_pre_expr (dump_file, expr);
3414 fprintf (dump_file, " (%04d)\n",
3415 get_expr_value_id (expr));
3417 if (insert_into_preds_of_block (block,
3418 get_expression_id (expr),
3419 avail))
3420 new_stuff = true;
3423 /* If all edges produce the same value and that value is
3424 an invariant, then the PHI has the same value on all
3425 edges. Note this. */
3426 else if (!cant_insert && all_same)
3428 gcc_assert (edoubleprime->kind == CONSTANT
3429 || edoubleprime->kind == NAME);
3431 tree temp = make_temp_ssa_name (get_expr_type (expr),
3432 NULL, "pretmp");
3433 gimple assign = gimple_build_assign (temp,
3434 edoubleprime->kind == CONSTANT ? PRE_EXPR_CONSTANT (edoubleprime) : PRE_EXPR_NAME (edoubleprime));
3435 gimple_stmt_iterator gsi = gsi_after_labels (block);
3436 gsi_insert_before (&gsi, assign, GSI_NEW_STMT);
3438 gimple_set_plf (assign, NECESSARY, false);
3439 VN_INFO_GET (temp)->value_id = val;
3440 VN_INFO (temp)->valnum = sccvn_valnum_from_value_id (val);
3441 if (VN_INFO (temp)->valnum == NULL_TREE)
3442 VN_INFO (temp)->valnum = temp;
3443 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (temp));
3444 pre_expr newe = get_or_alloc_expr_for_name (temp);
3445 add_to_value (val, newe);
3446 bitmap_value_replace_in_set (AVAIL_OUT (block), newe);
3447 bitmap_insert_into_set (NEW_SETS (block), newe);
3452 exprs.release ();
3453 avail.release ();
3454 return new_stuff;
3458 /* Perform insertion for partially anticipatable expressions. There
3459 is only one case we will perform insertion for these. This case is
3460 if the expression is partially anticipatable, and fully available.
3461 In this case, we know that putting it earlier will enable us to
3462 remove the later computation. */
3465 static bool
3466 do_partial_partial_insertion (basic_block block, basic_block dom)
3468 bool new_stuff = false;
3469 vec<pre_expr> exprs;
3470 pre_expr expr;
3471 vec<pre_expr> avail = vNULL;
3472 int i;
3474 exprs = sorted_array_from_bitmap_set (PA_IN (block));
3475 avail.safe_grow (EDGE_COUNT (block->preds));
3477 FOR_EACH_VEC_ELT (exprs, i, expr)
3479 if (expr->kind == NARY
3480 || expr->kind == REFERENCE)
3482 unsigned int val;
3483 bool by_all = true;
3484 bool cant_insert = false;
3485 edge pred;
3486 basic_block bprime;
3487 pre_expr eprime = NULL;
3488 edge_iterator ei;
3490 val = get_expr_value_id (expr);
3491 if (bitmap_set_contains_value (PHI_GEN (block), val))
3492 continue;
3493 if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3494 continue;
3496 FOR_EACH_EDGE (pred, ei, block->preds)
3498 unsigned int vprime;
3499 pre_expr edoubleprime;
3501 /* We should never run insertion for the exit block
3502 and so not come across fake pred edges. */
3503 gcc_assert (!(pred->flags & EDGE_FAKE));
3504 bprime = pred->src;
3505 eprime = phi_translate (expr, ANTIC_IN (block),
3506 PA_IN (block),
3507 bprime, block);
3509 /* eprime will generally only be NULL if the
3510 value of the expression, translated
3511 through the PHI for this predecessor, is
3512 undefined. If that is the case, we can't
3513 make the expression fully redundant,
3514 because its value is undefined along a
3515 predecessor path. We can thus break out
3516 early because it doesn't matter what the
3517 rest of the results are. */
3518 if (eprime == NULL)
3520 avail[pred->dest_idx] = NULL;
3521 cant_insert = true;
3522 break;
3525 eprime = fully_constant_expression (eprime);
3526 vprime = get_expr_value_id (eprime);
3527 edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime), vprime);
3528 avail[pred->dest_idx] = edoubleprime;
3529 if (edoubleprime == NULL)
3531 by_all = false;
3532 break;
3536 /* If we can insert it, it's not the same value
3537 already existing along every predecessor, and
3538 it's defined by some predecessor, it is
3539 partially redundant. */
3540 if (!cant_insert && by_all)
3542 edge succ;
3543 bool do_insertion = false;
3545 /* Insert only if we can remove a later expression on a path
3546 that we want to optimize for speed.
3547 The phi node that we will be inserting in BLOCK is not free,
3548 and inserting it for the sake of !optimize_for_speed successor
3549 may cause regressions on the speed path. */
3550 FOR_EACH_EDGE (succ, ei, block->succs)
3552 if (bitmap_set_contains_value (PA_IN (succ->dest), val)
3553 || bitmap_set_contains_value (ANTIC_IN (succ->dest), val))
3555 if (optimize_edge_for_speed_p (succ))
3556 do_insertion = true;
3560 if (!do_insertion)
3562 if (dump_file && (dump_flags & TDF_DETAILS))
3564 fprintf (dump_file, "Skipping partial partial redundancy "
3565 "for expression ");
3566 print_pre_expr (dump_file, expr);
3567 fprintf (dump_file, " (%04d), not (partially) anticipated "
3568 "on any to be optimized for speed edges\n", val);
3571 else if (dbg_cnt (treepre_insert))
3573 pre_stats.pa_insert++;
3574 if (dump_file && (dump_flags & TDF_DETAILS))
3576 fprintf (dump_file, "Found partial partial redundancy "
3577 "for expression ");
3578 print_pre_expr (dump_file, expr);
3579 fprintf (dump_file, " (%04d)\n",
3580 get_expr_value_id (expr));
3582 if (insert_into_preds_of_block (block,
3583 get_expression_id (expr),
3584 avail))
3585 new_stuff = true;
3591 exprs.release ();
3592 avail.release ();
3593 return new_stuff;
3596 static bool
3597 insert_aux (basic_block block)
3599 basic_block son;
3600 bool new_stuff = false;
3602 if (block)
3604 basic_block dom;
3605 dom = get_immediate_dominator (CDI_DOMINATORS, block);
3606 if (dom)
3608 unsigned i;
3609 bitmap_iterator bi;
3610 bitmap_set_t newset = NEW_SETS (dom);
3611 if (newset)
3613 /* Note that we need to value_replace both NEW_SETS, and
3614 AVAIL_OUT. For both the case of NEW_SETS, the value may be
3615 represented by some non-simple expression here that we want
3616 to replace it with. */
3617 FOR_EACH_EXPR_ID_IN_SET (newset, i, bi)
3619 pre_expr expr = expression_for_id (i);
3620 bitmap_value_replace_in_set (NEW_SETS (block), expr);
3621 bitmap_value_replace_in_set (AVAIL_OUT (block), expr);
3624 if (!single_pred_p (block))
3626 new_stuff |= do_regular_insertion (block, dom);
3627 if (do_partial_partial)
3628 new_stuff |= do_partial_partial_insertion (block, dom);
3632 for (son = first_dom_son (CDI_DOMINATORS, block);
3633 son;
3634 son = next_dom_son (CDI_DOMINATORS, son))
3636 new_stuff |= insert_aux (son);
3639 return new_stuff;
3642 /* Perform insertion of partially redundant values. */
3644 static void
3645 insert (void)
3647 bool new_stuff = true;
3648 basic_block bb;
3649 int num_iterations = 0;
3651 FOR_ALL_BB (bb)
3652 NEW_SETS (bb) = bitmap_set_new ();
3654 while (new_stuff)
3656 num_iterations++;
3657 if (dump_file && dump_flags & TDF_DETAILS)
3658 fprintf (dump_file, "Starting insert iteration %d\n", num_iterations);
3659 new_stuff = insert_aux (ENTRY_BLOCK_PTR);
3661 /* Clear the NEW sets before the next iteration. We have already
3662 fully propagated its contents. */
3663 if (new_stuff)
3664 FOR_ALL_BB (bb)
3665 bitmap_set_free (NEW_SETS (bb));
3667 statistics_histogram_event (cfun, "insert iterations", num_iterations);
3671 /* Compute the AVAIL set for all basic blocks.
3673 This function performs value numbering of the statements in each basic
3674 block. The AVAIL sets are built from information we glean while doing
3675 this value numbering, since the AVAIL sets contain only one entry per
3676 value.
3678 AVAIL_IN[BLOCK] = AVAIL_OUT[dom(BLOCK)].
3679 AVAIL_OUT[BLOCK] = AVAIL_IN[BLOCK] U PHI_GEN[BLOCK] U TMP_GEN[BLOCK]. */
3681 static void
3682 compute_avail (void)
3685 basic_block block, son;
3686 basic_block *worklist;
3687 size_t sp = 0;
3688 unsigned i;
3690 /* We pretend that default definitions are defined in the entry block.
3691 This includes function arguments and the static chain decl. */
3692 for (i = 1; i < num_ssa_names; ++i)
3694 tree name = ssa_name (i);
3695 pre_expr e;
3696 if (!name
3697 || !SSA_NAME_IS_DEFAULT_DEF (name)
3698 || has_zero_uses (name)
3699 || virtual_operand_p (name))
3700 continue;
3702 e = get_or_alloc_expr_for_name (name);
3703 add_to_value (get_expr_value_id (e), e);
3704 bitmap_insert_into_set (TMP_GEN (ENTRY_BLOCK_PTR), e);
3705 bitmap_value_insert_into_set (AVAIL_OUT (ENTRY_BLOCK_PTR), e);
3708 if (dump_file && (dump_flags & TDF_DETAILS))
3710 print_bitmap_set (dump_file, TMP_GEN (ENTRY_BLOCK_PTR),
3711 "tmp_gen", ENTRY_BLOCK);
3712 print_bitmap_set (dump_file, AVAIL_OUT (ENTRY_BLOCK_PTR),
3713 "avail_out", ENTRY_BLOCK);
3716 /* Allocate the worklist. */
3717 worklist = XNEWVEC (basic_block, n_basic_blocks);
3719 /* Seed the algorithm by putting the dominator children of the entry
3720 block on the worklist. */
3721 for (son = first_dom_son (CDI_DOMINATORS, ENTRY_BLOCK_PTR);
3722 son;
3723 son = next_dom_son (CDI_DOMINATORS, son))
3724 worklist[sp++] = son;
3726 /* Loop until the worklist is empty. */
3727 while (sp)
3729 gimple_stmt_iterator gsi;
3730 gimple stmt;
3731 basic_block dom;
3733 /* Pick a block from the worklist. */
3734 block = worklist[--sp];
3736 /* Initially, the set of available values in BLOCK is that of
3737 its immediate dominator. */
3738 dom = get_immediate_dominator (CDI_DOMINATORS, block);
3739 if (dom)
3740 bitmap_set_copy (AVAIL_OUT (block), AVAIL_OUT (dom));
3742 /* Generate values for PHI nodes. */
3743 for (gsi = gsi_start_phis (block); !gsi_end_p (gsi); gsi_next (&gsi))
3745 tree result = gimple_phi_result (gsi_stmt (gsi));
3747 /* We have no need for virtual phis, as they don't represent
3748 actual computations. */
3749 if (virtual_operand_p (result))
3750 continue;
3752 pre_expr e = get_or_alloc_expr_for_name (result);
3753 add_to_value (get_expr_value_id (e), e);
3754 bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3755 bitmap_insert_into_set (PHI_GEN (block), e);
3758 BB_MAY_NOTRETURN (block) = 0;
3760 /* Now compute value numbers and populate value sets with all
3761 the expressions computed in BLOCK. */
3762 for (gsi = gsi_start_bb (block); !gsi_end_p (gsi); gsi_next (&gsi))
3764 ssa_op_iter iter;
3765 tree op;
3767 stmt = gsi_stmt (gsi);
3769 /* Cache whether the basic-block has any non-visible side-effect
3770 or control flow.
3771 If this isn't a call or it is the last stmt in the
3772 basic-block then the CFG represents things correctly. */
3773 if (is_gimple_call (stmt) && !stmt_ends_bb_p (stmt))
3775 /* Non-looping const functions always return normally.
3776 Otherwise the call might not return or have side-effects
3777 that forbids hoisting possibly trapping expressions
3778 before it. */
3779 int flags = gimple_call_flags (stmt);
3780 if (!(flags & ECF_CONST)
3781 || (flags & ECF_LOOPING_CONST_OR_PURE))
3782 BB_MAY_NOTRETURN (block) = 1;
3785 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_DEF)
3787 pre_expr e = get_or_alloc_expr_for_name (op);
3789 add_to_value (get_expr_value_id (e), e);
3790 bitmap_insert_into_set (TMP_GEN (block), e);
3791 bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3794 if (gimple_has_side_effects (stmt)
3795 || stmt_could_throw_p (stmt)
3796 || is_gimple_debug (stmt))
3797 continue;
3799 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
3801 if (ssa_undefined_value_p (op))
3802 continue;
3803 pre_expr e = get_or_alloc_expr_for_name (op);
3804 bitmap_value_insert_into_set (EXP_GEN (block), e);
3807 switch (gimple_code (stmt))
3809 case GIMPLE_RETURN:
3810 continue;
3812 case GIMPLE_CALL:
3814 vn_reference_t ref;
3815 pre_expr result = NULL;
3816 vec<vn_reference_op_s> ops = vNULL;
3818 /* We can value number only calls to real functions. */
3819 if (gimple_call_internal_p (stmt))
3820 continue;
3822 copy_reference_ops_from_call (stmt, &ops);
3823 vn_reference_lookup_pieces (gimple_vuse (stmt), 0,
3824 gimple_expr_type (stmt),
3825 ops, &ref, VN_NOWALK);
3826 ops.release ();
3827 if (!ref)
3828 continue;
3830 /* If the value of the call is not invalidated in
3831 this block until it is computed, add the expression
3832 to EXP_GEN. */
3833 if (!gimple_vuse (stmt)
3834 || gimple_code
3835 (SSA_NAME_DEF_STMT (gimple_vuse (stmt))) == GIMPLE_PHI
3836 || gimple_bb (SSA_NAME_DEF_STMT
3837 (gimple_vuse (stmt))) != block)
3839 result = (pre_expr) pool_alloc (pre_expr_pool);
3840 result->kind = REFERENCE;
3841 result->id = 0;
3842 PRE_EXPR_REFERENCE (result) = ref;
3844 get_or_alloc_expression_id (result);
3845 add_to_value (get_expr_value_id (result), result);
3846 bitmap_value_insert_into_set (EXP_GEN (block), result);
3848 continue;
3851 case GIMPLE_ASSIGN:
3853 pre_expr result = NULL;
3854 switch (vn_get_stmt_kind (stmt))
3856 case VN_NARY:
3858 enum tree_code code = gimple_assign_rhs_code (stmt);
3859 vn_nary_op_t nary;
3861 /* COND_EXPR and VEC_COND_EXPR are awkward in
3862 that they contain an embedded complex expression.
3863 Don't even try to shove those through PRE. */
3864 if (code == COND_EXPR
3865 || code == VEC_COND_EXPR)
3866 continue;
3868 vn_nary_op_lookup_stmt (stmt, &nary);
3869 if (!nary)
3870 continue;
3872 /* If the NARY traps and there was a preceding
3873 point in the block that might not return avoid
3874 adding the nary to EXP_GEN. */
3875 if (BB_MAY_NOTRETURN (block)
3876 && vn_nary_may_trap (nary))
3877 continue;
3879 result = (pre_expr) pool_alloc (pre_expr_pool);
3880 result->kind = NARY;
3881 result->id = 0;
3882 PRE_EXPR_NARY (result) = nary;
3883 break;
3886 case VN_REFERENCE:
3888 vn_reference_t ref;
3889 vn_reference_lookup (gimple_assign_rhs1 (stmt),
3890 gimple_vuse (stmt),
3891 VN_WALK, &ref);
3892 if (!ref)
3893 continue;
3895 /* If the value of the reference is not invalidated in
3896 this block until it is computed, add the expression
3897 to EXP_GEN. */
3898 if (gimple_vuse (stmt))
3900 gimple def_stmt;
3901 bool ok = true;
3902 def_stmt = SSA_NAME_DEF_STMT (gimple_vuse (stmt));
3903 while (!gimple_nop_p (def_stmt)
3904 && gimple_code (def_stmt) != GIMPLE_PHI
3905 && gimple_bb (def_stmt) == block)
3907 if (stmt_may_clobber_ref_p
3908 (def_stmt, gimple_assign_rhs1 (stmt)))
3910 ok = false;
3911 break;
3913 def_stmt
3914 = SSA_NAME_DEF_STMT (gimple_vuse (def_stmt));
3916 if (!ok)
3917 continue;
3920 result = (pre_expr) pool_alloc (pre_expr_pool);
3921 result->kind = REFERENCE;
3922 result->id = 0;
3923 PRE_EXPR_REFERENCE (result) = ref;
3924 break;
3927 default:
3928 continue;
3931 get_or_alloc_expression_id (result);
3932 add_to_value (get_expr_value_id (result), result);
3933 bitmap_value_insert_into_set (EXP_GEN (block), result);
3934 continue;
3936 default:
3937 break;
3941 if (dump_file && (dump_flags & TDF_DETAILS))
3943 print_bitmap_set (dump_file, EXP_GEN (block),
3944 "exp_gen", block->index);
3945 print_bitmap_set (dump_file, PHI_GEN (block),
3946 "phi_gen", block->index);
3947 print_bitmap_set (dump_file, TMP_GEN (block),
3948 "tmp_gen", block->index);
3949 print_bitmap_set (dump_file, AVAIL_OUT (block),
3950 "avail_out", block->index);
3953 /* Put the dominator children of BLOCK on the worklist of blocks
3954 to compute available sets for. */
3955 for (son = first_dom_son (CDI_DOMINATORS, block);
3956 son;
3957 son = next_dom_son (CDI_DOMINATORS, son))
3958 worklist[sp++] = son;
3961 free (worklist);
3965 /* Local state for the eliminate domwalk. */
3966 static vec<gimple> el_to_remove;
3967 static vec<gimple> el_to_update;
3968 static unsigned int el_todo;
3969 static vec<tree> el_avail;
3970 static vec<tree> el_avail_stack;
3972 /* Return a leader for OP that is available at the current point of the
3973 eliminate domwalk. */
3975 static tree
3976 eliminate_avail (tree op)
3978 tree valnum = VN_INFO (op)->valnum;
3979 if (TREE_CODE (valnum) == SSA_NAME)
3981 if (SSA_NAME_IS_DEFAULT_DEF (valnum))
3982 return valnum;
3983 if (el_avail.length () > SSA_NAME_VERSION (valnum))
3984 return el_avail[SSA_NAME_VERSION (valnum)];
3986 else if (is_gimple_min_invariant (valnum))
3987 return valnum;
3988 return NULL_TREE;
3991 /* At the current point of the eliminate domwalk make OP available. */
3993 static void
3994 eliminate_push_avail (tree op)
3996 tree valnum = VN_INFO (op)->valnum;
3997 if (TREE_CODE (valnum) == SSA_NAME)
3999 if (el_avail.length () <= SSA_NAME_VERSION (valnum))
4000 el_avail.safe_grow_cleared (SSA_NAME_VERSION (valnum) + 1);
4001 el_avail[SSA_NAME_VERSION (valnum)] = op;
4002 el_avail_stack.safe_push (op);
4006 /* Insert the expression recorded by SCCVN for VAL at *GSI. Returns
4007 the leader for the expression if insertion was successful. */
4009 static tree
4010 eliminate_insert (gimple_stmt_iterator *gsi, tree val)
4012 tree expr = vn_get_expr_for (val);
4013 if (!CONVERT_EXPR_P (expr)
4014 && TREE_CODE (expr) != VIEW_CONVERT_EXPR)
4015 return NULL_TREE;
4017 tree op = TREE_OPERAND (expr, 0);
4018 tree leader = TREE_CODE (op) == SSA_NAME ? eliminate_avail (op) : op;
4019 if (!leader)
4020 return NULL_TREE;
4022 tree res = make_temp_ssa_name (TREE_TYPE (val), NULL, "pretmp");
4023 gimple tem = gimple_build_assign (res,
4024 fold_build1 (TREE_CODE (expr),
4025 TREE_TYPE (expr), leader));
4026 gsi_insert_before (gsi, tem, GSI_SAME_STMT);
4027 VN_INFO_GET (res)->valnum = val;
4029 if (TREE_CODE (leader) == SSA_NAME)
4030 gimple_set_plf (SSA_NAME_DEF_STMT (leader), NECESSARY, true);
4032 pre_stats.insertions++;
4033 if (dump_file && (dump_flags & TDF_DETAILS))
4035 fprintf (dump_file, "Inserted ");
4036 print_gimple_stmt (dump_file, tem, 0, 0);
4039 return res;
4042 class eliminate_dom_walker : public dom_walker
4044 public:
4045 eliminate_dom_walker (cdi_direction direction) : dom_walker (direction) {}
4047 virtual void before_dom_children (basic_block);
4048 virtual void after_dom_children (basic_block);
4051 /* Perform elimination for the basic-block B during the domwalk. */
4053 void
4054 eliminate_dom_walker::before_dom_children (basic_block b)
4056 gimple_stmt_iterator gsi;
4057 gimple stmt;
4059 /* Mark new bb. */
4060 el_avail_stack.safe_push (NULL_TREE);
4062 for (gsi = gsi_start_phis (b); !gsi_end_p (gsi);)
4064 gimple stmt, phi = gsi_stmt (gsi);
4065 tree sprime = NULL_TREE, res = PHI_RESULT (phi);
4066 gimple_stmt_iterator gsi2;
4068 /* We want to perform redundant PHI elimination. Do so by
4069 replacing the PHI with a single copy if possible.
4070 Do not touch inserted, single-argument or virtual PHIs. */
4071 if (gimple_phi_num_args (phi) == 1
4072 || virtual_operand_p (res))
4074 gsi_next (&gsi);
4075 continue;
4078 sprime = eliminate_avail (res);
4079 if (!sprime
4080 || sprime == res)
4082 eliminate_push_avail (res);
4083 gsi_next (&gsi);
4084 continue;
4086 else if (is_gimple_min_invariant (sprime))
4088 if (!useless_type_conversion_p (TREE_TYPE (res),
4089 TREE_TYPE (sprime)))
4090 sprime = fold_convert (TREE_TYPE (res), sprime);
4093 if (dump_file && (dump_flags & TDF_DETAILS))
4095 fprintf (dump_file, "Replaced redundant PHI node defining ");
4096 print_generic_expr (dump_file, res, 0);
4097 fprintf (dump_file, " with ");
4098 print_generic_expr (dump_file, sprime, 0);
4099 fprintf (dump_file, "\n");
4102 remove_phi_node (&gsi, false);
4104 if (inserted_exprs
4105 && !bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (res))
4106 && TREE_CODE (sprime) == SSA_NAME)
4107 gimple_set_plf (SSA_NAME_DEF_STMT (sprime), NECESSARY, true);
4109 if (!useless_type_conversion_p (TREE_TYPE (res), TREE_TYPE (sprime)))
4110 sprime = fold_convert (TREE_TYPE (res), sprime);
4111 stmt = gimple_build_assign (res, sprime);
4112 SSA_NAME_DEF_STMT (res) = stmt;
4113 gimple_set_plf (stmt, NECESSARY, gimple_plf (phi, NECESSARY));
4115 gsi2 = gsi_after_labels (b);
4116 gsi_insert_before (&gsi2, stmt, GSI_NEW_STMT);
4117 /* Queue the copy for eventual removal. */
4118 el_to_remove.safe_push (stmt);
4119 /* If we inserted this PHI node ourself, it's not an elimination. */
4120 if (inserted_exprs
4121 && bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (res)))
4122 pre_stats.phis--;
4123 else
4124 pre_stats.eliminations++;
4127 for (gsi = gsi_start_bb (b); !gsi_end_p (gsi); gsi_next (&gsi))
4129 tree lhs = NULL_TREE;
4130 tree rhs = NULL_TREE;
4132 stmt = gsi_stmt (gsi);
4134 if (gimple_has_lhs (stmt))
4135 lhs = gimple_get_lhs (stmt);
4137 if (gimple_assign_single_p (stmt))
4138 rhs = gimple_assign_rhs1 (stmt);
4140 /* Lookup the RHS of the expression, see if we have an
4141 available computation for it. If so, replace the RHS with
4142 the available computation. */
4143 if (gimple_has_lhs (stmt)
4144 && TREE_CODE (lhs) == SSA_NAME
4145 && !gimple_has_volatile_ops (stmt))
4147 tree sprime;
4148 gimple orig_stmt = stmt;
4150 sprime = eliminate_avail (lhs);
4151 /* If there is no usable leader mark lhs as leader for its value. */
4152 if (!sprime)
4153 eliminate_push_avail (lhs);
4155 /* See PR43491. Do not replace a global register variable when
4156 it is a the RHS of an assignment. Do replace local register
4157 variables since gcc does not guarantee a local variable will
4158 be allocated in register.
4159 Do not perform copy propagation or undo constant propagation. */
4160 if (gimple_assign_single_p (stmt)
4161 && (TREE_CODE (rhs) == SSA_NAME
4162 || is_gimple_min_invariant (rhs)
4163 || (TREE_CODE (rhs) == VAR_DECL
4164 && is_global_var (rhs)
4165 && DECL_HARD_REGISTER (rhs))))
4166 continue;
4168 if (!sprime)
4170 /* If there is no existing usable leader but SCCVN thinks
4171 it has an expression it wants to use as replacement,
4172 insert that. */
4173 tree val = VN_INFO (lhs)->valnum;
4174 if (val != VN_TOP
4175 && TREE_CODE (val) == SSA_NAME
4176 && VN_INFO (val)->needs_insertion
4177 && VN_INFO (val)->expr != NULL_TREE
4178 && (sprime = eliminate_insert (&gsi, val)) != NULL_TREE)
4179 eliminate_push_avail (sprime);
4181 else if (is_gimple_min_invariant (sprime))
4183 /* If there is no existing leader but SCCVN knows this
4184 value is constant, use that constant. */
4185 if (!useless_type_conversion_p (TREE_TYPE (lhs),
4186 TREE_TYPE (sprime)))
4187 sprime = fold_convert (TREE_TYPE (lhs), sprime);
4189 if (dump_file && (dump_flags & TDF_DETAILS))
4191 fprintf (dump_file, "Replaced ");
4192 print_gimple_expr (dump_file, stmt, 0, 0);
4193 fprintf (dump_file, " with ");
4194 print_generic_expr (dump_file, sprime, 0);
4195 fprintf (dump_file, " in ");
4196 print_gimple_stmt (dump_file, stmt, 0, 0);
4198 pre_stats.eliminations++;
4199 propagate_tree_value_into_stmt (&gsi, sprime);
4200 stmt = gsi_stmt (gsi);
4201 update_stmt (stmt);
4203 /* If we removed EH side-effects from the statement, clean
4204 its EH information. */
4205 if (maybe_clean_or_replace_eh_stmt (orig_stmt, stmt))
4207 bitmap_set_bit (need_eh_cleanup,
4208 gimple_bb (stmt)->index);
4209 if (dump_file && (dump_flags & TDF_DETAILS))
4210 fprintf (dump_file, " Removed EH side-effects.\n");
4212 continue;
4215 if (sprime
4216 && sprime != lhs
4217 && (rhs == NULL_TREE
4218 || TREE_CODE (rhs) != SSA_NAME
4219 || may_propagate_copy (rhs, sprime)))
4221 bool can_make_abnormal_goto
4222 = is_gimple_call (stmt)
4223 && stmt_can_make_abnormal_goto (stmt);
4225 gcc_assert (sprime != rhs);
4227 if (dump_file && (dump_flags & TDF_DETAILS))
4229 fprintf (dump_file, "Replaced ");
4230 print_gimple_expr (dump_file, stmt, 0, 0);
4231 fprintf (dump_file, " with ");
4232 print_generic_expr (dump_file, sprime, 0);
4233 fprintf (dump_file, " in ");
4234 print_gimple_stmt (dump_file, stmt, 0, 0);
4237 if (TREE_CODE (sprime) == SSA_NAME)
4238 gimple_set_plf (SSA_NAME_DEF_STMT (sprime),
4239 NECESSARY, true);
4240 /* We need to make sure the new and old types actually match,
4241 which may require adding a simple cast, which fold_convert
4242 will do for us. */
4243 if ((!rhs || TREE_CODE (rhs) != SSA_NAME)
4244 && !useless_type_conversion_p (gimple_expr_type (stmt),
4245 TREE_TYPE (sprime)))
4246 sprime = fold_convert (gimple_expr_type (stmt), sprime);
4248 pre_stats.eliminations++;
4249 propagate_tree_value_into_stmt (&gsi, sprime);
4250 stmt = gsi_stmt (gsi);
4251 update_stmt (stmt);
4253 /* If we removed EH side-effects from the statement, clean
4254 its EH information. */
4255 if (maybe_clean_or_replace_eh_stmt (orig_stmt, stmt))
4257 bitmap_set_bit (need_eh_cleanup,
4258 gimple_bb (stmt)->index);
4259 if (dump_file && (dump_flags & TDF_DETAILS))
4260 fprintf (dump_file, " Removed EH side-effects.\n");
4263 /* Likewise for AB side-effects. */
4264 if (can_make_abnormal_goto
4265 && !stmt_can_make_abnormal_goto (stmt))
4267 bitmap_set_bit (need_ab_cleanup,
4268 gimple_bb (stmt)->index);
4269 if (dump_file && (dump_flags & TDF_DETAILS))
4270 fprintf (dump_file, " Removed AB side-effects.\n");
4274 /* If the statement is a scalar store, see if the expression
4275 has the same value number as its rhs. If so, the store is
4276 dead. */
4277 else if (gimple_assign_single_p (stmt)
4278 && !gimple_has_volatile_ops (stmt)
4279 && !is_gimple_reg (gimple_assign_lhs (stmt))
4280 && (TREE_CODE (rhs) == SSA_NAME
4281 || is_gimple_min_invariant (rhs)))
4283 tree val;
4284 val = vn_reference_lookup (gimple_assign_lhs (stmt),
4285 gimple_vuse (stmt), VN_WALK, NULL);
4286 if (TREE_CODE (rhs) == SSA_NAME)
4287 rhs = VN_INFO (rhs)->valnum;
4288 if (val
4289 && operand_equal_p (val, rhs, 0))
4291 if (dump_file && (dump_flags & TDF_DETAILS))
4293 fprintf (dump_file, "Deleted redundant store ");
4294 print_gimple_stmt (dump_file, stmt, 0, 0);
4297 /* Queue stmt for removal. */
4298 el_to_remove.safe_push (stmt);
4301 /* Visit COND_EXPRs and fold the comparison with the
4302 available value-numbers. */
4303 else if (gimple_code (stmt) == GIMPLE_COND)
4305 tree op0 = gimple_cond_lhs (stmt);
4306 tree op1 = gimple_cond_rhs (stmt);
4307 tree result;
4309 if (TREE_CODE (op0) == SSA_NAME)
4310 op0 = VN_INFO (op0)->valnum;
4311 if (TREE_CODE (op1) == SSA_NAME)
4312 op1 = VN_INFO (op1)->valnum;
4313 result = fold_binary (gimple_cond_code (stmt), boolean_type_node,
4314 op0, op1);
4315 if (result && TREE_CODE (result) == INTEGER_CST)
4317 if (integer_zerop (result))
4318 gimple_cond_make_false (stmt);
4319 else
4320 gimple_cond_make_true (stmt);
4321 update_stmt (stmt);
4322 el_todo = TODO_cleanup_cfg;
4325 /* Visit indirect calls and turn them into direct calls if
4326 possible. */
4327 if (is_gimple_call (stmt))
4329 tree orig_fn = gimple_call_fn (stmt);
4330 tree fn;
4331 if (!orig_fn)
4332 continue;
4333 if (TREE_CODE (orig_fn) == SSA_NAME)
4334 fn = VN_INFO (orig_fn)->valnum;
4335 else if (TREE_CODE (orig_fn) == OBJ_TYPE_REF
4336 && TREE_CODE (OBJ_TYPE_REF_EXPR (orig_fn)) == SSA_NAME)
4338 fn = VN_INFO (OBJ_TYPE_REF_EXPR (orig_fn))->valnum;
4339 if (!gimple_call_addr_fndecl (fn))
4341 fn = ipa_intraprocedural_devirtualization (stmt);
4342 if (fn)
4343 fn = build_fold_addr_expr (fn);
4346 else
4347 continue;
4348 if (gimple_call_addr_fndecl (fn) != NULL_TREE
4349 && useless_type_conversion_p (TREE_TYPE (orig_fn),
4350 TREE_TYPE (fn)))
4352 bool can_make_abnormal_goto
4353 = stmt_can_make_abnormal_goto (stmt);
4354 bool was_noreturn = gimple_call_noreturn_p (stmt);
4356 if (dump_file && (dump_flags & TDF_DETAILS))
4358 fprintf (dump_file, "Replacing call target with ");
4359 print_generic_expr (dump_file, fn, 0);
4360 fprintf (dump_file, " in ");
4361 print_gimple_stmt (dump_file, stmt, 0, 0);
4364 gimple_call_set_fn (stmt, fn);
4365 el_to_update.safe_push (stmt);
4367 /* When changing a call into a noreturn call, cfg cleanup
4368 is needed to fix up the noreturn call. */
4369 if (!was_noreturn && gimple_call_noreturn_p (stmt))
4370 el_todo |= TODO_cleanup_cfg;
4372 /* If we removed EH side-effects from the statement, clean
4373 its EH information. */
4374 if (maybe_clean_or_replace_eh_stmt (stmt, stmt))
4376 bitmap_set_bit (need_eh_cleanup,
4377 gimple_bb (stmt)->index);
4378 if (dump_file && (dump_flags & TDF_DETAILS))
4379 fprintf (dump_file, " Removed EH side-effects.\n");
4382 /* Likewise for AB side-effects. */
4383 if (can_make_abnormal_goto
4384 && !stmt_can_make_abnormal_goto (stmt))
4386 bitmap_set_bit (need_ab_cleanup,
4387 gimple_bb (stmt)->index);
4388 if (dump_file && (dump_flags & TDF_DETAILS))
4389 fprintf (dump_file, " Removed AB side-effects.\n");
4392 /* Changing an indirect call to a direct call may
4393 have exposed different semantics. This may
4394 require an SSA update. */
4395 el_todo |= TODO_update_ssa_only_virtuals;
4401 /* Make no longer available leaders no longer available. */
4403 void
4404 eliminate_dom_walker::after_dom_children (basic_block)
4406 tree entry;
4407 while ((entry = el_avail_stack.pop ()) != NULL_TREE)
4408 el_avail[SSA_NAME_VERSION (VN_INFO (entry)->valnum)] = NULL_TREE;
4411 /* Eliminate fully redundant computations. */
4413 static unsigned int
4414 eliminate (void)
4416 gimple_stmt_iterator gsi;
4417 gimple stmt;
4418 unsigned i;
4420 need_eh_cleanup = BITMAP_ALLOC (NULL);
4421 need_ab_cleanup = BITMAP_ALLOC (NULL);
4423 el_to_remove.create (0);
4424 el_to_update.create (0);
4425 el_todo = 0;
4426 el_avail.create (0);
4427 el_avail_stack.create (0);
4429 eliminate_dom_walker (CDI_DOMINATORS).walk (cfun->cfg->x_entry_block_ptr);
4431 el_avail.release ();
4432 el_avail_stack.release ();
4434 /* We cannot remove stmts during BB walk, especially not release SSA
4435 names there as this confuses the VN machinery. The stmts ending
4436 up in el_to_remove are either stores or simple copies. */
4437 FOR_EACH_VEC_ELT (el_to_remove, i, stmt)
4439 tree lhs = gimple_assign_lhs (stmt);
4440 tree rhs = gimple_assign_rhs1 (stmt);
4441 use_operand_p use_p;
4442 gimple use_stmt;
4444 /* If there is a single use only, propagate the equivalency
4445 instead of keeping the copy. */
4446 if (TREE_CODE (lhs) == SSA_NAME
4447 && TREE_CODE (rhs) == SSA_NAME
4448 && single_imm_use (lhs, &use_p, &use_stmt)
4449 && may_propagate_copy (USE_FROM_PTR (use_p), rhs))
4451 SET_USE (use_p, rhs);
4452 update_stmt (use_stmt);
4453 if (inserted_exprs
4454 && bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (lhs))
4455 && TREE_CODE (rhs) == SSA_NAME)
4456 gimple_set_plf (SSA_NAME_DEF_STMT (rhs), NECESSARY, true);
4459 /* If this is a store or a now unused copy, remove it. */
4460 if (TREE_CODE (lhs) != SSA_NAME
4461 || has_zero_uses (lhs))
4463 basic_block bb = gimple_bb (stmt);
4464 gsi = gsi_for_stmt (stmt);
4465 unlink_stmt_vdef (stmt);
4466 if (gsi_remove (&gsi, true))
4467 bitmap_set_bit (need_eh_cleanup, bb->index);
4468 if (inserted_exprs
4469 && TREE_CODE (lhs) == SSA_NAME)
4470 bitmap_clear_bit (inserted_exprs, SSA_NAME_VERSION (lhs));
4471 release_defs (stmt);
4474 el_to_remove.release ();
4476 /* We cannot update call statements with virtual operands during
4477 SSA walk. This might remove them which in turn makes our
4478 VN lattice invalid. */
4479 FOR_EACH_VEC_ELT (el_to_update, i, stmt)
4480 update_stmt (stmt);
4481 el_to_update.release ();
4483 return el_todo;
4486 /* Perform CFG cleanups made necessary by elimination. */
4488 static unsigned
4489 fini_eliminate (void)
4491 bool do_eh_cleanup = !bitmap_empty_p (need_eh_cleanup);
4492 bool do_ab_cleanup = !bitmap_empty_p (need_ab_cleanup);
4494 if (do_eh_cleanup)
4495 gimple_purge_all_dead_eh_edges (need_eh_cleanup);
4497 if (do_ab_cleanup)
4498 gimple_purge_all_dead_abnormal_call_edges (need_ab_cleanup);
4500 BITMAP_FREE (need_eh_cleanup);
4501 BITMAP_FREE (need_ab_cleanup);
4503 if (do_eh_cleanup || do_ab_cleanup)
4504 return TODO_cleanup_cfg;
4505 return 0;
4508 /* Borrow a bit of tree-ssa-dce.c for the moment.
4509 XXX: In 4.1, we should be able to just run a DCE pass after PRE, though
4510 this may be a bit faster, and we may want critical edges kept split. */
4512 /* If OP's defining statement has not already been determined to be necessary,
4513 mark that statement necessary. Return the stmt, if it is newly
4514 necessary. */
4516 static inline gimple
4517 mark_operand_necessary (tree op)
4519 gimple stmt;
4521 gcc_assert (op);
4523 if (TREE_CODE (op) != SSA_NAME)
4524 return NULL;
4526 stmt = SSA_NAME_DEF_STMT (op);
4527 gcc_assert (stmt);
4529 if (gimple_plf (stmt, NECESSARY)
4530 || gimple_nop_p (stmt))
4531 return NULL;
4533 gimple_set_plf (stmt, NECESSARY, true);
4534 return stmt;
4537 /* Because we don't follow exactly the standard PRE algorithm, and decide not
4538 to insert PHI nodes sometimes, and because value numbering of casts isn't
4539 perfect, we sometimes end up inserting dead code. This simple DCE-like
4540 pass removes any insertions we made that weren't actually used. */
4542 static void
4543 remove_dead_inserted_code (void)
4545 bitmap worklist;
4546 unsigned i;
4547 bitmap_iterator bi;
4548 gimple t;
4550 worklist = BITMAP_ALLOC (NULL);
4551 EXECUTE_IF_SET_IN_BITMAP (inserted_exprs, 0, i, bi)
4553 t = SSA_NAME_DEF_STMT (ssa_name (i));
4554 if (gimple_plf (t, NECESSARY))
4555 bitmap_set_bit (worklist, i);
4557 while (!bitmap_empty_p (worklist))
4559 i = bitmap_first_set_bit (worklist);
4560 bitmap_clear_bit (worklist, i);
4561 t = SSA_NAME_DEF_STMT (ssa_name (i));
4563 /* PHI nodes are somewhat special in that each PHI alternative has
4564 data and control dependencies. All the statements feeding the
4565 PHI node's arguments are always necessary. */
4566 if (gimple_code (t) == GIMPLE_PHI)
4568 unsigned k;
4570 for (k = 0; k < gimple_phi_num_args (t); k++)
4572 tree arg = PHI_ARG_DEF (t, k);
4573 if (TREE_CODE (arg) == SSA_NAME)
4575 gimple n = mark_operand_necessary (arg);
4576 if (n)
4577 bitmap_set_bit (worklist, SSA_NAME_VERSION (arg));
4581 else
4583 /* Propagate through the operands. Examine all the USE, VUSE and
4584 VDEF operands in this statement. Mark all the statements
4585 which feed this statement's uses as necessary. */
4586 ssa_op_iter iter;
4587 tree use;
4589 /* The operands of VDEF expressions are also needed as they
4590 represent potential definitions that may reach this
4591 statement (VDEF operands allow us to follow def-def
4592 links). */
4594 FOR_EACH_SSA_TREE_OPERAND (use, t, iter, SSA_OP_ALL_USES)
4596 gimple n = mark_operand_necessary (use);
4597 if (n)
4598 bitmap_set_bit (worklist, SSA_NAME_VERSION (use));
4603 EXECUTE_IF_SET_IN_BITMAP (inserted_exprs, 0, i, bi)
4605 t = SSA_NAME_DEF_STMT (ssa_name (i));
4606 if (!gimple_plf (t, NECESSARY))
4608 gimple_stmt_iterator gsi;
4610 if (dump_file && (dump_flags & TDF_DETAILS))
4612 fprintf (dump_file, "Removing unnecessary insertion:");
4613 print_gimple_stmt (dump_file, t, 0, 0);
4616 gsi = gsi_for_stmt (t);
4617 if (gimple_code (t) == GIMPLE_PHI)
4618 remove_phi_node (&gsi, true);
4619 else
4621 gsi_remove (&gsi, true);
4622 release_defs (t);
4626 BITMAP_FREE (worklist);
4630 /* Initialize data structures used by PRE. */
4632 static void
4633 init_pre (void)
4635 basic_block bb;
4637 next_expression_id = 1;
4638 expressions.create (0);
4639 expressions.safe_push (NULL);
4640 value_expressions.create (get_max_value_id () + 1);
4641 value_expressions.safe_grow_cleared (get_max_value_id () + 1);
4642 name_to_id.create (0);
4644 inserted_exprs = BITMAP_ALLOC (NULL);
4646 connect_infinite_loops_to_exit ();
4647 memset (&pre_stats, 0, sizeof (pre_stats));
4649 postorder = XNEWVEC (int, n_basic_blocks);
4650 postorder_num = inverted_post_order_compute (postorder);
4652 alloc_aux_for_blocks (sizeof (struct bb_bitmap_sets));
4654 calculate_dominance_info (CDI_POST_DOMINATORS);
4655 calculate_dominance_info (CDI_DOMINATORS);
4657 bitmap_obstack_initialize (&grand_bitmap_obstack);
4658 phi_translate_table.create (5110);
4659 expression_to_id.create (num_ssa_names * 3);
4660 bitmap_set_pool = create_alloc_pool ("Bitmap sets",
4661 sizeof (struct bitmap_set), 30);
4662 pre_expr_pool = create_alloc_pool ("pre_expr nodes",
4663 sizeof (struct pre_expr_d), 30);
4664 FOR_ALL_BB (bb)
4666 EXP_GEN (bb) = bitmap_set_new ();
4667 PHI_GEN (bb) = bitmap_set_new ();
4668 TMP_GEN (bb) = bitmap_set_new ();
4669 AVAIL_OUT (bb) = bitmap_set_new ();
4674 /* Deallocate data structures used by PRE. */
4676 static void
4677 fini_pre ()
4679 free (postorder);
4680 value_expressions.release ();
4681 BITMAP_FREE (inserted_exprs);
4682 bitmap_obstack_release (&grand_bitmap_obstack);
4683 free_alloc_pool (bitmap_set_pool);
4684 free_alloc_pool (pre_expr_pool);
4685 phi_translate_table.dispose ();
4686 expression_to_id.dispose ();
4687 name_to_id.release ();
4689 free_aux_for_blocks ();
4691 free_dominance_info (CDI_POST_DOMINATORS);
4694 /* Gate and execute functions for PRE. */
4696 static unsigned int
4697 do_pre (void)
4699 unsigned int todo = 0;
4701 do_partial_partial =
4702 flag_tree_partial_pre && optimize_function_for_speed_p (cfun);
4704 /* This has to happen before SCCVN runs because
4705 loop_optimizer_init may create new phis, etc. */
4706 loop_optimizer_init (LOOPS_NORMAL);
4708 if (!run_scc_vn (VN_WALK))
4710 loop_optimizer_finalize ();
4711 return 0;
4714 init_pre ();
4715 scev_initialize ();
4717 /* Collect and value number expressions computed in each basic block. */
4718 compute_avail ();
4720 /* Insert can get quite slow on an incredibly large number of basic
4721 blocks due to some quadratic behavior. Until this behavior is
4722 fixed, don't run it when he have an incredibly large number of
4723 bb's. If we aren't going to run insert, there is no point in
4724 computing ANTIC, either, even though it's plenty fast. */
4725 if (n_basic_blocks < 4000)
4727 compute_antic ();
4728 insert ();
4731 /* Make sure to remove fake edges before committing our inserts.
4732 This makes sure we don't end up with extra critical edges that
4733 we would need to split. */
4734 remove_fake_exit_edges ();
4735 gsi_commit_edge_inserts ();
4737 /* Remove all the redundant expressions. */
4738 todo |= eliminate ();
4740 statistics_counter_event (cfun, "Insertions", pre_stats.insertions);
4741 statistics_counter_event (cfun, "PA inserted", pre_stats.pa_insert);
4742 statistics_counter_event (cfun, "New PHIs", pre_stats.phis);
4743 statistics_counter_event (cfun, "Eliminated", pre_stats.eliminations);
4745 clear_expression_ids ();
4746 remove_dead_inserted_code ();
4747 todo |= TODO_verify_flow;
4749 scev_finalize ();
4750 fini_pre ();
4751 todo |= fini_eliminate ();
4752 loop_optimizer_finalize ();
4754 /* TODO: tail_merge_optimize may merge all predecessors of a block, in which
4755 case we can merge the block with the remaining predecessor of the block.
4756 It should either:
4757 - call merge_blocks after each tail merge iteration
4758 - call merge_blocks after all tail merge iterations
4759 - mark TODO_cleanup_cfg when necessary
4760 - share the cfg cleanup with fini_pre. */
4761 todo |= tail_merge_optimize (todo);
4763 free_scc_vn ();
4765 /* Tail merging invalidates the virtual SSA web, together with
4766 cfg-cleanup opportunities exposed by PRE this will wreck the
4767 SSA updating machinery. So make sure to run update-ssa
4768 manually, before eventually scheduling cfg-cleanup as part of
4769 the todo. */
4770 update_ssa (TODO_update_ssa_only_virtuals);
4772 return todo;
4775 static bool
4776 gate_pre (void)
4778 return flag_tree_pre != 0;
4781 namespace {
4783 const pass_data pass_data_pre =
4785 GIMPLE_PASS, /* type */
4786 "pre", /* name */
4787 OPTGROUP_NONE, /* optinfo_flags */
4788 true, /* has_gate */
4789 true, /* has_execute */
4790 TV_TREE_PRE, /* tv_id */
4791 ( PROP_no_crit_edges | PROP_cfg | PROP_ssa ), /* properties_required */
4792 0, /* properties_provided */
4793 0, /* properties_destroyed */
4794 TODO_rebuild_alias, /* todo_flags_start */
4795 TODO_verify_ssa, /* todo_flags_finish */
4798 class pass_pre : public gimple_opt_pass
4800 public:
4801 pass_pre (gcc::context *ctxt)
4802 : gimple_opt_pass (pass_data_pre, ctxt)
4805 /* opt_pass methods: */
4806 bool gate () { return gate_pre (); }
4807 unsigned int execute () { return do_pre (); }
4809 }; // class pass_pre
4811 } // anon namespace
4813 gimple_opt_pass *
4814 make_pass_pre (gcc::context *ctxt)
4816 return new pass_pre (ctxt);
4820 /* Gate and execute functions for FRE. */
4822 static unsigned int
4823 execute_fre (void)
4825 unsigned int todo = 0;
4827 if (!run_scc_vn (VN_WALKREWRITE))
4828 return 0;
4830 memset (&pre_stats, 0, sizeof (pre_stats));
4832 /* Remove all the redundant expressions. */
4833 todo |= eliminate ();
4835 todo |= fini_eliminate ();
4837 free_scc_vn ();
4839 statistics_counter_event (cfun, "Insertions", pre_stats.insertions);
4840 statistics_counter_event (cfun, "Eliminated", pre_stats.eliminations);
4842 return todo;
4845 static bool
4846 gate_fre (void)
4848 return flag_tree_fre != 0;
4851 namespace {
4853 const pass_data pass_data_fre =
4855 GIMPLE_PASS, /* type */
4856 "fre", /* name */
4857 OPTGROUP_NONE, /* optinfo_flags */
4858 true, /* has_gate */
4859 true, /* has_execute */
4860 TV_TREE_FRE, /* tv_id */
4861 ( PROP_cfg | PROP_ssa ), /* properties_required */
4862 0, /* properties_provided */
4863 0, /* properties_destroyed */
4864 0, /* todo_flags_start */
4865 TODO_verify_ssa, /* todo_flags_finish */
4868 class pass_fre : public gimple_opt_pass
4870 public:
4871 pass_fre (gcc::context *ctxt)
4872 : gimple_opt_pass (pass_data_fre, ctxt)
4875 /* opt_pass methods: */
4876 opt_pass * clone () { return new pass_fre (m_ctxt); }
4877 bool gate () { return gate_fre (); }
4878 unsigned int execute () { return execute_fre (); }
4880 }; // class pass_fre
4882 } // anon namespace
4884 gimple_opt_pass *
4885 make_pass_fre (gcc::context *ctxt)
4887 return new pass_fre (ctxt);