1 /* SSA-PRE for trees.
2    Copyright (C) 2001-2014 Free Software Foundation, Inc.
3    Contributed by Daniel Berlin <dan@dberlin.org> and Steven Bosscher
4    <stevenb@suse.de>
5 
6 This file is part of GCC.
7 
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.
12 
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.
17 
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/>.  */
21 
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 "hash-table.h"
31 #include "tree-ssa-alias.h"
32 #include "internal-fn.h"
33 #include "gimple-fold.h"
34 #include "tree-eh.h"
35 #include "gimple-expr.h"
36 #include "is-a.h"
37 #include "gimple.h"
38 #include "gimplify.h"
39 #include "gimple-iterator.h"
40 #include "gimplify-me.h"
41 #include "gimple-ssa.h"
42 #include "tree-cfg.h"
43 #include "tree-phinodes.h"
44 #include "ssa-iterators.h"
45 #include "stringpool.h"
46 #include "tree-ssanames.h"
47 #include "tree-ssa-loop.h"
48 #include "tree-into-ssa.h"
49 #include "expr.h"
50 #include "tree-dfa.h"
51 #include "tree-ssa.h"
52 #include "tree-iterator.h"
53 #include "alloc-pool.h"
54 #include "obstack.h"
55 #include "tree-pass.h"
56 #include "flags.h"
57 #include "langhooks.h"
58 #include "cfgloop.h"
59 #include "tree-ssa-sccvn.h"
60 #include "tree-scalar-evolution.h"
61 #include "params.h"
62 #include "dbgcnt.h"
63 #include "domwalk.h"
64 #include "ipa-prop.h"
65 #include "tree-ssa-propagate.h"
66 
67 /* TODO:
68 
69    1. Avail sets can be shared by making an avail_find_leader that
70       walks up the dominator tree and looks in those avail sets.
71       This might affect code optimality, it's unclear right now.
72    2. Strength reduction can be performed by anticipating expressions
73       we can repair later on.
74    3. We can do back-substitution or smarter value numbering to catch
75       commutative expressions split up over multiple statements.
76 */
77 
78 /* For ease of terminology, "expression node" in the below refers to
79    every expression node but GIMPLE_ASSIGN, because GIMPLE_ASSIGNs
80    represent the actual statement containing the expressions we care about,
81    and we cache the value number by putting it in the expression.  */
82 
83 /* Basic algorithm
84 
85    First we walk the statements to generate the AVAIL sets, the
86    EXP_GEN sets, and the tmp_gen sets.  EXP_GEN sets represent the
87    generation of values/expressions by a given block.  We use them
88    when computing the ANTIC sets.  The AVAIL sets consist of
89    SSA_NAME's that represent values, so we know what values are
90    available in what blocks.  AVAIL is a forward dataflow problem.  In
91    SSA, values are never killed, so we don't need a kill set, or a
92    fixpoint iteration, in order to calculate the AVAIL sets.  In
93    traditional parlance, AVAIL sets tell us the downsafety of the
94    expressions/values.
95 
96    Next, we generate the ANTIC sets.  These sets represent the
97    anticipatable expressions.  ANTIC is a backwards dataflow
98    problem.  An expression is anticipatable in a given block if it could
99    be generated in that block.  This means that if we had to perform
100    an insertion in that block, of the value of that expression, we
101    could.  Calculating the ANTIC sets requires phi translation of
102    expressions, because the flow goes backwards through phis.  We must
103    iterate to a fixpoint of the ANTIC sets, because we have a kill
104    set.  Even in SSA form, values are not live over the entire
105    function, only from their definition point onwards.  So we have to
106    remove values from the ANTIC set once we go past the definition
107    point of the leaders that make them up.
108    compute_antic/compute_antic_aux performs this computation.
109 
110    Third, we perform insertions to make partially redundant
111    expressions fully redundant.
112 
113    An expression is partially redundant (excluding partial
114    anticipation) if:
115 
116    1. It is AVAIL in some, but not all, of the predecessors of a
117       given block.
118    2. It is ANTIC in all the predecessors.
119 
120    In order to make it fully redundant, we insert the expression into
121    the predecessors where it is not available, but is ANTIC.
122 
123    For the partial anticipation case, we only perform insertion if it
124    is partially anticipated in some block, and fully available in all
125    of the predecessors.
126 
127    insert/insert_aux/do_regular_insertion/do_partial_partial_insertion
128    performs these steps.
129 
130    Fourth, we eliminate fully redundant expressions.
131    This is a simple statement walk that replaces redundant
132    calculations with the now available values.  */
133 
134 /* Representations of value numbers:
135 
136    Value numbers are represented by a representative SSA_NAME.  We
137    will create fake SSA_NAME's in situations where we need a
138    representative but do not have one (because it is a complex
139    expression).  In order to facilitate storing the value numbers in
140    bitmaps, and keep the number of wasted SSA_NAME's down, we also
141    associate a value_id with each value number, and create full blown
142    ssa_name's only where we actually need them (IE in operands of
143    existing expressions).
144 
145    Theoretically you could replace all the value_id's with
146    SSA_NAME_VERSION, but this would allocate a large number of
147    SSA_NAME's (which are each > 30 bytes) just to get a 4 byte number.
148    It would also require an additional indirection at each point we
149    use the value id.  */
150 
151 /* Representation of expressions on value numbers:
152 
153    Expressions consisting of value numbers are represented the same
154    way as our VN internally represents them, with an additional
155    "pre_expr" wrapping around them in order to facilitate storing all
156    of the expressions in the same sets.  */
157 
158 /* Representation of sets:
159 
160    The dataflow sets do not need to be sorted in any particular order
161    for the majority of their lifetime, are simply represented as two
162    bitmaps, one that keeps track of values present in the set, and one
163    that keeps track of expressions present in the set.
164 
165    When we need them in topological order, we produce it on demand by
166    transforming the bitmap into an array and sorting it into topo
167    order.  */
168 
169 /* Type of expression, used to know which member of the PRE_EXPR union
170    is valid.  */
171 
172 enum pre_expr_kind
173 {
174     NAME,
175     NARY,
176     REFERENCE,
177     CONSTANT
178 };
179 
180 typedef union pre_expr_union_d
181 {
182   tree name;
183   tree constant;
184   vn_nary_op_t nary;
185   vn_reference_t reference;
186 } pre_expr_union;
187 
188 typedef struct pre_expr_d : typed_noop_remove <pre_expr_d>
189 {
190   enum pre_expr_kind kind;
191   unsigned int id;
192   pre_expr_union u;
193 
194   /* hash_table support.  */
195   typedef pre_expr_d value_type;
196   typedef pre_expr_d compare_type;
197   static inline hashval_t hash (const pre_expr_d *);
198   static inline int equal (const pre_expr_d *, const pre_expr_d *);
199 } *pre_expr;
200 
201 #define PRE_EXPR_NAME(e) (e)->u.name
202 #define PRE_EXPR_NARY(e) (e)->u.nary
203 #define PRE_EXPR_REFERENCE(e) (e)->u.reference
204 #define PRE_EXPR_CONSTANT(e) (e)->u.constant
205 
206 /* Compare E1 and E1 for equality.  */
207 
208 inline int
equal(const value_type * e1,const compare_type * e2)209 pre_expr_d::equal (const value_type *e1, const compare_type *e2)
210 {
211   if (e1->kind != e2->kind)
212     return false;
213 
214   switch (e1->kind)
215     {
216     case CONSTANT:
217       return vn_constant_eq_with_type (PRE_EXPR_CONSTANT (e1),
218 				       PRE_EXPR_CONSTANT (e2));
219     case NAME:
220       return PRE_EXPR_NAME (e1) == PRE_EXPR_NAME (e2);
221     case NARY:
222       return vn_nary_op_eq (PRE_EXPR_NARY (e1), PRE_EXPR_NARY (e2));
223     case REFERENCE:
224       return vn_reference_eq (PRE_EXPR_REFERENCE (e1),
225 			      PRE_EXPR_REFERENCE (e2));
226     default:
227       gcc_unreachable ();
228     }
229 }
230 
231 /* Hash E.  */
232 
233 inline hashval_t
hash(const value_type * e)234 pre_expr_d::hash (const value_type *e)
235 {
236   switch (e->kind)
237     {
238     case CONSTANT:
239       return vn_hash_constant_with_type (PRE_EXPR_CONSTANT (e));
240     case NAME:
241       return SSA_NAME_VERSION (PRE_EXPR_NAME (e));
242     case NARY:
243       return PRE_EXPR_NARY (e)->hashcode;
244     case REFERENCE:
245       return PRE_EXPR_REFERENCE (e)->hashcode;
246     default:
247       gcc_unreachable ();
248     }
249 }
250 
251 /* Next global expression id number.  */
252 static unsigned int next_expression_id;
253 
254 /* Mapping from expression to id number we can use in bitmap sets.  */
255 static vec<pre_expr> expressions;
256 static hash_table <pre_expr_d> expression_to_id;
257 static vec<unsigned> name_to_id;
258 
259 /* Allocate an expression id for EXPR.  */
260 
261 static inline unsigned int
alloc_expression_id(pre_expr expr)262 alloc_expression_id (pre_expr expr)
263 {
264   struct pre_expr_d **slot;
265   /* Make sure we won't overflow. */
266   gcc_assert (next_expression_id + 1 > next_expression_id);
267   expr->id = next_expression_id++;
268   expressions.safe_push (expr);
269   if (expr->kind == NAME)
270     {
271       unsigned version = SSA_NAME_VERSION (PRE_EXPR_NAME (expr));
272       /* vec::safe_grow_cleared allocates no headroom.  Avoid frequent
273 	 re-allocations by using vec::reserve upfront.  There is no
274 	 vec::quick_grow_cleared unfortunately.  */
275       unsigned old_len = name_to_id.length ();
276       name_to_id.reserve (num_ssa_names - old_len);
277       name_to_id.safe_grow_cleared (num_ssa_names);
278       gcc_assert (name_to_id[version] == 0);
279       name_to_id[version] = expr->id;
280     }
281   else
282     {
283       slot = expression_to_id.find_slot (expr, INSERT);
284       gcc_assert (!*slot);
285       *slot = expr;
286     }
287   return next_expression_id - 1;
288 }
289 
290 /* Return the expression id for tree EXPR.  */
291 
292 static inline unsigned int
get_expression_id(const pre_expr expr)293 get_expression_id (const pre_expr expr)
294 {
295   return expr->id;
296 }
297 
298 static inline unsigned int
lookup_expression_id(const pre_expr expr)299 lookup_expression_id (const pre_expr expr)
300 {
301   struct pre_expr_d **slot;
302 
303   if (expr->kind == NAME)
304     {
305       unsigned version = SSA_NAME_VERSION (PRE_EXPR_NAME (expr));
306       if (name_to_id.length () <= version)
307 	return 0;
308       return name_to_id[version];
309     }
310   else
311     {
312       slot = expression_to_id.find_slot (expr, NO_INSERT);
313       if (!slot)
314 	return 0;
315       return ((pre_expr)*slot)->id;
316     }
317 }
318 
319 /* Return the existing expression id for EXPR, or create one if one
320    does not exist yet.  */
321 
322 static inline unsigned int
get_or_alloc_expression_id(pre_expr expr)323 get_or_alloc_expression_id (pre_expr expr)
324 {
325   unsigned int id = lookup_expression_id (expr);
326   if (id == 0)
327     return alloc_expression_id (expr);
328   return expr->id = id;
329 }
330 
331 /* Return the expression that has expression id ID */
332 
333 static inline pre_expr
expression_for_id(unsigned int id)334 expression_for_id (unsigned int id)
335 {
336   return expressions[id];
337 }
338 
339 /* Free the expression id field in all of our expressions,
340    and then destroy the expressions array.  */
341 
342 static void
clear_expression_ids(void)343 clear_expression_ids (void)
344 {
345   expressions.release ();
346 }
347 
348 static alloc_pool pre_expr_pool;
349 
350 /* Given an SSA_NAME NAME, get or create a pre_expr to represent it.  */
351 
352 static pre_expr
get_or_alloc_expr_for_name(tree name)353 get_or_alloc_expr_for_name (tree name)
354 {
355   struct pre_expr_d expr;
356   pre_expr result;
357   unsigned int result_id;
358 
359   expr.kind = NAME;
360   expr.id = 0;
361   PRE_EXPR_NAME (&expr) = name;
362   result_id = lookup_expression_id (&expr);
363   if (result_id != 0)
364     return expression_for_id (result_id);
365 
366   result = (pre_expr) pool_alloc (pre_expr_pool);
367   result->kind = NAME;
368   PRE_EXPR_NAME (result) = name;
369   alloc_expression_id (result);
370   return result;
371 }
372 
373 /* An unordered bitmap set.  One bitmap tracks values, the other,
374    expressions.  */
375 typedef struct bitmap_set
376 {
377   bitmap_head expressions;
378   bitmap_head values;
379 } *bitmap_set_t;
380 
381 #define FOR_EACH_EXPR_ID_IN_SET(set, id, bi)		\
382   EXECUTE_IF_SET_IN_BITMAP (&(set)->expressions, 0, (id), (bi))
383 
384 #define FOR_EACH_VALUE_ID_IN_SET(set, id, bi)		\
385   EXECUTE_IF_SET_IN_BITMAP (&(set)->values, 0, (id), (bi))
386 
387 /* Mapping from value id to expressions with that value_id.  */
388 static vec<bitmap> value_expressions;
389 
390 /* Sets that we need to keep track of.  */
391 typedef struct bb_bitmap_sets
392 {
393   /* The EXP_GEN set, which represents expressions/values generated in
394      a basic block.  */
395   bitmap_set_t exp_gen;
396 
397   /* The PHI_GEN set, which represents PHI results generated in a
398      basic block.  */
399   bitmap_set_t phi_gen;
400 
401   /* The TMP_GEN set, which represents results/temporaries generated
402      in a basic block. IE the LHS of an expression.  */
403   bitmap_set_t tmp_gen;
404 
405   /* The AVAIL_OUT set, which represents which values are available in
406      a given basic block.  */
407   bitmap_set_t avail_out;
408 
409   /* The ANTIC_IN set, which represents which values are anticipatable
410      in a given basic block.  */
411   bitmap_set_t antic_in;
412 
413   /* The PA_IN set, which represents which values are
414      partially anticipatable in a given basic block.  */
415   bitmap_set_t pa_in;
416 
417   /* The NEW_SETS set, which is used during insertion to augment the
418      AVAIL_OUT set of blocks with the new insertions performed during
419      the current iteration.  */
420   bitmap_set_t new_sets;
421 
422   /* A cache for value_dies_in_block_x.  */
423   bitmap expr_dies;
424 
425   /* True if we have visited this block during ANTIC calculation.  */
426   unsigned int visited : 1;
427 
428   /* True we have deferred processing this block during ANTIC
429      calculation until its successor is processed.  */
430   unsigned int deferred : 1;
431 
432   /* True when the block contains a call that might not return.  */
433   unsigned int contains_may_not_return_call : 1;
434 } *bb_value_sets_t;
435 
436 #define EXP_GEN(BB)	((bb_value_sets_t) ((BB)->aux))->exp_gen
437 #define PHI_GEN(BB)	((bb_value_sets_t) ((BB)->aux))->phi_gen
438 #define TMP_GEN(BB)	((bb_value_sets_t) ((BB)->aux))->tmp_gen
439 #define AVAIL_OUT(BB)	((bb_value_sets_t) ((BB)->aux))->avail_out
440 #define ANTIC_IN(BB)	((bb_value_sets_t) ((BB)->aux))->antic_in
441 #define PA_IN(BB)	((bb_value_sets_t) ((BB)->aux))->pa_in
442 #define NEW_SETS(BB)	((bb_value_sets_t) ((BB)->aux))->new_sets
443 #define EXPR_DIES(BB)	((bb_value_sets_t) ((BB)->aux))->expr_dies
444 #define BB_VISITED(BB)	((bb_value_sets_t) ((BB)->aux))->visited
445 #define BB_DEFERRED(BB) ((bb_value_sets_t) ((BB)->aux))->deferred
446 #define BB_MAY_NOTRETURN(BB) ((bb_value_sets_t) ((BB)->aux))->contains_may_not_return_call
447 
448 
449 /* Basic block list in postorder.  */
450 static int *postorder;
451 static int postorder_num;
452 
453 /* This structure is used to keep track of statistics on what
454    optimization PRE was able to perform.  */
455 static struct
456 {
457   /* The number of RHS computations eliminated by PRE.  */
458   int eliminations;
459 
460   /* The number of new expressions/temporaries generated by PRE.  */
461   int insertions;
462 
463   /* The number of inserts found due to partial anticipation  */
464   int pa_insert;
465 
466   /* The number of new PHI nodes added by PRE.  */
467   int phis;
468 } pre_stats;
469 
470 static bool do_partial_partial;
471 static pre_expr bitmap_find_leader (bitmap_set_t, unsigned int);
472 static void bitmap_value_insert_into_set (bitmap_set_t, pre_expr);
473 static void bitmap_value_replace_in_set (bitmap_set_t, pre_expr);
474 static void bitmap_set_copy (bitmap_set_t, bitmap_set_t);
475 static bool bitmap_set_contains_value (bitmap_set_t, unsigned int);
476 static void bitmap_insert_into_set (bitmap_set_t, pre_expr);
477 static void bitmap_insert_into_set_1 (bitmap_set_t, pre_expr,
478 				      unsigned int, bool);
479 static bitmap_set_t bitmap_set_new (void);
480 static tree create_expression_by_pieces (basic_block, pre_expr, gimple_seq *,
481 					 tree);
482 static tree find_or_generate_expression (basic_block, tree, gimple_seq *);
483 static unsigned int get_expr_value_id (pre_expr);
484 
485 /* We can add and remove elements and entries to and from sets
486    and hash tables, so we use alloc pools for them.  */
487 
488 static alloc_pool bitmap_set_pool;
489 static bitmap_obstack grand_bitmap_obstack;
490 
491 /* Set of blocks with statements that have had their EH properties changed.  */
492 static bitmap need_eh_cleanup;
493 
494 /* Set of blocks with statements that have had their AB properties changed.  */
495 static bitmap need_ab_cleanup;
496 
497 /* A three tuple {e, pred, v} used to cache phi translations in the
498    phi_translate_table.  */
499 
500 typedef struct expr_pred_trans_d : typed_free_remove<expr_pred_trans_d>
501 {
502   /* The expression.  */
503   pre_expr e;
504 
505   /* The predecessor block along which we translated the expression.  */
506   basic_block pred;
507 
508   /* The value that resulted from the translation.  */
509   pre_expr v;
510 
511   /* The hashcode for the expression, pred pair. This is cached for
512      speed reasons.  */
513   hashval_t hashcode;
514 
515   /* hash_table support.  */
516   typedef expr_pred_trans_d value_type;
517   typedef expr_pred_trans_d compare_type;
518   static inline hashval_t hash (const value_type *);
519   static inline int equal (const value_type *, const compare_type *);
520 } *expr_pred_trans_t;
521 typedef const struct expr_pred_trans_d *const_expr_pred_trans_t;
522 
523 inline hashval_t
hash(const expr_pred_trans_d * e)524 expr_pred_trans_d::hash (const expr_pred_trans_d *e)
525 {
526   return e->hashcode;
527 }
528 
529 inline int
equal(const value_type * ve1,const compare_type * ve2)530 expr_pred_trans_d::equal (const value_type *ve1,
531 			  const compare_type *ve2)
532 {
533   basic_block b1 = ve1->pred;
534   basic_block b2 = ve2->pred;
535 
536   /* If they are not translations for the same basic block, they can't
537      be equal.  */
538   if (b1 != b2)
539     return false;
540   return pre_expr_d::equal (ve1->e, ve2->e);
541 }
542 
543 /* The phi_translate_table caches phi translations for a given
544    expression and predecessor.  */
545 static hash_table <expr_pred_trans_d> phi_translate_table;
546 
547 /* Add the tuple mapping from {expression E, basic block PRED} to
548    the phi translation table and return whether it pre-existed.  */
549 
550 static inline bool
phi_trans_add(expr_pred_trans_t * entry,pre_expr e,basic_block pred)551 phi_trans_add (expr_pred_trans_t *entry, pre_expr e, basic_block pred)
552 {
553   expr_pred_trans_t *slot;
554   expr_pred_trans_d tem;
555   hashval_t hash = iterative_hash_hashval_t (pre_expr_d::hash (e),
556 					     pred->index);
557   tem.e = e;
558   tem.pred = pred;
559   tem.hashcode = hash;
560   slot = phi_translate_table.find_slot_with_hash (&tem, hash, INSERT);
561   if (*slot)
562     {
563       *entry = *slot;
564       return true;
565     }
566 
567   *entry = *slot = XNEW (struct expr_pred_trans_d);
568   (*entry)->e = e;
569   (*entry)->pred = pred;
570   (*entry)->hashcode = hash;
571   return false;
572 }
573 
574 
575 /* Add expression E to the expression set of value id V.  */
576 
577 static void
add_to_value(unsigned int v,pre_expr e)578 add_to_value (unsigned int v, pre_expr e)
579 {
580   bitmap set;
581 
582   gcc_checking_assert (get_expr_value_id (e) == v);
583 
584   if (v >= value_expressions.length ())
585     {
586       value_expressions.safe_grow_cleared (v + 1);
587     }
588 
589   set = value_expressions[v];
590   if (!set)
591     {
592       set = BITMAP_ALLOC (&grand_bitmap_obstack);
593       value_expressions[v] = set;
594     }
595 
596   bitmap_set_bit (set, get_or_alloc_expression_id (e));
597 }
598 
599 /* Create a new bitmap set and return it.  */
600 
601 static bitmap_set_t
bitmap_set_new(void)602 bitmap_set_new (void)
603 {
604   bitmap_set_t ret = (bitmap_set_t) pool_alloc (bitmap_set_pool);
605   bitmap_initialize (&ret->expressions, &grand_bitmap_obstack);
606   bitmap_initialize (&ret->values, &grand_bitmap_obstack);
607   return ret;
608 }
609 
610 /* Return the value id for a PRE expression EXPR.  */
611 
612 static unsigned int
get_expr_value_id(pre_expr expr)613 get_expr_value_id (pre_expr expr)
614 {
615   unsigned int id;
616   switch (expr->kind)
617     {
618     case CONSTANT:
619       id = get_constant_value_id (PRE_EXPR_CONSTANT (expr));
620       break;
621     case NAME:
622       id = VN_INFO (PRE_EXPR_NAME (expr))->value_id;
623       break;
624     case NARY:
625       id = PRE_EXPR_NARY (expr)->value_id;
626       break;
627     case REFERENCE:
628       id = PRE_EXPR_REFERENCE (expr)->value_id;
629       break;
630     default:
631       gcc_unreachable ();
632     }
633   /* ???  We cannot assert that expr has a value-id (it can be 0), because
634      we assign value-ids only to expressions that have a result
635      in set_hashtable_value_ids.  */
636   return id;
637 }
638 
639 /* Return a SCCVN valnum (SSA name or constant) for the PRE value-id VAL.  */
640 
641 static tree
sccvn_valnum_from_value_id(unsigned int val)642 sccvn_valnum_from_value_id (unsigned int val)
643 {
644   bitmap_iterator bi;
645   unsigned int i;
646   bitmap exprset = value_expressions[val];
647   EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
648     {
649       pre_expr vexpr = expression_for_id (i);
650       if (vexpr->kind == NAME)
651 	return VN_INFO (PRE_EXPR_NAME (vexpr))->valnum;
652       else if (vexpr->kind == CONSTANT)
653 	return PRE_EXPR_CONSTANT (vexpr);
654     }
655   return NULL_TREE;
656 }
657 
658 /* Remove an expression EXPR from a bitmapped set.  */
659 
660 static void
bitmap_remove_from_set(bitmap_set_t set,pre_expr expr)661 bitmap_remove_from_set (bitmap_set_t set, pre_expr expr)
662 {
663   unsigned int val  = get_expr_value_id (expr);
664   if (!value_id_constant_p (val))
665     {
666       bitmap_clear_bit (&set->values, val);
667       bitmap_clear_bit (&set->expressions, get_expression_id (expr));
668     }
669 }
670 
671 static void
bitmap_insert_into_set_1(bitmap_set_t set,pre_expr expr,unsigned int val,bool allow_constants)672 bitmap_insert_into_set_1 (bitmap_set_t set, pre_expr expr,
673 			  unsigned int val, bool allow_constants)
674 {
675   if (allow_constants || !value_id_constant_p (val))
676     {
677       /* We specifically expect this and only this function to be able to
678 	 insert constants into a set.  */
679       bitmap_set_bit (&set->values, val);
680       bitmap_set_bit (&set->expressions, get_or_alloc_expression_id (expr));
681     }
682 }
683 
684 /* Insert an expression EXPR into a bitmapped set.  */
685 
686 static void
bitmap_insert_into_set(bitmap_set_t set,pre_expr expr)687 bitmap_insert_into_set (bitmap_set_t set, pre_expr expr)
688 {
689   bitmap_insert_into_set_1 (set, expr, get_expr_value_id (expr), false);
690 }
691 
692 /* Copy a bitmapped set ORIG, into bitmapped set DEST.  */
693 
694 static void
bitmap_set_copy(bitmap_set_t dest,bitmap_set_t orig)695 bitmap_set_copy (bitmap_set_t dest, bitmap_set_t orig)
696 {
697   bitmap_copy (&dest->expressions, &orig->expressions);
698   bitmap_copy (&dest->values, &orig->values);
699 }
700 
701 
702 /* Free memory used up by SET.  */
703 static void
bitmap_set_free(bitmap_set_t set)704 bitmap_set_free (bitmap_set_t set)
705 {
706   bitmap_clear (&set->expressions);
707   bitmap_clear (&set->values);
708 }
709 
710 
711 /* Generate an topological-ordered array of bitmap set SET.  */
712 
713 static vec<pre_expr>
sorted_array_from_bitmap_set(bitmap_set_t set)714 sorted_array_from_bitmap_set (bitmap_set_t set)
715 {
716   unsigned int i, j;
717   bitmap_iterator bi, bj;
718   vec<pre_expr> result;
719 
720   /* Pre-allocate roughly enough space for the array.  */
721   result.create (bitmap_count_bits (&set->values));
722 
723   FOR_EACH_VALUE_ID_IN_SET (set, i, bi)
724     {
725       /* The number of expressions having a given value is usually
726 	 relatively small.  Thus, rather than making a vector of all
727 	 the expressions and sorting it by value-id, we walk the values
728 	 and check in the reverse mapping that tells us what expressions
729 	 have a given value, to filter those in our set.  As a result,
730 	 the expressions are inserted in value-id order, which means
731 	 topological order.
732 
733 	 If this is somehow a significant lose for some cases, we can
734 	 choose which set to walk based on the set size.  */
735       bitmap exprset = value_expressions[i];
736       EXECUTE_IF_SET_IN_BITMAP (exprset, 0, j, bj)
737 	{
738 	  if (bitmap_bit_p (&set->expressions, j))
739 	    result.safe_push (expression_for_id (j));
740         }
741     }
742 
743   return result;
744 }
745 
746 /* Perform bitmapped set operation DEST &= ORIG.  */
747 
748 static void
bitmap_set_and(bitmap_set_t dest,bitmap_set_t orig)749 bitmap_set_and (bitmap_set_t dest, bitmap_set_t orig)
750 {
751   bitmap_iterator bi;
752   unsigned int i;
753 
754   if (dest != orig)
755     {
756       bitmap_head temp;
757       bitmap_initialize (&temp, &grand_bitmap_obstack);
758 
759       bitmap_and_into (&dest->values, &orig->values);
760       bitmap_copy (&temp, &dest->expressions);
761       EXECUTE_IF_SET_IN_BITMAP (&temp, 0, i, bi)
762 	{
763 	  pre_expr expr = expression_for_id (i);
764 	  unsigned int value_id = get_expr_value_id (expr);
765 	  if (!bitmap_bit_p (&dest->values, value_id))
766 	    bitmap_clear_bit (&dest->expressions, i);
767 	}
768       bitmap_clear (&temp);
769     }
770 }
771 
772 /* Subtract all values and expressions contained in ORIG from DEST.  */
773 
774 static bitmap_set_t
bitmap_set_subtract(bitmap_set_t dest,bitmap_set_t orig)775 bitmap_set_subtract (bitmap_set_t dest, bitmap_set_t orig)
776 {
777   bitmap_set_t result = bitmap_set_new ();
778   bitmap_iterator bi;
779   unsigned int i;
780 
781   bitmap_and_compl (&result->expressions, &dest->expressions,
782 		    &orig->expressions);
783 
784   FOR_EACH_EXPR_ID_IN_SET (result, i, bi)
785     {
786       pre_expr expr = expression_for_id (i);
787       unsigned int value_id = get_expr_value_id (expr);
788       bitmap_set_bit (&result->values, value_id);
789     }
790 
791   return result;
792 }
793 
794 /* Subtract all the values in bitmap set B from bitmap set A.  */
795 
796 static void
bitmap_set_subtract_values(bitmap_set_t a,bitmap_set_t b)797 bitmap_set_subtract_values (bitmap_set_t a, bitmap_set_t b)
798 {
799   unsigned int i;
800   bitmap_iterator bi;
801   bitmap_head temp;
802 
803   bitmap_initialize (&temp, &grand_bitmap_obstack);
804 
805   bitmap_copy (&temp, &a->expressions);
806   EXECUTE_IF_SET_IN_BITMAP (&temp, 0, i, bi)
807     {
808       pre_expr expr = expression_for_id (i);
809       if (bitmap_set_contains_value (b, get_expr_value_id (expr)))
810 	bitmap_remove_from_set (a, expr);
811     }
812   bitmap_clear (&temp);
813 }
814 
815 
816 /* Return true if bitmapped set SET contains the value VALUE_ID.  */
817 
818 static bool
bitmap_set_contains_value(bitmap_set_t set,unsigned int value_id)819 bitmap_set_contains_value (bitmap_set_t set, unsigned int value_id)
820 {
821   if (value_id_constant_p (value_id))
822     return true;
823 
824   if (!set || bitmap_empty_p (&set->expressions))
825     return false;
826 
827   return bitmap_bit_p (&set->values, value_id);
828 }
829 
830 static inline bool
bitmap_set_contains_expr(bitmap_set_t set,const pre_expr expr)831 bitmap_set_contains_expr (bitmap_set_t set, const pre_expr expr)
832 {
833   return bitmap_bit_p (&set->expressions, get_expression_id (expr));
834 }
835 
836 /* Replace an instance of value LOOKFOR with expression EXPR in SET.  */
837 
838 static void
bitmap_set_replace_value(bitmap_set_t set,unsigned int lookfor,const pre_expr expr)839 bitmap_set_replace_value (bitmap_set_t set, unsigned int lookfor,
840 			  const pre_expr expr)
841 {
842   bitmap exprset;
843   unsigned int i;
844   bitmap_iterator bi;
845 
846   if (value_id_constant_p (lookfor))
847     return;
848 
849   if (!bitmap_set_contains_value (set, lookfor))
850     return;
851 
852   /* The number of expressions having a given value is usually
853      significantly less than the total number of expressions in SET.
854      Thus, rather than check, for each expression in SET, whether it
855      has the value LOOKFOR, we walk the reverse mapping that tells us
856      what expressions have a given value, and see if any of those
857      expressions are in our set.  For large testcases, this is about
858      5-10x faster than walking the bitmap.  If this is somehow a
859      significant lose for some cases, we can choose which set to walk
860      based on the set size.  */
861   exprset = value_expressions[lookfor];
862   EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
863     {
864       if (bitmap_clear_bit (&set->expressions, i))
865 	{
866 	  bitmap_set_bit (&set->expressions, get_expression_id (expr));
867 	  return;
868 	}
869     }
870 
871   gcc_unreachable ();
872 }
873 
874 /* Return true if two bitmap sets are equal.  */
875 
876 static bool
bitmap_set_equal(bitmap_set_t a,bitmap_set_t b)877 bitmap_set_equal (bitmap_set_t a, bitmap_set_t b)
878 {
879   return bitmap_equal_p (&a->values, &b->values);
880 }
881 
882 /* Replace an instance of EXPR's VALUE with EXPR in SET if it exists,
883    and add it otherwise.  */
884 
885 static void
bitmap_value_replace_in_set(bitmap_set_t set,pre_expr expr)886 bitmap_value_replace_in_set (bitmap_set_t set, pre_expr expr)
887 {
888   unsigned int val = get_expr_value_id (expr);
889 
890   if (bitmap_set_contains_value (set, val))
891     bitmap_set_replace_value (set, val, expr);
892   else
893     bitmap_insert_into_set (set, expr);
894 }
895 
896 /* Insert EXPR into SET if EXPR's value is not already present in
897    SET.  */
898 
899 static void
bitmap_value_insert_into_set(bitmap_set_t set,pre_expr expr)900 bitmap_value_insert_into_set (bitmap_set_t set, pre_expr expr)
901 {
902   unsigned int val = get_expr_value_id (expr);
903 
904   gcc_checking_assert (expr->id == get_or_alloc_expression_id (expr));
905 
906   /* Constant values are always considered to be part of the set.  */
907   if (value_id_constant_p (val))
908     return;
909 
910   /* If the value membership changed, add the expression.  */
911   if (bitmap_set_bit (&set->values, val))
912     bitmap_set_bit (&set->expressions, expr->id);
913 }
914 
915 /* Print out EXPR to outfile.  */
916 
917 static void
print_pre_expr(FILE * outfile,const pre_expr expr)918 print_pre_expr (FILE *outfile, const pre_expr expr)
919 {
920   switch (expr->kind)
921     {
922     case CONSTANT:
923       print_generic_expr (outfile, PRE_EXPR_CONSTANT (expr), 0);
924       break;
925     case NAME:
926       print_generic_expr (outfile, PRE_EXPR_NAME (expr), 0);
927       break;
928     case NARY:
929       {
930 	unsigned int i;
931 	vn_nary_op_t nary = PRE_EXPR_NARY (expr);
932 	fprintf (outfile, "{%s,", get_tree_code_name (nary->opcode));
933 	for (i = 0; i < nary->length; i++)
934 	  {
935 	    print_generic_expr (outfile, nary->op[i], 0);
936 	    if (i != (unsigned) nary->length - 1)
937 	      fprintf (outfile, ",");
938 	  }
939 	fprintf (outfile, "}");
940       }
941       break;
942 
943     case REFERENCE:
944       {
945 	vn_reference_op_t vro;
946 	unsigned int i;
947 	vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
948 	fprintf (outfile, "{");
949 	for (i = 0;
950 	     ref->operands.iterate (i, &vro);
951 	     i++)
952 	  {
953 	    bool closebrace = false;
954 	    if (vro->opcode != SSA_NAME
955 		&& TREE_CODE_CLASS (vro->opcode) != tcc_declaration)
956 	      {
957 		fprintf (outfile, "%s", get_tree_code_name (vro->opcode));
958 		if (vro->op0)
959 		  {
960 		    fprintf (outfile, "<");
961 		    closebrace = true;
962 		  }
963 	      }
964 	    if (vro->op0)
965 	      {
966 		print_generic_expr (outfile, vro->op0, 0);
967 		if (vro->op1)
968 		  {
969 		    fprintf (outfile, ",");
970 		    print_generic_expr (outfile, vro->op1, 0);
971 		  }
972 		if (vro->op2)
973 		  {
974 		    fprintf (outfile, ",");
975 		    print_generic_expr (outfile, vro->op2, 0);
976 		  }
977 	      }
978 	    if (closebrace)
979 		fprintf (outfile, ">");
980 	    if (i != ref->operands.length () - 1)
981 	      fprintf (outfile, ",");
982 	  }
983 	fprintf (outfile, "}");
984 	if (ref->vuse)
985 	  {
986 	    fprintf (outfile, "@");
987 	    print_generic_expr (outfile, ref->vuse, 0);
988 	  }
989       }
990       break;
991     }
992 }
993 void debug_pre_expr (pre_expr);
994 
995 /* Like print_pre_expr but always prints to stderr.  */
996 DEBUG_FUNCTION void
debug_pre_expr(pre_expr e)997 debug_pre_expr (pre_expr e)
998 {
999   print_pre_expr (stderr, e);
1000   fprintf (stderr, "\n");
1001 }
1002 
1003 /* Print out SET to OUTFILE.  */
1004 
1005 static void
print_bitmap_set(FILE * outfile,bitmap_set_t set,const char * setname,int blockindex)1006 print_bitmap_set (FILE *outfile, bitmap_set_t set,
1007 		  const char *setname, int blockindex)
1008 {
1009   fprintf (outfile, "%s[%d] := { ", setname, blockindex);
1010   if (set)
1011     {
1012       bool first = true;
1013       unsigned i;
1014       bitmap_iterator bi;
1015 
1016       FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
1017 	{
1018 	  const pre_expr expr = expression_for_id (i);
1019 
1020 	  if (!first)
1021 	    fprintf (outfile, ", ");
1022 	  first = false;
1023 	  print_pre_expr (outfile, expr);
1024 
1025 	  fprintf (outfile, " (%04d)", get_expr_value_id (expr));
1026 	}
1027     }
1028   fprintf (outfile, " }\n");
1029 }
1030 
1031 void debug_bitmap_set (bitmap_set_t);
1032 
1033 DEBUG_FUNCTION void
debug_bitmap_set(bitmap_set_t set)1034 debug_bitmap_set (bitmap_set_t set)
1035 {
1036   print_bitmap_set (stderr, set, "debug", 0);
1037 }
1038 
1039 void debug_bitmap_sets_for (basic_block);
1040 
1041 DEBUG_FUNCTION void
debug_bitmap_sets_for(basic_block bb)1042 debug_bitmap_sets_for (basic_block bb)
1043 {
1044   print_bitmap_set (stderr, AVAIL_OUT (bb), "avail_out", bb->index);
1045   print_bitmap_set (stderr, EXP_GEN (bb), "exp_gen", bb->index);
1046   print_bitmap_set (stderr, PHI_GEN (bb), "phi_gen", bb->index);
1047   print_bitmap_set (stderr, TMP_GEN (bb), "tmp_gen", bb->index);
1048   print_bitmap_set (stderr, ANTIC_IN (bb), "antic_in", bb->index);
1049   if (do_partial_partial)
1050     print_bitmap_set (stderr, PA_IN (bb), "pa_in", bb->index);
1051   print_bitmap_set (stderr, NEW_SETS (bb), "new_sets", bb->index);
1052 }
1053 
1054 /* Print out the expressions that have VAL to OUTFILE.  */
1055 
1056 static void
print_value_expressions(FILE * outfile,unsigned int val)1057 print_value_expressions (FILE *outfile, unsigned int val)
1058 {
1059   bitmap set = value_expressions[val];
1060   if (set)
1061     {
1062       bitmap_set x;
1063       char s[10];
1064       sprintf (s, "%04d", val);
1065       x.expressions = *set;
1066       print_bitmap_set (outfile, &x, s, 0);
1067     }
1068 }
1069 
1070 
1071 DEBUG_FUNCTION void
debug_value_expressions(unsigned int val)1072 debug_value_expressions (unsigned int val)
1073 {
1074   print_value_expressions (stderr, val);
1075 }
1076 
1077 /* Given a CONSTANT, allocate a new CONSTANT type PRE_EXPR to
1078    represent it.  */
1079 
1080 static pre_expr
get_or_alloc_expr_for_constant(tree constant)1081 get_or_alloc_expr_for_constant (tree constant)
1082 {
1083   unsigned int result_id;
1084   unsigned int value_id;
1085   struct pre_expr_d expr;
1086   pre_expr newexpr;
1087 
1088   expr.kind = CONSTANT;
1089   PRE_EXPR_CONSTANT (&expr) = constant;
1090   result_id = lookup_expression_id (&expr);
1091   if (result_id != 0)
1092     return expression_for_id (result_id);
1093 
1094   newexpr = (pre_expr) pool_alloc (pre_expr_pool);
1095   newexpr->kind = CONSTANT;
1096   PRE_EXPR_CONSTANT (newexpr) = constant;
1097   alloc_expression_id (newexpr);
1098   value_id = get_or_alloc_constant_value_id (constant);
1099   add_to_value (value_id, newexpr);
1100   return newexpr;
1101 }
1102 
1103 /* Given a value id V, find the actual tree representing the constant
1104    value if there is one, and return it. Return NULL if we can't find
1105    a constant.  */
1106 
1107 static tree
get_constant_for_value_id(unsigned int v)1108 get_constant_for_value_id (unsigned int v)
1109 {
1110   if (value_id_constant_p (v))
1111     {
1112       unsigned int i;
1113       bitmap_iterator bi;
1114       bitmap exprset = value_expressions[v];
1115 
1116       EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
1117 	{
1118 	  pre_expr expr = expression_for_id (i);
1119 	  if (expr->kind == CONSTANT)
1120 	    return PRE_EXPR_CONSTANT (expr);
1121 	}
1122     }
1123   return NULL;
1124 }
1125 
1126 /* Get or allocate a pre_expr for a piece of GIMPLE, and return it.
1127    Currently only supports constants and SSA_NAMES.  */
1128 static pre_expr
get_or_alloc_expr_for(tree t)1129 get_or_alloc_expr_for (tree t)
1130 {
1131   if (TREE_CODE (t) == SSA_NAME)
1132     return get_or_alloc_expr_for_name (t);
1133   else if (is_gimple_min_invariant (t))
1134     return get_or_alloc_expr_for_constant (t);
1135   else
1136     {
1137       /* More complex expressions can result from SCCVN expression
1138 	 simplification that inserts values for them.  As they all
1139 	 do not have VOPs the get handled by the nary ops struct.  */
1140       vn_nary_op_t result;
1141       unsigned int result_id;
1142       vn_nary_op_lookup (t, &result);
1143       if (result != NULL)
1144 	{
1145 	  pre_expr e = (pre_expr) pool_alloc (pre_expr_pool);
1146 	  e->kind = NARY;
1147 	  PRE_EXPR_NARY (e) = result;
1148 	  result_id = lookup_expression_id (e);
1149 	  if (result_id != 0)
1150 	    {
1151 	      pool_free (pre_expr_pool, e);
1152 	      e = expression_for_id (result_id);
1153 	      return e;
1154 	    }
1155 	  alloc_expression_id (e);
1156 	  return e;
1157 	}
1158     }
1159   return NULL;
1160 }
1161 
1162 /* Return the folded version of T if T, when folded, is a gimple
1163    min_invariant.  Otherwise, return T.  */
1164 
1165 static pre_expr
fully_constant_expression(pre_expr e)1166 fully_constant_expression (pre_expr e)
1167 {
1168   switch (e->kind)
1169     {
1170     case CONSTANT:
1171       return e;
1172     case NARY:
1173       {
1174 	vn_nary_op_t nary = PRE_EXPR_NARY (e);
1175 	switch (TREE_CODE_CLASS (nary->opcode))
1176 	  {
1177 	  case tcc_binary:
1178 	  case tcc_comparison:
1179 	    {
1180 	      /* We have to go from trees to pre exprs to value ids to
1181 		 constants.  */
1182 	      tree naryop0 = nary->op[0];
1183 	      tree naryop1 = nary->op[1];
1184 	      tree result;
1185 	      if (!is_gimple_min_invariant (naryop0))
1186 		{
1187 		  pre_expr rep0 = get_or_alloc_expr_for (naryop0);
1188 		  unsigned int vrep0 = get_expr_value_id (rep0);
1189 		  tree const0 = get_constant_for_value_id (vrep0);
1190 		  if (const0)
1191 		    naryop0 = fold_convert (TREE_TYPE (naryop0), const0);
1192 		}
1193 	      if (!is_gimple_min_invariant (naryop1))
1194 		{
1195 		  pre_expr rep1 = get_or_alloc_expr_for (naryop1);
1196 		  unsigned int vrep1 = get_expr_value_id (rep1);
1197 		  tree const1 = get_constant_for_value_id (vrep1);
1198 		  if (const1)
1199 		    naryop1 = fold_convert (TREE_TYPE (naryop1), const1);
1200 		}
1201 	      result = fold_binary (nary->opcode, nary->type,
1202 				    naryop0, naryop1);
1203 	      if (result && is_gimple_min_invariant (result))
1204 		return get_or_alloc_expr_for_constant (result);
1205 	      /* We might have simplified the expression to a
1206 		 SSA_NAME for example from x_1 * 1.  But we cannot
1207 		 insert a PHI for x_1 unconditionally as x_1 might
1208 		 not be available readily.  */
1209 	      return e;
1210 	    }
1211 	  case tcc_reference:
1212 	    if (nary->opcode != REALPART_EXPR
1213 		&& nary->opcode != IMAGPART_EXPR
1214 		&& nary->opcode != VIEW_CONVERT_EXPR)
1215 	      return e;
1216 	    /* Fallthrough.  */
1217 	  case tcc_unary:
1218 	    {
1219 	      /* We have to go from trees to pre exprs to value ids to
1220 		 constants.  */
1221 	      tree naryop0 = nary->op[0];
1222 	      tree const0, result;
1223 	      if (is_gimple_min_invariant (naryop0))
1224 		const0 = naryop0;
1225 	      else
1226 		{
1227 		  pre_expr rep0 = get_or_alloc_expr_for (naryop0);
1228 		  unsigned int vrep0 = get_expr_value_id (rep0);
1229 		  const0 = get_constant_for_value_id (vrep0);
1230 		}
1231 	      result = NULL;
1232 	      if (const0)
1233 		{
1234 		  tree type1 = TREE_TYPE (nary->op[0]);
1235 		  const0 = fold_convert (type1, const0);
1236 		  result = fold_unary (nary->opcode, nary->type, const0);
1237 		}
1238 	      if (result && is_gimple_min_invariant (result))
1239 		return get_or_alloc_expr_for_constant (result);
1240 	      return e;
1241 	    }
1242 	  default:
1243 	    return e;
1244 	  }
1245       }
1246     case REFERENCE:
1247       {
1248 	vn_reference_t ref = PRE_EXPR_REFERENCE (e);
1249 	tree folded;
1250 	if ((folded = fully_constant_vn_reference_p (ref)))
1251 	  return get_or_alloc_expr_for_constant (folded);
1252 	return e;
1253       }
1254     default:
1255       return e;
1256     }
1257   return e;
1258 }
1259 
1260 /* Translate the VUSE backwards through phi nodes in PHIBLOCK, so that
1261    it has the value it would have in BLOCK.  Set *SAME_VALID to true
1262    in case the new vuse doesn't change the value id of the OPERANDS.  */
1263 
1264 static tree
translate_vuse_through_block(vec<vn_reference_op_s> operands,alias_set_type set,tree type,tree vuse,basic_block phiblock,basic_block block,bool * same_valid)1265 translate_vuse_through_block (vec<vn_reference_op_s> operands,
1266 			      alias_set_type set, tree type, tree vuse,
1267 			      basic_block phiblock,
1268 			      basic_block block, bool *same_valid)
1269 {
1270   gimple phi = SSA_NAME_DEF_STMT (vuse);
1271   ao_ref ref;
1272   edge e = NULL;
1273   bool use_oracle;
1274 
1275   *same_valid = true;
1276 
1277   if (gimple_bb (phi) != phiblock)
1278     return vuse;
1279 
1280   use_oracle = ao_ref_init_from_vn_reference (&ref, set, type, operands);
1281 
1282   /* Use the alias-oracle to find either the PHI node in this block,
1283      the first VUSE used in this block that is equivalent to vuse or
1284      the first VUSE which definition in this block kills the value.  */
1285   if (gimple_code (phi) == GIMPLE_PHI)
1286     e = find_edge (block, phiblock);
1287   else if (use_oracle)
1288     while (!stmt_may_clobber_ref_p_1 (phi, &ref))
1289       {
1290 	vuse = gimple_vuse (phi);
1291 	phi = SSA_NAME_DEF_STMT (vuse);
1292 	if (gimple_bb (phi) != phiblock)
1293 	  return vuse;
1294 	if (gimple_code (phi) == GIMPLE_PHI)
1295 	  {
1296 	    e = find_edge (block, phiblock);
1297 	    break;
1298 	  }
1299       }
1300   else
1301     return NULL_TREE;
1302 
1303   if (e)
1304     {
1305       if (use_oracle)
1306 	{
1307 	  bitmap visited = NULL;
1308 	  unsigned int cnt;
1309 	  /* Try to find a vuse that dominates this phi node by skipping
1310 	     non-clobbering statements.  */
1311 	  vuse = get_continuation_for_phi (phi, &ref, &cnt, &visited, false);
1312 	  if (visited)
1313 	    BITMAP_FREE (visited);
1314 	}
1315       else
1316 	vuse = NULL_TREE;
1317       if (!vuse)
1318 	{
1319 	  /* If we didn't find any, the value ID can't stay the same,
1320 	     but return the translated vuse.  */
1321 	  *same_valid = false;
1322 	  vuse = PHI_ARG_DEF (phi, e->dest_idx);
1323 	}
1324       /* ??? We would like to return vuse here as this is the canonical
1325          upmost vdef that this reference is associated with.  But during
1326 	 insertion of the references into the hash tables we only ever
1327 	 directly insert with their direct gimple_vuse, hence returning
1328 	 something else would make us not find the other expression.  */
1329       return PHI_ARG_DEF (phi, e->dest_idx);
1330     }
1331 
1332   return NULL_TREE;
1333 }
1334 
1335 /* Like bitmap_find_leader, but checks for the value existing in SET1 *or*
1336    SET2.  This is used to avoid making a set consisting of the union
1337    of PA_IN and ANTIC_IN during insert.  */
1338 
1339 static inline pre_expr
find_leader_in_sets(unsigned int val,bitmap_set_t set1,bitmap_set_t set2)1340 find_leader_in_sets (unsigned int val, bitmap_set_t set1, bitmap_set_t set2)
1341 {
1342   pre_expr result;
1343 
1344   result = bitmap_find_leader (set1, val);
1345   if (!result && set2)
1346     result = bitmap_find_leader (set2, val);
1347   return result;
1348 }
1349 
1350 /* Get the tree type for our PRE expression e.  */
1351 
1352 static tree
get_expr_type(const pre_expr e)1353 get_expr_type (const pre_expr e)
1354 {
1355   switch (e->kind)
1356     {
1357     case NAME:
1358       return TREE_TYPE (PRE_EXPR_NAME (e));
1359     case CONSTANT:
1360       return TREE_TYPE (PRE_EXPR_CONSTANT (e));
1361     case REFERENCE:
1362       return PRE_EXPR_REFERENCE (e)->type;
1363     case NARY:
1364       return PRE_EXPR_NARY (e)->type;
1365     }
1366   gcc_unreachable ();
1367 }
1368 
1369 /* Get a representative SSA_NAME for a given expression.
1370    Since all of our sub-expressions are treated as values, we require
1371    them to be SSA_NAME's for simplicity.
1372    Prior versions of GVNPRE used to use "value handles" here, so that
1373    an expression would be VH.11 + VH.10 instead of d_3 + e_6.  In
1374    either case, the operands are really values (IE we do not expect
1375    them to be usable without finding leaders).  */
1376 
1377 static tree
get_representative_for(const pre_expr e)1378 get_representative_for (const pre_expr e)
1379 {
1380   tree name;
1381   unsigned int value_id = get_expr_value_id (e);
1382 
1383   switch (e->kind)
1384     {
1385     case NAME:
1386       return PRE_EXPR_NAME (e);
1387     case CONSTANT:
1388       return PRE_EXPR_CONSTANT (e);
1389     case NARY:
1390     case REFERENCE:
1391       {
1392 	/* Go through all of the expressions representing this value
1393 	   and pick out an SSA_NAME.  */
1394 	unsigned int i;
1395 	bitmap_iterator bi;
1396 	bitmap exprs = value_expressions[value_id];
1397 	EXECUTE_IF_SET_IN_BITMAP (exprs, 0, i, bi)
1398 	  {
1399 	    pre_expr rep = expression_for_id (i);
1400 	    if (rep->kind == NAME)
1401 	      return PRE_EXPR_NAME (rep);
1402 	    else if (rep->kind == CONSTANT)
1403 	      return PRE_EXPR_CONSTANT (rep);
1404 	  }
1405       }
1406       break;
1407     }
1408 
1409   /* If we reached here we couldn't find an SSA_NAME.  This can
1410      happen when we've discovered a value that has never appeared in
1411      the program as set to an SSA_NAME, as the result of phi translation.
1412      Create one here.
1413      ???  We should be able to re-use this when we insert the statement
1414      to compute it.  */
1415   name = make_temp_ssa_name (get_expr_type (e), gimple_build_nop (), "pretmp");
1416   VN_INFO_GET (name)->value_id = value_id;
1417   VN_INFO (name)->valnum = name;
1418   /* ???  For now mark this SSA name for release by SCCVN.  */
1419   VN_INFO (name)->needs_insertion = true;
1420   add_to_value (value_id, get_or_alloc_expr_for_name (name));
1421   if (dump_file && (dump_flags & TDF_DETAILS))
1422     {
1423       fprintf (dump_file, "Created SSA_NAME representative ");
1424       print_generic_expr (dump_file, name, 0);
1425       fprintf (dump_file, " for expression:");
1426       print_pre_expr (dump_file, e);
1427       fprintf (dump_file, " (%04d)\n", value_id);
1428     }
1429 
1430   return name;
1431 }
1432 
1433 
1434 
1435 static pre_expr
1436 phi_translate (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1437 	       basic_block pred, basic_block phiblock);
1438 
1439 /* Translate EXPR using phis in PHIBLOCK, so that it has the values of
1440    the phis in PRED.  Return NULL if we can't find a leader for each part
1441    of the translated expression.  */
1442 
1443 static pre_expr
phi_translate_1(pre_expr expr,bitmap_set_t set1,bitmap_set_t set2,basic_block pred,basic_block phiblock)1444 phi_translate_1 (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1445 		 basic_block pred, basic_block phiblock)
1446 {
1447   switch (expr->kind)
1448     {
1449     case NARY:
1450       {
1451 	unsigned int i;
1452 	bool changed = false;
1453 	vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1454 	vn_nary_op_t newnary = XALLOCAVAR (struct vn_nary_op_s,
1455 					   sizeof_vn_nary_op (nary->length));
1456 	memcpy (newnary, nary, sizeof_vn_nary_op (nary->length));
1457 
1458 	for (i = 0; i < newnary->length; i++)
1459 	  {
1460 	    if (TREE_CODE (newnary->op[i]) != SSA_NAME)
1461 	      continue;
1462 	    else
1463 	      {
1464                 pre_expr leader, result;
1465 		unsigned int op_val_id = VN_INFO (newnary->op[i])->value_id;
1466 		leader = find_leader_in_sets (op_val_id, set1, set2);
1467                 result = phi_translate (leader, set1, set2, pred, phiblock);
1468 		if (result && result != leader)
1469 		  {
1470 		    tree name = get_representative_for (result);
1471 		    if (!name)
1472 		      return NULL;
1473 		    newnary->op[i] = name;
1474 		  }
1475 		else if (!result)
1476 		  return NULL;
1477 
1478 		changed |= newnary->op[i] != nary->op[i];
1479 	      }
1480 	  }
1481 	if (changed)
1482 	  {
1483 	    pre_expr constant;
1484 	    unsigned int new_val_id;
1485 
1486 	    tree result = vn_nary_op_lookup_pieces (newnary->length,
1487 						    newnary->opcode,
1488 						    newnary->type,
1489 						    &newnary->op[0],
1490 						    &nary);
1491 	    if (result && is_gimple_min_invariant (result))
1492 	      return get_or_alloc_expr_for_constant (result);
1493 
1494 	    expr = (pre_expr) pool_alloc (pre_expr_pool);
1495 	    expr->kind = NARY;
1496 	    expr->id = 0;
1497 	    if (nary)
1498 	      {
1499 		PRE_EXPR_NARY (expr) = nary;
1500 		constant = fully_constant_expression (expr);
1501 		if (constant != expr)
1502 		  return constant;
1503 
1504 		new_val_id = nary->value_id;
1505 		get_or_alloc_expression_id (expr);
1506 	      }
1507 	    else
1508 	      {
1509 		new_val_id = get_next_value_id ();
1510 		value_expressions.safe_grow_cleared (get_max_value_id () + 1);
1511 		nary = vn_nary_op_insert_pieces (newnary->length,
1512 						 newnary->opcode,
1513 						 newnary->type,
1514 						 &newnary->op[0],
1515 						 result, new_val_id);
1516 		PRE_EXPR_NARY (expr) = nary;
1517 		constant = fully_constant_expression (expr);
1518 		if (constant != expr)
1519 		  return constant;
1520 		get_or_alloc_expression_id (expr);
1521 	      }
1522 	    add_to_value (new_val_id, expr);
1523 	  }
1524 	return expr;
1525       }
1526       break;
1527 
1528     case REFERENCE:
1529       {
1530 	vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1531 	vec<vn_reference_op_s> operands = ref->operands;
1532 	tree vuse = ref->vuse;
1533 	tree newvuse = vuse;
1534 	vec<vn_reference_op_s> newoperands = vNULL;
1535 	bool changed = false, same_valid = true;
1536 	unsigned int i, j, n;
1537 	vn_reference_op_t operand;
1538 	vn_reference_t newref;
1539 
1540 	for (i = 0, j = 0;
1541 	     operands.iterate (i, &operand); i++, j++)
1542 	  {
1543 	    pre_expr opresult;
1544 	    pre_expr leader;
1545 	    tree op[3];
1546 	    tree type = operand->type;
1547 	    vn_reference_op_s newop = *operand;
1548 	    op[0] = operand->op0;
1549 	    op[1] = operand->op1;
1550 	    op[2] = operand->op2;
1551 	    for (n = 0; n < 3; ++n)
1552 	      {
1553 		unsigned int op_val_id;
1554 		if (!op[n])
1555 		  continue;
1556 		if (TREE_CODE (op[n]) != SSA_NAME)
1557 		  {
1558 		    /* We can't possibly insert these.  */
1559 		    if (n != 0
1560 			&& !is_gimple_min_invariant (op[n]))
1561 		      break;
1562 		    continue;
1563 		  }
1564 		op_val_id = VN_INFO (op[n])->value_id;
1565 		leader = find_leader_in_sets (op_val_id, set1, set2);
1566 		if (!leader)
1567 		  break;
1568 		opresult = phi_translate (leader, set1, set2, pred, phiblock);
1569 		if (!opresult)
1570 		  break;
1571 		if (opresult != leader)
1572 		  {
1573 		    tree name = get_representative_for (opresult);
1574 		    if (!name)
1575 		      break;
1576 		    changed |= name != op[n];
1577 		    op[n] = name;
1578 		  }
1579 	      }
1580 	    if (n != 3)
1581 	      {
1582 		newoperands.release ();
1583 		return NULL;
1584 	      }
1585 	    if (!newoperands.exists ())
1586 	      newoperands = operands.copy ();
1587 	    /* We may have changed from an SSA_NAME to a constant */
1588 	    if (newop.opcode == SSA_NAME && TREE_CODE (op[0]) != SSA_NAME)
1589 	      newop.opcode = TREE_CODE (op[0]);
1590 	    newop.type = type;
1591 	    newop.op0 = op[0];
1592 	    newop.op1 = op[1];
1593 	    newop.op2 = op[2];
1594 	    /* If it transforms a non-constant ARRAY_REF into a constant
1595 	       one, adjust the constant offset.  */
1596 	    if (newop.opcode == ARRAY_REF
1597 		&& newop.off == -1
1598 		&& TREE_CODE (op[0]) == INTEGER_CST
1599 		&& TREE_CODE (op[1]) == INTEGER_CST
1600 		&& TREE_CODE (op[2]) == INTEGER_CST)
1601 	      {
1602 		double_int off = tree_to_double_int (op[0]);
1603 		off += -tree_to_double_int (op[1]);
1604 		off *= tree_to_double_int (op[2]);
1605 		if (off.fits_shwi ())
1606 		  newop.off = off.low;
1607 	      }
1608 	    newoperands[j] = newop;
1609 	    /* If it transforms from an SSA_NAME to an address, fold with
1610 	       a preceding indirect reference.  */
1611 	    if (j > 0 && op[0] && TREE_CODE (op[0]) == ADDR_EXPR
1612 		&& newoperands[j - 1].opcode == MEM_REF)
1613 	      vn_reference_fold_indirect (&newoperands, &j);
1614 	  }
1615 	if (i != operands.length ())
1616 	  {
1617 	    newoperands.release ();
1618 	    return NULL;
1619 	  }
1620 
1621 	if (vuse)
1622 	  {
1623 	    newvuse = translate_vuse_through_block (newoperands,
1624 						    ref->set, ref->type,
1625 						    vuse, phiblock, pred,
1626 						    &same_valid);
1627 	    if (newvuse == NULL_TREE)
1628 	      {
1629 		newoperands.release ();
1630 		return NULL;
1631 	      }
1632 	  }
1633 
1634 	if (changed || newvuse != vuse)
1635 	  {
1636 	    unsigned int new_val_id;
1637 	    pre_expr constant;
1638 
1639 	    tree result = vn_reference_lookup_pieces (newvuse, ref->set,
1640 						      ref->type,
1641 						      newoperands,
1642 						      &newref, VN_WALK);
1643 	    if (result)
1644 	      newoperands.release ();
1645 
1646 	    /* We can always insert constants, so if we have a partial
1647 	       redundant constant load of another type try to translate it
1648 	       to a constant of appropriate type.  */
1649 	    if (result && is_gimple_min_invariant (result))
1650 	      {
1651 		tree tem = result;
1652 		if (!useless_type_conversion_p (ref->type, TREE_TYPE (result)))
1653 		  {
1654 		    tem = fold_unary (VIEW_CONVERT_EXPR, ref->type, result);
1655 		    if (tem && !is_gimple_min_invariant (tem))
1656 		      tem = NULL_TREE;
1657 		  }
1658 		if (tem)
1659 		  return get_or_alloc_expr_for_constant (tem);
1660 	      }
1661 
1662 	    /* If we'd have to convert things we would need to validate
1663 	       if we can insert the translated expression.  So fail
1664 	       here for now - we cannot insert an alias with a different
1665 	       type in the VN tables either, as that would assert.  */
1666 	    if (result
1667 		&& !useless_type_conversion_p (ref->type, TREE_TYPE (result)))
1668 	      return NULL;
1669 	    else if (!result && newref
1670 		     && !useless_type_conversion_p (ref->type, newref->type))
1671 	      {
1672 		newoperands.release ();
1673 		return NULL;
1674 	      }
1675 
1676 	    expr = (pre_expr) pool_alloc (pre_expr_pool);
1677 	    expr->kind = REFERENCE;
1678 	    expr->id = 0;
1679 
1680 	    if (newref)
1681 	      {
1682 		PRE_EXPR_REFERENCE (expr) = newref;
1683 		constant = fully_constant_expression (expr);
1684 		if (constant != expr)
1685 		  return constant;
1686 
1687 		new_val_id = newref->value_id;
1688 		get_or_alloc_expression_id (expr);
1689 	      }
1690 	    else
1691 	      {
1692 		if (changed || !same_valid)
1693 		  {
1694 		    new_val_id = get_next_value_id ();
1695 		    value_expressions.safe_grow_cleared
1696 		      (get_max_value_id () + 1);
1697 		  }
1698 		else
1699 		  new_val_id = ref->value_id;
1700 		newref = vn_reference_insert_pieces (newvuse, ref->set,
1701 						     ref->type,
1702 						     newoperands,
1703 						     result, new_val_id);
1704 		newoperands.create (0);
1705 		PRE_EXPR_REFERENCE (expr) = newref;
1706 		constant = fully_constant_expression (expr);
1707 		if (constant != expr)
1708 		  return constant;
1709 		get_or_alloc_expression_id (expr);
1710 	      }
1711 	    add_to_value (new_val_id, expr);
1712 	  }
1713 	newoperands.release ();
1714 	return expr;
1715       }
1716       break;
1717 
1718     case NAME:
1719       {
1720 	tree name = PRE_EXPR_NAME (expr);
1721 	gimple def_stmt = SSA_NAME_DEF_STMT (name);
1722 	/* If the SSA name is defined by a PHI node in this block,
1723 	   translate it.  */
1724 	if (gimple_code (def_stmt) == GIMPLE_PHI
1725 	    && gimple_bb (def_stmt) == phiblock)
1726 	  {
1727 	    edge e = find_edge (pred, gimple_bb (def_stmt));
1728 	    tree def = PHI_ARG_DEF (def_stmt, e->dest_idx);
1729 
1730 	    /* Handle constant. */
1731 	    if (is_gimple_min_invariant (def))
1732 	      return get_or_alloc_expr_for_constant (def);
1733 
1734 	    return get_or_alloc_expr_for_name (def);
1735 	  }
1736 	/* Otherwise return it unchanged - it will get cleaned if its
1737 	   value is not available in PREDs AVAIL_OUT set of expressions.  */
1738 	return expr;
1739       }
1740 
1741     default:
1742       gcc_unreachable ();
1743     }
1744 }
1745 
1746 /* Wrapper around phi_translate_1 providing caching functionality.  */
1747 
1748 static pre_expr
phi_translate(pre_expr expr,bitmap_set_t set1,bitmap_set_t set2,basic_block pred,basic_block phiblock)1749 phi_translate (pre_expr expr, bitmap_set_t set1, bitmap_set_t set2,
1750 	       basic_block pred, basic_block phiblock)
1751 {
1752   expr_pred_trans_t slot = NULL;
1753   pre_expr phitrans;
1754 
1755   if (!expr)
1756     return NULL;
1757 
1758   /* Constants contain no values that need translation.  */
1759   if (expr->kind == CONSTANT)
1760     return expr;
1761 
1762   if (value_id_constant_p (get_expr_value_id (expr)))
1763     return expr;
1764 
1765   /* Don't add translations of NAMEs as those are cheap to translate.  */
1766   if (expr->kind != NAME)
1767     {
1768       if (phi_trans_add (&slot, expr, pred))
1769 	return slot->v;
1770       /* Store NULL for the value we want to return in the case of
1771 	 recursing.  */
1772       slot->v = NULL;
1773     }
1774 
1775   /* Translate.  */
1776   phitrans = phi_translate_1 (expr, set1, set2, pred, phiblock);
1777 
1778   if (slot)
1779     {
1780       if (phitrans)
1781 	slot->v = phitrans;
1782       else
1783 	/* Remove failed translations again, they cause insert
1784 	   iteration to not pick up new opportunities reliably.  */
1785 	phi_translate_table.remove_elt_with_hash (slot, slot->hashcode);
1786     }
1787 
1788   return phitrans;
1789 }
1790 
1791 
1792 /* For each expression in SET, translate the values through phi nodes
1793    in PHIBLOCK using edge PHIBLOCK->PRED, and store the resulting
1794    expressions in DEST.  */
1795 
1796 static void
phi_translate_set(bitmap_set_t dest,bitmap_set_t set,basic_block pred,basic_block phiblock)1797 phi_translate_set (bitmap_set_t dest, bitmap_set_t set, basic_block pred,
1798 		   basic_block phiblock)
1799 {
1800   vec<pre_expr> exprs;
1801   pre_expr expr;
1802   int i;
1803 
1804   if (gimple_seq_empty_p (phi_nodes (phiblock)))
1805     {
1806       bitmap_set_copy (dest, set);
1807       return;
1808     }
1809 
1810   exprs = sorted_array_from_bitmap_set (set);
1811   FOR_EACH_VEC_ELT (exprs, i, expr)
1812     {
1813       pre_expr translated;
1814       translated = phi_translate (expr, set, NULL, pred, phiblock);
1815       if (!translated)
1816 	continue;
1817 
1818       /* We might end up with multiple expressions from SET being
1819 	 translated to the same value.  In this case we do not want
1820 	 to retain the NARY or REFERENCE expression but prefer a NAME
1821 	 which would be the leader.  */
1822       if (translated->kind == NAME)
1823 	bitmap_value_replace_in_set (dest, translated);
1824       else
1825 	bitmap_value_insert_into_set (dest, translated);
1826     }
1827   exprs.release ();
1828 }
1829 
1830 /* Find the leader for a value (i.e., the name representing that
1831    value) in a given set, and return it.  Return NULL if no leader
1832    is found.  */
1833 
1834 static pre_expr
bitmap_find_leader(bitmap_set_t set,unsigned int val)1835 bitmap_find_leader (bitmap_set_t set, unsigned int val)
1836 {
1837   if (value_id_constant_p (val))
1838     {
1839       unsigned int i;
1840       bitmap_iterator bi;
1841       bitmap exprset = value_expressions[val];
1842 
1843       EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
1844 	{
1845 	  pre_expr expr = expression_for_id (i);
1846 	  if (expr->kind == CONSTANT)
1847 	    return expr;
1848 	}
1849     }
1850   if (bitmap_set_contains_value (set, val))
1851     {
1852       /* Rather than walk the entire bitmap of expressions, and see
1853 	 whether any of them has the value we are looking for, we look
1854 	 at the reverse mapping, which tells us the set of expressions
1855 	 that have a given value (IE value->expressions with that
1856 	 value) and see if any of those expressions are in our set.
1857 	 The number of expressions per value is usually significantly
1858 	 less than the number of expressions in the set.  In fact, for
1859 	 large testcases, doing it this way is roughly 5-10x faster
1860 	 than walking the bitmap.
1861 	 If this is somehow a significant lose for some cases, we can
1862 	 choose which set to walk based on which set is smaller.  */
1863       unsigned int i;
1864       bitmap_iterator bi;
1865       bitmap exprset = value_expressions[val];
1866 
1867       EXECUTE_IF_AND_IN_BITMAP (exprset, &set->expressions, 0, i, bi)
1868 	return expression_for_id (i);
1869     }
1870   return NULL;
1871 }
1872 
1873 /* Determine if EXPR, a memory expression, is ANTIC_IN at the top of
1874    BLOCK by seeing if it is not killed in the block.  Note that we are
1875    only determining whether there is a store that kills it.  Because
1876    of the order in which clean iterates over values, we are guaranteed
1877    that altered operands will have caused us to be eliminated from the
1878    ANTIC_IN set already.  */
1879 
1880 static bool
value_dies_in_block_x(pre_expr expr,basic_block block)1881 value_dies_in_block_x (pre_expr expr, basic_block block)
1882 {
1883   tree vuse = PRE_EXPR_REFERENCE (expr)->vuse;
1884   vn_reference_t refx = PRE_EXPR_REFERENCE (expr);
1885   gimple def;
1886   gimple_stmt_iterator gsi;
1887   unsigned id = get_expression_id (expr);
1888   bool res = false;
1889   ao_ref ref;
1890 
1891   if (!vuse)
1892     return false;
1893 
1894   /* Lookup a previously calculated result.  */
1895   if (EXPR_DIES (block)
1896       && bitmap_bit_p (EXPR_DIES (block), id * 2))
1897     return bitmap_bit_p (EXPR_DIES (block), id * 2 + 1);
1898 
1899   /* A memory expression {e, VUSE} dies in the block if there is a
1900      statement that may clobber e.  If, starting statement walk from the
1901      top of the basic block, a statement uses VUSE there can be no kill
1902      inbetween that use and the original statement that loaded {e, VUSE},
1903      so we can stop walking.  */
1904   ref.base = NULL_TREE;
1905   for (gsi = gsi_start_bb (block); !gsi_end_p (gsi); gsi_next (&gsi))
1906     {
1907       tree def_vuse, def_vdef;
1908       def = gsi_stmt (gsi);
1909       def_vuse = gimple_vuse (def);
1910       def_vdef = gimple_vdef (def);
1911 
1912       /* Not a memory statement.  */
1913       if (!def_vuse)
1914 	continue;
1915 
1916       /* Not a may-def.  */
1917       if (!def_vdef)
1918 	{
1919 	  /* A load with the same VUSE, we're done.  */
1920 	  if (def_vuse == vuse)
1921 	    break;
1922 
1923 	  continue;
1924 	}
1925 
1926       /* Init ref only if we really need it.  */
1927       if (ref.base == NULL_TREE
1928 	  && !ao_ref_init_from_vn_reference (&ref, refx->set, refx->type,
1929 					     refx->operands))
1930 	{
1931 	  res = true;
1932 	  break;
1933 	}
1934       /* If the statement may clobber expr, it dies.  */
1935       if (stmt_may_clobber_ref_p_1 (def, &ref))
1936 	{
1937 	  res = true;
1938 	  break;
1939 	}
1940     }
1941 
1942   /* Remember the result.  */
1943   if (!EXPR_DIES (block))
1944     EXPR_DIES (block) = BITMAP_ALLOC (&grand_bitmap_obstack);
1945   bitmap_set_bit (EXPR_DIES (block), id * 2);
1946   if (res)
1947     bitmap_set_bit (EXPR_DIES (block), id * 2 + 1);
1948 
1949   return res;
1950 }
1951 
1952 
1953 /* Determine if OP is valid in SET1 U SET2, which it is when the union
1954    contains its value-id.  */
1955 
1956 static bool
op_valid_in_sets(bitmap_set_t set1,bitmap_set_t set2,tree op)1957 op_valid_in_sets (bitmap_set_t set1, bitmap_set_t set2, tree op)
1958 {
1959   if (op && TREE_CODE (op) == SSA_NAME)
1960     {
1961       unsigned int value_id = VN_INFO (op)->value_id;
1962       if (!(bitmap_set_contains_value (set1, value_id)
1963 	    || (set2 && bitmap_set_contains_value  (set2, value_id))))
1964 	return false;
1965     }
1966   return true;
1967 }
1968 
1969 /* Determine if the expression EXPR is valid in SET1 U SET2.
1970    ONLY SET2 CAN BE NULL.
1971    This means that we have a leader for each part of the expression
1972    (if it consists of values), or the expression is an SSA_NAME.
1973    For loads/calls, we also see if the vuse is killed in this block.  */
1974 
1975 static bool
valid_in_sets(bitmap_set_t set1,bitmap_set_t set2,pre_expr expr,basic_block block)1976 valid_in_sets (bitmap_set_t set1, bitmap_set_t set2, pre_expr expr,
1977 	       basic_block block)
1978 {
1979   switch (expr->kind)
1980     {
1981     case NAME:
1982       return bitmap_find_leader (AVAIL_OUT (block),
1983 				 get_expr_value_id (expr)) != NULL;
1984     case NARY:
1985       {
1986 	unsigned int i;
1987 	vn_nary_op_t nary = PRE_EXPR_NARY (expr);
1988 	for (i = 0; i < nary->length; i++)
1989 	  if (!op_valid_in_sets (set1, set2, nary->op[i]))
1990 	    return false;
1991 	return true;
1992       }
1993       break;
1994     case REFERENCE:
1995       {
1996 	vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
1997 	vn_reference_op_t vro;
1998 	unsigned int i;
1999 
2000 	FOR_EACH_VEC_ELT (ref->operands, i, vro)
2001 	  {
2002 	    if (!op_valid_in_sets (set1, set2, vro->op0)
2003 		|| !op_valid_in_sets (set1, set2, vro->op1)
2004 		|| !op_valid_in_sets (set1, set2, vro->op2))
2005 	      return false;
2006 	  }
2007 	return true;
2008       }
2009     default:
2010       gcc_unreachable ();
2011     }
2012 }
2013 
2014 /* Clean the set of expressions that are no longer valid in SET1 or
2015    SET2.  This means expressions that are made up of values we have no
2016    leaders for in SET1 or SET2.  This version is used for partial
2017    anticipation, which means it is not valid in either ANTIC_IN or
2018    PA_IN.  */
2019 
2020 static void
dependent_clean(bitmap_set_t set1,bitmap_set_t set2,basic_block block)2021 dependent_clean (bitmap_set_t set1, bitmap_set_t set2, basic_block block)
2022 {
2023   vec<pre_expr> exprs = sorted_array_from_bitmap_set (set1);
2024   pre_expr expr;
2025   int i;
2026 
2027   FOR_EACH_VEC_ELT (exprs, i, expr)
2028     {
2029       if (!valid_in_sets (set1, set2, expr, block))
2030 	bitmap_remove_from_set (set1, expr);
2031     }
2032   exprs.release ();
2033 }
2034 
2035 /* Clean the set of expressions that are no longer valid in SET.  This
2036    means expressions that are made up of values we have no leaders for
2037    in SET.  */
2038 
2039 static void
clean(bitmap_set_t set,basic_block block)2040 clean (bitmap_set_t set, basic_block block)
2041 {
2042   vec<pre_expr> exprs = sorted_array_from_bitmap_set (set);
2043   pre_expr expr;
2044   int i;
2045 
2046   FOR_EACH_VEC_ELT (exprs, i, expr)
2047     {
2048       if (!valid_in_sets (set, NULL, expr, block))
2049 	bitmap_remove_from_set (set, expr);
2050     }
2051   exprs.release ();
2052 }
2053 
2054 /* Clean the set of expressions that are no longer valid in SET because
2055    they are clobbered in BLOCK or because they trap and may not be executed.  */
2056 
2057 static void
prune_clobbered_mems(bitmap_set_t set,basic_block block)2058 prune_clobbered_mems (bitmap_set_t set, basic_block block)
2059 {
2060   bitmap_iterator bi;
2061   unsigned i;
2062 
2063   FOR_EACH_EXPR_ID_IN_SET (set, i, bi)
2064     {
2065       pre_expr expr = expression_for_id (i);
2066       if (expr->kind == REFERENCE)
2067 	{
2068 	  vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
2069 	  if (ref->vuse)
2070 	    {
2071 	      gimple def_stmt = SSA_NAME_DEF_STMT (ref->vuse);
2072 	      if (!gimple_nop_p (def_stmt)
2073 		  && ((gimple_bb (def_stmt) != block
2074 		       && !dominated_by_p (CDI_DOMINATORS,
2075 					   block, gimple_bb (def_stmt)))
2076 		      || (gimple_bb (def_stmt) == block
2077 			  && value_dies_in_block_x (expr, block))))
2078 		bitmap_remove_from_set (set, expr);
2079 	    }
2080 	}
2081       else if (expr->kind == NARY)
2082 	{
2083 	  vn_nary_op_t nary = PRE_EXPR_NARY (expr);
2084 	  /* If the NARY may trap make sure the block does not contain
2085 	     a possible exit point.
2086 	     ???  This is overly conservative if we translate AVAIL_OUT
2087 	     as the available expression might be after the exit point.  */
2088 	  if (BB_MAY_NOTRETURN (block)
2089 	      && vn_nary_may_trap (nary))
2090 	    bitmap_remove_from_set (set, expr);
2091 	}
2092     }
2093 }
2094 
2095 static sbitmap has_abnormal_preds;
2096 
2097 /* List of blocks that may have changed during ANTIC computation and
2098    thus need to be iterated over.  */
2099 
2100 static sbitmap changed_blocks;
2101 
2102 /* Decide whether to defer a block for a later iteration, or PHI
2103    translate SOURCE to DEST using phis in PHIBLOCK.  Return false if we
2104    should defer the block, and true if we processed it.  */
2105 
2106 static bool
defer_or_phi_translate_block(bitmap_set_t dest,bitmap_set_t source,basic_block block,basic_block phiblock)2107 defer_or_phi_translate_block (bitmap_set_t dest, bitmap_set_t source,
2108 			      basic_block block, basic_block phiblock)
2109 {
2110   if (!BB_VISITED (phiblock))
2111     {
2112       bitmap_set_bit (changed_blocks, block->index);
2113       BB_VISITED (block) = 0;
2114       BB_DEFERRED (block) = 1;
2115       return false;
2116     }
2117   else
2118     phi_translate_set (dest, source, block, phiblock);
2119   return true;
2120 }
2121 
2122 /* Compute the ANTIC set for BLOCK.
2123 
2124    If succs(BLOCK) > 1 then
2125      ANTIC_OUT[BLOCK] = intersection of ANTIC_IN[b] for all succ(BLOCK)
2126    else if succs(BLOCK) == 1 then
2127      ANTIC_OUT[BLOCK] = phi_translate (ANTIC_IN[succ(BLOCK)])
2128 
2129    ANTIC_IN[BLOCK] = clean(ANTIC_OUT[BLOCK] U EXP_GEN[BLOCK] - TMP_GEN[BLOCK])
2130 */
2131 
2132 static bool
compute_antic_aux(basic_block block,bool block_has_abnormal_pred_edge)2133 compute_antic_aux (basic_block block, bool block_has_abnormal_pred_edge)
2134 {
2135   bool changed = false;
2136   bitmap_set_t S, old, ANTIC_OUT;
2137   bitmap_iterator bi;
2138   unsigned int bii;
2139   edge e;
2140   edge_iterator ei;
2141 
2142   old = ANTIC_OUT = S = NULL;
2143   BB_VISITED (block) = 1;
2144 
2145   /* If any edges from predecessors are abnormal, antic_in is empty,
2146      so do nothing.  */
2147   if (block_has_abnormal_pred_edge)
2148     goto maybe_dump_sets;
2149 
2150   old = ANTIC_IN (block);
2151   ANTIC_OUT = bitmap_set_new ();
2152 
2153   /* If the block has no successors, ANTIC_OUT is empty.  */
2154   if (EDGE_COUNT (block->succs) == 0)
2155     ;
2156   /* If we have one successor, we could have some phi nodes to
2157      translate through.  */
2158   else if (single_succ_p (block))
2159     {
2160       basic_block succ_bb = single_succ (block);
2161 
2162       /* We trade iterations of the dataflow equations for having to
2163 	 phi translate the maximal set, which is incredibly slow
2164 	 (since the maximal set often has 300+ members, even when you
2165 	 have a small number of blocks).
2166 	 Basically, we defer the computation of ANTIC for this block
2167 	 until we have processed it's successor, which will inevitably
2168 	 have a *much* smaller set of values to phi translate once
2169 	 clean has been run on it.
2170 	 The cost of doing this is that we technically perform more
2171 	 iterations, however, they are lower cost iterations.
2172 
2173 	 Timings for PRE on tramp3d-v4:
2174 	 without maximal set fix: 11 seconds
2175 	 with maximal set fix/without deferring: 26 seconds
2176 	 with maximal set fix/with deferring: 11 seconds
2177      */
2178 
2179       if (!defer_or_phi_translate_block (ANTIC_OUT, ANTIC_IN (succ_bb),
2180 					block, succ_bb))
2181 	{
2182 	  changed = true;
2183 	  goto maybe_dump_sets;
2184 	}
2185     }
2186   /* If we have multiple successors, we take the intersection of all of
2187      them.  Note that in the case of loop exit phi nodes, we may have
2188      phis to translate through.  */
2189   else
2190     {
2191       size_t i;
2192       basic_block bprime, first = NULL;
2193 
2194       auto_vec<basic_block> worklist (EDGE_COUNT (block->succs));
2195       FOR_EACH_EDGE (e, ei, block->succs)
2196 	{
2197 	  if (!first
2198 	      && BB_VISITED (e->dest))
2199 	    first = e->dest;
2200 	  else if (BB_VISITED (e->dest))
2201 	    worklist.quick_push (e->dest);
2202 	}
2203 
2204       /* Of multiple successors we have to have visited one already.  */
2205       if (!first)
2206 	{
2207 	  bitmap_set_bit (changed_blocks, block->index);
2208 	  BB_VISITED (block) = 0;
2209 	  BB_DEFERRED (block) = 1;
2210 	  changed = true;
2211 	  goto maybe_dump_sets;
2212 	}
2213 
2214       if (!gimple_seq_empty_p (phi_nodes (first)))
2215 	phi_translate_set (ANTIC_OUT, ANTIC_IN (first), block, first);
2216       else
2217 	bitmap_set_copy (ANTIC_OUT, ANTIC_IN (first));
2218 
2219       FOR_EACH_VEC_ELT (worklist, i, bprime)
2220 	{
2221 	  if (!gimple_seq_empty_p (phi_nodes (bprime)))
2222 	    {
2223 	      bitmap_set_t tmp = bitmap_set_new ();
2224 	      phi_translate_set (tmp, ANTIC_IN (bprime), block, bprime);
2225 	      bitmap_set_and (ANTIC_OUT, tmp);
2226 	      bitmap_set_free (tmp);
2227 	    }
2228 	  else
2229 	    bitmap_set_and (ANTIC_OUT, ANTIC_IN (bprime));
2230 	}
2231     }
2232 
2233   /* Prune expressions that are clobbered in block and thus become
2234      invalid if translated from ANTIC_OUT to ANTIC_IN.  */
2235   prune_clobbered_mems (ANTIC_OUT, block);
2236 
2237   /* Generate ANTIC_OUT - TMP_GEN.  */
2238   S = bitmap_set_subtract (ANTIC_OUT, TMP_GEN (block));
2239 
2240   /* Start ANTIC_IN with EXP_GEN - TMP_GEN.  */
2241   ANTIC_IN (block) = bitmap_set_subtract (EXP_GEN (block),
2242 					  TMP_GEN (block));
2243 
2244   /* Then union in the ANTIC_OUT - TMP_GEN values,
2245      to get ANTIC_OUT U EXP_GEN - TMP_GEN */
2246   FOR_EACH_EXPR_ID_IN_SET (S, bii, bi)
2247     bitmap_value_insert_into_set (ANTIC_IN (block),
2248 				  expression_for_id (bii));
2249 
2250   clean (ANTIC_IN (block), block);
2251 
2252   if (!bitmap_set_equal (old, ANTIC_IN (block)))
2253     {
2254       changed = true;
2255       bitmap_set_bit (changed_blocks, block->index);
2256       FOR_EACH_EDGE (e, ei, block->preds)
2257 	bitmap_set_bit (changed_blocks, e->src->index);
2258     }
2259   else
2260     bitmap_clear_bit (changed_blocks, block->index);
2261 
2262  maybe_dump_sets:
2263   if (dump_file && (dump_flags & TDF_DETAILS))
2264     {
2265       if (!BB_DEFERRED (block) || BB_VISITED (block))
2266 	{
2267 	  if (ANTIC_OUT)
2268 	    print_bitmap_set (dump_file, ANTIC_OUT, "ANTIC_OUT", block->index);
2269 
2270 	  print_bitmap_set (dump_file, ANTIC_IN (block), "ANTIC_IN",
2271 			    block->index);
2272 
2273 	  if (S)
2274 	    print_bitmap_set (dump_file, S, "S", block->index);
2275 	}
2276       else
2277 	{
2278 	  fprintf (dump_file,
2279 		   "Block %d was deferred for a future iteration.\n",
2280 		   block->index);
2281 	}
2282     }
2283   if (old)
2284     bitmap_set_free (old);
2285   if (S)
2286     bitmap_set_free (S);
2287   if (ANTIC_OUT)
2288     bitmap_set_free (ANTIC_OUT);
2289   return changed;
2290 }
2291 
2292 /* Compute PARTIAL_ANTIC for BLOCK.
2293 
2294    If succs(BLOCK) > 1 then
2295      PA_OUT[BLOCK] = value wise union of PA_IN[b] + all ANTIC_IN not
2296      in ANTIC_OUT for all succ(BLOCK)
2297    else if succs(BLOCK) == 1 then
2298      PA_OUT[BLOCK] = phi_translate (PA_IN[succ(BLOCK)])
2299 
2300    PA_IN[BLOCK] = dependent_clean(PA_OUT[BLOCK] - TMP_GEN[BLOCK]
2301 				  - ANTIC_IN[BLOCK])
2302 
2303 */
2304 static bool
compute_partial_antic_aux(basic_block block,bool block_has_abnormal_pred_edge)2305 compute_partial_antic_aux (basic_block block,
2306 			   bool block_has_abnormal_pred_edge)
2307 {
2308   bool changed = false;
2309   bitmap_set_t old_PA_IN;
2310   bitmap_set_t PA_OUT;
2311   edge e;
2312   edge_iterator ei;
2313   unsigned long max_pa = PARAM_VALUE (PARAM_MAX_PARTIAL_ANTIC_LENGTH);
2314 
2315   old_PA_IN = PA_OUT = NULL;
2316 
2317   /* If any edges from predecessors are abnormal, antic_in is empty,
2318      so do nothing.  */
2319   if (block_has_abnormal_pred_edge)
2320     goto maybe_dump_sets;
2321 
2322   /* If there are too many partially anticipatable values in the
2323      block, phi_translate_set can take an exponential time: stop
2324      before the translation starts.  */
2325   if (max_pa
2326       && single_succ_p (block)
2327       && bitmap_count_bits (&PA_IN (single_succ (block))->values) > max_pa)
2328     goto maybe_dump_sets;
2329 
2330   old_PA_IN = PA_IN (block);
2331   PA_OUT = bitmap_set_new ();
2332 
2333   /* If the block has no successors, ANTIC_OUT is empty.  */
2334   if (EDGE_COUNT (block->succs) == 0)
2335     ;
2336   /* If we have one successor, we could have some phi nodes to
2337      translate through.  Note that we can't phi translate across DFS
2338      back edges in partial antic, because it uses a union operation on
2339      the successors.  For recurrences like IV's, we will end up
2340      generating a new value in the set on each go around (i + 3 (VH.1)
2341      VH.1 + 1 (VH.2), VH.2 + 1 (VH.3), etc), forever.  */
2342   else if (single_succ_p (block))
2343     {
2344       basic_block succ = single_succ (block);
2345       if (!(single_succ_edge (block)->flags & EDGE_DFS_BACK))
2346 	phi_translate_set (PA_OUT, PA_IN (succ), block, succ);
2347     }
2348   /* If we have multiple successors, we take the union of all of
2349      them.  */
2350   else
2351     {
2352       size_t i;
2353       basic_block bprime;
2354 
2355       auto_vec<basic_block> worklist (EDGE_COUNT (block->succs));
2356       FOR_EACH_EDGE (e, ei, block->succs)
2357 	{
2358 	  if (e->flags & EDGE_DFS_BACK)
2359 	    continue;
2360 	  worklist.quick_push (e->dest);
2361 	}
2362       if (worklist.length () > 0)
2363 	{
2364 	  FOR_EACH_VEC_ELT (worklist, i, bprime)
2365 	    {
2366 	      unsigned int i;
2367 	      bitmap_iterator bi;
2368 
2369 	      FOR_EACH_EXPR_ID_IN_SET (ANTIC_IN (bprime), i, bi)
2370 		bitmap_value_insert_into_set (PA_OUT,
2371 					      expression_for_id (i));
2372 	      if (!gimple_seq_empty_p (phi_nodes (bprime)))
2373 		{
2374 		  bitmap_set_t pa_in = bitmap_set_new ();
2375 		  phi_translate_set (pa_in, PA_IN (bprime), block, bprime);
2376 		  FOR_EACH_EXPR_ID_IN_SET (pa_in, i, bi)
2377 		    bitmap_value_insert_into_set (PA_OUT,
2378 						  expression_for_id (i));
2379 		  bitmap_set_free (pa_in);
2380 		}
2381 	      else
2382 		FOR_EACH_EXPR_ID_IN_SET (PA_IN (bprime), i, bi)
2383 		  bitmap_value_insert_into_set (PA_OUT,
2384 						expression_for_id (i));
2385 	    }
2386 	}
2387     }
2388 
2389   /* Prune expressions that are clobbered in block and thus become
2390      invalid if translated from PA_OUT to PA_IN.  */
2391   prune_clobbered_mems (PA_OUT, block);
2392 
2393   /* PA_IN starts with PA_OUT - TMP_GEN.
2394      Then we subtract things from ANTIC_IN.  */
2395   PA_IN (block) = bitmap_set_subtract (PA_OUT, TMP_GEN (block));
2396 
2397   /* For partial antic, we want to put back in the phi results, since
2398      we will properly avoid making them partially antic over backedges.  */
2399   bitmap_ior_into (&PA_IN (block)->values, &PHI_GEN (block)->values);
2400   bitmap_ior_into (&PA_IN (block)->expressions, &PHI_GEN (block)->expressions);
2401 
2402   /* PA_IN[block] = PA_IN[block] - ANTIC_IN[block] */
2403   bitmap_set_subtract_values (PA_IN (block), ANTIC_IN (block));
2404 
2405   dependent_clean (PA_IN (block), ANTIC_IN (block), block);
2406 
2407   if (!bitmap_set_equal (old_PA_IN, PA_IN (block)))
2408     {
2409       changed = true;
2410       bitmap_set_bit (changed_blocks, block->index);
2411       FOR_EACH_EDGE (e, ei, block->preds)
2412 	bitmap_set_bit (changed_blocks, e->src->index);
2413     }
2414   else
2415     bitmap_clear_bit (changed_blocks, block->index);
2416 
2417  maybe_dump_sets:
2418   if (dump_file && (dump_flags & TDF_DETAILS))
2419     {
2420       if (PA_OUT)
2421 	print_bitmap_set (dump_file, PA_OUT, "PA_OUT", block->index);
2422 
2423       print_bitmap_set (dump_file, PA_IN (block), "PA_IN", block->index);
2424     }
2425   if (old_PA_IN)
2426     bitmap_set_free (old_PA_IN);
2427   if (PA_OUT)
2428     bitmap_set_free (PA_OUT);
2429   return changed;
2430 }
2431 
2432 /* Compute ANTIC and partial ANTIC sets.  */
2433 
2434 static void
compute_antic(void)2435 compute_antic (void)
2436 {
2437   bool changed = true;
2438   int num_iterations = 0;
2439   basic_block block;
2440   int i;
2441 
2442   /* If any predecessor edges are abnormal, we punt, so antic_in is empty.
2443      We pre-build the map of blocks with incoming abnormal edges here.  */
2444   has_abnormal_preds = sbitmap_alloc (last_basic_block_for_fn (cfun));
2445   bitmap_clear (has_abnormal_preds);
2446 
2447   FOR_ALL_BB_FN (block, cfun)
2448     {
2449       edge_iterator ei;
2450       edge e;
2451 
2452       FOR_EACH_EDGE (e, ei, block->preds)
2453 	{
2454 	  e->flags &= ~EDGE_DFS_BACK;
2455 	  if (e->flags & EDGE_ABNORMAL)
2456 	    {
2457 	      bitmap_set_bit (has_abnormal_preds, block->index);
2458 	      break;
2459 	    }
2460 	}
2461 
2462       BB_VISITED (block) = 0;
2463       BB_DEFERRED (block) = 0;
2464 
2465       /* While we are here, give empty ANTIC_IN sets to each block.  */
2466       ANTIC_IN (block) = bitmap_set_new ();
2467       PA_IN (block) = bitmap_set_new ();
2468     }
2469 
2470   /* At the exit block we anticipate nothing.  */
2471   BB_VISITED (EXIT_BLOCK_PTR_FOR_FN (cfun)) = 1;
2472 
2473   changed_blocks = sbitmap_alloc (last_basic_block_for_fn (cfun) + 1);
2474   bitmap_ones (changed_blocks);
2475   while (changed)
2476     {
2477       if (dump_file && (dump_flags & TDF_DETAILS))
2478 	fprintf (dump_file, "Starting iteration %d\n", num_iterations);
2479       /* ???  We need to clear our PHI translation cache here as the
2480          ANTIC sets shrink and we restrict valid translations to
2481 	 those having operands with leaders in ANTIC.  Same below
2482 	 for PA ANTIC computation.  */
2483       num_iterations++;
2484       changed = false;
2485       for (i = postorder_num - 1; i >= 0; i--)
2486 	{
2487 	  if (bitmap_bit_p (changed_blocks, postorder[i]))
2488 	    {
2489 	      basic_block block = BASIC_BLOCK_FOR_FN (cfun, postorder[i]);
2490 	      changed |= compute_antic_aux (block,
2491 					    bitmap_bit_p (has_abnormal_preds,
2492 						      block->index));
2493 	    }
2494 	}
2495       /* Theoretically possible, but *highly* unlikely.  */
2496       gcc_checking_assert (num_iterations < 500);
2497     }
2498 
2499   statistics_histogram_event (cfun, "compute_antic iterations",
2500 			      num_iterations);
2501 
2502   if (do_partial_partial)
2503     {
2504       bitmap_ones (changed_blocks);
2505       mark_dfs_back_edges ();
2506       num_iterations = 0;
2507       changed = true;
2508       while (changed)
2509 	{
2510 	  if (dump_file && (dump_flags & TDF_DETAILS))
2511 	    fprintf (dump_file, "Starting iteration %d\n", num_iterations);
2512 	  num_iterations++;
2513 	  changed = false;
2514 	  for (i = postorder_num - 1 ; i >= 0; i--)
2515 	    {
2516 	      if (bitmap_bit_p (changed_blocks, postorder[i]))
2517 		{
2518 		  basic_block block = BASIC_BLOCK_FOR_FN (cfun, postorder[i]);
2519 		  changed
2520 		    |= compute_partial_antic_aux (block,
2521 						  bitmap_bit_p (has_abnormal_preds,
2522 							    block->index));
2523 		}
2524 	    }
2525 	  /* Theoretically possible, but *highly* unlikely.  */
2526 	  gcc_checking_assert (num_iterations < 500);
2527 	}
2528       statistics_histogram_event (cfun, "compute_partial_antic iterations",
2529 				  num_iterations);
2530     }
2531   sbitmap_free (has_abnormal_preds);
2532   sbitmap_free (changed_blocks);
2533 }
2534 
2535 
2536 /* Inserted expressions are placed onto this worklist, which is used
2537    for performing quick dead code elimination of insertions we made
2538    that didn't turn out to be necessary.   */
2539 static bitmap inserted_exprs;
2540 
2541 /* The actual worker for create_component_ref_by_pieces.  */
2542 
2543 static tree
create_component_ref_by_pieces_1(basic_block block,vn_reference_t ref,unsigned int * operand,gimple_seq * stmts)2544 create_component_ref_by_pieces_1 (basic_block block, vn_reference_t ref,
2545 				  unsigned int *operand, gimple_seq *stmts)
2546 {
2547   vn_reference_op_t currop = &ref->operands[*operand];
2548   tree genop;
2549   ++*operand;
2550   switch (currop->opcode)
2551     {
2552     case CALL_EXPR:
2553       {
2554 	tree folded, sc = NULL_TREE;
2555 	unsigned int nargs = 0;
2556 	tree fn, *args;
2557 	if (TREE_CODE (currop->op0) == FUNCTION_DECL)
2558 	  fn = currop->op0;
2559 	else
2560 	  fn = find_or_generate_expression (block, currop->op0, stmts);
2561 	if (!fn)
2562 	  return NULL_TREE;
2563 	if (currop->op1)
2564 	  {
2565 	    sc = find_or_generate_expression (block, currop->op1, stmts);
2566 	    if (!sc)
2567 	      return NULL_TREE;
2568 	  }
2569 	args = XNEWVEC (tree, ref->operands.length () - 1);
2570 	while (*operand < ref->operands.length ())
2571 	  {
2572 	    args[nargs] = create_component_ref_by_pieces_1 (block, ref,
2573 							    operand, stmts);
2574 	    if (!args[nargs])
2575 	      return NULL_TREE;
2576 	    nargs++;
2577 	  }
2578 	folded = build_call_array (currop->type,
2579 				   (TREE_CODE (fn) == FUNCTION_DECL
2580 				    ? build_fold_addr_expr (fn) : fn),
2581 				   nargs, args);
2582 	free (args);
2583 	if (sc)
2584 	  CALL_EXPR_STATIC_CHAIN (folded) = sc;
2585 	return folded;
2586       }
2587 
2588     case MEM_REF:
2589       {
2590 	tree baseop = create_component_ref_by_pieces_1 (block, ref, operand,
2591 							stmts);
2592 	if (!baseop)
2593 	  return NULL_TREE;
2594 	tree offset = currop->op0;
2595 	if (TREE_CODE (baseop) == ADDR_EXPR
2596 	    && handled_component_p (TREE_OPERAND (baseop, 0)))
2597 	  {
2598 	    HOST_WIDE_INT off;
2599 	    tree base;
2600 	    base = get_addr_base_and_unit_offset (TREE_OPERAND (baseop, 0),
2601 						  &off);
2602 	    gcc_assert (base);
2603 	    offset = int_const_binop (PLUS_EXPR, offset,
2604 				      build_int_cst (TREE_TYPE (offset),
2605 						     off));
2606 	    baseop = build_fold_addr_expr (base);
2607 	  }
2608 	return fold_build2 (MEM_REF, currop->type, baseop, offset);
2609       }
2610 
2611     case TARGET_MEM_REF:
2612       {
2613 	tree genop0 = NULL_TREE, genop1 = NULL_TREE;
2614 	vn_reference_op_t nextop = &ref->operands[++*operand];
2615 	tree baseop = create_component_ref_by_pieces_1 (block, ref, operand,
2616 							stmts);
2617 	if (!baseop)
2618 	  return NULL_TREE;
2619 	if (currop->op0)
2620 	  {
2621 	    genop0 = find_or_generate_expression (block, currop->op0, stmts);
2622 	    if (!genop0)
2623 	      return NULL_TREE;
2624 	  }
2625 	if (nextop->op0)
2626 	  {
2627 	    genop1 = find_or_generate_expression (block, nextop->op0, stmts);
2628 	    if (!genop1)
2629 	      return NULL_TREE;
2630 	  }
2631 	return build5 (TARGET_MEM_REF, currop->type,
2632 		       baseop, currop->op2, genop0, currop->op1, genop1);
2633       }
2634 
2635     case ADDR_EXPR:
2636       if (currop->op0)
2637 	{
2638 	  gcc_assert (is_gimple_min_invariant (currop->op0));
2639 	  return currop->op0;
2640 	}
2641       /* Fallthrough.  */
2642     case REALPART_EXPR:
2643     case IMAGPART_EXPR:
2644     case VIEW_CONVERT_EXPR:
2645       {
2646 	tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2647 							stmts);
2648 	if (!genop0)
2649 	  return NULL_TREE;
2650 	return fold_build1 (currop->opcode, currop->type, genop0);
2651       }
2652 
2653     case WITH_SIZE_EXPR:
2654       {
2655 	tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2656 							stmts);
2657 	if (!genop0)
2658 	  return NULL_TREE;
2659 	tree genop1 = find_or_generate_expression (block, currop->op0, stmts);
2660 	if (!genop1)
2661 	  return NULL_TREE;
2662 	return fold_build2 (currop->opcode, currop->type, genop0, genop1);
2663       }
2664 
2665     case BIT_FIELD_REF:
2666       {
2667 	tree genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2668 							stmts);
2669 	if (!genop0)
2670 	  return NULL_TREE;
2671 	tree op1 = currop->op0;
2672 	tree op2 = currop->op1;
2673 	return fold_build3 (BIT_FIELD_REF, currop->type, genop0, op1, op2);
2674       }
2675 
2676       /* For array ref vn_reference_op's, operand 1 of the array ref
2677 	 is op0 of the reference op and operand 3 of the array ref is
2678 	 op1.  */
2679     case ARRAY_RANGE_REF:
2680     case ARRAY_REF:
2681       {
2682 	tree genop0;
2683 	tree genop1 = currop->op0;
2684 	tree genop2 = currop->op1;
2685 	tree genop3 = currop->op2;
2686 	genop0 = create_component_ref_by_pieces_1 (block, ref, operand,
2687 						   stmts);
2688 	if (!genop0)
2689 	  return NULL_TREE;
2690 	genop1 = find_or_generate_expression (block, genop1, stmts);
2691 	if (!genop1)
2692 	  return NULL_TREE;
2693 	if (genop2)
2694 	  {
2695 	    tree domain_type = TYPE_DOMAIN (TREE_TYPE (genop0));
2696 	    /* Drop zero minimum index if redundant.  */
2697 	    if (integer_zerop (genop2)
2698 		&& (!domain_type
2699 		    || integer_zerop (TYPE_MIN_VALUE (domain_type))))
2700 	      genop2 = NULL_TREE;
2701 	    else
2702 	      {
2703 		genop2 = find_or_generate_expression (block, genop2, stmts);
2704 		if (!genop2)
2705 		  return NULL_TREE;
2706 	      }
2707 	  }
2708 	if (genop3)
2709 	  {
2710 	    tree elmt_type = TREE_TYPE (TREE_TYPE (genop0));
2711 	    /* We can't always put a size in units of the element alignment
2712 	       here as the element alignment may be not visible.  See
2713 	       PR43783.  Simply drop the element size for constant
2714 	       sizes.  */
2715 	    if (tree_int_cst_equal (genop3, TYPE_SIZE_UNIT (elmt_type)))
2716 	      genop3 = NULL_TREE;
2717 	    else
2718 	      {
2719 		genop3 = size_binop (EXACT_DIV_EXPR, genop3,
2720 				     size_int (TYPE_ALIGN_UNIT (elmt_type)));
2721 		genop3 = find_or_generate_expression (block, genop3, stmts);
2722 		if (!genop3)
2723 		  return NULL_TREE;
2724 	      }
2725 	  }
2726 	return build4 (currop->opcode, currop->type, genop0, genop1,
2727 		       genop2, genop3);
2728       }
2729     case COMPONENT_REF:
2730       {
2731 	tree op0;
2732 	tree op1;
2733 	tree genop2 = currop->op1;
2734 	op0 = create_component_ref_by_pieces_1 (block, ref, operand, stmts);
2735 	if (!op0)
2736 	  return NULL_TREE;
2737 	/* op1 should be a FIELD_DECL, which are represented by themselves.  */
2738 	op1 = currop->op0;
2739 	if (genop2)
2740 	  {
2741 	    genop2 = find_or_generate_expression (block, genop2, stmts);
2742 	    if (!genop2)
2743 	      return NULL_TREE;
2744 	  }
2745 	return fold_build3 (COMPONENT_REF, TREE_TYPE (op1), op0, op1, genop2);
2746       }
2747 
2748     case SSA_NAME:
2749       {
2750 	genop = find_or_generate_expression (block, currop->op0, stmts);
2751 	return genop;
2752       }
2753     case STRING_CST:
2754     case INTEGER_CST:
2755     case COMPLEX_CST:
2756     case VECTOR_CST:
2757     case REAL_CST:
2758     case CONSTRUCTOR:
2759     case VAR_DECL:
2760     case PARM_DECL:
2761     case CONST_DECL:
2762     case RESULT_DECL:
2763     case FUNCTION_DECL:
2764       return currop->op0;
2765 
2766     default:
2767       gcc_unreachable ();
2768     }
2769 }
2770 
2771 /* For COMPONENT_REF's and ARRAY_REF's, we can't have any intermediates for the
2772    COMPONENT_REF or MEM_REF or ARRAY_REF portion, because we'd end up with
2773    trying to rename aggregates into ssa form directly, which is a no no.
2774 
2775    Thus, this routine doesn't create temporaries, it just builds a
2776    single access expression for the array, calling
2777    find_or_generate_expression to build the innermost pieces.
2778 
2779    This function is a subroutine of create_expression_by_pieces, and
2780    should not be called on it's own unless you really know what you
2781    are doing.  */
2782 
2783 static tree
create_component_ref_by_pieces(basic_block block,vn_reference_t ref,gimple_seq * stmts)2784 create_component_ref_by_pieces (basic_block block, vn_reference_t ref,
2785 				gimple_seq *stmts)
2786 {
2787   unsigned int op = 0;
2788   return create_component_ref_by_pieces_1 (block, ref, &op, stmts);
2789 }
2790 
2791 /* Find a simple leader for an expression, or generate one using
2792    create_expression_by_pieces from a NARY expression for the value.
2793    BLOCK is the basic_block we are looking for leaders in.
2794    OP is the tree expression to find a leader for or generate.
2795    Returns the leader or NULL_TREE on failure.  */
2796 
2797 static tree
find_or_generate_expression(basic_block block,tree op,gimple_seq * stmts)2798 find_or_generate_expression (basic_block block, tree op, gimple_seq *stmts)
2799 {
2800   pre_expr expr = get_or_alloc_expr_for (op);
2801   unsigned int lookfor = get_expr_value_id (expr);
2802   pre_expr leader = bitmap_find_leader (AVAIL_OUT (block), lookfor);
2803   if (leader)
2804     {
2805       if (leader->kind == NAME)
2806 	return PRE_EXPR_NAME (leader);
2807       else if (leader->kind == CONSTANT)
2808 	return PRE_EXPR_CONSTANT (leader);
2809 
2810       /* Defer.  */
2811       return NULL_TREE;
2812     }
2813 
2814   /* It must be a complex expression, so generate it recursively.  Note
2815      that this is only necessary to handle gcc.dg/tree-ssa/ssa-pre28.c
2816      where the insert algorithm fails to insert a required expression.  */
2817   bitmap exprset = value_expressions[lookfor];
2818   bitmap_iterator bi;
2819   unsigned int i;
2820   EXECUTE_IF_SET_IN_BITMAP (exprset, 0, i, bi)
2821     {
2822       pre_expr temp = expression_for_id (i);
2823       /* We cannot insert random REFERENCE expressions at arbitrary
2824 	 places.  We can insert NARYs which eventually re-materializes
2825 	 its operand values.  */
2826       if (temp->kind == NARY)
2827 	return create_expression_by_pieces (block, temp, stmts,
2828 					    get_expr_type (expr));
2829     }
2830 
2831   /* Defer.  */
2832   return NULL_TREE;
2833 }
2834 
2835 #define NECESSARY GF_PLF_1
2836 
2837 /* Create an expression in pieces, so that we can handle very complex
2838    expressions that may be ANTIC, but not necessary GIMPLE.
2839    BLOCK is the basic block the expression will be inserted into,
2840    EXPR is the expression to insert (in value form)
2841    STMTS is a statement list to append the necessary insertions into.
2842 
2843    This function will die if we hit some value that shouldn't be
2844    ANTIC but is (IE there is no leader for it, or its components).
2845    The function returns NULL_TREE in case a different antic expression
2846    has to be inserted first.
2847    This function may also generate expressions that are themselves
2848    partially or fully redundant.  Those that are will be either made
2849    fully redundant during the next iteration of insert (for partially
2850    redundant ones), or eliminated by eliminate (for fully redundant
2851    ones).  */
2852 
2853 static tree
create_expression_by_pieces(basic_block block,pre_expr expr,gimple_seq * stmts,tree type)2854 create_expression_by_pieces (basic_block block, pre_expr expr,
2855 			     gimple_seq *stmts, tree type)
2856 {
2857   tree name;
2858   tree folded;
2859   gimple_seq forced_stmts = NULL;
2860   unsigned int value_id;
2861   gimple_stmt_iterator gsi;
2862   tree exprtype = type ? type : get_expr_type (expr);
2863   pre_expr nameexpr;
2864   gimple newstmt;
2865 
2866   switch (expr->kind)
2867     {
2868       /* We may hit the NAME/CONSTANT case if we have to convert types
2869 	 that value numbering saw through.  */
2870     case NAME:
2871       folded = PRE_EXPR_NAME (expr);
2872       break;
2873     case CONSTANT:
2874       folded = PRE_EXPR_CONSTANT (expr);
2875       break;
2876     case REFERENCE:
2877       {
2878 	vn_reference_t ref = PRE_EXPR_REFERENCE (expr);
2879 	folded = create_component_ref_by_pieces (block, ref, stmts);
2880 	if (!folded)
2881 	  return NULL_TREE;
2882       }
2883       break;
2884     case NARY:
2885       {
2886 	vn_nary_op_t nary = PRE_EXPR_NARY (expr);
2887 	tree *genop = XALLOCAVEC (tree, nary->length);
2888 	unsigned i;
2889 	for (i = 0; i < nary->length; ++i)
2890 	  {
2891 	    genop[i] = find_or_generate_expression (block, nary->op[i], stmts);
2892 	    if (!genop[i])
2893 	      return NULL_TREE;
2894 	    /* Ensure genop[] is properly typed for POINTER_PLUS_EXPR.  It
2895 	       may have conversions stripped.  */
2896 	    if (nary->opcode == POINTER_PLUS_EXPR)
2897 	      {
2898 		if (i == 0)
2899 		  genop[i] = fold_convert (nary->type, genop[i]);
2900 		else if (i == 1)
2901 		  genop[i] = convert_to_ptrofftype (genop[i]);
2902 	      }
2903 	    else
2904 	      genop[i] = fold_convert (TREE_TYPE (nary->op[i]), genop[i]);
2905 	  }
2906 	if (nary->opcode == CONSTRUCTOR)
2907 	  {
2908 	    vec<constructor_elt, va_gc> *elts = NULL;
2909 	    for (i = 0; i < nary->length; ++i)
2910 	      CONSTRUCTOR_APPEND_ELT (elts, NULL_TREE, genop[i]);
2911 	    folded = build_constructor (nary->type, elts);
2912 	  }
2913 	else
2914 	  {
2915 	    switch (nary->length)
2916 	      {
2917 	      case 1:
2918 		folded = fold_build1 (nary->opcode, nary->type,
2919 				      genop[0]);
2920 		break;
2921 	      case 2:
2922 		folded = fold_build2 (nary->opcode, nary->type,
2923 				      genop[0], genop[1]);
2924 		break;
2925 	      case 3:
2926 		folded = fold_build3 (nary->opcode, nary->type,
2927 				      genop[0], genop[1], genop[2]);
2928 		break;
2929 	      default:
2930 		gcc_unreachable ();
2931 	      }
2932 	  }
2933       }
2934       break;
2935     default:
2936       gcc_unreachable ();
2937     }
2938 
2939   if (!useless_type_conversion_p (exprtype, TREE_TYPE (folded)))
2940     folded = fold_convert (exprtype, folded);
2941 
2942   /* Force the generated expression to be a sequence of GIMPLE
2943      statements.
2944      We have to call unshare_expr because force_gimple_operand may
2945      modify the tree we pass to it.  */
2946   folded = force_gimple_operand (unshare_expr (folded), &forced_stmts,
2947 				 false, NULL);
2948 
2949   /* If we have any intermediate expressions to the value sets, add them
2950      to the value sets and chain them in the instruction stream.  */
2951   if (forced_stmts)
2952     {
2953       gsi = gsi_start (forced_stmts);
2954       for (; !gsi_end_p (gsi); gsi_next (&gsi))
2955 	{
2956 	  gimple stmt = gsi_stmt (gsi);
2957 	  tree forcedname = gimple_get_lhs (stmt);
2958 	  pre_expr nameexpr;
2959 
2960 	  if (TREE_CODE (forcedname) == SSA_NAME)
2961 	    {
2962 	      bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (forcedname));
2963 	      VN_INFO_GET (forcedname)->valnum = forcedname;
2964 	      VN_INFO (forcedname)->value_id = get_next_value_id ();
2965 	      nameexpr = get_or_alloc_expr_for_name (forcedname);
2966 	      add_to_value (VN_INFO (forcedname)->value_id, nameexpr);
2967 	      bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
2968 	      bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
2969 	    }
2970 	}
2971       gimple_seq_add_seq (stmts, forced_stmts);
2972     }
2973 
2974   name = make_temp_ssa_name (exprtype, NULL, "pretmp");
2975   newstmt = gimple_build_assign (name, folded);
2976   gimple_set_plf (newstmt, NECESSARY, false);
2977 
2978   gimple_seq_add_stmt (stmts, newstmt);
2979   bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (name));
2980 
2981   /* Fold the last statement.  */
2982   gsi = gsi_last (*stmts);
2983   if (fold_stmt_inplace (&gsi))
2984     update_stmt (gsi_stmt (gsi));
2985 
2986   /* Add a value number to the temporary.
2987      The value may already exist in either NEW_SETS, or AVAIL_OUT, because
2988      we are creating the expression by pieces, and this particular piece of
2989      the expression may have been represented.  There is no harm in replacing
2990      here.  */
2991   value_id = get_expr_value_id (expr);
2992   VN_INFO_GET (name)->value_id = value_id;
2993   VN_INFO (name)->valnum = sccvn_valnum_from_value_id (value_id);
2994   if (VN_INFO (name)->valnum == NULL_TREE)
2995     VN_INFO (name)->valnum = name;
2996   gcc_assert (VN_INFO (name)->valnum != NULL_TREE);
2997   nameexpr = get_or_alloc_expr_for_name (name);
2998   add_to_value (value_id, nameexpr);
2999   if (NEW_SETS (block))
3000     bitmap_value_replace_in_set (NEW_SETS (block), nameexpr);
3001   bitmap_value_replace_in_set (AVAIL_OUT (block), nameexpr);
3002 
3003   pre_stats.insertions++;
3004   if (dump_file && (dump_flags & TDF_DETAILS))
3005     {
3006       fprintf (dump_file, "Inserted ");
3007       print_gimple_stmt (dump_file, newstmt, 0, 0);
3008       fprintf (dump_file, " in predecessor %d (%04d)\n",
3009 	       block->index, value_id);
3010     }
3011 
3012   return name;
3013 }
3014 
3015 
3016 /* Returns true if we want to inhibit the insertions of PHI nodes
3017    for the given EXPR for basic block BB (a member of a loop).
3018    We want to do this, when we fear that the induction variable we
3019    create might inhibit vectorization.  */
3020 
3021 static bool
inhibit_phi_insertion(basic_block bb,pre_expr expr)3022 inhibit_phi_insertion (basic_block bb, pre_expr expr)
3023 {
3024   vn_reference_t vr = PRE_EXPR_REFERENCE (expr);
3025   vec<vn_reference_op_s> ops = vr->operands;
3026   vn_reference_op_t op;
3027   unsigned i;
3028 
3029   /* If we aren't going to vectorize we don't inhibit anything.  */
3030   if (!flag_tree_loop_vectorize)
3031     return false;
3032 
3033   /* Otherwise we inhibit the insertion when the address of the
3034      memory reference is a simple induction variable.  In other
3035      cases the vectorizer won't do anything anyway (either it's
3036      loop invariant or a complicated expression).  */
3037   FOR_EACH_VEC_ELT (ops, i, op)
3038     {
3039       switch (op->opcode)
3040 	{
3041 	case CALL_EXPR:
3042 	  /* Calls are not a problem.  */
3043 	  return false;
3044 
3045 	case ARRAY_REF:
3046 	case ARRAY_RANGE_REF:
3047 	  if (TREE_CODE (op->op0) != SSA_NAME)
3048 	    break;
3049 	  /* Fallthru.  */
3050 	case SSA_NAME:
3051 	  {
3052 	    basic_block defbb = gimple_bb (SSA_NAME_DEF_STMT (op->op0));
3053 	    affine_iv iv;
3054 	    /* Default defs are loop invariant.  */
3055 	    if (!defbb)
3056 	      break;
3057 	    /* Defined outside this loop, also loop invariant.  */
3058 	    if (!flow_bb_inside_loop_p (bb->loop_father, defbb))
3059 	      break;
3060 	    /* If it's a simple induction variable inhibit insertion,
3061 	       the vectorizer might be interested in this one.  */
3062 	    if (simple_iv (bb->loop_father, bb->loop_father,
3063 			   op->op0, &iv, true))
3064 	      return true;
3065 	    /* No simple IV, vectorizer can't do anything, hence no
3066 	       reason to inhibit the transformation for this operand.  */
3067 	    break;
3068 	  }
3069 	default:
3070 	  break;
3071 	}
3072     }
3073   return false;
3074 }
3075 
3076 /* Insert the to-be-made-available values of expression EXPRNUM for each
3077    predecessor, stored in AVAIL, into the predecessors of BLOCK, and
3078    merge the result with a phi node, given the same value number as
3079    NODE.  Return true if we have inserted new stuff.  */
3080 
3081 static bool
insert_into_preds_of_block(basic_block block,unsigned int exprnum,vec<pre_expr> avail)3082 insert_into_preds_of_block (basic_block block, unsigned int exprnum,
3083 			    vec<pre_expr> avail)
3084 {
3085   pre_expr expr = expression_for_id (exprnum);
3086   pre_expr newphi;
3087   unsigned int val = get_expr_value_id (expr);
3088   edge pred;
3089   bool insertions = false;
3090   bool nophi = false;
3091   basic_block bprime;
3092   pre_expr eprime;
3093   edge_iterator ei;
3094   tree type = get_expr_type (expr);
3095   tree temp;
3096   gimple phi;
3097 
3098   /* Make sure we aren't creating an induction variable.  */
3099   if (bb_loop_depth (block) > 0 && EDGE_COUNT (block->preds) == 2)
3100     {
3101       bool firstinsideloop = false;
3102       bool secondinsideloop = false;
3103       firstinsideloop = flow_bb_inside_loop_p (block->loop_father,
3104 					       EDGE_PRED (block, 0)->src);
3105       secondinsideloop = flow_bb_inside_loop_p (block->loop_father,
3106 						EDGE_PRED (block, 1)->src);
3107       /* Induction variables only have one edge inside the loop.  */
3108       if ((firstinsideloop ^ secondinsideloop)
3109 	  && (expr->kind != REFERENCE
3110 	      || inhibit_phi_insertion (block, expr)))
3111 	{
3112 	  if (dump_file && (dump_flags & TDF_DETAILS))
3113 	    fprintf (dump_file, "Skipping insertion of phi for partial redundancy: Looks like an induction variable\n");
3114 	  nophi = true;
3115 	}
3116     }
3117 
3118   /* Make the necessary insertions.  */
3119   FOR_EACH_EDGE (pred, ei, block->preds)
3120     {
3121       gimple_seq stmts = NULL;
3122       tree builtexpr;
3123       bprime = pred->src;
3124       eprime = avail[pred->dest_idx];
3125 
3126       if (eprime->kind != NAME && eprime->kind != CONSTANT)
3127 	{
3128 	  builtexpr = create_expression_by_pieces (bprime, eprime,
3129 						   &stmts, type);
3130 	  gcc_assert (!(pred->flags & EDGE_ABNORMAL));
3131 	  gsi_insert_seq_on_edge (pred, stmts);
3132 	  if (!builtexpr)
3133 	    {
3134 	      /* We cannot insert a PHI node if we failed to insert
3135 		 on one edge.  */
3136 	      nophi = true;
3137 	      continue;
3138 	    }
3139 	  avail[pred->dest_idx] = get_or_alloc_expr_for_name (builtexpr);
3140 	  insertions = true;
3141 	}
3142       else if (eprime->kind == CONSTANT)
3143 	{
3144 	  /* Constants may not have the right type, fold_convert
3145 	     should give us back a constant with the right type.  */
3146 	  tree constant = PRE_EXPR_CONSTANT (eprime);
3147 	  if (!useless_type_conversion_p (type, TREE_TYPE (constant)))
3148 	    {
3149 	      tree builtexpr = fold_convert (type, constant);
3150 	      if (!is_gimple_min_invariant (builtexpr))
3151 		{
3152 		  tree forcedexpr = force_gimple_operand (builtexpr,
3153 							  &stmts, true,
3154 							  NULL);
3155 		  if (!is_gimple_min_invariant (forcedexpr))
3156 		    {
3157 		      if (forcedexpr != builtexpr)
3158 			{
3159 			  VN_INFO_GET (forcedexpr)->valnum = PRE_EXPR_CONSTANT (eprime);
3160 			  VN_INFO (forcedexpr)->value_id = get_expr_value_id (eprime);
3161 			}
3162 		      if (stmts)
3163 			{
3164 			  gimple_stmt_iterator gsi;
3165 			  gsi = gsi_start (stmts);
3166 			  for (; !gsi_end_p (gsi); gsi_next (&gsi))
3167 			    {
3168 			      gimple stmt = gsi_stmt (gsi);
3169 			      tree lhs = gimple_get_lhs (stmt);
3170 			      if (TREE_CODE (lhs) == SSA_NAME)
3171 				bitmap_set_bit (inserted_exprs,
3172 						SSA_NAME_VERSION (lhs));
3173 			      gimple_set_plf (stmt, NECESSARY, false);
3174 			    }
3175 			  gsi_insert_seq_on_edge (pred, stmts);
3176 			}
3177 		      avail[pred->dest_idx]
3178 			= get_or_alloc_expr_for_name (forcedexpr);
3179 		    }
3180 		}
3181 	      else
3182 		avail[pred->dest_idx]
3183 		    = get_or_alloc_expr_for_constant (builtexpr);
3184 	    }
3185 	}
3186       else if (eprime->kind == NAME)
3187 	{
3188 	  /* We may have to do a conversion because our value
3189 	     numbering can look through types in certain cases, but
3190 	     our IL requires all operands of a phi node have the same
3191 	     type.  */
3192 	  tree name = PRE_EXPR_NAME (eprime);
3193 	  if (!useless_type_conversion_p (type, TREE_TYPE (name)))
3194 	    {
3195 	      tree builtexpr;
3196 	      tree forcedexpr;
3197 	      builtexpr = fold_convert (type, name);
3198 	      forcedexpr = force_gimple_operand (builtexpr,
3199 						 &stmts, true,
3200 						 NULL);
3201 
3202 	      if (forcedexpr != name)
3203 		{
3204 		  VN_INFO_GET (forcedexpr)->valnum = VN_INFO (name)->valnum;
3205 		  VN_INFO (forcedexpr)->value_id = VN_INFO (name)->value_id;
3206 		}
3207 
3208 	      if (stmts)
3209 		{
3210 		  gimple_stmt_iterator gsi;
3211 		  gsi = gsi_start (stmts);
3212 		  for (; !gsi_end_p (gsi); gsi_next (&gsi))
3213 		    {
3214 		      gimple stmt = gsi_stmt (gsi);
3215 		      tree lhs = gimple_get_lhs (stmt);
3216 		      if (TREE_CODE (lhs) == SSA_NAME)
3217 			bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (lhs));
3218 		      gimple_set_plf (stmt, NECESSARY, false);
3219 		    }
3220 		  gsi_insert_seq_on_edge (pred, stmts);
3221 		}
3222 	      avail[pred->dest_idx] = get_or_alloc_expr_for_name (forcedexpr);
3223 	    }
3224 	}
3225     }
3226   /* If we didn't want a phi node, and we made insertions, we still have
3227      inserted new stuff, and thus return true.  If we didn't want a phi node,
3228      and didn't make insertions, we haven't added anything new, so return
3229      false.  */
3230   if (nophi && insertions)
3231     return true;
3232   else if (nophi && !insertions)
3233     return false;
3234 
3235   /* Now build a phi for the new variable.  */
3236   temp = make_temp_ssa_name (type, NULL, "prephitmp");
3237   phi = create_phi_node (temp, block);
3238 
3239   gimple_set_plf (phi, NECESSARY, false);
3240   VN_INFO_GET (temp)->value_id = val;
3241   VN_INFO (temp)->valnum = sccvn_valnum_from_value_id (val);
3242   if (VN_INFO (temp)->valnum == NULL_TREE)
3243     VN_INFO (temp)->valnum = temp;
3244   bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (temp));
3245   FOR_EACH_EDGE (pred, ei, block->preds)
3246     {
3247       pre_expr ae = avail[pred->dest_idx];
3248       gcc_assert (get_expr_type (ae) == type
3249 		  || useless_type_conversion_p (type, get_expr_type (ae)));
3250       if (ae->kind == CONSTANT)
3251 	add_phi_arg (phi, unshare_expr (PRE_EXPR_CONSTANT (ae)),
3252 		     pred, UNKNOWN_LOCATION);
3253       else
3254 	add_phi_arg (phi, PRE_EXPR_NAME (ae), pred, UNKNOWN_LOCATION);
3255     }
3256 
3257   newphi = get_or_alloc_expr_for_name (temp);
3258   add_to_value (val, newphi);
3259 
3260   /* The value should *not* exist in PHI_GEN, or else we wouldn't be doing
3261      this insertion, since we test for the existence of this value in PHI_GEN
3262      before proceeding with the partial redundancy checks in insert_aux.
3263 
3264      The value may exist in AVAIL_OUT, in particular, it could be represented
3265      by the expression we are trying to eliminate, in which case we want the
3266      replacement to occur.  If it's not existing in AVAIL_OUT, we want it
3267      inserted there.
3268 
3269      Similarly, to the PHI_GEN case, the value should not exist in NEW_SETS of
3270      this block, because if it did, it would have existed in our dominator's
3271      AVAIL_OUT, and would have been skipped due to the full redundancy check.
3272   */
3273 
3274   bitmap_insert_into_set (PHI_GEN (block), newphi);
3275   bitmap_value_replace_in_set (AVAIL_OUT (block),
3276 			       newphi);
3277   bitmap_insert_into_set (NEW_SETS (block),
3278 			  newphi);
3279 
3280   if (dump_file && (dump_flags & TDF_DETAILS))
3281     {
3282       fprintf (dump_file, "Created phi ");
3283       print_gimple_stmt (dump_file, phi, 0, 0);
3284       fprintf (dump_file, " in block %d (%04d)\n", block->index, val);
3285     }
3286   pre_stats.phis++;
3287   return true;
3288 }
3289 
3290 
3291 
3292 /* Perform insertion of partially redundant values.
3293    For BLOCK, do the following:
3294    1.  Propagate the NEW_SETS of the dominator into the current block.
3295    If the block has multiple predecessors,
3296        2a. Iterate over the ANTIC expressions for the block to see if
3297 	   any of them are partially redundant.
3298        2b. If so, insert them into the necessary predecessors to make
3299 	   the expression fully redundant.
3300        2c. Insert a new PHI merging the values of the predecessors.
3301        2d. Insert the new PHI, and the new expressions, into the
3302 	   NEW_SETS set.
3303    3. Recursively call ourselves on the dominator children of BLOCK.
3304 
3305    Steps 1, 2a, and 3 are done by insert_aux. 2b, 2c and 2d are done by
3306    do_regular_insertion and do_partial_insertion.
3307 
3308 */
3309 
3310 static bool
do_regular_insertion(basic_block block,basic_block dom)3311 do_regular_insertion (basic_block block, basic_block dom)
3312 {
3313   bool new_stuff = false;
3314   vec<pre_expr> exprs;
3315   pre_expr expr;
3316   vec<pre_expr> avail = vNULL;
3317   int i;
3318 
3319   exprs = sorted_array_from_bitmap_set (ANTIC_IN (block));
3320   avail.safe_grow (EDGE_COUNT (block->preds));
3321 
3322   FOR_EACH_VEC_ELT (exprs, i, expr)
3323     {
3324       if (expr->kind == NARY
3325 	  || expr->kind == REFERENCE)
3326 	{
3327 	  unsigned int val;
3328 	  bool by_some = false;
3329 	  bool cant_insert = false;
3330 	  bool all_same = true;
3331 	  pre_expr first_s = NULL;
3332 	  edge pred;
3333 	  basic_block bprime;
3334 	  pre_expr eprime = NULL;
3335 	  edge_iterator ei;
3336 	  pre_expr edoubleprime = NULL;
3337 	  bool do_insertion = false;
3338 
3339 	  val = get_expr_value_id (expr);
3340 	  if (bitmap_set_contains_value (PHI_GEN (block), val))
3341 	    continue;
3342 	  if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3343 	    {
3344 	      if (dump_file && (dump_flags & TDF_DETAILS))
3345 		{
3346 		  fprintf (dump_file, "Found fully redundant value: ");
3347 		  print_pre_expr (dump_file, expr);
3348 		  fprintf (dump_file, "\n");
3349 		}
3350 	      continue;
3351 	    }
3352 
3353 	  FOR_EACH_EDGE (pred, ei, block->preds)
3354 	    {
3355 	      unsigned int vprime;
3356 
3357 	      /* We should never run insertion for the exit block
3358 	         and so not come across fake pred edges.  */
3359 	      gcc_assert (!(pred->flags & EDGE_FAKE));
3360 	      bprime = pred->src;
3361 	      eprime = phi_translate (expr, ANTIC_IN (block), NULL,
3362 				      bprime, block);
3363 
3364 	      /* eprime will generally only be NULL if the
3365 		 value of the expression, translated
3366 		 through the PHI for this predecessor, is
3367 		 undefined.  If that is the case, we can't
3368 		 make the expression fully redundant,
3369 		 because its value is undefined along a
3370 		 predecessor path.  We can thus break out
3371 		 early because it doesn't matter what the
3372 		 rest of the results are.  */
3373 	      if (eprime == NULL)
3374 		{
3375 		  avail[pred->dest_idx] = NULL;
3376 		  cant_insert = true;
3377 		  break;
3378 		}
3379 
3380 	      eprime = fully_constant_expression (eprime);
3381 	      vprime = get_expr_value_id (eprime);
3382 	      edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime),
3383 						 vprime);
3384 	      if (edoubleprime == NULL)
3385 		{
3386 		  avail[pred->dest_idx] = eprime;
3387 		  all_same = false;
3388 		}
3389 	      else
3390 		{
3391 		  avail[pred->dest_idx] = edoubleprime;
3392 		  by_some = true;
3393 		  /* We want to perform insertions to remove a redundancy on
3394 		     a path in the CFG we want to optimize for speed.  */
3395 		  if (optimize_edge_for_speed_p (pred))
3396 		    do_insertion = true;
3397 		  if (first_s == NULL)
3398 		    first_s = edoubleprime;
3399 		  else if (!pre_expr_d::equal (first_s, edoubleprime))
3400 		    all_same = false;
3401 		}
3402 	    }
3403 	  /* If we can insert it, it's not the same value
3404 	     already existing along every predecessor, and
3405 	     it's defined by some predecessor, it is
3406 	     partially redundant.  */
3407 	  if (!cant_insert && !all_same && by_some)
3408 	    {
3409 	      if (!do_insertion)
3410 		{
3411 		  if (dump_file && (dump_flags & TDF_DETAILS))
3412 		    {
3413 		      fprintf (dump_file, "Skipping partial redundancy for "
3414 			       "expression ");
3415 		      print_pre_expr (dump_file, expr);
3416 		      fprintf (dump_file, " (%04d), no redundancy on to be "
3417 			       "optimized for speed edge\n", val);
3418 		    }
3419 		}
3420 	      else if (dbg_cnt (treepre_insert))
3421 		{
3422 		  if (dump_file && (dump_flags & TDF_DETAILS))
3423 		    {
3424 		      fprintf (dump_file, "Found partial redundancy for "
3425 			       "expression ");
3426 		      print_pre_expr (dump_file, expr);
3427 		      fprintf (dump_file, " (%04d)\n",
3428 			       get_expr_value_id (expr));
3429 		    }
3430 		  if (insert_into_preds_of_block (block,
3431 						  get_expression_id (expr),
3432 						  avail))
3433 		    new_stuff = true;
3434 		}
3435 	    }
3436 	  /* If all edges produce the same value and that value is
3437 	     an invariant, then the PHI has the same value on all
3438 	     edges.  Note this.  */
3439 	  else if (!cant_insert && all_same)
3440 	    {
3441 	      gcc_assert (edoubleprime->kind == CONSTANT
3442 			  || edoubleprime->kind == NAME);
3443 
3444 	      tree temp = make_temp_ssa_name (get_expr_type (expr),
3445 					      NULL, "pretmp");
3446 	      gimple assign = gimple_build_assign (temp,
3447 						   edoubleprime->kind == CONSTANT ? PRE_EXPR_CONSTANT (edoubleprime) : PRE_EXPR_NAME (edoubleprime));
3448 	      gimple_stmt_iterator gsi = gsi_after_labels (block);
3449 	      gsi_insert_before (&gsi, assign, GSI_NEW_STMT);
3450 
3451 	      gimple_set_plf (assign, NECESSARY, false);
3452 	      VN_INFO_GET (temp)->value_id = val;
3453 	      VN_INFO (temp)->valnum = sccvn_valnum_from_value_id (val);
3454 	      if (VN_INFO (temp)->valnum == NULL_TREE)
3455 		VN_INFO (temp)->valnum = temp;
3456 	      bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (temp));
3457 	      pre_expr newe = get_or_alloc_expr_for_name (temp);
3458 	      add_to_value (val, newe);
3459 	      bitmap_value_replace_in_set (AVAIL_OUT (block), newe);
3460 	      bitmap_insert_into_set (NEW_SETS (block), newe);
3461 	    }
3462 	}
3463     }
3464 
3465   exprs.release ();
3466   return new_stuff;
3467 }
3468 
3469 
3470 /* Perform insertion for partially anticipatable expressions.  There
3471    is only one case we will perform insertion for these.  This case is
3472    if the expression is partially anticipatable, and fully available.
3473    In this case, we know that putting it earlier will enable us to
3474    remove the later computation.  */
3475 
3476 
3477 static bool
do_partial_partial_insertion(basic_block block,basic_block dom)3478 do_partial_partial_insertion (basic_block block, basic_block dom)
3479 {
3480   bool new_stuff = false;
3481   vec<pre_expr> exprs;
3482   pre_expr expr;
3483   auto_vec<pre_expr> avail;
3484   int i;
3485 
3486   exprs = sorted_array_from_bitmap_set (PA_IN (block));
3487   avail.safe_grow (EDGE_COUNT (block->preds));
3488 
3489   FOR_EACH_VEC_ELT (exprs, i, expr)
3490     {
3491       if (expr->kind == NARY
3492 	  || expr->kind == REFERENCE)
3493 	{
3494 	  unsigned int val;
3495 	  bool by_all = true;
3496 	  bool cant_insert = false;
3497 	  edge pred;
3498 	  basic_block bprime;
3499 	  pre_expr eprime = NULL;
3500 	  edge_iterator ei;
3501 
3502 	  val = get_expr_value_id (expr);
3503 	  if (bitmap_set_contains_value (PHI_GEN (block), val))
3504 	    continue;
3505 	  if (bitmap_set_contains_value (AVAIL_OUT (dom), val))
3506 	    continue;
3507 
3508 	  FOR_EACH_EDGE (pred, ei, block->preds)
3509 	    {
3510 	      unsigned int vprime;
3511 	      pre_expr edoubleprime;
3512 
3513 	      /* We should never run insertion for the exit block
3514 	         and so not come across fake pred edges.  */
3515 	      gcc_assert (!(pred->flags & EDGE_FAKE));
3516 	      bprime = pred->src;
3517 	      eprime = phi_translate (expr, ANTIC_IN (block),
3518 				      PA_IN (block),
3519 				      bprime, block);
3520 
3521 	      /* eprime will generally only be NULL if the
3522 		 value of the expression, translated
3523 		 through the PHI for this predecessor, is
3524 		 undefined.  If that is the case, we can't
3525 		 make the expression fully redundant,
3526 		 because its value is undefined along a
3527 		 predecessor path.  We can thus break out
3528 		 early because it doesn't matter what the
3529 		 rest of the results are.  */
3530 	      if (eprime == NULL)
3531 		{
3532 		  avail[pred->dest_idx] = NULL;
3533 		  cant_insert = true;
3534 		  break;
3535 		}
3536 
3537 	      eprime = fully_constant_expression (eprime);
3538 	      vprime = get_expr_value_id (eprime);
3539 	      edoubleprime = bitmap_find_leader (AVAIL_OUT (bprime), vprime);
3540 	      avail[pred->dest_idx] = edoubleprime;
3541 	      if (edoubleprime == NULL)
3542 		{
3543 		  by_all = false;
3544 		  break;
3545 		}
3546 	    }
3547 
3548 	  /* If we can insert it, it's not the same value
3549 	     already existing along every predecessor, and
3550 	     it's defined by some predecessor, it is
3551 	     partially redundant.  */
3552 	  if (!cant_insert && by_all)
3553 	    {
3554 	      edge succ;
3555 	      bool do_insertion = false;
3556 
3557 	      /* Insert only if we can remove a later expression on a path
3558 		 that we want to optimize for speed.
3559 		 The phi node that we will be inserting in BLOCK is not free,
3560 		 and inserting it for the sake of !optimize_for_speed successor
3561 		 may cause regressions on the speed path.  */
3562 	      FOR_EACH_EDGE (succ, ei, block->succs)
3563 		{
3564 		  if (bitmap_set_contains_value (PA_IN (succ->dest), val)
3565 		      || bitmap_set_contains_value (ANTIC_IN (succ->dest), val))
3566 		    {
3567 		      if (optimize_edge_for_speed_p (succ))
3568 			do_insertion = true;
3569 		    }
3570 		}
3571 
3572 	      if (!do_insertion)
3573 		{
3574 		  if (dump_file && (dump_flags & TDF_DETAILS))
3575 		    {
3576 		      fprintf (dump_file, "Skipping partial partial redundancy "
3577 			       "for expression ");
3578 		      print_pre_expr (dump_file, expr);
3579 		      fprintf (dump_file, " (%04d), not (partially) anticipated "
3580 			       "on any to be optimized for speed edges\n", val);
3581 		    }
3582 		}
3583 	      else if (dbg_cnt (treepre_insert))
3584 		{
3585 		  pre_stats.pa_insert++;
3586 		  if (dump_file && (dump_flags & TDF_DETAILS))
3587 		    {
3588 		      fprintf (dump_file, "Found partial partial redundancy "
3589 			       "for expression ");
3590 		      print_pre_expr (dump_file, expr);
3591 		      fprintf (dump_file, " (%04d)\n",
3592 			       get_expr_value_id (expr));
3593 		    }
3594 		  if (insert_into_preds_of_block (block,
3595 						  get_expression_id (expr),
3596 						  avail))
3597 		    new_stuff = true;
3598 		}
3599 	    }
3600 	}
3601     }
3602 
3603   exprs.release ();
3604   return new_stuff;
3605 }
3606 
3607 static bool
insert_aux(basic_block block)3608 insert_aux (basic_block block)
3609 {
3610   basic_block son;
3611   bool new_stuff = false;
3612 
3613   if (block)
3614     {
3615       basic_block dom;
3616       dom = get_immediate_dominator (CDI_DOMINATORS, block);
3617       if (dom)
3618 	{
3619 	  unsigned i;
3620 	  bitmap_iterator bi;
3621 	  bitmap_set_t newset = NEW_SETS (dom);
3622 	  if (newset)
3623 	    {
3624 	      /* Note that we need to value_replace both NEW_SETS, and
3625 		 AVAIL_OUT. For both the case of NEW_SETS, the value may be
3626 		 represented by some non-simple expression here that we want
3627 		 to replace it with.  */
3628 	      FOR_EACH_EXPR_ID_IN_SET (newset, i, bi)
3629 		{
3630 		  pre_expr expr = expression_for_id (i);
3631 		  bitmap_value_replace_in_set (NEW_SETS (block), expr);
3632 		  bitmap_value_replace_in_set (AVAIL_OUT (block), expr);
3633 		}
3634 	    }
3635 	  if (!single_pred_p (block))
3636 	    {
3637 	      new_stuff |= do_regular_insertion (block, dom);
3638 	      if (do_partial_partial)
3639 		new_stuff |= do_partial_partial_insertion (block, dom);
3640 	    }
3641 	}
3642     }
3643   for (son = first_dom_son (CDI_DOMINATORS, block);
3644        son;
3645        son = next_dom_son (CDI_DOMINATORS, son))
3646     {
3647       new_stuff |= insert_aux (son);
3648     }
3649 
3650   return new_stuff;
3651 }
3652 
3653 /* Perform insertion of partially redundant values.  */
3654 
3655 static void
insert(void)3656 insert (void)
3657 {
3658   bool new_stuff = true;
3659   basic_block bb;
3660   int num_iterations = 0;
3661 
3662   FOR_ALL_BB_FN (bb, cfun)
3663     NEW_SETS (bb) = bitmap_set_new ();
3664 
3665   while (new_stuff)
3666     {
3667       num_iterations++;
3668       if (dump_file && dump_flags & TDF_DETAILS)
3669 	fprintf (dump_file, "Starting insert iteration %d\n", num_iterations);
3670       new_stuff = insert_aux (ENTRY_BLOCK_PTR_FOR_FN (cfun));
3671 
3672       /* Clear the NEW sets before the next iteration.  We have already
3673          fully propagated its contents.  */
3674       if (new_stuff)
3675 	FOR_ALL_BB_FN (bb, cfun)
3676 	  bitmap_set_free (NEW_SETS (bb));
3677     }
3678   statistics_histogram_event (cfun, "insert iterations", num_iterations);
3679 }
3680 
3681 
3682 /* Compute the AVAIL set for all basic blocks.
3683 
3684    This function performs value numbering of the statements in each basic
3685    block.  The AVAIL sets are built from information we glean while doing
3686    this value numbering, since the AVAIL sets contain only one entry per
3687    value.
3688 
3689    AVAIL_IN[BLOCK] = AVAIL_OUT[dom(BLOCK)].
3690    AVAIL_OUT[BLOCK] = AVAIL_IN[BLOCK] U PHI_GEN[BLOCK] U TMP_GEN[BLOCK].  */
3691 
3692 static void
compute_avail(void)3693 compute_avail (void)
3694 {
3695 
3696   basic_block block, son;
3697   basic_block *worklist;
3698   size_t sp = 0;
3699   unsigned i;
3700 
3701   /* We pretend that default definitions are defined in the entry block.
3702      This includes function arguments and the static chain decl.  */
3703   for (i = 1; i < num_ssa_names; ++i)
3704     {
3705       tree name = ssa_name (i);
3706       pre_expr e;
3707       if (!name
3708 	  || !SSA_NAME_IS_DEFAULT_DEF (name)
3709 	  || has_zero_uses (name)
3710 	  || virtual_operand_p (name))
3711 	continue;
3712 
3713       e = get_or_alloc_expr_for_name (name);
3714       add_to_value (get_expr_value_id (e), e);
3715       bitmap_insert_into_set (TMP_GEN (ENTRY_BLOCK_PTR_FOR_FN (cfun)), e);
3716       bitmap_value_insert_into_set (AVAIL_OUT (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
3717 				    e);
3718     }
3719 
3720   if (dump_file && (dump_flags & TDF_DETAILS))
3721     {
3722       print_bitmap_set (dump_file, TMP_GEN (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
3723 			"tmp_gen", ENTRY_BLOCK);
3724       print_bitmap_set (dump_file, AVAIL_OUT (ENTRY_BLOCK_PTR_FOR_FN (cfun)),
3725 			"avail_out", ENTRY_BLOCK);
3726     }
3727 
3728   /* Allocate the worklist.  */
3729   worklist = XNEWVEC (basic_block, n_basic_blocks_for_fn (cfun));
3730 
3731   /* Seed the algorithm by putting the dominator children of the entry
3732      block on the worklist.  */
3733   for (son = first_dom_son (CDI_DOMINATORS, ENTRY_BLOCK_PTR_FOR_FN (cfun));
3734        son;
3735        son = next_dom_son (CDI_DOMINATORS, son))
3736     worklist[sp++] = son;
3737 
3738   /* Loop until the worklist is empty.  */
3739   while (sp)
3740     {
3741       gimple_stmt_iterator gsi;
3742       gimple stmt;
3743       basic_block dom;
3744 
3745       /* Pick a block from the worklist.  */
3746       block = worklist[--sp];
3747 
3748       /* Initially, the set of available values in BLOCK is that of
3749 	 its immediate dominator.  */
3750       dom = get_immediate_dominator (CDI_DOMINATORS, block);
3751       if (dom)
3752 	bitmap_set_copy (AVAIL_OUT (block), AVAIL_OUT (dom));
3753 
3754       /* Generate values for PHI nodes.  */
3755       for (gsi = gsi_start_phis (block); !gsi_end_p (gsi); gsi_next (&gsi))
3756 	{
3757 	  tree result = gimple_phi_result (gsi_stmt (gsi));
3758 
3759 	  /* We have no need for virtual phis, as they don't represent
3760 	     actual computations.  */
3761 	  if (virtual_operand_p (result))
3762 	    continue;
3763 
3764 	  pre_expr e = get_or_alloc_expr_for_name (result);
3765 	  add_to_value (get_expr_value_id (e), e);
3766 	  bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3767 	  bitmap_insert_into_set (PHI_GEN (block), e);
3768 	}
3769 
3770       BB_MAY_NOTRETURN (block) = 0;
3771 
3772       /* Now compute value numbers and populate value sets with all
3773 	 the expressions computed in BLOCK.  */
3774       for (gsi = gsi_start_bb (block); !gsi_end_p (gsi); gsi_next (&gsi))
3775 	{
3776 	  ssa_op_iter iter;
3777 	  tree op;
3778 
3779 	  stmt = gsi_stmt (gsi);
3780 
3781 	  /* Cache whether the basic-block has any non-visible side-effect
3782 	     or control flow.
3783 	     If this isn't a call or it is the last stmt in the
3784 	     basic-block then the CFG represents things correctly.  */
3785 	  if (is_gimple_call (stmt) && !stmt_ends_bb_p (stmt))
3786 	    {
3787 	      /* Non-looping const functions always return normally.
3788 		 Otherwise the call might not return or have side-effects
3789 		 that forbids hoisting possibly trapping expressions
3790 		 before it.  */
3791 	      int flags = gimple_call_flags (stmt);
3792 	      if (!(flags & ECF_CONST)
3793 		  || (flags & ECF_LOOPING_CONST_OR_PURE))
3794 		BB_MAY_NOTRETURN (block) = 1;
3795 	    }
3796 
3797 	  FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_DEF)
3798 	    {
3799 	      pre_expr e = get_or_alloc_expr_for_name (op);
3800 
3801 	      add_to_value (get_expr_value_id (e), e);
3802 	      bitmap_insert_into_set (TMP_GEN (block), e);
3803 	      bitmap_value_insert_into_set (AVAIL_OUT (block), e);
3804 	    }
3805 
3806 	  if (gimple_has_side_effects (stmt)
3807 	      || stmt_could_throw_p (stmt)
3808 	      || is_gimple_debug (stmt))
3809 	    continue;
3810 
3811 	  FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
3812 	    {
3813 	      if (ssa_undefined_value_p (op))
3814 		continue;
3815 	      pre_expr e = get_or_alloc_expr_for_name (op);
3816 	      bitmap_value_insert_into_set (EXP_GEN (block), e);
3817 	    }
3818 
3819 	  switch (gimple_code (stmt))
3820 	    {
3821 	    case GIMPLE_RETURN:
3822 	      continue;
3823 
3824 	    case GIMPLE_CALL:
3825 	      {
3826 		vn_reference_t ref;
3827 		pre_expr result = NULL;
3828 		auto_vec<vn_reference_op_s> ops;
3829 
3830 		/* We can value number only calls to real functions.  */
3831 		if (gimple_call_internal_p (stmt))
3832 		  continue;
3833 
3834 		copy_reference_ops_from_call (stmt, &ops);
3835 		vn_reference_lookup_pieces (gimple_vuse (stmt), 0,
3836 					    gimple_expr_type (stmt),
3837 					    ops, &ref, VN_NOWALK);
3838 		if (!ref)
3839 		  continue;
3840 
3841 		/* If the value of the call is not invalidated in
3842 		   this block until it is computed, add the expression
3843 		   to EXP_GEN.  */
3844 		if (!gimple_vuse (stmt)
3845 		    || gimple_code
3846 		         (SSA_NAME_DEF_STMT (gimple_vuse (stmt))) == GIMPLE_PHI
3847 		    || gimple_bb (SSA_NAME_DEF_STMT
3848 				    (gimple_vuse (stmt))) != block)
3849 		  {
3850 		    result = (pre_expr) pool_alloc (pre_expr_pool);
3851 		    result->kind = REFERENCE;
3852 		    result->id = 0;
3853 		    PRE_EXPR_REFERENCE (result) = ref;
3854 
3855 		    get_or_alloc_expression_id (result);
3856 		    add_to_value (get_expr_value_id (result), result);
3857 		    bitmap_value_insert_into_set (EXP_GEN (block), result);
3858 		  }
3859 		continue;
3860 	      }
3861 
3862 	    case GIMPLE_ASSIGN:
3863 	      {
3864 		pre_expr result = NULL;
3865 		switch (vn_get_stmt_kind (stmt))
3866 		  {
3867 		  case VN_NARY:
3868 		    {
3869 		      enum tree_code code = gimple_assign_rhs_code (stmt);
3870 		      vn_nary_op_t nary;
3871 
3872 		      /* COND_EXPR and VEC_COND_EXPR are awkward in
3873 			 that they contain an embedded complex expression.
3874 			 Don't even try to shove those through PRE.  */
3875 		      if (code == COND_EXPR
3876 			  || code == VEC_COND_EXPR)
3877 			continue;
3878 
3879 		      vn_nary_op_lookup_stmt (stmt, &nary);
3880 		      if (!nary)
3881 			continue;
3882 
3883 		      /* If the NARY traps and there was a preceding
3884 		         point in the block that might not return avoid
3885 			 adding the nary to EXP_GEN.  */
3886 		      if (BB_MAY_NOTRETURN (block)
3887 			  && vn_nary_may_trap (nary))
3888 			continue;
3889 
3890 		      result = (pre_expr) pool_alloc (pre_expr_pool);
3891 		      result->kind = NARY;
3892 		      result->id = 0;
3893 		      PRE_EXPR_NARY (result) = nary;
3894 		      break;
3895 		    }
3896 
3897 		  case VN_REFERENCE:
3898 		    {
3899 		      vn_reference_t ref;
3900 		      vn_reference_lookup (gimple_assign_rhs1 (stmt),
3901 					   gimple_vuse (stmt),
3902 					   VN_WALK, &ref);
3903 		      if (!ref)
3904 			continue;
3905 
3906 		      /* If the value of the reference is not invalidated in
3907 			 this block until it is computed, add the expression
3908 			 to EXP_GEN.  */
3909 		      if (gimple_vuse (stmt))
3910 			{
3911 			  gimple def_stmt;
3912 			  bool ok = true;
3913 			  def_stmt = SSA_NAME_DEF_STMT (gimple_vuse (stmt));
3914 			  while (!gimple_nop_p (def_stmt)
3915 				 && gimple_code (def_stmt) != GIMPLE_PHI
3916 				 && gimple_bb (def_stmt) == block)
3917 			    {
3918 			      if (stmt_may_clobber_ref_p
3919 				    (def_stmt, gimple_assign_rhs1 (stmt)))
3920 				{
3921 				  ok = false;
3922 				  break;
3923 				}
3924 			      def_stmt
3925 				= SSA_NAME_DEF_STMT (gimple_vuse (def_stmt));
3926 			    }
3927 			  if (!ok)
3928 			    continue;
3929 			}
3930 
3931 		      result = (pre_expr) pool_alloc (pre_expr_pool);
3932 		      result->kind = REFERENCE;
3933 		      result->id = 0;
3934 		      PRE_EXPR_REFERENCE (result) = ref;
3935 		      break;
3936 		    }
3937 
3938 		  default:
3939 		    continue;
3940 		  }
3941 
3942 		get_or_alloc_expression_id (result);
3943 		add_to_value (get_expr_value_id (result), result);
3944 		bitmap_value_insert_into_set (EXP_GEN (block), result);
3945 		continue;
3946 	      }
3947 	    default:
3948 	      break;
3949 	    }
3950 	}
3951 
3952       if (dump_file && (dump_flags & TDF_DETAILS))
3953 	{
3954 	  print_bitmap_set (dump_file, EXP_GEN (block),
3955 			    "exp_gen", block->index);
3956 	  print_bitmap_set (dump_file, PHI_GEN (block),
3957 			    "phi_gen", block->index);
3958 	  print_bitmap_set (dump_file, TMP_GEN (block),
3959 			    "tmp_gen", block->index);
3960 	  print_bitmap_set (dump_file, AVAIL_OUT (block),
3961 			    "avail_out", block->index);
3962 	}
3963 
3964       /* Put the dominator children of BLOCK on the worklist of blocks
3965 	 to compute available sets for.  */
3966       for (son = first_dom_son (CDI_DOMINATORS, block);
3967 	   son;
3968 	   son = next_dom_son (CDI_DOMINATORS, son))
3969 	worklist[sp++] = son;
3970     }
3971 
3972   free (worklist);
3973 }
3974 
3975 
3976 /* Local state for the eliminate domwalk.  */
3977 static vec<gimple> el_to_remove;
3978 static vec<gimple> el_to_update;
3979 static unsigned int el_todo;
3980 static vec<tree> el_avail;
3981 static vec<tree> el_avail_stack;
3982 
3983 /* Return a leader for OP that is available at the current point of the
3984    eliminate domwalk.  */
3985 
3986 static tree
eliminate_avail(tree op)3987 eliminate_avail (tree op)
3988 {
3989   tree valnum = VN_INFO (op)->valnum;
3990   if (TREE_CODE (valnum) == SSA_NAME)
3991     {
3992       if (SSA_NAME_IS_DEFAULT_DEF (valnum))
3993 	return valnum;
3994       if (el_avail.length () > SSA_NAME_VERSION (valnum))
3995 	return el_avail[SSA_NAME_VERSION (valnum)];
3996     }
3997   else if (is_gimple_min_invariant (valnum))
3998     return valnum;
3999   return NULL_TREE;
4000 }
4001 
4002 /* At the current point of the eliminate domwalk make OP available.  */
4003 
4004 static void
eliminate_push_avail(tree op)4005 eliminate_push_avail (tree op)
4006 {
4007   tree valnum = VN_INFO (op)->valnum;
4008   if (TREE_CODE (valnum) == SSA_NAME)
4009     {
4010       if (el_avail.length () <= SSA_NAME_VERSION (valnum))
4011 	el_avail.safe_grow_cleared (SSA_NAME_VERSION (valnum) + 1);
4012       el_avail[SSA_NAME_VERSION (valnum)] = op;
4013       el_avail_stack.safe_push (op);
4014     }
4015 }
4016 
4017 /* Insert the expression recorded by SCCVN for VAL at *GSI.  Returns
4018    the leader for the expression if insertion was successful.  */
4019 
4020 static tree
eliminate_insert(gimple_stmt_iterator * gsi,tree val)4021 eliminate_insert (gimple_stmt_iterator *gsi, tree val)
4022 {
4023   tree expr = vn_get_expr_for (val);
4024   if (!CONVERT_EXPR_P (expr)
4025       && TREE_CODE (expr) != VIEW_CONVERT_EXPR)
4026     return NULL_TREE;
4027 
4028   tree op = TREE_OPERAND (expr, 0);
4029   tree leader = TREE_CODE (op) == SSA_NAME ? eliminate_avail (op) : op;
4030   if (!leader)
4031     return NULL_TREE;
4032 
4033   tree res = make_temp_ssa_name (TREE_TYPE (val), NULL, "pretmp");
4034   gimple tem = gimple_build_assign (res,
4035 				    fold_build1 (TREE_CODE (expr),
4036 						 TREE_TYPE (expr), leader));
4037   gsi_insert_before (gsi, tem, GSI_SAME_STMT);
4038   VN_INFO_GET (res)->valnum = val;
4039 
4040   if (TREE_CODE (leader) == SSA_NAME)
4041     gimple_set_plf (SSA_NAME_DEF_STMT (leader), NECESSARY, true);
4042 
4043   pre_stats.insertions++;
4044   if (dump_file && (dump_flags & TDF_DETAILS))
4045     {
4046       fprintf (dump_file, "Inserted ");
4047       print_gimple_stmt (dump_file, tem, 0, 0);
4048     }
4049 
4050   return res;
4051 }
4052 
4053 class eliminate_dom_walker : public dom_walker
4054 {
4055 public:
eliminate_dom_walker(cdi_direction direction)4056   eliminate_dom_walker (cdi_direction direction) : dom_walker (direction) {}
4057 
4058   virtual void before_dom_children (basic_block);
4059   virtual void after_dom_children (basic_block);
4060 };
4061 
4062 /* Perform elimination for the basic-block B during the domwalk.  */
4063 
4064 void
before_dom_children(basic_block b)4065 eliminate_dom_walker::before_dom_children (basic_block b)
4066 {
4067   gimple_stmt_iterator gsi;
4068   gimple stmt;
4069 
4070   /* Mark new bb.  */
4071   el_avail_stack.safe_push (NULL_TREE);
4072 
4073   for (gsi = gsi_start_phis (b); !gsi_end_p (gsi);)
4074     {
4075       gimple stmt, phi = gsi_stmt (gsi);
4076       tree sprime = NULL_TREE, res = PHI_RESULT (phi);
4077       gimple_stmt_iterator gsi2;
4078 
4079       /* We want to perform redundant PHI elimination.  Do so by
4080 	 replacing the PHI with a single copy if possible.
4081 	 Do not touch inserted, single-argument or virtual PHIs.  */
4082       if (gimple_phi_num_args (phi) == 1
4083 	  || virtual_operand_p (res))
4084 	{
4085 	  gsi_next (&gsi);
4086 	  continue;
4087 	}
4088 
4089       sprime = eliminate_avail (res);
4090       if (!sprime
4091 	  || sprime == res)
4092 	{
4093 	  eliminate_push_avail (res);
4094 	  gsi_next (&gsi);
4095 	  continue;
4096 	}
4097       else if (is_gimple_min_invariant (sprime))
4098 	{
4099 	  if (!useless_type_conversion_p (TREE_TYPE (res),
4100 					  TREE_TYPE (sprime)))
4101 	    sprime = fold_convert (TREE_TYPE (res), sprime);
4102 	}
4103 
4104       if (dump_file && (dump_flags & TDF_DETAILS))
4105 	{
4106 	  fprintf (dump_file, "Replaced redundant PHI node defining ");
4107 	  print_generic_expr (dump_file, res, 0);
4108 	  fprintf (dump_file, " with ");
4109 	  print_generic_expr (dump_file, sprime, 0);
4110 	  fprintf (dump_file, "\n");
4111 	}
4112 
4113       remove_phi_node (&gsi, false);
4114 
4115       if (inserted_exprs
4116 	  && !bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (res))
4117 	  && TREE_CODE (sprime) == SSA_NAME)
4118 	gimple_set_plf (SSA_NAME_DEF_STMT (sprime), NECESSARY, true);
4119 
4120       if (!useless_type_conversion_p (TREE_TYPE (res), TREE_TYPE (sprime)))
4121 	sprime = fold_convert (TREE_TYPE (res), sprime);
4122       stmt = gimple_build_assign (res, sprime);
4123       gimple_set_plf (stmt, NECESSARY, gimple_plf (phi, NECESSARY));
4124 
4125       gsi2 = gsi_after_labels (b);
4126       gsi_insert_before (&gsi2, stmt, GSI_NEW_STMT);
4127       /* Queue the copy for eventual removal.  */
4128       el_to_remove.safe_push (stmt);
4129       /* If we inserted this PHI node ourself, it's not an elimination.  */
4130       if (inserted_exprs
4131 	  && bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (res)))
4132 	pre_stats.phis--;
4133       else
4134 	pre_stats.eliminations++;
4135     }
4136 
4137   for (gsi = gsi_start_bb (b); !gsi_end_p (gsi); gsi_next (&gsi))
4138     {
4139       tree lhs = NULL_TREE;
4140       tree rhs = NULL_TREE;
4141 
4142       stmt = gsi_stmt (gsi);
4143 
4144       if (gimple_has_lhs (stmt))
4145 	lhs = gimple_get_lhs (stmt);
4146 
4147       if (gimple_assign_single_p (stmt))
4148 	rhs = gimple_assign_rhs1 (stmt);
4149 
4150       /* Lookup the RHS of the expression, see if we have an
4151 	 available computation for it.  If so, replace the RHS with
4152 	 the available computation.  */
4153       if (gimple_has_lhs (stmt)
4154 	  && TREE_CODE (lhs) == SSA_NAME
4155 	  && !gimple_has_volatile_ops  (stmt))
4156 	{
4157 	  tree sprime;
4158 	  gimple orig_stmt = stmt;
4159 
4160 	  sprime = eliminate_avail (lhs);
4161 	  /* If there is no usable leader mark lhs as leader for its value.  */
4162 	  if (!sprime)
4163 	    eliminate_push_avail (lhs);
4164 
4165 	  /* See PR43491.  Do not replace a global register variable when
4166 	     it is a the RHS of an assignment.  Do replace local register
4167 	     variables since gcc does not guarantee a local variable will
4168 	     be allocated in register.
4169 	     Do not perform copy propagation or undo constant propagation.  */
4170 	  if (gimple_assign_single_p (stmt)
4171 	      && (TREE_CODE (rhs) == SSA_NAME
4172 		  || is_gimple_min_invariant (rhs)
4173 		  || (TREE_CODE (rhs) == VAR_DECL
4174 		      && is_global_var (rhs)
4175 		      && DECL_HARD_REGISTER (rhs))))
4176 	    continue;
4177 
4178 	  if (!sprime)
4179 	    {
4180 	      /* If there is no existing usable leader but SCCVN thinks
4181 		 it has an expression it wants to use as replacement,
4182 		 insert that.  */
4183 	      tree val = VN_INFO (lhs)->valnum;
4184 	      if (val != VN_TOP
4185 		  && TREE_CODE (val) == SSA_NAME
4186 		  && VN_INFO (val)->needs_insertion
4187 		  && VN_INFO (val)->expr != NULL_TREE
4188 		  && (sprime = eliminate_insert (&gsi, val)) != NULL_TREE)
4189 		eliminate_push_avail (sprime);
4190 	    }
4191 	  else if (is_gimple_min_invariant (sprime))
4192 	    {
4193 	      /* If there is no existing leader but SCCVN knows this
4194 		 value is constant, use that constant.  */
4195 	      if (!useless_type_conversion_p (TREE_TYPE (lhs),
4196 					      TREE_TYPE (sprime)))
4197 		sprime = fold_convert (TREE_TYPE (lhs), sprime);
4198 
4199 	      if (dump_file && (dump_flags & TDF_DETAILS))
4200 		{
4201 		  fprintf (dump_file, "Replaced ");
4202 		  print_gimple_expr (dump_file, stmt, 0, 0);
4203 		  fprintf (dump_file, " with ");
4204 		  print_generic_expr (dump_file, sprime, 0);
4205 		  fprintf (dump_file, " in ");
4206 		  print_gimple_stmt (dump_file, stmt, 0, 0);
4207 		}
4208 	      pre_stats.eliminations++;
4209 	      propagate_tree_value_into_stmt (&gsi, sprime);
4210 	      stmt = gsi_stmt (gsi);
4211 	      update_stmt (stmt);
4212 
4213 	      /* If we removed EH side-effects from the statement, clean
4214 		 its EH information.  */
4215 	      if (maybe_clean_or_replace_eh_stmt (orig_stmt, stmt))
4216 		{
4217 		  bitmap_set_bit (need_eh_cleanup,
4218 				  gimple_bb (stmt)->index);
4219 		  if (dump_file && (dump_flags & TDF_DETAILS))
4220 		    fprintf (dump_file, "  Removed EH side-effects.\n");
4221 		}
4222 	      continue;
4223 	    }
4224 
4225 	  if (sprime
4226 	      && sprime != lhs
4227 	      && (rhs == NULL_TREE
4228 		  || TREE_CODE (rhs) != SSA_NAME
4229 		  || may_propagate_copy (rhs, sprime)))
4230 	    {
4231 	      bool can_make_abnormal_goto
4232 		  = is_gimple_call (stmt)
4233 		  && stmt_can_make_abnormal_goto (stmt);
4234 
4235 	      gcc_assert (sprime != rhs);
4236 
4237 	      if (dump_file && (dump_flags & TDF_DETAILS))
4238 		{
4239 		  fprintf (dump_file, "Replaced ");
4240 		  print_gimple_expr (dump_file, stmt, 0, 0);
4241 		  fprintf (dump_file, " with ");
4242 		  print_generic_expr (dump_file, sprime, 0);
4243 		  fprintf (dump_file, " in ");
4244 		  print_gimple_stmt (dump_file, stmt, 0, 0);
4245 		}
4246 
4247 	      if (TREE_CODE (sprime) == SSA_NAME)
4248 		gimple_set_plf (SSA_NAME_DEF_STMT (sprime),
4249 				NECESSARY, true);
4250 	      /* We need to make sure the new and old types actually match,
4251 		 which may require adding a simple cast, which fold_convert
4252 		 will do for us.  */
4253 	      if ((!rhs || TREE_CODE (rhs) != SSA_NAME)
4254 		  && !useless_type_conversion_p (gimple_expr_type (stmt),
4255 						 TREE_TYPE (sprime)))
4256 		sprime = fold_convert (gimple_expr_type (stmt), sprime);
4257 
4258 	      pre_stats.eliminations++;
4259 	      propagate_tree_value_into_stmt (&gsi, sprime);
4260 	      stmt = gsi_stmt (gsi);
4261 	      update_stmt (stmt);
4262 
4263 	      /* If we removed EH side-effects from the statement, clean
4264 		 its EH information.  */
4265 	      if (maybe_clean_or_replace_eh_stmt (orig_stmt, stmt))
4266 		{
4267 		  bitmap_set_bit (need_eh_cleanup,
4268 				  gimple_bb (stmt)->index);
4269 		  if (dump_file && (dump_flags & TDF_DETAILS))
4270 		    fprintf (dump_file, "  Removed EH side-effects.\n");
4271 		}
4272 
4273 	      /* Likewise for AB side-effects.  */
4274 	      if (can_make_abnormal_goto
4275 		  && !stmt_can_make_abnormal_goto (stmt))
4276 		{
4277 		  bitmap_set_bit (need_ab_cleanup,
4278 				  gimple_bb (stmt)->index);
4279 		  if (dump_file && (dump_flags & TDF_DETAILS))
4280 		    fprintf (dump_file, "  Removed AB side-effects.\n");
4281 		}
4282 	    }
4283 	}
4284       /* If the statement is a scalar store, see if the expression
4285 	 has the same value number as its rhs.  If so, the store is
4286 	 dead.  */
4287       else if (gimple_assign_single_p (stmt)
4288 	       && !gimple_has_volatile_ops (stmt)
4289 	       && !is_gimple_reg (gimple_assign_lhs (stmt))
4290 	       && (TREE_CODE (rhs) == SSA_NAME
4291 		   || is_gimple_min_invariant (rhs)))
4292 	{
4293 	  tree val;
4294 	  val = vn_reference_lookup (gimple_assign_lhs (stmt),
4295 				     gimple_vuse (stmt), VN_WALK, NULL);
4296 	  if (TREE_CODE (rhs) == SSA_NAME)
4297 	    rhs = VN_INFO (rhs)->valnum;
4298 	  if (val
4299 	      && operand_equal_p (val, rhs, 0))
4300 	    {
4301 	      if (dump_file && (dump_flags & TDF_DETAILS))
4302 		{
4303 		  fprintf (dump_file, "Deleted redundant store ");
4304 		  print_gimple_stmt (dump_file, stmt, 0, 0);
4305 		}
4306 
4307 	      /* Queue stmt for removal.  */
4308 	      el_to_remove.safe_push (stmt);
4309 	    }
4310 	}
4311       /* Visit COND_EXPRs and fold the comparison with the
4312 	 available value-numbers.  */
4313       else if (gimple_code (stmt) == GIMPLE_COND)
4314 	{
4315 	  tree op0 = gimple_cond_lhs (stmt);
4316 	  tree op1 = gimple_cond_rhs (stmt);
4317 	  tree result;
4318 
4319 	  if (TREE_CODE (op0) == SSA_NAME)
4320 	    op0 = VN_INFO (op0)->valnum;
4321 	  if (TREE_CODE (op1) == SSA_NAME)
4322 	    op1 = VN_INFO (op1)->valnum;
4323 	  result = fold_binary (gimple_cond_code (stmt), boolean_type_node,
4324 				op0, op1);
4325 	  if (result && TREE_CODE (result) == INTEGER_CST)
4326 	    {
4327 	      if (integer_zerop (result))
4328 		gimple_cond_make_false (stmt);
4329 	      else
4330 		gimple_cond_make_true (stmt);
4331 	      update_stmt (stmt);
4332 	      el_todo = TODO_cleanup_cfg;
4333 	    }
4334 	}
4335       /* Visit indirect calls and turn them into direct calls if
4336 	 possible.  */
4337       if (is_gimple_call (stmt))
4338 	{
4339 	  tree orig_fn = gimple_call_fn (stmt);
4340 	  tree fn;
4341 	  if (!orig_fn)
4342 	    continue;
4343 	  if (TREE_CODE (orig_fn) == SSA_NAME)
4344 	    fn = VN_INFO (orig_fn)->valnum;
4345 	  else if (TREE_CODE (orig_fn) == OBJ_TYPE_REF
4346 		   && TREE_CODE (OBJ_TYPE_REF_EXPR (orig_fn)) == SSA_NAME)
4347 	    {
4348 	      fn = VN_INFO (OBJ_TYPE_REF_EXPR (orig_fn))->valnum;
4349 	      if (!gimple_call_addr_fndecl (fn))
4350 		{
4351 		  fn = ipa_intraprocedural_devirtualization (stmt);
4352 		  if (fn)
4353 		    fn = build_fold_addr_expr (fn);
4354 		}
4355 	    }
4356 	  else
4357 	    continue;
4358 	  if (gimple_call_addr_fndecl (fn) != NULL_TREE
4359 	      && useless_type_conversion_p (TREE_TYPE (orig_fn),
4360 					    TREE_TYPE (fn)))
4361 	    {
4362 	      bool can_make_abnormal_goto
4363 		  = stmt_can_make_abnormal_goto (stmt);
4364 	      bool was_noreturn = gimple_call_noreturn_p (stmt);
4365 
4366 	      if (dump_file && (dump_flags & TDF_DETAILS))
4367 		{
4368 		  fprintf (dump_file, "Replacing call target with ");
4369 		  print_generic_expr (dump_file, fn, 0);
4370 		  fprintf (dump_file, " in ");
4371 		  print_gimple_stmt (dump_file, stmt, 0, 0);
4372 		}
4373 
4374 	      gimple_call_set_fn (stmt, fn);
4375 	      el_to_update.safe_push (stmt);
4376 
4377 	      /* When changing a call into a noreturn call, cfg cleanup
4378 		 is needed to fix up the noreturn call.  */
4379 	      if (!was_noreturn && gimple_call_noreturn_p (stmt))
4380 		el_todo |= TODO_cleanup_cfg;
4381 
4382 	      /* If we removed EH side-effects from the statement, clean
4383 		 its EH information.  */
4384 	      if (maybe_clean_or_replace_eh_stmt (stmt, stmt))
4385 		{
4386 		  bitmap_set_bit (need_eh_cleanup,
4387 				  gimple_bb (stmt)->index);
4388 		  if (dump_file && (dump_flags & TDF_DETAILS))
4389 		    fprintf (dump_file, "  Removed EH side-effects.\n");
4390 		}
4391 
4392 	      /* Likewise for AB side-effects.  */
4393 	      if (can_make_abnormal_goto
4394 		  && !stmt_can_make_abnormal_goto (stmt))
4395 		{
4396 		  bitmap_set_bit (need_ab_cleanup,
4397 				  gimple_bb (stmt)->index);
4398 		  if (dump_file && (dump_flags & TDF_DETAILS))
4399 		    fprintf (dump_file, "  Removed AB side-effects.\n");
4400 		}
4401 
4402 	      /* Changing an indirect call to a direct call may
4403 		 have exposed different semantics.  This may
4404 		 require an SSA update.  */
4405 	      el_todo |= TODO_update_ssa_only_virtuals;
4406 	    }
4407 	}
4408     }
4409 }
4410 
4411 /* Make no longer available leaders no longer available.  */
4412 
4413 void
after_dom_children(basic_block)4414 eliminate_dom_walker::after_dom_children (basic_block)
4415 {
4416   tree entry;
4417   while ((entry = el_avail_stack.pop ()) != NULL_TREE)
4418     el_avail[SSA_NAME_VERSION (VN_INFO (entry)->valnum)] = NULL_TREE;
4419 }
4420 
4421 /* Eliminate fully redundant computations.  */
4422 
4423 static unsigned int
eliminate(void)4424 eliminate (void)
4425 {
4426   gimple_stmt_iterator gsi;
4427   gimple stmt;
4428   unsigned i;
4429 
4430   need_eh_cleanup = BITMAP_ALLOC (NULL);
4431   need_ab_cleanup = BITMAP_ALLOC (NULL);
4432 
4433   el_to_remove.create (0);
4434   el_to_update.create (0);
4435   el_todo = 0;
4436   el_avail.create (0);
4437   el_avail_stack.create (0);
4438 
4439   eliminate_dom_walker (CDI_DOMINATORS).walk (cfun->cfg->x_entry_block_ptr);
4440 
4441   el_avail.release ();
4442   el_avail_stack.release ();
4443 
4444   /* We cannot remove stmts during BB walk, especially not release SSA
4445      names there as this confuses the VN machinery.  The stmts ending
4446      up in el_to_remove are either stores or simple copies.  */
4447   FOR_EACH_VEC_ELT (el_to_remove, i, stmt)
4448     {
4449       tree lhs = gimple_assign_lhs (stmt);
4450       tree rhs = gimple_assign_rhs1 (stmt);
4451       use_operand_p use_p;
4452       gimple use_stmt;
4453 
4454       /* If there is a single use only, propagate the equivalency
4455 	 instead of keeping the copy.  */
4456       if (TREE_CODE (lhs) == SSA_NAME
4457 	  && TREE_CODE (rhs) == SSA_NAME
4458 	  && single_imm_use (lhs, &use_p, &use_stmt)
4459 	  && may_propagate_copy (USE_FROM_PTR (use_p), rhs))
4460 	{
4461 	  SET_USE (use_p, rhs);
4462 	  update_stmt (use_stmt);
4463 	  if (inserted_exprs
4464 	      && bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (lhs))
4465 	      && TREE_CODE (rhs) == SSA_NAME)
4466 	    gimple_set_plf (SSA_NAME_DEF_STMT (rhs), NECESSARY, true);
4467 	}
4468 
4469       /* If this is a store or a now unused copy, remove it.  */
4470       if (TREE_CODE (lhs) != SSA_NAME
4471 	  || has_zero_uses (lhs))
4472 	{
4473 	  basic_block bb = gimple_bb (stmt);
4474 	  gsi = gsi_for_stmt (stmt);
4475 	  unlink_stmt_vdef (stmt);
4476 	  if (gsi_remove (&gsi, true))
4477 	    bitmap_set_bit (need_eh_cleanup, bb->index);
4478 	  if (inserted_exprs
4479 	      && TREE_CODE (lhs) == SSA_NAME)
4480 	    bitmap_clear_bit (inserted_exprs, SSA_NAME_VERSION (lhs));
4481 	  release_defs (stmt);
4482 	}
4483     }
4484   el_to_remove.release ();
4485 
4486   /* We cannot update call statements with virtual operands during
4487      SSA walk.  This might remove them which in turn makes our
4488      VN lattice invalid.  */
4489   FOR_EACH_VEC_ELT (el_to_update, i, stmt)
4490     update_stmt (stmt);
4491   el_to_update.release ();
4492 
4493   return el_todo;
4494 }
4495 
4496 /* Perform CFG cleanups made necessary by elimination.  */
4497 
4498 static unsigned
fini_eliminate(void)4499 fini_eliminate (void)
4500 {
4501   bool do_eh_cleanup = !bitmap_empty_p (need_eh_cleanup);
4502   bool do_ab_cleanup = !bitmap_empty_p (need_ab_cleanup);
4503 
4504   if (do_eh_cleanup)
4505     gimple_purge_all_dead_eh_edges (need_eh_cleanup);
4506 
4507   if (do_ab_cleanup)
4508     gimple_purge_all_dead_abnormal_call_edges (need_ab_cleanup);
4509 
4510   BITMAP_FREE (need_eh_cleanup);
4511   BITMAP_FREE (need_ab_cleanup);
4512 
4513   if (do_eh_cleanup || do_ab_cleanup)
4514     return TODO_cleanup_cfg;
4515   return 0;
4516 }
4517 
4518 /* Borrow a bit of tree-ssa-dce.c for the moment.
4519    XXX: In 4.1, we should be able to just run a DCE pass after PRE, though
4520    this may be a bit faster, and we may want critical edges kept split.  */
4521 
4522 /* If OP's defining statement has not already been determined to be necessary,
4523    mark that statement necessary. Return the stmt, if it is newly
4524    necessary.  */
4525 
4526 static inline gimple
mark_operand_necessary(tree op)4527 mark_operand_necessary (tree op)
4528 {
4529   gimple stmt;
4530 
4531   gcc_assert (op);
4532 
4533   if (TREE_CODE (op) != SSA_NAME)
4534     return NULL;
4535 
4536   stmt = SSA_NAME_DEF_STMT (op);
4537   gcc_assert (stmt);
4538 
4539   if (gimple_plf (stmt, NECESSARY)
4540       || gimple_nop_p (stmt))
4541     return NULL;
4542 
4543   gimple_set_plf (stmt, NECESSARY, true);
4544   return stmt;
4545 }
4546 
4547 /* Because we don't follow exactly the standard PRE algorithm, and decide not
4548    to insert PHI nodes sometimes, and because value numbering of casts isn't
4549    perfect, we sometimes end up inserting dead code.   This simple DCE-like
4550    pass removes any insertions we made that weren't actually used.  */
4551 
4552 static void
remove_dead_inserted_code(void)4553 remove_dead_inserted_code (void)
4554 {
4555   bitmap worklist;
4556   unsigned i;
4557   bitmap_iterator bi;
4558   gimple t;
4559 
4560   worklist = BITMAP_ALLOC (NULL);
4561   EXECUTE_IF_SET_IN_BITMAP (inserted_exprs, 0, i, bi)
4562     {
4563       t = SSA_NAME_DEF_STMT (ssa_name (i));
4564       if (gimple_plf (t, NECESSARY))
4565 	bitmap_set_bit (worklist, i);
4566     }
4567   while (!bitmap_empty_p (worklist))
4568     {
4569       i = bitmap_first_set_bit (worklist);
4570       bitmap_clear_bit (worklist, i);
4571       t = SSA_NAME_DEF_STMT (ssa_name (i));
4572 
4573       /* PHI nodes are somewhat special in that each PHI alternative has
4574 	 data and control dependencies.  All the statements feeding the
4575 	 PHI node's arguments are always necessary. */
4576       if (gimple_code (t) == GIMPLE_PHI)
4577 	{
4578 	  unsigned k;
4579 
4580 	  for (k = 0; k < gimple_phi_num_args (t); k++)
4581 	    {
4582 	      tree arg = PHI_ARG_DEF (t, k);
4583 	      if (TREE_CODE (arg) == SSA_NAME)
4584 		{
4585 		  gimple n = mark_operand_necessary (arg);
4586 		  if (n)
4587 		    bitmap_set_bit (worklist, SSA_NAME_VERSION (arg));
4588 		}
4589 	    }
4590 	}
4591       else
4592 	{
4593 	  /* Propagate through the operands.  Examine all the USE, VUSE and
4594 	     VDEF operands in this statement.  Mark all the statements
4595 	     which feed this statement's uses as necessary.  */
4596 	  ssa_op_iter iter;
4597 	  tree use;
4598 
4599 	  /* The operands of VDEF expressions are also needed as they
4600 	     represent potential definitions that may reach this
4601 	     statement (VDEF operands allow us to follow def-def
4602 	     links).  */
4603 
4604 	  FOR_EACH_SSA_TREE_OPERAND (use, t, iter, SSA_OP_ALL_USES)
4605 	    {
4606 	      gimple n = mark_operand_necessary (use);
4607 	      if (n)
4608 		bitmap_set_bit (worklist, SSA_NAME_VERSION (use));
4609 	    }
4610 	}
4611     }
4612 
4613   EXECUTE_IF_SET_IN_BITMAP (inserted_exprs, 0, i, bi)
4614     {
4615       t = SSA_NAME_DEF_STMT (ssa_name (i));
4616       if (!gimple_plf (t, NECESSARY))
4617 	{
4618 	  gimple_stmt_iterator gsi;
4619 
4620 	  if (dump_file && (dump_flags & TDF_DETAILS))
4621 	    {
4622 	      fprintf (dump_file, "Removing unnecessary insertion:");
4623 	      print_gimple_stmt (dump_file, t, 0, 0);
4624 	    }
4625 
4626 	  gsi = gsi_for_stmt (t);
4627 	  if (gimple_code (t) == GIMPLE_PHI)
4628 	    remove_phi_node (&gsi, true);
4629 	  else
4630 	    {
4631 	      gsi_remove (&gsi, true);
4632 	      release_defs (t);
4633 	    }
4634 	}
4635     }
4636   BITMAP_FREE (worklist);
4637 }
4638 
4639 
4640 /* Initialize data structures used by PRE.  */
4641 
4642 static void
init_pre(void)4643 init_pre (void)
4644 {
4645   basic_block bb;
4646 
4647   next_expression_id = 1;
4648   expressions.create (0);
4649   expressions.safe_push (NULL);
4650   value_expressions.create (get_max_value_id () + 1);
4651   value_expressions.safe_grow_cleared (get_max_value_id () + 1);
4652   name_to_id.create (0);
4653 
4654   inserted_exprs = BITMAP_ALLOC (NULL);
4655 
4656   connect_infinite_loops_to_exit ();
4657   memset (&pre_stats, 0, sizeof (pre_stats));
4658 
4659   postorder = XNEWVEC (int, n_basic_blocks_for_fn (cfun));
4660   postorder_num = inverted_post_order_compute (postorder);
4661 
4662   alloc_aux_for_blocks (sizeof (struct bb_bitmap_sets));
4663 
4664   calculate_dominance_info (CDI_POST_DOMINATORS);
4665   calculate_dominance_info (CDI_DOMINATORS);
4666 
4667   bitmap_obstack_initialize (&grand_bitmap_obstack);
4668   phi_translate_table.create (5110);
4669   expression_to_id.create (num_ssa_names * 3);
4670   bitmap_set_pool = create_alloc_pool ("Bitmap sets",
4671 				       sizeof (struct bitmap_set), 30);
4672   pre_expr_pool = create_alloc_pool ("pre_expr nodes",
4673 				     sizeof (struct pre_expr_d), 30);
4674   FOR_ALL_BB_FN (bb, cfun)
4675     {
4676       EXP_GEN (bb) = bitmap_set_new ();
4677       PHI_GEN (bb) = bitmap_set_new ();
4678       TMP_GEN (bb) = bitmap_set_new ();
4679       AVAIL_OUT (bb) = bitmap_set_new ();
4680     }
4681 }
4682 
4683 
4684 /* Deallocate data structures used by PRE.  */
4685 
4686 static void
fini_pre()4687 fini_pre ()
4688 {
4689   free (postorder);
4690   value_expressions.release ();
4691   BITMAP_FREE (inserted_exprs);
4692   bitmap_obstack_release (&grand_bitmap_obstack);
4693   free_alloc_pool (bitmap_set_pool);
4694   free_alloc_pool (pre_expr_pool);
4695   phi_translate_table.dispose ();
4696   expression_to_id.dispose ();
4697   name_to_id.release ();
4698 
4699   free_aux_for_blocks ();
4700 
4701   free_dominance_info (CDI_POST_DOMINATORS);
4702 }
4703 
4704 /* Gate and execute functions for PRE.  */
4705 
4706 static unsigned int
do_pre(void)4707 do_pre (void)
4708 {
4709   unsigned int todo = 0;
4710 
4711   do_partial_partial =
4712     flag_tree_partial_pre && optimize_function_for_speed_p (cfun);
4713 
4714   /* This has to happen before SCCVN runs because
4715      loop_optimizer_init may create new phis, etc.  */
4716   loop_optimizer_init (LOOPS_NORMAL);
4717 
4718   if (!run_scc_vn (VN_WALK))
4719     {
4720       loop_optimizer_finalize ();
4721       return 0;
4722     }
4723 
4724   init_pre ();
4725   scev_initialize ();
4726 
4727   /* Collect and value number expressions computed in each basic block.  */
4728   compute_avail ();
4729 
4730   /* Insert can get quite slow on an incredibly large number of basic
4731      blocks due to some quadratic behavior.  Until this behavior is
4732      fixed, don't run it when he have an incredibly large number of
4733      bb's.  If we aren't going to run insert, there is no point in
4734      computing ANTIC, either, even though it's plenty fast.  */
4735   if (n_basic_blocks_for_fn (cfun) < 4000)
4736     {
4737       compute_antic ();
4738       insert ();
4739     }
4740 
4741   /* Make sure to remove fake edges before committing our inserts.
4742      This makes sure we don't end up with extra critical edges that
4743      we would need to split.  */
4744   remove_fake_exit_edges ();
4745   gsi_commit_edge_inserts ();
4746 
4747   /* Remove all the redundant expressions.  */
4748   todo |= eliminate ();
4749 
4750   statistics_counter_event (cfun, "Insertions", pre_stats.insertions);
4751   statistics_counter_event (cfun, "PA inserted", pre_stats.pa_insert);
4752   statistics_counter_event (cfun, "New PHIs", pre_stats.phis);
4753   statistics_counter_event (cfun, "Eliminated", pre_stats.eliminations);
4754 
4755   clear_expression_ids ();
4756   remove_dead_inserted_code ();
4757   todo |= TODO_verify_flow;
4758 
4759   scev_finalize ();
4760   fini_pre ();
4761   todo |= fini_eliminate ();
4762   loop_optimizer_finalize ();
4763 
4764   /* TODO: tail_merge_optimize may merge all predecessors of a block, in which
4765      case we can merge the block with the remaining predecessor of the block.
4766      It should either:
4767      - call merge_blocks after each tail merge iteration
4768      - call merge_blocks after all tail merge iterations
4769      - mark TODO_cleanup_cfg when necessary
4770      - share the cfg cleanup with fini_pre.  */
4771   todo |= tail_merge_optimize (todo);
4772 
4773   free_scc_vn ();
4774 
4775   /* Tail merging invalidates the virtual SSA web, together with
4776      cfg-cleanup opportunities exposed by PRE this will wreck the
4777      SSA updating machinery.  So make sure to run update-ssa
4778      manually, before eventually scheduling cfg-cleanup as part of
4779      the todo.  */
4780   update_ssa (TODO_update_ssa_only_virtuals);
4781 
4782   return todo;
4783 }
4784 
4785 static bool
gate_pre(void)4786 gate_pre (void)
4787 {
4788   return flag_tree_pre != 0;
4789 }
4790 
4791 namespace {
4792 
4793 const pass_data pass_data_pre =
4794 {
4795   GIMPLE_PASS, /* type */
4796   "pre", /* name */
4797   OPTGROUP_NONE, /* optinfo_flags */
4798   true, /* has_gate */
4799   true, /* has_execute */
4800   TV_TREE_PRE, /* tv_id */
4801   /* PROP_no_crit_edges is ensured by placing pass_split_crit_edges before
4802      pass_pre.  */
4803   ( PROP_no_crit_edges | PROP_cfg | PROP_ssa ), /* properties_required */
4804   0, /* properties_provided */
4805   PROP_no_crit_edges, /* properties_destroyed */
4806   TODO_rebuild_alias, /* todo_flags_start */
4807   TODO_verify_ssa, /* todo_flags_finish */
4808 };
4809 
4810 class pass_pre : public gimple_opt_pass
4811 {
4812 public:
pass_pre(gcc::context * ctxt)4813   pass_pre (gcc::context *ctxt)
4814     : gimple_opt_pass (pass_data_pre, ctxt)
4815   {}
4816 
4817   /* opt_pass methods: */
gate()4818   bool gate () { return gate_pre (); }
execute()4819   unsigned int execute () { return do_pre (); }
4820 
4821 }; // class pass_pre
4822 
4823 } // anon namespace
4824 
4825 gimple_opt_pass *
make_pass_pre(gcc::context * ctxt)4826 make_pass_pre (gcc::context *ctxt)
4827 {
4828   return new pass_pre (ctxt);
4829 }
4830 
4831 
4832 /* Gate and execute functions for FRE.  */
4833 
4834 static unsigned int
execute_fre(void)4835 execute_fre (void)
4836 {
4837   unsigned int todo = 0;
4838 
4839   if (!run_scc_vn (VN_WALKREWRITE))
4840     return 0;
4841 
4842   memset (&pre_stats, 0, sizeof (pre_stats));
4843 
4844   /* Remove all the redundant expressions.  */
4845   todo |= eliminate ();
4846 
4847   todo |= fini_eliminate ();
4848 
4849   free_scc_vn ();
4850 
4851   statistics_counter_event (cfun, "Insertions", pre_stats.insertions);
4852   statistics_counter_event (cfun, "Eliminated", pre_stats.eliminations);
4853 
4854   return todo;
4855 }
4856 
4857 static bool
gate_fre(void)4858 gate_fre (void)
4859 {
4860   return flag_tree_fre != 0;
4861 }
4862 
4863 namespace {
4864 
4865 const pass_data pass_data_fre =
4866 {
4867   GIMPLE_PASS, /* type */
4868   "fre", /* name */
4869   OPTGROUP_NONE, /* optinfo_flags */
4870   true, /* has_gate */
4871   true, /* has_execute */
4872   TV_TREE_FRE, /* tv_id */
4873   ( PROP_cfg | PROP_ssa ), /* properties_required */
4874   0, /* properties_provided */
4875   0, /* properties_destroyed */
4876   0, /* todo_flags_start */
4877   TODO_verify_ssa, /* todo_flags_finish */
4878 };
4879 
4880 class pass_fre : public gimple_opt_pass
4881 {
4882 public:
pass_fre(gcc::context * ctxt)4883   pass_fre (gcc::context *ctxt)
4884     : gimple_opt_pass (pass_data_fre, ctxt)
4885   {}
4886 
4887   /* opt_pass methods: */
clone()4888   opt_pass * clone () { return new pass_fre (m_ctxt); }
gate()4889   bool gate () { return gate_fre (); }
execute()4890   unsigned int execute () { return execute_fre (); }
4891 
4892 }; // class pass_fre
4893 
4894 } // anon namespace
4895 
4896 gimple_opt_pass *
make_pass_fre(gcc::context * ctxt)4897 make_pass_fre (gcc::context *ctxt)
4898 {
4899   return new pass_fre (ctxt);
4900 }
4901