c++: improve verify_constant diagnostic [PR91483]
[official-gcc.git] / gcc / tree-ssa-sccvn.cc
blobb1678911671e0d3805c4936ffab6e11a781f0d12
1 /* SCC value numbering for trees
2 Copyright (C) 2006-2023 Free Software Foundation, Inc.
3 Contributed by Daniel Berlin <dan@dberlin.org>
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "splay-tree.h"
25 #include "backend.h"
26 #include "rtl.h"
27 #include "tree.h"
28 #include "gimple.h"
29 #include "ssa.h"
30 #include "expmed.h"
31 #include "insn-config.h"
32 #include "memmodel.h"
33 #include "emit-rtl.h"
34 #include "cgraph.h"
35 #include "gimple-pretty-print.h"
36 #include "alias.h"
37 #include "fold-const.h"
38 #include "stor-layout.h"
39 #include "cfganal.h"
40 #include "tree-inline.h"
41 #include "internal-fn.h"
42 #include "gimple-iterator.h"
43 #include "gimple-fold.h"
44 #include "tree-eh.h"
45 #include "gimplify.h"
46 #include "flags.h"
47 #include "dojump.h"
48 #include "explow.h"
49 #include "calls.h"
50 #include "varasm.h"
51 #include "stmt.h"
52 #include "expr.h"
53 #include "tree-dfa.h"
54 #include "tree-ssa.h"
55 #include "dumpfile.h"
56 #include "cfgloop.h"
57 #include "tree-ssa-propagate.h"
58 #include "tree-cfg.h"
59 #include "domwalk.h"
60 #include "gimple-match.h"
61 #include "stringpool.h"
62 #include "attribs.h"
63 #include "tree-pass.h"
64 #include "statistics.h"
65 #include "langhooks.h"
66 #include "ipa-utils.h"
67 #include "dbgcnt.h"
68 #include "tree-cfgcleanup.h"
69 #include "tree-ssa-loop.h"
70 #include "tree-scalar-evolution.h"
71 #include "tree-ssa-loop-niter.h"
72 #include "builtins.h"
73 #include "fold-const-call.h"
74 #include "ipa-modref-tree.h"
75 #include "ipa-modref.h"
76 #include "tree-ssa-sccvn.h"
77 #include "alloc-pool.h"
78 #include "symbol-summary.h"
79 #include "ipa-prop.h"
81 /* This algorithm is based on the SCC algorithm presented by Keith
82 Cooper and L. Taylor Simpson in "SCC-Based Value numbering"
83 (http://citeseer.ist.psu.edu/41805.html). In
84 straight line code, it is equivalent to a regular hash based value
85 numbering that is performed in reverse postorder.
87 For code with cycles, there are two alternatives, both of which
88 require keeping the hashtables separate from the actual list of
89 value numbers for SSA names.
91 1. Iterate value numbering in an RPO walk of the blocks, removing
92 all the entries from the hashtable after each iteration (but
93 keeping the SSA name->value number mapping between iterations).
94 Iterate until it does not change.
96 2. Perform value numbering as part of an SCC walk on the SSA graph,
97 iterating only the cycles in the SSA graph until they do not change
98 (using a separate, optimistic hashtable for value numbering the SCC
99 operands).
101 The second is not just faster in practice (because most SSA graph
102 cycles do not involve all the variables in the graph), it also has
103 some nice properties.
105 One of these nice properties is that when we pop an SCC off the
106 stack, we are guaranteed to have processed all the operands coming from
107 *outside of that SCC*, so we do not need to do anything special to
108 ensure they have value numbers.
110 Another nice property is that the SCC walk is done as part of a DFS
111 of the SSA graph, which makes it easy to perform combining and
112 simplifying operations at the same time.
114 The code below is deliberately written in a way that makes it easy
115 to separate the SCC walk from the other work it does.
117 In order to propagate constants through the code, we track which
118 expressions contain constants, and use those while folding. In
119 theory, we could also track expressions whose value numbers are
120 replaced, in case we end up folding based on expression
121 identities.
123 In order to value number memory, we assign value numbers to vuses.
124 This enables us to note that, for example, stores to the same
125 address of the same value from the same starting memory states are
126 equivalent.
127 TODO:
129 1. We can iterate only the changing portions of the SCC's, but
130 I have not seen an SCC big enough for this to be a win.
131 2. If you differentiate between phi nodes for loops and phi nodes
132 for if-then-else, you can properly consider phi nodes in different
133 blocks for equivalence.
134 3. We could value number vuses in more cases, particularly, whole
135 structure copies.
138 /* There's no BB_EXECUTABLE but we can use BB_VISITED. */
139 #define BB_EXECUTABLE BB_VISITED
141 static vn_lookup_kind default_vn_walk_kind;
143 /* vn_nary_op hashtable helpers. */
145 struct vn_nary_op_hasher : nofree_ptr_hash <vn_nary_op_s>
147 typedef vn_nary_op_s *compare_type;
148 static inline hashval_t hash (const vn_nary_op_s *);
149 static inline bool equal (const vn_nary_op_s *, const vn_nary_op_s *);
152 /* Return the computed hashcode for nary operation P1. */
154 inline hashval_t
155 vn_nary_op_hasher::hash (const vn_nary_op_s *vno1)
157 return vno1->hashcode;
160 /* Compare nary operations P1 and P2 and return true if they are
161 equivalent. */
163 inline bool
164 vn_nary_op_hasher::equal (const vn_nary_op_s *vno1, const vn_nary_op_s *vno2)
166 return vno1 == vno2 || vn_nary_op_eq (vno1, vno2);
169 typedef hash_table<vn_nary_op_hasher> vn_nary_op_table_type;
170 typedef vn_nary_op_table_type::iterator vn_nary_op_iterator_type;
173 /* vn_phi hashtable helpers. */
175 static int
176 vn_phi_eq (const_vn_phi_t const vp1, const_vn_phi_t const vp2);
178 struct vn_phi_hasher : nofree_ptr_hash <vn_phi_s>
180 static inline hashval_t hash (const vn_phi_s *);
181 static inline bool equal (const vn_phi_s *, const vn_phi_s *);
184 /* Return the computed hashcode for phi operation P1. */
186 inline hashval_t
187 vn_phi_hasher::hash (const vn_phi_s *vp1)
189 return vp1->hashcode;
192 /* Compare two phi entries for equality, ignoring VN_TOP arguments. */
194 inline bool
195 vn_phi_hasher::equal (const vn_phi_s *vp1, const vn_phi_s *vp2)
197 return vp1 == vp2 || vn_phi_eq (vp1, vp2);
200 typedef hash_table<vn_phi_hasher> vn_phi_table_type;
201 typedef vn_phi_table_type::iterator vn_phi_iterator_type;
204 /* Compare two reference operands P1 and P2 for equality. Return true if
205 they are equal, and false otherwise. */
207 static int
208 vn_reference_op_eq (const void *p1, const void *p2)
210 const_vn_reference_op_t const vro1 = (const_vn_reference_op_t) p1;
211 const_vn_reference_op_t const vro2 = (const_vn_reference_op_t) p2;
213 return (vro1->opcode == vro2->opcode
214 /* We do not care for differences in type qualification. */
215 && (vro1->type == vro2->type
216 || (vro1->type && vro2->type
217 && types_compatible_p (TYPE_MAIN_VARIANT (vro1->type),
218 TYPE_MAIN_VARIANT (vro2->type))))
219 && expressions_equal_p (vro1->op0, vro2->op0)
220 && expressions_equal_p (vro1->op1, vro2->op1)
221 && expressions_equal_p (vro1->op2, vro2->op2)
222 && (vro1->opcode != CALL_EXPR || vro1->clique == vro2->clique));
225 /* Free a reference operation structure VP. */
227 static inline void
228 free_reference (vn_reference_s *vr)
230 vr->operands.release ();
234 /* vn_reference hashtable helpers. */
236 struct vn_reference_hasher : nofree_ptr_hash <vn_reference_s>
238 static inline hashval_t hash (const vn_reference_s *);
239 static inline bool equal (const vn_reference_s *, const vn_reference_s *);
242 /* Return the hashcode for a given reference operation P1. */
244 inline hashval_t
245 vn_reference_hasher::hash (const vn_reference_s *vr1)
247 return vr1->hashcode;
250 inline bool
251 vn_reference_hasher::equal (const vn_reference_s *v, const vn_reference_s *c)
253 return v == c || vn_reference_eq (v, c);
256 typedef hash_table<vn_reference_hasher> vn_reference_table_type;
257 typedef vn_reference_table_type::iterator vn_reference_iterator_type;
259 /* Pretty-print OPS to OUTFILE. */
261 void
262 print_vn_reference_ops (FILE *outfile, const vec<vn_reference_op_s> ops)
264 vn_reference_op_t vro;
265 unsigned int i;
266 fprintf (outfile, "{");
267 for (i = 0; ops.iterate (i, &vro); i++)
269 bool closebrace = false;
270 if (vro->opcode != SSA_NAME
271 && TREE_CODE_CLASS (vro->opcode) != tcc_declaration)
273 fprintf (outfile, "%s", get_tree_code_name (vro->opcode));
274 if (vro->op0 || vro->opcode == CALL_EXPR)
276 fprintf (outfile, "<");
277 closebrace = true;
280 if (vro->op0 || vro->opcode == CALL_EXPR)
282 if (!vro->op0)
283 fprintf (outfile, internal_fn_name ((internal_fn)vro->clique));
284 else
285 print_generic_expr (outfile, vro->op0);
286 if (vro->op1)
288 fprintf (outfile, ",");
289 print_generic_expr (outfile, vro->op1);
291 if (vro->op2)
293 fprintf (outfile, ",");
294 print_generic_expr (outfile, vro->op2);
297 if (closebrace)
298 fprintf (outfile, ">");
299 if (i != ops.length () - 1)
300 fprintf (outfile, ",");
302 fprintf (outfile, "}");
305 DEBUG_FUNCTION void
306 debug_vn_reference_ops (const vec<vn_reference_op_s> ops)
308 print_vn_reference_ops (stderr, ops);
309 fputc ('\n', stderr);
312 /* The set of VN hashtables. */
314 typedef struct vn_tables_s
316 vn_nary_op_table_type *nary;
317 vn_phi_table_type *phis;
318 vn_reference_table_type *references;
319 } *vn_tables_t;
322 /* vn_constant hashtable helpers. */
324 struct vn_constant_hasher : free_ptr_hash <vn_constant_s>
326 static inline hashval_t hash (const vn_constant_s *);
327 static inline bool equal (const vn_constant_s *, const vn_constant_s *);
330 /* Hash table hash function for vn_constant_t. */
332 inline hashval_t
333 vn_constant_hasher::hash (const vn_constant_s *vc1)
335 return vc1->hashcode;
338 /* Hash table equality function for vn_constant_t. */
340 inline bool
341 vn_constant_hasher::equal (const vn_constant_s *vc1, const vn_constant_s *vc2)
343 if (vc1->hashcode != vc2->hashcode)
344 return false;
346 return vn_constant_eq_with_type (vc1->constant, vc2->constant);
349 static hash_table<vn_constant_hasher> *constant_to_value_id;
352 /* Obstack we allocate the vn-tables elements from. */
353 static obstack vn_tables_obstack;
354 /* Special obstack we never unwind. */
355 static obstack vn_tables_insert_obstack;
357 static vn_reference_t last_inserted_ref;
358 static vn_phi_t last_inserted_phi;
359 static vn_nary_op_t last_inserted_nary;
360 static vn_ssa_aux_t last_pushed_avail;
362 /* Valid hashtables storing information we have proven to be
363 correct. */
364 static vn_tables_t valid_info;
367 /* Valueization hook for simplify_replace_tree. Valueize NAME if it is
368 an SSA name, otherwise just return it. */
369 tree (*vn_valueize) (tree);
370 static tree
371 vn_valueize_for_srt (tree t, void* context ATTRIBUTE_UNUSED)
373 basic_block saved_vn_context_bb = vn_context_bb;
374 /* Look for sth available at the definition block of the argument.
375 This avoids inconsistencies between availability there which
376 decides if the stmt can be removed and availability at the
377 use site. The SSA property ensures that things available
378 at the definition are also available at uses. */
379 if (!SSA_NAME_IS_DEFAULT_DEF (t))
380 vn_context_bb = gimple_bb (SSA_NAME_DEF_STMT (t));
381 tree res = vn_valueize (t);
382 vn_context_bb = saved_vn_context_bb;
383 return res;
387 /* This represents the top of the VN lattice, which is the universal
388 value. */
390 tree VN_TOP;
392 /* Unique counter for our value ids. */
394 static unsigned int next_value_id;
395 static int next_constant_value_id;
398 /* Table of vn_ssa_aux_t's, one per ssa_name. The vn_ssa_aux_t objects
399 are allocated on an obstack for locality reasons, and to free them
400 without looping over the vec. */
402 struct vn_ssa_aux_hasher : typed_noop_remove <vn_ssa_aux_t>
404 typedef vn_ssa_aux_t value_type;
405 typedef tree compare_type;
406 static inline hashval_t hash (const value_type &);
407 static inline bool equal (const value_type &, const compare_type &);
408 static inline void mark_deleted (value_type &) {}
409 static const bool empty_zero_p = true;
410 static inline void mark_empty (value_type &e) { e = NULL; }
411 static inline bool is_deleted (value_type &) { return false; }
412 static inline bool is_empty (value_type &e) { return e == NULL; }
415 hashval_t
416 vn_ssa_aux_hasher::hash (const value_type &entry)
418 return SSA_NAME_VERSION (entry->name);
421 bool
422 vn_ssa_aux_hasher::equal (const value_type &entry, const compare_type &name)
424 return name == entry->name;
427 static hash_table<vn_ssa_aux_hasher> *vn_ssa_aux_hash;
428 typedef hash_table<vn_ssa_aux_hasher>::iterator vn_ssa_aux_iterator_type;
429 static struct obstack vn_ssa_aux_obstack;
431 static vn_nary_op_t vn_nary_op_insert_stmt (gimple *, tree);
432 static vn_nary_op_t vn_nary_op_insert_into (vn_nary_op_t,
433 vn_nary_op_table_type *);
434 static void init_vn_nary_op_from_pieces (vn_nary_op_t, unsigned int,
435 enum tree_code, tree, tree *);
436 static tree vn_lookup_simplify_result (gimple_match_op *);
437 static vn_reference_t vn_reference_lookup_or_insert_for_pieces
438 (tree, alias_set_type, alias_set_type, tree,
439 vec<vn_reference_op_s, va_heap>, tree);
441 /* Return whether there is value numbering information for a given SSA name. */
443 bool
444 has_VN_INFO (tree name)
446 return vn_ssa_aux_hash->find_with_hash (name, SSA_NAME_VERSION (name));
449 vn_ssa_aux_t
450 VN_INFO (tree name)
452 vn_ssa_aux_t *res
453 = vn_ssa_aux_hash->find_slot_with_hash (name, SSA_NAME_VERSION (name),
454 INSERT);
455 if (*res != NULL)
456 return *res;
458 vn_ssa_aux_t newinfo = *res = XOBNEW (&vn_ssa_aux_obstack, struct vn_ssa_aux);
459 memset (newinfo, 0, sizeof (struct vn_ssa_aux));
460 newinfo->name = name;
461 newinfo->valnum = VN_TOP;
462 /* We are using the visited flag to handle uses with defs not within the
463 region being value-numbered. */
464 newinfo->visited = false;
466 /* Given we create the VN_INFOs on-demand now we have to do initialization
467 different than VN_TOP here. */
468 if (SSA_NAME_IS_DEFAULT_DEF (name))
469 switch (TREE_CODE (SSA_NAME_VAR (name)))
471 case VAR_DECL:
472 /* All undefined vars are VARYING. */
473 newinfo->valnum = name;
474 newinfo->visited = true;
475 break;
477 case PARM_DECL:
478 /* Parameters are VARYING but we can record a condition
479 if we know it is a non-NULL pointer. */
480 newinfo->visited = true;
481 newinfo->valnum = name;
482 if (POINTER_TYPE_P (TREE_TYPE (name))
483 && nonnull_arg_p (SSA_NAME_VAR (name)))
485 tree ops[2];
486 ops[0] = name;
487 ops[1] = build_int_cst (TREE_TYPE (name), 0);
488 vn_nary_op_t nary;
489 /* Allocate from non-unwinding stack. */
490 nary = alloc_vn_nary_op_noinit (2, &vn_tables_insert_obstack);
491 init_vn_nary_op_from_pieces (nary, 2, NE_EXPR,
492 boolean_type_node, ops);
493 nary->predicated_values = 0;
494 nary->u.result = boolean_true_node;
495 vn_nary_op_insert_into (nary, valid_info->nary);
496 gcc_assert (nary->unwind_to == NULL);
497 /* Also do not link it into the undo chain. */
498 last_inserted_nary = nary->next;
499 nary->next = (vn_nary_op_t)(void *)-1;
500 nary = alloc_vn_nary_op_noinit (2, &vn_tables_insert_obstack);
501 init_vn_nary_op_from_pieces (nary, 2, EQ_EXPR,
502 boolean_type_node, ops);
503 nary->predicated_values = 0;
504 nary->u.result = boolean_false_node;
505 vn_nary_op_insert_into (nary, valid_info->nary);
506 gcc_assert (nary->unwind_to == NULL);
507 last_inserted_nary = nary->next;
508 nary->next = (vn_nary_op_t)(void *)-1;
509 if (dump_file && (dump_flags & TDF_DETAILS))
511 fprintf (dump_file, "Recording ");
512 print_generic_expr (dump_file, name, TDF_SLIM);
513 fprintf (dump_file, " != 0\n");
516 break;
518 case RESULT_DECL:
519 /* If the result is passed by invisible reference the default
520 def is initialized, otherwise it's uninitialized. Still
521 undefined is varying. */
522 newinfo->visited = true;
523 newinfo->valnum = name;
524 break;
526 default:
527 gcc_unreachable ();
529 return newinfo;
532 /* Return the SSA value of X. */
534 inline tree
535 SSA_VAL (tree x, bool *visited = NULL)
537 vn_ssa_aux_t tem = vn_ssa_aux_hash->find_with_hash (x, SSA_NAME_VERSION (x));
538 if (visited)
539 *visited = tem && tem->visited;
540 return tem && tem->visited ? tem->valnum : x;
543 /* Return the SSA value of the VUSE x, supporting released VDEFs
544 during elimination which will value-number the VDEF to the
545 associated VUSE (but not substitute in the whole lattice). */
547 static inline tree
548 vuse_ssa_val (tree x)
550 if (!x)
551 return NULL_TREE;
555 x = SSA_VAL (x);
556 gcc_assert (x != VN_TOP);
558 while (SSA_NAME_IN_FREE_LIST (x));
560 return x;
563 /* Similar to the above but used as callback for walk_non_aliased_vuses
564 and thus should stop at unvisited VUSE to not walk across region
565 boundaries. */
567 static tree
568 vuse_valueize (tree vuse)
572 bool visited;
573 vuse = SSA_VAL (vuse, &visited);
574 if (!visited)
575 return NULL_TREE;
576 gcc_assert (vuse != VN_TOP);
578 while (SSA_NAME_IN_FREE_LIST (vuse));
579 return vuse;
583 /* Return the vn_kind the expression computed by the stmt should be
584 associated with. */
586 enum vn_kind
587 vn_get_stmt_kind (gimple *stmt)
589 switch (gimple_code (stmt))
591 case GIMPLE_CALL:
592 return VN_REFERENCE;
593 case GIMPLE_PHI:
594 return VN_PHI;
595 case GIMPLE_ASSIGN:
597 enum tree_code code = gimple_assign_rhs_code (stmt);
598 tree rhs1 = gimple_assign_rhs1 (stmt);
599 switch (get_gimple_rhs_class (code))
601 case GIMPLE_UNARY_RHS:
602 case GIMPLE_BINARY_RHS:
603 case GIMPLE_TERNARY_RHS:
604 return VN_NARY;
605 case GIMPLE_SINGLE_RHS:
606 switch (TREE_CODE_CLASS (code))
608 case tcc_reference:
609 /* VOP-less references can go through unary case. */
610 if ((code == REALPART_EXPR
611 || code == IMAGPART_EXPR
612 || code == VIEW_CONVERT_EXPR
613 || code == BIT_FIELD_REF)
614 && (TREE_CODE (TREE_OPERAND (rhs1, 0)) == SSA_NAME
615 || is_gimple_min_invariant (TREE_OPERAND (rhs1, 0))))
616 return VN_NARY;
618 /* Fallthrough. */
619 case tcc_declaration:
620 return VN_REFERENCE;
622 case tcc_constant:
623 return VN_CONSTANT;
625 default:
626 if (code == ADDR_EXPR)
627 return (is_gimple_min_invariant (rhs1)
628 ? VN_CONSTANT : VN_REFERENCE);
629 else if (code == CONSTRUCTOR)
630 return VN_NARY;
631 return VN_NONE;
633 default:
634 return VN_NONE;
637 default:
638 return VN_NONE;
642 /* Lookup a value id for CONSTANT and return it. If it does not
643 exist returns 0. */
645 unsigned int
646 get_constant_value_id (tree constant)
648 vn_constant_s **slot;
649 struct vn_constant_s vc;
651 vc.hashcode = vn_hash_constant_with_type (constant);
652 vc.constant = constant;
653 slot = constant_to_value_id->find_slot (&vc, NO_INSERT);
654 if (slot)
655 return (*slot)->value_id;
656 return 0;
659 /* Lookup a value id for CONSTANT, and if it does not exist, create a
660 new one and return it. If it does exist, return it. */
662 unsigned int
663 get_or_alloc_constant_value_id (tree constant)
665 vn_constant_s **slot;
666 struct vn_constant_s vc;
667 vn_constant_t vcp;
669 /* If the hashtable isn't initialized we're not running from PRE and thus
670 do not need value-ids. */
671 if (!constant_to_value_id)
672 return 0;
674 vc.hashcode = vn_hash_constant_with_type (constant);
675 vc.constant = constant;
676 slot = constant_to_value_id->find_slot (&vc, INSERT);
677 if (*slot)
678 return (*slot)->value_id;
680 vcp = XNEW (struct vn_constant_s);
681 vcp->hashcode = vc.hashcode;
682 vcp->constant = constant;
683 vcp->value_id = get_next_constant_value_id ();
684 *slot = vcp;
685 return vcp->value_id;
688 /* Compute the hash for a reference operand VRO1. */
690 static void
691 vn_reference_op_compute_hash (const vn_reference_op_t vro1, inchash::hash &hstate)
693 hstate.add_int (vro1->opcode);
694 if (vro1->opcode == CALL_EXPR && !vro1->op0)
695 hstate.add_int (vro1->clique);
696 if (vro1->op0)
697 inchash::add_expr (vro1->op0, hstate);
698 if (vro1->op1)
699 inchash::add_expr (vro1->op1, hstate);
700 if (vro1->op2)
701 inchash::add_expr (vro1->op2, hstate);
704 /* Compute a hash for the reference operation VR1 and return it. */
706 static hashval_t
707 vn_reference_compute_hash (const vn_reference_t vr1)
709 inchash::hash hstate;
710 hashval_t result;
711 int i;
712 vn_reference_op_t vro;
713 poly_int64 off = -1;
714 bool deref = false;
716 FOR_EACH_VEC_ELT (vr1->operands, i, vro)
718 if (vro->opcode == MEM_REF)
719 deref = true;
720 else if (vro->opcode != ADDR_EXPR)
721 deref = false;
722 if (maybe_ne (vro->off, -1))
724 if (known_eq (off, -1))
725 off = 0;
726 off += vro->off;
728 else
730 if (maybe_ne (off, -1)
731 && maybe_ne (off, 0))
732 hstate.add_poly_int (off);
733 off = -1;
734 if (deref
735 && vro->opcode == ADDR_EXPR)
737 if (vro->op0)
739 tree op = TREE_OPERAND (vro->op0, 0);
740 hstate.add_int (TREE_CODE (op));
741 inchash::add_expr (op, hstate);
744 else
745 vn_reference_op_compute_hash (vro, hstate);
748 result = hstate.end ();
749 /* ??? We would ICE later if we hash instead of adding that in. */
750 if (vr1->vuse)
751 result += SSA_NAME_VERSION (vr1->vuse);
753 return result;
756 /* Return true if reference operations VR1 and VR2 are equivalent. This
757 means they have the same set of operands and vuses. */
759 bool
760 vn_reference_eq (const_vn_reference_t const vr1, const_vn_reference_t const vr2)
762 unsigned i, j;
764 /* Early out if this is not a hash collision. */
765 if (vr1->hashcode != vr2->hashcode)
766 return false;
768 /* The VOP needs to be the same. */
769 if (vr1->vuse != vr2->vuse)
770 return false;
772 /* If the operands are the same we are done. */
773 if (vr1->operands == vr2->operands)
774 return true;
776 if (!vr1->type || !vr2->type)
778 if (vr1->type != vr2->type)
779 return false;
781 else if (vr1->type == vr2->type)
783 else if (COMPLETE_TYPE_P (vr1->type) != COMPLETE_TYPE_P (vr2->type)
784 || (COMPLETE_TYPE_P (vr1->type)
785 && !expressions_equal_p (TYPE_SIZE (vr1->type),
786 TYPE_SIZE (vr2->type))))
787 return false;
788 else if (vr1->operands[0].opcode == CALL_EXPR
789 && !types_compatible_p (vr1->type, vr2->type))
790 return false;
791 else if (INTEGRAL_TYPE_P (vr1->type)
792 && INTEGRAL_TYPE_P (vr2->type))
794 if (TYPE_PRECISION (vr1->type) != TYPE_PRECISION (vr2->type))
795 return false;
797 else if (INTEGRAL_TYPE_P (vr1->type)
798 && (TYPE_PRECISION (vr1->type)
799 != TREE_INT_CST_LOW (TYPE_SIZE (vr1->type))))
800 return false;
801 else if (INTEGRAL_TYPE_P (vr2->type)
802 && (TYPE_PRECISION (vr2->type)
803 != TREE_INT_CST_LOW (TYPE_SIZE (vr2->type))))
804 return false;
805 else if (VECTOR_BOOLEAN_TYPE_P (vr1->type)
806 && VECTOR_BOOLEAN_TYPE_P (vr2->type))
808 /* Vector boolean types can have padding, verify we are dealing with
809 the same number of elements, aka the precision of the types.
810 For example, In most architecture the precision_size of vbool*_t
811 types are caculated like below:
812 precision_size = type_size * 8
814 Unfortunately, the RISC-V will adjust the precision_size for the
815 vbool*_t in order to align the ISA as below:
816 type_size = [1, 1, 1, 1, 2, 4, 8]
817 precision_size = [1, 2, 4, 8, 16, 32, 64]
819 Then the precision_size of RISC-V vbool*_t will not be the multiple
820 of the type_size. We take care of this case consolidated here. */
821 if (maybe_ne (TYPE_VECTOR_SUBPARTS (vr1->type),
822 TYPE_VECTOR_SUBPARTS (vr2->type)))
823 return false;
826 i = 0;
827 j = 0;
830 poly_int64 off1 = 0, off2 = 0;
831 vn_reference_op_t vro1, vro2;
832 vn_reference_op_s tem1, tem2;
833 bool deref1 = false, deref2 = false;
834 bool reverse1 = false, reverse2 = false;
835 for (; vr1->operands.iterate (i, &vro1); i++)
837 if (vro1->opcode == MEM_REF)
838 deref1 = true;
839 /* Do not look through a storage order barrier. */
840 else if (vro1->opcode == VIEW_CONVERT_EXPR && vro1->reverse)
841 return false;
842 reverse1 |= vro1->reverse;
843 if (known_eq (vro1->off, -1))
844 break;
845 off1 += vro1->off;
847 for (; vr2->operands.iterate (j, &vro2); j++)
849 if (vro2->opcode == MEM_REF)
850 deref2 = true;
851 /* Do not look through a storage order barrier. */
852 else if (vro2->opcode == VIEW_CONVERT_EXPR && vro2->reverse)
853 return false;
854 reverse2 |= vro2->reverse;
855 if (known_eq (vro2->off, -1))
856 break;
857 off2 += vro2->off;
859 if (maybe_ne (off1, off2) || reverse1 != reverse2)
860 return false;
861 if (deref1 && vro1->opcode == ADDR_EXPR)
863 memset (&tem1, 0, sizeof (tem1));
864 tem1.op0 = TREE_OPERAND (vro1->op0, 0);
865 tem1.type = TREE_TYPE (tem1.op0);
866 tem1.opcode = TREE_CODE (tem1.op0);
867 vro1 = &tem1;
868 deref1 = false;
870 if (deref2 && vro2->opcode == ADDR_EXPR)
872 memset (&tem2, 0, sizeof (tem2));
873 tem2.op0 = TREE_OPERAND (vro2->op0, 0);
874 tem2.type = TREE_TYPE (tem2.op0);
875 tem2.opcode = TREE_CODE (tem2.op0);
876 vro2 = &tem2;
877 deref2 = false;
879 if (deref1 != deref2)
880 return false;
881 if (!vn_reference_op_eq (vro1, vro2))
882 return false;
883 ++j;
884 ++i;
886 while (vr1->operands.length () != i
887 || vr2->operands.length () != j);
889 return true;
892 /* Copy the operations present in load/store REF into RESULT, a vector of
893 vn_reference_op_s's. */
895 static void
896 copy_reference_ops_from_ref (tree ref, vec<vn_reference_op_s> *result)
898 /* For non-calls, store the information that makes up the address. */
899 tree orig = ref;
900 while (ref)
902 vn_reference_op_s temp;
904 memset (&temp, 0, sizeof (temp));
905 temp.type = TREE_TYPE (ref);
906 temp.opcode = TREE_CODE (ref);
907 temp.off = -1;
909 switch (temp.opcode)
911 case MODIFY_EXPR:
912 temp.op0 = TREE_OPERAND (ref, 1);
913 break;
914 case WITH_SIZE_EXPR:
915 temp.op0 = TREE_OPERAND (ref, 1);
916 temp.off = 0;
917 break;
918 case MEM_REF:
919 /* The base address gets its own vn_reference_op_s structure. */
920 temp.op0 = TREE_OPERAND (ref, 1);
921 if (!mem_ref_offset (ref).to_shwi (&temp.off))
922 temp.off = -1;
923 temp.clique = MR_DEPENDENCE_CLIQUE (ref);
924 temp.base = MR_DEPENDENCE_BASE (ref);
925 temp.reverse = REF_REVERSE_STORAGE_ORDER (ref);
926 break;
927 case TARGET_MEM_REF:
928 /* The base address gets its own vn_reference_op_s structure. */
929 temp.op0 = TMR_INDEX (ref);
930 temp.op1 = TMR_STEP (ref);
931 temp.op2 = TMR_OFFSET (ref);
932 temp.clique = MR_DEPENDENCE_CLIQUE (ref);
933 temp.base = MR_DEPENDENCE_BASE (ref);
934 result->safe_push (temp);
935 memset (&temp, 0, sizeof (temp));
936 temp.type = NULL_TREE;
937 temp.opcode = ERROR_MARK;
938 temp.op0 = TMR_INDEX2 (ref);
939 temp.off = -1;
940 break;
941 case BIT_FIELD_REF:
942 /* Record bits, position and storage order. */
943 temp.op0 = TREE_OPERAND (ref, 1);
944 temp.op1 = TREE_OPERAND (ref, 2);
945 if (!multiple_p (bit_field_offset (ref), BITS_PER_UNIT, &temp.off))
946 temp.off = -1;
947 temp.reverse = REF_REVERSE_STORAGE_ORDER (ref);
948 break;
949 case COMPONENT_REF:
950 /* The field decl is enough to unambiguously specify the field,
951 so use its type here. */
952 temp.type = TREE_TYPE (TREE_OPERAND (ref, 1));
953 temp.op0 = TREE_OPERAND (ref, 1);
954 temp.op1 = TREE_OPERAND (ref, 2);
955 temp.reverse = (AGGREGATE_TYPE_P (TREE_TYPE (TREE_OPERAND (ref, 0)))
956 && TYPE_REVERSE_STORAGE_ORDER
957 (TREE_TYPE (TREE_OPERAND (ref, 0))));
959 tree this_offset = component_ref_field_offset (ref);
960 if (this_offset
961 && poly_int_tree_p (this_offset))
963 tree bit_offset = DECL_FIELD_BIT_OFFSET (TREE_OPERAND (ref, 1));
964 if (TREE_INT_CST_LOW (bit_offset) % BITS_PER_UNIT == 0)
966 poly_offset_int off
967 = (wi::to_poly_offset (this_offset)
968 + (wi::to_offset (bit_offset) >> LOG2_BITS_PER_UNIT));
969 /* Probibit value-numbering zero offset components
970 of addresses the same before the pass folding
971 __builtin_object_size had a chance to run. */
972 if (TREE_CODE (orig) != ADDR_EXPR
973 || maybe_ne (off, 0)
974 || (cfun->curr_properties & PROP_objsz))
975 off.to_shwi (&temp.off);
979 break;
980 case ARRAY_RANGE_REF:
981 case ARRAY_REF:
983 tree eltype = TREE_TYPE (TREE_TYPE (TREE_OPERAND (ref, 0)));
984 /* Record index as operand. */
985 temp.op0 = TREE_OPERAND (ref, 1);
986 /* Always record lower bounds and element size. */
987 temp.op1 = array_ref_low_bound (ref);
988 /* But record element size in units of the type alignment. */
989 temp.op2 = TREE_OPERAND (ref, 3);
990 temp.align = eltype->type_common.align;
991 if (! temp.op2)
992 temp.op2 = size_binop (EXACT_DIV_EXPR, TYPE_SIZE_UNIT (eltype),
993 size_int (TYPE_ALIGN_UNIT (eltype)));
994 if (poly_int_tree_p (temp.op0)
995 && poly_int_tree_p (temp.op1)
996 && TREE_CODE (temp.op2) == INTEGER_CST)
998 poly_offset_int off = ((wi::to_poly_offset (temp.op0)
999 - wi::to_poly_offset (temp.op1))
1000 * wi::to_offset (temp.op2)
1001 * vn_ref_op_align_unit (&temp));
1002 off.to_shwi (&temp.off);
1004 temp.reverse = (AGGREGATE_TYPE_P (TREE_TYPE (TREE_OPERAND (ref, 0)))
1005 && TYPE_REVERSE_STORAGE_ORDER
1006 (TREE_TYPE (TREE_OPERAND (ref, 0))));
1008 break;
1009 case VAR_DECL:
1010 if (DECL_HARD_REGISTER (ref))
1012 temp.op0 = ref;
1013 break;
1015 /* Fallthru. */
1016 case PARM_DECL:
1017 case CONST_DECL:
1018 case RESULT_DECL:
1019 /* Canonicalize decls to MEM[&decl] which is what we end up with
1020 when valueizing MEM[ptr] with ptr = &decl. */
1021 temp.opcode = MEM_REF;
1022 temp.op0 = build_int_cst (build_pointer_type (TREE_TYPE (ref)), 0);
1023 temp.off = 0;
1024 result->safe_push (temp);
1025 temp.opcode = ADDR_EXPR;
1026 temp.op0 = build1 (ADDR_EXPR, TREE_TYPE (temp.op0), ref);
1027 temp.type = TREE_TYPE (temp.op0);
1028 temp.off = -1;
1029 break;
1030 case STRING_CST:
1031 case INTEGER_CST:
1032 case POLY_INT_CST:
1033 case COMPLEX_CST:
1034 case VECTOR_CST:
1035 case REAL_CST:
1036 case FIXED_CST:
1037 case CONSTRUCTOR:
1038 case SSA_NAME:
1039 temp.op0 = ref;
1040 break;
1041 case ADDR_EXPR:
1042 if (is_gimple_min_invariant (ref))
1044 temp.op0 = ref;
1045 break;
1047 break;
1048 /* These are only interesting for their operands, their
1049 existence, and their type. They will never be the last
1050 ref in the chain of references (IE they require an
1051 operand), so we don't have to put anything
1052 for op* as it will be handled by the iteration */
1053 case REALPART_EXPR:
1054 temp.off = 0;
1055 break;
1056 case VIEW_CONVERT_EXPR:
1057 temp.off = 0;
1058 temp.reverse = storage_order_barrier_p (ref);
1059 break;
1060 case IMAGPART_EXPR:
1061 /* This is only interesting for its constant offset. */
1062 temp.off = TREE_INT_CST_LOW (TYPE_SIZE_UNIT (TREE_TYPE (ref)));
1063 break;
1064 default:
1065 gcc_unreachable ();
1067 result->safe_push (temp);
1069 if (REFERENCE_CLASS_P (ref)
1070 || TREE_CODE (ref) == MODIFY_EXPR
1071 || TREE_CODE (ref) == WITH_SIZE_EXPR
1072 || (TREE_CODE (ref) == ADDR_EXPR
1073 && !is_gimple_min_invariant (ref)))
1074 ref = TREE_OPERAND (ref, 0);
1075 else
1076 ref = NULL_TREE;
1080 /* Build a alias-oracle reference abstraction in *REF from the vn_reference
1081 operands in *OPS, the reference alias set SET and the reference type TYPE.
1082 Return true if something useful was produced. */
1084 bool
1085 ao_ref_init_from_vn_reference (ao_ref *ref,
1086 alias_set_type set, alias_set_type base_set,
1087 tree type, const vec<vn_reference_op_s> &ops)
1089 unsigned i;
1090 tree base = NULL_TREE;
1091 tree *op0_p = &base;
1092 poly_offset_int offset = 0;
1093 poly_offset_int max_size;
1094 poly_offset_int size = -1;
1095 tree size_tree = NULL_TREE;
1097 /* We don't handle calls. */
1098 if (!type)
1099 return false;
1101 machine_mode mode = TYPE_MODE (type);
1102 if (mode == BLKmode)
1103 size_tree = TYPE_SIZE (type);
1104 else
1105 size = GET_MODE_BITSIZE (mode);
1106 if (size_tree != NULL_TREE
1107 && poly_int_tree_p (size_tree))
1108 size = wi::to_poly_offset (size_tree);
1110 /* Lower the final access size from the outermost expression. */
1111 const_vn_reference_op_t cst_op = &ops[0];
1112 /* Cast away constness for the sake of the const-unsafe
1113 FOR_EACH_VEC_ELT(). */
1114 vn_reference_op_t op = const_cast<vn_reference_op_t>(cst_op);
1115 size_tree = NULL_TREE;
1116 if (op->opcode == COMPONENT_REF)
1117 size_tree = DECL_SIZE (op->op0);
1118 else if (op->opcode == BIT_FIELD_REF)
1119 size_tree = op->op0;
1120 if (size_tree != NULL_TREE
1121 && poly_int_tree_p (size_tree)
1122 && (!known_size_p (size)
1123 || known_lt (wi::to_poly_offset (size_tree), size)))
1124 size = wi::to_poly_offset (size_tree);
1126 /* Initially, maxsize is the same as the accessed element size.
1127 In the following it will only grow (or become -1). */
1128 max_size = size;
1130 /* Compute cumulative bit-offset for nested component-refs and array-refs,
1131 and find the ultimate containing object. */
1132 FOR_EACH_VEC_ELT (ops, i, op)
1134 switch (op->opcode)
1136 /* These may be in the reference ops, but we cannot do anything
1137 sensible with them here. */
1138 case ADDR_EXPR:
1139 /* Apart from ADDR_EXPR arguments to MEM_REF. */
1140 if (base != NULL_TREE
1141 && TREE_CODE (base) == MEM_REF
1142 && op->op0
1143 && DECL_P (TREE_OPERAND (op->op0, 0)))
1145 const_vn_reference_op_t pop = &ops[i-1];
1146 base = TREE_OPERAND (op->op0, 0);
1147 if (known_eq (pop->off, -1))
1149 max_size = -1;
1150 offset = 0;
1152 else
1153 offset += pop->off * BITS_PER_UNIT;
1154 op0_p = NULL;
1155 break;
1157 /* Fallthru. */
1158 case CALL_EXPR:
1159 return false;
1161 /* Record the base objects. */
1162 case MEM_REF:
1163 *op0_p = build2 (MEM_REF, op->type,
1164 NULL_TREE, op->op0);
1165 MR_DEPENDENCE_CLIQUE (*op0_p) = op->clique;
1166 MR_DEPENDENCE_BASE (*op0_p) = op->base;
1167 op0_p = &TREE_OPERAND (*op0_p, 0);
1168 break;
1170 case VAR_DECL:
1171 case PARM_DECL:
1172 case RESULT_DECL:
1173 case SSA_NAME:
1174 *op0_p = op->op0;
1175 op0_p = NULL;
1176 break;
1178 /* And now the usual component-reference style ops. */
1179 case BIT_FIELD_REF:
1180 offset += wi::to_poly_offset (op->op1);
1181 break;
1183 case COMPONENT_REF:
1185 tree field = op->op0;
1186 /* We do not have a complete COMPONENT_REF tree here so we
1187 cannot use component_ref_field_offset. Do the interesting
1188 parts manually. */
1189 tree this_offset = DECL_FIELD_OFFSET (field);
1191 if (op->op1 || !poly_int_tree_p (this_offset))
1192 max_size = -1;
1193 else
1195 poly_offset_int woffset = (wi::to_poly_offset (this_offset)
1196 << LOG2_BITS_PER_UNIT);
1197 woffset += wi::to_offset (DECL_FIELD_BIT_OFFSET (field));
1198 offset += woffset;
1200 break;
1203 case ARRAY_RANGE_REF:
1204 case ARRAY_REF:
1205 /* We recorded the lower bound and the element size. */
1206 if (!poly_int_tree_p (op->op0)
1207 || !poly_int_tree_p (op->op1)
1208 || TREE_CODE (op->op2) != INTEGER_CST)
1209 max_size = -1;
1210 else
1212 poly_offset_int woffset
1213 = wi::sext (wi::to_poly_offset (op->op0)
1214 - wi::to_poly_offset (op->op1),
1215 TYPE_PRECISION (sizetype));
1216 woffset *= wi::to_offset (op->op2) * vn_ref_op_align_unit (op);
1217 woffset <<= LOG2_BITS_PER_UNIT;
1218 offset += woffset;
1220 break;
1222 case REALPART_EXPR:
1223 break;
1225 case IMAGPART_EXPR:
1226 offset += size;
1227 break;
1229 case VIEW_CONVERT_EXPR:
1230 break;
1232 case STRING_CST:
1233 case INTEGER_CST:
1234 case COMPLEX_CST:
1235 case VECTOR_CST:
1236 case REAL_CST:
1237 case CONSTRUCTOR:
1238 case CONST_DECL:
1239 return false;
1241 default:
1242 return false;
1246 if (base == NULL_TREE)
1247 return false;
1249 ref->ref = NULL_TREE;
1250 ref->base = base;
1251 ref->ref_alias_set = set;
1252 ref->base_alias_set = base_set;
1253 /* We discount volatiles from value-numbering elsewhere. */
1254 ref->volatile_p = false;
1256 if (!size.to_shwi (&ref->size) || maybe_lt (ref->size, 0))
1258 ref->offset = 0;
1259 ref->size = -1;
1260 ref->max_size = -1;
1261 return true;
1264 if (!offset.to_shwi (&ref->offset))
1266 ref->offset = 0;
1267 ref->max_size = -1;
1268 return true;
1271 if (!max_size.to_shwi (&ref->max_size) || maybe_lt (ref->max_size, 0))
1272 ref->max_size = -1;
1274 return true;
1277 /* Copy the operations present in load/store/call REF into RESULT, a vector of
1278 vn_reference_op_s's. */
1280 static void
1281 copy_reference_ops_from_call (gcall *call,
1282 vec<vn_reference_op_s> *result)
1284 vn_reference_op_s temp;
1285 unsigned i;
1286 tree lhs = gimple_call_lhs (call);
1287 int lr;
1289 /* If 2 calls have a different non-ssa lhs, vdef value numbers should be
1290 different. By adding the lhs here in the vector, we ensure that the
1291 hashcode is different, guaranteeing a different value number. */
1292 if (lhs && TREE_CODE (lhs) != SSA_NAME)
1294 memset (&temp, 0, sizeof (temp));
1295 temp.opcode = MODIFY_EXPR;
1296 temp.type = TREE_TYPE (lhs);
1297 temp.op0 = lhs;
1298 temp.off = -1;
1299 result->safe_push (temp);
1302 /* Copy the type, opcode, function, static chain and EH region, if any. */
1303 memset (&temp, 0, sizeof (temp));
1304 temp.type = gimple_call_fntype (call);
1305 temp.opcode = CALL_EXPR;
1306 temp.op0 = gimple_call_fn (call);
1307 if (gimple_call_internal_p (call))
1308 temp.clique = gimple_call_internal_fn (call);
1309 temp.op1 = gimple_call_chain (call);
1310 if (stmt_could_throw_p (cfun, call) && (lr = lookup_stmt_eh_lp (call)) > 0)
1311 temp.op2 = size_int (lr);
1312 temp.off = -1;
1313 result->safe_push (temp);
1315 /* Copy the call arguments. As they can be references as well,
1316 just chain them together. */
1317 for (i = 0; i < gimple_call_num_args (call); ++i)
1319 tree callarg = gimple_call_arg (call, i);
1320 copy_reference_ops_from_ref (callarg, result);
1324 /* Fold *& at position *I_P in a vn_reference_op_s vector *OPS. Updates
1325 *I_P to point to the last element of the replacement. */
1326 static bool
1327 vn_reference_fold_indirect (vec<vn_reference_op_s> *ops,
1328 unsigned int *i_p)
1330 unsigned int i = *i_p;
1331 vn_reference_op_t op = &(*ops)[i];
1332 vn_reference_op_t mem_op = &(*ops)[i - 1];
1333 tree addr_base;
1334 poly_int64 addr_offset = 0;
1336 /* The only thing we have to do is from &OBJ.foo.bar add the offset
1337 from .foo.bar to the preceding MEM_REF offset and replace the
1338 address with &OBJ. */
1339 addr_base = get_addr_base_and_unit_offset_1 (TREE_OPERAND (op->op0, 0),
1340 &addr_offset, vn_valueize);
1341 gcc_checking_assert (addr_base && TREE_CODE (addr_base) != MEM_REF);
1342 if (addr_base != TREE_OPERAND (op->op0, 0))
1344 poly_offset_int off
1345 = (poly_offset_int::from (wi::to_poly_wide (mem_op->op0),
1346 SIGNED)
1347 + addr_offset);
1348 mem_op->op0 = wide_int_to_tree (TREE_TYPE (mem_op->op0), off);
1349 op->op0 = build_fold_addr_expr (addr_base);
1350 if (tree_fits_shwi_p (mem_op->op0))
1351 mem_op->off = tree_to_shwi (mem_op->op0);
1352 else
1353 mem_op->off = -1;
1354 return true;
1356 return false;
1359 /* Fold *& at position *I_P in a vn_reference_op_s vector *OPS. Updates
1360 *I_P to point to the last element of the replacement. */
1361 static bool
1362 vn_reference_maybe_forwprop_address (vec<vn_reference_op_s> *ops,
1363 unsigned int *i_p)
1365 bool changed = false;
1366 vn_reference_op_t op;
1370 unsigned int i = *i_p;
1371 op = &(*ops)[i];
1372 vn_reference_op_t mem_op = &(*ops)[i - 1];
1373 gimple *def_stmt;
1374 enum tree_code code;
1375 poly_offset_int off;
1377 def_stmt = SSA_NAME_DEF_STMT (op->op0);
1378 if (!is_gimple_assign (def_stmt))
1379 return changed;
1381 code = gimple_assign_rhs_code (def_stmt);
1382 if (code != ADDR_EXPR
1383 && code != POINTER_PLUS_EXPR)
1384 return changed;
1386 off = poly_offset_int::from (wi::to_poly_wide (mem_op->op0), SIGNED);
1388 /* The only thing we have to do is from &OBJ.foo.bar add the offset
1389 from .foo.bar to the preceding MEM_REF offset and replace the
1390 address with &OBJ. */
1391 if (code == ADDR_EXPR)
1393 tree addr, addr_base;
1394 poly_int64 addr_offset;
1396 addr = gimple_assign_rhs1 (def_stmt);
1397 addr_base = get_addr_base_and_unit_offset_1 (TREE_OPERAND (addr, 0),
1398 &addr_offset,
1399 vn_valueize);
1400 /* If that didn't work because the address isn't invariant propagate
1401 the reference tree from the address operation in case the current
1402 dereference isn't offsetted. */
1403 if (!addr_base
1404 && *i_p == ops->length () - 1
1405 && known_eq (off, 0)
1406 /* This makes us disable this transform for PRE where the
1407 reference ops might be also used for code insertion which
1408 is invalid. */
1409 && default_vn_walk_kind == VN_WALKREWRITE)
1411 auto_vec<vn_reference_op_s, 32> tem;
1412 copy_reference_ops_from_ref (TREE_OPERAND (addr, 0), &tem);
1413 /* Make sure to preserve TBAA info. The only objects not
1414 wrapped in MEM_REFs that can have their address taken are
1415 STRING_CSTs. */
1416 if (tem.length () >= 2
1417 && tem[tem.length () - 2].opcode == MEM_REF)
1419 vn_reference_op_t new_mem_op = &tem[tem.length () - 2];
1420 new_mem_op->op0
1421 = wide_int_to_tree (TREE_TYPE (mem_op->op0),
1422 wi::to_poly_wide (new_mem_op->op0));
1424 else
1425 gcc_assert (tem.last ().opcode == STRING_CST);
1426 ops->pop ();
1427 ops->pop ();
1428 ops->safe_splice (tem);
1429 --*i_p;
1430 return true;
1432 if (!addr_base
1433 || TREE_CODE (addr_base) != MEM_REF
1434 || (TREE_CODE (TREE_OPERAND (addr_base, 0)) == SSA_NAME
1435 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (TREE_OPERAND (addr_base,
1436 0))))
1437 return changed;
1439 off += addr_offset;
1440 off += mem_ref_offset (addr_base);
1441 op->op0 = TREE_OPERAND (addr_base, 0);
1443 else
1445 tree ptr, ptroff;
1446 ptr = gimple_assign_rhs1 (def_stmt);
1447 ptroff = gimple_assign_rhs2 (def_stmt);
1448 if (TREE_CODE (ptr) != SSA_NAME
1449 || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ptr)
1450 /* Make sure to not endlessly recurse.
1451 See gcc.dg/tree-ssa/20040408-1.c for an example. Can easily
1452 happen when we value-number a PHI to its backedge value. */
1453 || SSA_VAL (ptr) == op->op0
1454 || !poly_int_tree_p (ptroff))
1455 return changed;
1457 off += wi::to_poly_offset (ptroff);
1458 op->op0 = ptr;
1461 mem_op->op0 = wide_int_to_tree (TREE_TYPE (mem_op->op0), off);
1462 if (tree_fits_shwi_p (mem_op->op0))
1463 mem_op->off = tree_to_shwi (mem_op->op0);
1464 else
1465 mem_op->off = -1;
1466 /* ??? Can end up with endless recursion here!?
1467 gcc.c-torture/execute/strcmp-1.c */
1468 if (TREE_CODE (op->op0) == SSA_NAME)
1469 op->op0 = SSA_VAL (op->op0);
1470 if (TREE_CODE (op->op0) != SSA_NAME)
1471 op->opcode = TREE_CODE (op->op0);
1473 changed = true;
1475 /* Tail-recurse. */
1476 while (TREE_CODE (op->op0) == SSA_NAME);
1478 /* Fold a remaining *&. */
1479 if (TREE_CODE (op->op0) == ADDR_EXPR)
1480 vn_reference_fold_indirect (ops, i_p);
1482 return changed;
1485 /* Optimize the reference REF to a constant if possible or return
1486 NULL_TREE if not. */
1488 tree
1489 fully_constant_vn_reference_p (vn_reference_t ref)
1491 vec<vn_reference_op_s> operands = ref->operands;
1492 vn_reference_op_t op;
1494 /* Try to simplify the translated expression if it is
1495 a call to a builtin function with at most two arguments. */
1496 op = &operands[0];
1497 if (op->opcode == CALL_EXPR
1498 && (!op->op0
1499 || (TREE_CODE (op->op0) == ADDR_EXPR
1500 && TREE_CODE (TREE_OPERAND (op->op0, 0)) == FUNCTION_DECL
1501 && fndecl_built_in_p (TREE_OPERAND (op->op0, 0),
1502 BUILT_IN_NORMAL)))
1503 && operands.length () >= 2
1504 && operands.length () <= 3)
1506 vn_reference_op_t arg0, arg1 = NULL;
1507 bool anyconst = false;
1508 arg0 = &operands[1];
1509 if (operands.length () > 2)
1510 arg1 = &operands[2];
1511 if (TREE_CODE_CLASS (arg0->opcode) == tcc_constant
1512 || (arg0->opcode == ADDR_EXPR
1513 && is_gimple_min_invariant (arg0->op0)))
1514 anyconst = true;
1515 if (arg1
1516 && (TREE_CODE_CLASS (arg1->opcode) == tcc_constant
1517 || (arg1->opcode == ADDR_EXPR
1518 && is_gimple_min_invariant (arg1->op0))))
1519 anyconst = true;
1520 if (anyconst)
1522 combined_fn fn;
1523 if (op->op0)
1524 fn = as_combined_fn (DECL_FUNCTION_CODE
1525 (TREE_OPERAND (op->op0, 0)));
1526 else
1527 fn = as_combined_fn ((internal_fn) op->clique);
1528 tree folded;
1529 if (arg1)
1530 folded = fold_const_call (fn, ref->type, arg0->op0, arg1->op0);
1531 else
1532 folded = fold_const_call (fn, ref->type, arg0->op0);
1533 if (folded
1534 && is_gimple_min_invariant (folded))
1535 return folded;
1539 /* Simplify reads from constants or constant initializers. */
1540 else if (BITS_PER_UNIT == 8
1541 && ref->type
1542 && COMPLETE_TYPE_P (ref->type)
1543 && is_gimple_reg_type (ref->type))
1545 poly_int64 off = 0;
1546 HOST_WIDE_INT size;
1547 if (INTEGRAL_TYPE_P (ref->type))
1548 size = TYPE_PRECISION (ref->type);
1549 else if (tree_fits_shwi_p (TYPE_SIZE (ref->type)))
1550 size = tree_to_shwi (TYPE_SIZE (ref->type));
1551 else
1552 return NULL_TREE;
1553 if (size % BITS_PER_UNIT != 0
1554 || size > MAX_BITSIZE_MODE_ANY_MODE)
1555 return NULL_TREE;
1556 size /= BITS_PER_UNIT;
1557 unsigned i;
1558 for (i = 0; i < operands.length (); ++i)
1560 if (TREE_CODE_CLASS (operands[i].opcode) == tcc_constant)
1562 ++i;
1563 break;
1565 if (known_eq (operands[i].off, -1))
1566 return NULL_TREE;
1567 off += operands[i].off;
1568 if (operands[i].opcode == MEM_REF)
1570 ++i;
1571 break;
1574 vn_reference_op_t base = &operands[--i];
1575 tree ctor = error_mark_node;
1576 tree decl = NULL_TREE;
1577 if (TREE_CODE_CLASS (base->opcode) == tcc_constant)
1578 ctor = base->op0;
1579 else if (base->opcode == MEM_REF
1580 && base[1].opcode == ADDR_EXPR
1581 && (VAR_P (TREE_OPERAND (base[1].op0, 0))
1582 || TREE_CODE (TREE_OPERAND (base[1].op0, 0)) == CONST_DECL
1583 || TREE_CODE (TREE_OPERAND (base[1].op0, 0)) == STRING_CST))
1585 decl = TREE_OPERAND (base[1].op0, 0);
1586 if (TREE_CODE (decl) == STRING_CST)
1587 ctor = decl;
1588 else
1589 ctor = ctor_for_folding (decl);
1591 if (ctor == NULL_TREE)
1592 return build_zero_cst (ref->type);
1593 else if (ctor != error_mark_node)
1595 HOST_WIDE_INT const_off;
1596 if (decl)
1598 tree res = fold_ctor_reference (ref->type, ctor,
1599 off * BITS_PER_UNIT,
1600 size * BITS_PER_UNIT, decl);
1601 if (res)
1603 STRIP_USELESS_TYPE_CONVERSION (res);
1604 if (is_gimple_min_invariant (res))
1605 return res;
1608 else if (off.is_constant (&const_off))
1610 unsigned char buf[MAX_BITSIZE_MODE_ANY_MODE / BITS_PER_UNIT];
1611 int len = native_encode_expr (ctor, buf, size, const_off);
1612 if (len > 0)
1613 return native_interpret_expr (ref->type, buf, len);
1618 return NULL_TREE;
1621 /* Return true if OPS contain a storage order barrier. */
1623 static bool
1624 contains_storage_order_barrier_p (vec<vn_reference_op_s> ops)
1626 vn_reference_op_t op;
1627 unsigned i;
1629 FOR_EACH_VEC_ELT (ops, i, op)
1630 if (op->opcode == VIEW_CONVERT_EXPR && op->reverse)
1631 return true;
1633 return false;
1636 /* Return true if OPS represent an access with reverse storage order. */
1638 static bool
1639 reverse_storage_order_for_component_p (vec<vn_reference_op_s> ops)
1641 unsigned i = 0;
1642 if (ops[i].opcode == REALPART_EXPR || ops[i].opcode == IMAGPART_EXPR)
1643 ++i;
1644 switch (ops[i].opcode)
1646 case ARRAY_REF:
1647 case COMPONENT_REF:
1648 case BIT_FIELD_REF:
1649 case MEM_REF:
1650 return ops[i].reverse;
1651 default:
1652 return false;
1656 /* Transform any SSA_NAME's in a vector of vn_reference_op_s
1657 structures into their value numbers. This is done in-place, and
1658 the vector passed in is returned. *VALUEIZED_ANYTHING will specify
1659 whether any operands were valueized. */
1661 static void
1662 valueize_refs_1 (vec<vn_reference_op_s> *orig, bool *valueized_anything,
1663 bool with_avail = false)
1665 *valueized_anything = false;
1667 for (unsigned i = 0; i < orig->length (); ++i)
1669 re_valueize:
1670 vn_reference_op_t vro = &(*orig)[i];
1671 if (vro->opcode == SSA_NAME
1672 || (vro->op0 && TREE_CODE (vro->op0) == SSA_NAME))
1674 tree tem = with_avail ? vn_valueize (vro->op0) : SSA_VAL (vro->op0);
1675 if (tem != vro->op0)
1677 *valueized_anything = true;
1678 vro->op0 = tem;
1680 /* If it transforms from an SSA_NAME to a constant, update
1681 the opcode. */
1682 if (TREE_CODE (vro->op0) != SSA_NAME && vro->opcode == SSA_NAME)
1683 vro->opcode = TREE_CODE (vro->op0);
1685 if (vro->op1 && TREE_CODE (vro->op1) == SSA_NAME)
1687 tree tem = with_avail ? vn_valueize (vro->op1) : SSA_VAL (vro->op1);
1688 if (tem != vro->op1)
1690 *valueized_anything = true;
1691 vro->op1 = tem;
1694 if (vro->op2 && TREE_CODE (vro->op2) == SSA_NAME)
1696 tree tem = with_avail ? vn_valueize (vro->op2) : SSA_VAL (vro->op2);
1697 if (tem != vro->op2)
1699 *valueized_anything = true;
1700 vro->op2 = tem;
1703 /* If it transforms from an SSA_NAME to an address, fold with
1704 a preceding indirect reference. */
1705 if (i > 0
1706 && vro->op0
1707 && TREE_CODE (vro->op0) == ADDR_EXPR
1708 && (*orig)[i - 1].opcode == MEM_REF)
1710 if (vn_reference_fold_indirect (orig, &i))
1711 *valueized_anything = true;
1713 else if (i > 0
1714 && vro->opcode == SSA_NAME
1715 && (*orig)[i - 1].opcode == MEM_REF)
1717 if (vn_reference_maybe_forwprop_address (orig, &i))
1719 *valueized_anything = true;
1720 /* Re-valueize the current operand. */
1721 goto re_valueize;
1724 /* If it transforms a non-constant ARRAY_REF into a constant
1725 one, adjust the constant offset. */
1726 else if (vro->opcode == ARRAY_REF
1727 && known_eq (vro->off, -1)
1728 && poly_int_tree_p (vro->op0)
1729 && poly_int_tree_p (vro->op1)
1730 && TREE_CODE (vro->op2) == INTEGER_CST)
1732 poly_offset_int off = ((wi::to_poly_offset (vro->op0)
1733 - wi::to_poly_offset (vro->op1))
1734 * wi::to_offset (vro->op2)
1735 * vn_ref_op_align_unit (vro));
1736 off.to_shwi (&vro->off);
1741 static void
1742 valueize_refs (vec<vn_reference_op_s> *orig)
1744 bool tem;
1745 valueize_refs_1 (orig, &tem);
1748 static vec<vn_reference_op_s> shared_lookup_references;
1750 /* Create a vector of vn_reference_op_s structures from REF, a
1751 REFERENCE_CLASS_P tree. The vector is shared among all callers of
1752 this function. *VALUEIZED_ANYTHING will specify whether any
1753 operands were valueized. */
1755 static vec<vn_reference_op_s>
1756 valueize_shared_reference_ops_from_ref (tree ref, bool *valueized_anything)
1758 if (!ref)
1759 return vNULL;
1760 shared_lookup_references.truncate (0);
1761 copy_reference_ops_from_ref (ref, &shared_lookup_references);
1762 valueize_refs_1 (&shared_lookup_references, valueized_anything);
1763 return shared_lookup_references;
1766 /* Create a vector of vn_reference_op_s structures from CALL, a
1767 call statement. The vector is shared among all callers of
1768 this function. */
1770 static vec<vn_reference_op_s>
1771 valueize_shared_reference_ops_from_call (gcall *call)
1773 if (!call)
1774 return vNULL;
1775 shared_lookup_references.truncate (0);
1776 copy_reference_ops_from_call (call, &shared_lookup_references);
1777 valueize_refs (&shared_lookup_references);
1778 return shared_lookup_references;
1781 /* Lookup a SCCVN reference operation VR in the current hash table.
1782 Returns the resulting value number if it exists in the hash table,
1783 NULL_TREE otherwise. VNRESULT will be filled in with the actual
1784 vn_reference_t stored in the hashtable if something is found. */
1786 static tree
1787 vn_reference_lookup_1 (vn_reference_t vr, vn_reference_t *vnresult)
1789 vn_reference_s **slot;
1790 hashval_t hash;
1792 hash = vr->hashcode;
1793 slot = valid_info->references->find_slot_with_hash (vr, hash, NO_INSERT);
1794 if (slot)
1796 if (vnresult)
1797 *vnresult = (vn_reference_t)*slot;
1798 return ((vn_reference_t)*slot)->result;
1801 return NULL_TREE;
1805 /* Partial definition tracking support. */
1807 struct pd_range
1809 HOST_WIDE_INT offset;
1810 HOST_WIDE_INT size;
1813 struct pd_data
1815 tree rhs;
1816 HOST_WIDE_INT rhs_off;
1817 HOST_WIDE_INT offset;
1818 HOST_WIDE_INT size;
1821 /* Context for alias walking. */
1823 struct vn_walk_cb_data
1825 vn_walk_cb_data (vn_reference_t vr_, tree orig_ref_, tree *last_vuse_ptr_,
1826 vn_lookup_kind vn_walk_kind_, bool tbaa_p_, tree mask_,
1827 bool redundant_store_removal_p_)
1828 : vr (vr_), last_vuse_ptr (last_vuse_ptr_), last_vuse (NULL_TREE),
1829 mask (mask_), masked_result (NULL_TREE), same_val (NULL_TREE),
1830 vn_walk_kind (vn_walk_kind_),
1831 tbaa_p (tbaa_p_), redundant_store_removal_p (redundant_store_removal_p_),
1832 saved_operands (vNULL), first_set (-2), first_base_set (-2),
1833 known_ranges (NULL)
1835 if (!last_vuse_ptr)
1836 last_vuse_ptr = &last_vuse;
1837 ao_ref_init (&orig_ref, orig_ref_);
1838 if (mask)
1840 wide_int w = wi::to_wide (mask);
1841 unsigned int pos = 0, prec = w.get_precision ();
1842 pd_data pd;
1843 pd.rhs = build_constructor (NULL_TREE, NULL);
1844 pd.rhs_off = 0;
1845 /* When bitwise and with a constant is done on a memory load,
1846 we don't really need all the bits to be defined or defined
1847 to constants, we don't really care what is in the position
1848 corresponding to 0 bits in the mask.
1849 So, push the ranges of those 0 bits in the mask as artificial
1850 zero stores and let the partial def handling code do the
1851 rest. */
1852 while (pos < prec)
1854 int tz = wi::ctz (w);
1855 if (pos + tz > prec)
1856 tz = prec - pos;
1857 if (tz)
1859 if (BYTES_BIG_ENDIAN)
1860 pd.offset = prec - pos - tz;
1861 else
1862 pd.offset = pos;
1863 pd.size = tz;
1864 void *r = push_partial_def (pd, 0, 0, 0, prec);
1865 gcc_assert (r == NULL_TREE);
1867 pos += tz;
1868 if (pos == prec)
1869 break;
1870 w = wi::lrshift (w, tz);
1871 tz = wi::ctz (wi::bit_not (w));
1872 if (pos + tz > prec)
1873 tz = prec - pos;
1874 pos += tz;
1875 w = wi::lrshift (w, tz);
1879 ~vn_walk_cb_data ();
1880 void *finish (alias_set_type, alias_set_type, tree);
1881 void *push_partial_def (pd_data pd,
1882 alias_set_type, alias_set_type, HOST_WIDE_INT,
1883 HOST_WIDE_INT);
1885 vn_reference_t vr;
1886 ao_ref orig_ref;
1887 tree *last_vuse_ptr;
1888 tree last_vuse;
1889 tree mask;
1890 tree masked_result;
1891 tree same_val;
1892 vn_lookup_kind vn_walk_kind;
1893 bool tbaa_p;
1894 bool redundant_store_removal_p;
1895 vec<vn_reference_op_s> saved_operands;
1897 /* The VDEFs of partial defs we come along. */
1898 auto_vec<pd_data, 2> partial_defs;
1899 /* The first defs range to avoid splay tree setup in most cases. */
1900 pd_range first_range;
1901 alias_set_type first_set;
1902 alias_set_type first_base_set;
1903 splay_tree known_ranges;
1904 obstack ranges_obstack;
1907 vn_walk_cb_data::~vn_walk_cb_data ()
1909 if (known_ranges)
1911 splay_tree_delete (known_ranges);
1912 obstack_free (&ranges_obstack, NULL);
1914 saved_operands.release ();
1917 void *
1918 vn_walk_cb_data::finish (alias_set_type set, alias_set_type base_set, tree val)
1920 if (first_set != -2)
1922 set = first_set;
1923 base_set = first_base_set;
1925 if (mask)
1927 masked_result = val;
1928 return (void *) -1;
1930 if (same_val && !operand_equal_p (val, same_val))
1931 return (void *) -1;
1932 vec<vn_reference_op_s> &operands
1933 = saved_operands.exists () ? saved_operands : vr->operands;
1934 return vn_reference_lookup_or_insert_for_pieces (last_vuse, set, base_set,
1935 vr->type, operands, val);
1938 /* pd_range splay-tree helpers. */
1940 static int
1941 pd_range_compare (splay_tree_key offset1p, splay_tree_key offset2p)
1943 HOST_WIDE_INT offset1 = *(HOST_WIDE_INT *)offset1p;
1944 HOST_WIDE_INT offset2 = *(HOST_WIDE_INT *)offset2p;
1945 if (offset1 < offset2)
1946 return -1;
1947 else if (offset1 > offset2)
1948 return 1;
1949 return 0;
1952 static void *
1953 pd_tree_alloc (int size, void *data_)
1955 vn_walk_cb_data *data = (vn_walk_cb_data *)data_;
1956 return obstack_alloc (&data->ranges_obstack, size);
1959 static void
1960 pd_tree_dealloc (void *, void *)
1964 /* Push PD to the vector of partial definitions returning a
1965 value when we are ready to combine things with VUSE, SET and MAXSIZEI,
1966 NULL when we want to continue looking for partial defs or -1
1967 on failure. */
1969 void *
1970 vn_walk_cb_data::push_partial_def (pd_data pd,
1971 alias_set_type set, alias_set_type base_set,
1972 HOST_WIDE_INT offseti,
1973 HOST_WIDE_INT maxsizei)
1975 const HOST_WIDE_INT bufsize = 64;
1976 /* We're using a fixed buffer for encoding so fail early if the object
1977 we want to interpret is bigger. */
1978 if (maxsizei > bufsize * BITS_PER_UNIT
1979 || CHAR_BIT != 8
1980 || BITS_PER_UNIT != 8
1981 /* Not prepared to handle PDP endian. */
1982 || BYTES_BIG_ENDIAN != WORDS_BIG_ENDIAN)
1983 return (void *)-1;
1985 /* Turn too large constant stores into non-constant stores. */
1986 if (CONSTANT_CLASS_P (pd.rhs) && pd.size > bufsize * BITS_PER_UNIT)
1987 pd.rhs = error_mark_node;
1989 /* And for non-constant or CONSTRUCTOR stores shrink them to only keep at
1990 most a partial byte before and/or after the region. */
1991 if (!CONSTANT_CLASS_P (pd.rhs))
1993 if (pd.offset < offseti)
1995 HOST_WIDE_INT o = ROUND_DOWN (offseti - pd.offset, BITS_PER_UNIT);
1996 gcc_assert (pd.size > o);
1997 pd.size -= o;
1998 pd.offset += o;
2000 if (pd.size > maxsizei)
2001 pd.size = maxsizei + ((pd.size - maxsizei) % BITS_PER_UNIT);
2004 pd.offset -= offseti;
2006 bool pd_constant_p = (TREE_CODE (pd.rhs) == CONSTRUCTOR
2007 || CONSTANT_CLASS_P (pd.rhs));
2008 pd_range *r;
2009 if (partial_defs.is_empty ())
2011 /* If we get a clobber upfront, fail. */
2012 if (TREE_CLOBBER_P (pd.rhs))
2013 return (void *)-1;
2014 if (!pd_constant_p)
2015 return (void *)-1;
2016 partial_defs.safe_push (pd);
2017 first_range.offset = pd.offset;
2018 first_range.size = pd.size;
2019 first_set = set;
2020 first_base_set = base_set;
2021 last_vuse_ptr = NULL;
2022 r = &first_range;
2023 /* Go check if the first partial definition was a full one in case
2024 the caller didn't optimize for this. */
2026 else
2028 if (!known_ranges)
2030 /* ??? Optimize the case where the 2nd partial def completes
2031 things. */
2032 gcc_obstack_init (&ranges_obstack);
2033 known_ranges = splay_tree_new_with_allocator (pd_range_compare, 0, 0,
2034 pd_tree_alloc,
2035 pd_tree_dealloc, this);
2036 splay_tree_insert (known_ranges,
2037 (splay_tree_key)&first_range.offset,
2038 (splay_tree_value)&first_range);
2041 pd_range newr = { pd.offset, pd.size };
2042 splay_tree_node n;
2043 /* Lookup the predecessor of offset + 1 and see if we need to merge. */
2044 HOST_WIDE_INT loffset = newr.offset + 1;
2045 if ((n = splay_tree_predecessor (known_ranges, (splay_tree_key)&loffset))
2046 && ((r = (pd_range *)n->value), true)
2047 && ranges_known_overlap_p (r->offset, r->size + 1,
2048 newr.offset, newr.size))
2050 /* Ignore partial defs already covered. Here we also drop shadowed
2051 clobbers arriving here at the floor. */
2052 if (known_subrange_p (newr.offset, newr.size, r->offset, r->size))
2053 return NULL;
2054 r->size
2055 = MAX (r->offset + r->size, newr.offset + newr.size) - r->offset;
2057 else
2059 /* newr.offset wasn't covered yet, insert the range. */
2060 r = XOBNEW (&ranges_obstack, pd_range);
2061 *r = newr;
2062 splay_tree_insert (known_ranges, (splay_tree_key)&r->offset,
2063 (splay_tree_value)r);
2065 /* Merge r which now contains newr and is a member of the splay tree with
2066 adjacent overlapping ranges. */
2067 pd_range *rafter;
2068 while ((n = splay_tree_successor (known_ranges,
2069 (splay_tree_key)&r->offset))
2070 && ((rafter = (pd_range *)n->value), true)
2071 && ranges_known_overlap_p (r->offset, r->size + 1,
2072 rafter->offset, rafter->size))
2074 r->size = MAX (r->offset + r->size,
2075 rafter->offset + rafter->size) - r->offset;
2076 splay_tree_remove (known_ranges, (splay_tree_key)&rafter->offset);
2078 /* If we get a clobber, fail. */
2079 if (TREE_CLOBBER_P (pd.rhs))
2080 return (void *)-1;
2081 /* Non-constants are OK as long as they are shadowed by a constant. */
2082 if (!pd_constant_p)
2083 return (void *)-1;
2084 partial_defs.safe_push (pd);
2087 /* Now we have merged newr into the range tree. When we have covered
2088 [offseti, sizei] then the tree will contain exactly one node which has
2089 the desired properties and it will be 'r'. */
2090 if (!known_subrange_p (0, maxsizei, r->offset, r->size))
2091 /* Continue looking for partial defs. */
2092 return NULL;
2094 /* Now simply native encode all partial defs in reverse order. */
2095 unsigned ndefs = partial_defs.length ();
2096 /* We support up to 512-bit values (for V8DFmode). */
2097 unsigned char buffer[bufsize + 1];
2098 unsigned char this_buffer[bufsize + 1];
2099 int len;
2101 memset (buffer, 0, bufsize + 1);
2102 unsigned needed_len = ROUND_UP (maxsizei, BITS_PER_UNIT) / BITS_PER_UNIT;
2103 while (!partial_defs.is_empty ())
2105 pd_data pd = partial_defs.pop ();
2106 unsigned int amnt;
2107 if (TREE_CODE (pd.rhs) == CONSTRUCTOR)
2109 /* Empty CONSTRUCTOR. */
2110 if (pd.size >= needed_len * BITS_PER_UNIT)
2111 len = needed_len;
2112 else
2113 len = ROUND_UP (pd.size, BITS_PER_UNIT) / BITS_PER_UNIT;
2114 memset (this_buffer, 0, len);
2116 else if (pd.rhs_off >= 0)
2118 len = native_encode_expr (pd.rhs, this_buffer, bufsize,
2119 (MAX (0, -pd.offset)
2120 + pd.rhs_off) / BITS_PER_UNIT);
2121 if (len <= 0
2122 || len < (ROUND_UP (pd.size, BITS_PER_UNIT) / BITS_PER_UNIT
2123 - MAX (0, -pd.offset) / BITS_PER_UNIT))
2125 if (dump_file && (dump_flags & TDF_DETAILS))
2126 fprintf (dump_file, "Failed to encode %u "
2127 "partial definitions\n", ndefs);
2128 return (void *)-1;
2131 else /* negative pd.rhs_off indicates we want to chop off first bits */
2133 if (-pd.rhs_off >= bufsize)
2134 return (void *)-1;
2135 len = native_encode_expr (pd.rhs,
2136 this_buffer + -pd.rhs_off / BITS_PER_UNIT,
2137 bufsize - -pd.rhs_off / BITS_PER_UNIT,
2138 MAX (0, -pd.offset) / BITS_PER_UNIT);
2139 if (len <= 0
2140 || len < (ROUND_UP (pd.size, BITS_PER_UNIT) / BITS_PER_UNIT
2141 - MAX (0, -pd.offset) / BITS_PER_UNIT))
2143 if (dump_file && (dump_flags & TDF_DETAILS))
2144 fprintf (dump_file, "Failed to encode %u "
2145 "partial definitions\n", ndefs);
2146 return (void *)-1;
2150 unsigned char *p = buffer;
2151 HOST_WIDE_INT size = pd.size;
2152 if (pd.offset < 0)
2153 size -= ROUND_DOWN (-pd.offset, BITS_PER_UNIT);
2154 this_buffer[len] = 0;
2155 if (BYTES_BIG_ENDIAN)
2157 /* LSB of this_buffer[len - 1] byte should be at
2158 pd.offset + pd.size - 1 bits in buffer. */
2159 amnt = ((unsigned HOST_WIDE_INT) pd.offset
2160 + pd.size) % BITS_PER_UNIT;
2161 if (amnt)
2162 shift_bytes_in_array_right (this_buffer, len + 1, amnt);
2163 unsigned char *q = this_buffer;
2164 unsigned int off = 0;
2165 if (pd.offset >= 0)
2167 unsigned int msk;
2168 off = pd.offset / BITS_PER_UNIT;
2169 gcc_assert (off < needed_len);
2170 p = buffer + off;
2171 if (size <= amnt)
2173 msk = ((1 << size) - 1) << (BITS_PER_UNIT - amnt);
2174 *p = (*p & ~msk) | (this_buffer[len] & msk);
2175 size = 0;
2177 else
2179 if (TREE_CODE (pd.rhs) != CONSTRUCTOR)
2180 q = (this_buffer + len
2181 - (ROUND_UP (size - amnt, BITS_PER_UNIT)
2182 / BITS_PER_UNIT));
2183 if (pd.offset % BITS_PER_UNIT)
2185 msk = -1U << (BITS_PER_UNIT
2186 - (pd.offset % BITS_PER_UNIT));
2187 *p = (*p & msk) | (*q & ~msk);
2188 p++;
2189 q++;
2190 off++;
2191 size -= BITS_PER_UNIT - (pd.offset % BITS_PER_UNIT);
2192 gcc_assert (size >= 0);
2196 else if (TREE_CODE (pd.rhs) != CONSTRUCTOR)
2198 q = (this_buffer + len
2199 - (ROUND_UP (size - amnt, BITS_PER_UNIT)
2200 / BITS_PER_UNIT));
2201 if (pd.offset % BITS_PER_UNIT)
2203 q++;
2204 size -= BITS_PER_UNIT - ((unsigned HOST_WIDE_INT) pd.offset
2205 % BITS_PER_UNIT);
2206 gcc_assert (size >= 0);
2209 if ((unsigned HOST_WIDE_INT) size / BITS_PER_UNIT + off
2210 > needed_len)
2211 size = (needed_len - off) * BITS_PER_UNIT;
2212 memcpy (p, q, size / BITS_PER_UNIT);
2213 if (size % BITS_PER_UNIT)
2215 unsigned int msk
2216 = -1U << (BITS_PER_UNIT - (size % BITS_PER_UNIT));
2217 p += size / BITS_PER_UNIT;
2218 q += size / BITS_PER_UNIT;
2219 *p = (*q & msk) | (*p & ~msk);
2222 else
2224 if (pd.offset >= 0)
2226 /* LSB of this_buffer[0] byte should be at pd.offset bits
2227 in buffer. */
2228 unsigned int msk;
2229 size = MIN (size, (HOST_WIDE_INT) needed_len * BITS_PER_UNIT);
2230 amnt = pd.offset % BITS_PER_UNIT;
2231 if (amnt)
2232 shift_bytes_in_array_left (this_buffer, len + 1, amnt);
2233 unsigned int off = pd.offset / BITS_PER_UNIT;
2234 gcc_assert (off < needed_len);
2235 size = MIN (size,
2236 (HOST_WIDE_INT) (needed_len - off) * BITS_PER_UNIT);
2237 p = buffer + off;
2238 if (amnt + size < BITS_PER_UNIT)
2240 /* Low amnt bits come from *p, then size bits
2241 from this_buffer[0] and the remaining again from
2242 *p. */
2243 msk = ((1 << size) - 1) << amnt;
2244 *p = (*p & ~msk) | (this_buffer[0] & msk);
2245 size = 0;
2247 else if (amnt)
2249 msk = -1U << amnt;
2250 *p = (*p & ~msk) | (this_buffer[0] & msk);
2251 p++;
2252 size -= (BITS_PER_UNIT - amnt);
2255 else
2257 amnt = (unsigned HOST_WIDE_INT) pd.offset % BITS_PER_UNIT;
2258 if (amnt)
2259 size -= BITS_PER_UNIT - amnt;
2260 size = MIN (size, (HOST_WIDE_INT) needed_len * BITS_PER_UNIT);
2261 if (amnt)
2262 shift_bytes_in_array_left (this_buffer, len + 1, amnt);
2264 memcpy (p, this_buffer + (amnt != 0), size / BITS_PER_UNIT);
2265 p += size / BITS_PER_UNIT;
2266 if (size % BITS_PER_UNIT)
2268 unsigned int msk = -1U << (size % BITS_PER_UNIT);
2269 *p = (this_buffer[(amnt != 0) + size / BITS_PER_UNIT]
2270 & ~msk) | (*p & msk);
2275 tree type = vr->type;
2276 /* Make sure to interpret in a type that has a range covering the whole
2277 access size. */
2278 if (INTEGRAL_TYPE_P (vr->type) && maxsizei != TYPE_PRECISION (vr->type))
2279 type = build_nonstandard_integer_type (maxsizei, TYPE_UNSIGNED (type));
2280 tree val;
2281 if (BYTES_BIG_ENDIAN)
2283 unsigned sz = needed_len;
2284 if (maxsizei % BITS_PER_UNIT)
2285 shift_bytes_in_array_right (buffer, needed_len,
2286 BITS_PER_UNIT
2287 - (maxsizei % BITS_PER_UNIT));
2288 if (INTEGRAL_TYPE_P (type))
2289 sz = GET_MODE_SIZE (SCALAR_INT_TYPE_MODE (type));
2290 if (sz > needed_len)
2292 memcpy (this_buffer + (sz - needed_len), buffer, needed_len);
2293 val = native_interpret_expr (type, this_buffer, sz);
2295 else
2296 val = native_interpret_expr (type, buffer, needed_len);
2298 else
2299 val = native_interpret_expr (type, buffer, bufsize);
2300 /* If we chop off bits because the types precision doesn't match the memory
2301 access size this is ok when optimizing reads but not when called from
2302 the DSE code during elimination. */
2303 if (val && type != vr->type)
2305 if (! int_fits_type_p (val, vr->type))
2306 val = NULL_TREE;
2307 else
2308 val = fold_convert (vr->type, val);
2311 if (val)
2313 if (dump_file && (dump_flags & TDF_DETAILS))
2314 fprintf (dump_file,
2315 "Successfully combined %u partial definitions\n", ndefs);
2316 /* We are using the alias-set of the first store we encounter which
2317 should be appropriate here. */
2318 return finish (first_set, first_base_set, val);
2320 else
2322 if (dump_file && (dump_flags & TDF_DETAILS))
2323 fprintf (dump_file,
2324 "Failed to interpret %u encoded partial definitions\n", ndefs);
2325 return (void *)-1;
2329 /* Callback for walk_non_aliased_vuses. Adjusts the vn_reference_t VR_
2330 with the current VUSE and performs the expression lookup. */
2332 static void *
2333 vn_reference_lookup_2 (ao_ref *op, tree vuse, void *data_)
2335 vn_walk_cb_data *data = (vn_walk_cb_data *)data_;
2336 vn_reference_t vr = data->vr;
2337 vn_reference_s **slot;
2338 hashval_t hash;
2340 /* If we have partial definitions recorded we have to go through
2341 vn_reference_lookup_3. */
2342 if (!data->partial_defs.is_empty ())
2343 return NULL;
2345 if (data->last_vuse_ptr)
2347 *data->last_vuse_ptr = vuse;
2348 data->last_vuse = vuse;
2351 /* Fixup vuse and hash. */
2352 if (vr->vuse)
2353 vr->hashcode = vr->hashcode - SSA_NAME_VERSION (vr->vuse);
2354 vr->vuse = vuse_ssa_val (vuse);
2355 if (vr->vuse)
2356 vr->hashcode = vr->hashcode + SSA_NAME_VERSION (vr->vuse);
2358 hash = vr->hashcode;
2359 slot = valid_info->references->find_slot_with_hash (vr, hash, NO_INSERT);
2360 if (slot)
2362 if ((*slot)->result && data->saved_operands.exists ())
2363 return data->finish (vr->set, vr->base_set, (*slot)->result);
2364 return *slot;
2367 if (SSA_NAME_IS_DEFAULT_DEF (vuse))
2369 HOST_WIDE_INT op_offset, op_size;
2370 tree v = NULL_TREE;
2371 tree base = ao_ref_base (op);
2373 if (base
2374 && op->offset.is_constant (&op_offset)
2375 && op->size.is_constant (&op_size)
2376 && op->max_size_known_p ()
2377 && known_eq (op->size, op->max_size))
2379 if (TREE_CODE (base) == PARM_DECL)
2380 v = ipcp_get_aggregate_const (cfun, base, false, op_offset,
2381 op_size);
2382 else if (TREE_CODE (base) == MEM_REF
2383 && integer_zerop (TREE_OPERAND (base, 1))
2384 && TREE_CODE (TREE_OPERAND (base, 0)) == SSA_NAME
2385 && SSA_NAME_IS_DEFAULT_DEF (TREE_OPERAND (base, 0))
2386 && (TREE_CODE (SSA_NAME_VAR (TREE_OPERAND (base, 0)))
2387 == PARM_DECL))
2388 v = ipcp_get_aggregate_const (cfun,
2389 SSA_NAME_VAR (TREE_OPERAND (base, 0)),
2390 true, op_offset, op_size);
2392 if (v)
2393 return data->finish (vr->set, vr->base_set, v);
2396 return NULL;
2399 /* Lookup an existing or insert a new vn_reference entry into the
2400 value table for the VUSE, SET, TYPE, OPERANDS reference which
2401 has the value VALUE which is either a constant or an SSA name. */
2403 static vn_reference_t
2404 vn_reference_lookup_or_insert_for_pieces (tree vuse,
2405 alias_set_type set,
2406 alias_set_type base_set,
2407 tree type,
2408 vec<vn_reference_op_s,
2409 va_heap> operands,
2410 tree value)
2412 vn_reference_s vr1;
2413 vn_reference_t result;
2414 unsigned value_id;
2415 vr1.vuse = vuse ? SSA_VAL (vuse) : NULL_TREE;
2416 vr1.operands = operands;
2417 vr1.type = type;
2418 vr1.set = set;
2419 vr1.base_set = base_set;
2420 vr1.hashcode = vn_reference_compute_hash (&vr1);
2421 if (vn_reference_lookup_1 (&vr1, &result))
2422 return result;
2423 if (TREE_CODE (value) == SSA_NAME)
2424 value_id = VN_INFO (value)->value_id;
2425 else
2426 value_id = get_or_alloc_constant_value_id (value);
2427 return vn_reference_insert_pieces (vuse, set, base_set, type,
2428 operands.copy (), value, value_id);
2431 /* Return a value-number for RCODE OPS... either by looking up an existing
2432 value-number for the possibly simplified result or by inserting the
2433 operation if INSERT is true. If SIMPLIFY is false, return a value
2434 number for the unsimplified expression. */
2436 static tree
2437 vn_nary_build_or_lookup_1 (gimple_match_op *res_op, bool insert,
2438 bool simplify)
2440 tree result = NULL_TREE;
2441 /* We will be creating a value number for
2442 RCODE (OPS...).
2443 So first simplify and lookup this expression to see if it
2444 is already available. */
2445 /* For simplification valueize. */
2446 unsigned i = 0;
2447 if (simplify)
2448 for (i = 0; i < res_op->num_ops; ++i)
2449 if (TREE_CODE (res_op->ops[i]) == SSA_NAME)
2451 tree tem = vn_valueize (res_op->ops[i]);
2452 if (!tem)
2453 break;
2454 res_op->ops[i] = tem;
2456 /* If valueization of an operand fails (it is not available), skip
2457 simplification. */
2458 bool res = false;
2459 if (i == res_op->num_ops)
2461 mprts_hook = vn_lookup_simplify_result;
2462 res = res_op->resimplify (NULL, vn_valueize);
2463 mprts_hook = NULL;
2465 gimple *new_stmt = NULL;
2466 if (res
2467 && gimple_simplified_result_is_gimple_val (res_op))
2469 /* The expression is already available. */
2470 result = res_op->ops[0];
2471 /* Valueize it, simplification returns sth in AVAIL only. */
2472 if (TREE_CODE (result) == SSA_NAME)
2473 result = SSA_VAL (result);
2475 else
2477 tree val = vn_lookup_simplify_result (res_op);
2478 if (!val && insert)
2480 gimple_seq stmts = NULL;
2481 result = maybe_push_res_to_seq (res_op, &stmts);
2482 if (result)
2484 gcc_assert (gimple_seq_singleton_p (stmts));
2485 new_stmt = gimple_seq_first_stmt (stmts);
2488 else
2489 /* The expression is already available. */
2490 result = val;
2492 if (new_stmt)
2494 /* The expression is not yet available, value-number lhs to
2495 the new SSA_NAME we created. */
2496 /* Initialize value-number information properly. */
2497 vn_ssa_aux_t result_info = VN_INFO (result);
2498 result_info->valnum = result;
2499 result_info->value_id = get_next_value_id ();
2500 result_info->visited = 1;
2501 gimple_seq_add_stmt_without_update (&VN_INFO (result)->expr,
2502 new_stmt);
2503 result_info->needs_insertion = true;
2504 /* ??? PRE phi-translation inserts NARYs without corresponding
2505 SSA name result. Re-use those but set their result according
2506 to the stmt we just built. */
2507 vn_nary_op_t nary = NULL;
2508 vn_nary_op_lookup_stmt (new_stmt, &nary);
2509 if (nary)
2511 gcc_assert (! nary->predicated_values && nary->u.result == NULL_TREE);
2512 nary->u.result = gimple_assign_lhs (new_stmt);
2514 /* As all "inserted" statements are singleton SCCs, insert
2515 to the valid table. This is strictly needed to
2516 avoid re-generating new value SSA_NAMEs for the same
2517 expression during SCC iteration over and over (the
2518 optimistic table gets cleared after each iteration).
2519 We do not need to insert into the optimistic table, as
2520 lookups there will fall back to the valid table. */
2521 else
2523 unsigned int length = vn_nary_length_from_stmt (new_stmt);
2524 vn_nary_op_t vno1
2525 = alloc_vn_nary_op_noinit (length, &vn_tables_insert_obstack);
2526 vno1->value_id = result_info->value_id;
2527 vno1->length = length;
2528 vno1->predicated_values = 0;
2529 vno1->u.result = result;
2530 init_vn_nary_op_from_stmt (vno1, as_a <gassign *> (new_stmt));
2531 vn_nary_op_insert_into (vno1, valid_info->nary);
2532 /* Also do not link it into the undo chain. */
2533 last_inserted_nary = vno1->next;
2534 vno1->next = (vn_nary_op_t)(void *)-1;
2536 if (dump_file && (dump_flags & TDF_DETAILS))
2538 fprintf (dump_file, "Inserting name ");
2539 print_generic_expr (dump_file, result);
2540 fprintf (dump_file, " for expression ");
2541 print_gimple_expr (dump_file, new_stmt, 0, TDF_SLIM);
2542 fprintf (dump_file, "\n");
2545 return result;
2548 /* Return a value-number for RCODE OPS... either by looking up an existing
2549 value-number for the simplified result or by inserting the operation. */
2551 static tree
2552 vn_nary_build_or_lookup (gimple_match_op *res_op)
2554 return vn_nary_build_or_lookup_1 (res_op, true, true);
2557 /* Try to simplify the expression RCODE OPS... of type TYPE and return
2558 its value if present. */
2560 tree
2561 vn_nary_simplify (vn_nary_op_t nary)
2563 if (nary->length > gimple_match_op::MAX_NUM_OPS)
2564 return NULL_TREE;
2565 gimple_match_op op (gimple_match_cond::UNCOND, nary->opcode,
2566 nary->type, nary->length);
2567 memcpy (op.ops, nary->op, sizeof (tree) * nary->length);
2568 return vn_nary_build_or_lookup_1 (&op, false, true);
2571 /* Elimination engine. */
2573 class eliminate_dom_walker : public dom_walker
2575 public:
2576 eliminate_dom_walker (cdi_direction, bitmap);
2577 ~eliminate_dom_walker ();
2579 edge before_dom_children (basic_block) final override;
2580 void after_dom_children (basic_block) final override;
2582 virtual tree eliminate_avail (basic_block, tree op);
2583 virtual void eliminate_push_avail (basic_block, tree op);
2584 tree eliminate_insert (basic_block, gimple_stmt_iterator *gsi, tree val);
2586 void eliminate_stmt (basic_block, gimple_stmt_iterator *);
2588 unsigned eliminate_cleanup (bool region_p = false);
2590 bool do_pre;
2591 unsigned int el_todo;
2592 unsigned int eliminations;
2593 unsigned int insertions;
2595 /* SSA names that had their defs inserted by PRE if do_pre. */
2596 bitmap inserted_exprs;
2598 /* Blocks with statements that have had their EH properties changed. */
2599 bitmap need_eh_cleanup;
2601 /* Blocks with statements that have had their AB properties changed. */
2602 bitmap need_ab_cleanup;
2604 /* Local state for the eliminate domwalk. */
2605 auto_vec<gimple *> to_remove;
2606 auto_vec<gimple *> to_fixup;
2607 auto_vec<tree> avail;
2608 auto_vec<tree> avail_stack;
2611 /* Adaptor to the elimination engine using RPO availability. */
2613 class rpo_elim : public eliminate_dom_walker
2615 public:
2616 rpo_elim(basic_block entry_)
2617 : eliminate_dom_walker (CDI_DOMINATORS, NULL), entry (entry_),
2618 m_avail_freelist (NULL) {}
2620 tree eliminate_avail (basic_block, tree op) final override;
2622 void eliminate_push_avail (basic_block, tree) final override;
2624 basic_block entry;
2625 /* Freelist of avail entries which are allocated from the vn_ssa_aux
2626 obstack. */
2627 vn_avail *m_avail_freelist;
2630 /* Global RPO state for access from hooks. */
2631 static eliminate_dom_walker *rpo_avail;
2632 basic_block vn_context_bb;
2634 /* Return true if BASE1 and BASE2 can be adjusted so they have the
2635 same address and adjust *OFFSET1 and *OFFSET2 accordingly.
2636 Otherwise return false. */
2638 static bool
2639 adjust_offsets_for_equal_base_address (tree base1, poly_int64 *offset1,
2640 tree base2, poly_int64 *offset2)
2642 poly_int64 soff;
2643 if (TREE_CODE (base1) == MEM_REF
2644 && TREE_CODE (base2) == MEM_REF)
2646 if (mem_ref_offset (base1).to_shwi (&soff))
2648 base1 = TREE_OPERAND (base1, 0);
2649 *offset1 += soff * BITS_PER_UNIT;
2651 if (mem_ref_offset (base2).to_shwi (&soff))
2653 base2 = TREE_OPERAND (base2, 0);
2654 *offset2 += soff * BITS_PER_UNIT;
2656 return operand_equal_p (base1, base2, 0);
2658 return operand_equal_p (base1, base2, OEP_ADDRESS_OF);
2661 /* Callback for walk_non_aliased_vuses. Tries to perform a lookup
2662 from the statement defining VUSE and if not successful tries to
2663 translate *REFP and VR_ through an aggregate copy at the definition
2664 of VUSE. If *DISAMBIGUATE_ONLY is true then do not perform translation
2665 of *REF and *VR. If only disambiguation was performed then
2666 *DISAMBIGUATE_ONLY is set to true. */
2668 static void *
2669 vn_reference_lookup_3 (ao_ref *ref, tree vuse, void *data_,
2670 translate_flags *disambiguate_only)
2672 vn_walk_cb_data *data = (vn_walk_cb_data *)data_;
2673 vn_reference_t vr = data->vr;
2674 gimple *def_stmt = SSA_NAME_DEF_STMT (vuse);
2675 tree base = ao_ref_base (ref);
2676 HOST_WIDE_INT offseti = 0, maxsizei, sizei = 0;
2677 static vec<vn_reference_op_s> lhs_ops;
2678 ao_ref lhs_ref;
2679 bool lhs_ref_ok = false;
2680 poly_int64 copy_size;
2682 /* First try to disambiguate after value-replacing in the definitions LHS. */
2683 if (is_gimple_assign (def_stmt))
2685 tree lhs = gimple_assign_lhs (def_stmt);
2686 bool valueized_anything = false;
2687 /* Avoid re-allocation overhead. */
2688 lhs_ops.truncate (0);
2689 basic_block saved_rpo_bb = vn_context_bb;
2690 vn_context_bb = gimple_bb (def_stmt);
2691 if (*disambiguate_only <= TR_VALUEIZE_AND_DISAMBIGUATE)
2693 copy_reference_ops_from_ref (lhs, &lhs_ops);
2694 valueize_refs_1 (&lhs_ops, &valueized_anything, true);
2696 vn_context_bb = saved_rpo_bb;
2697 ao_ref_init (&lhs_ref, lhs);
2698 lhs_ref_ok = true;
2699 if (valueized_anything
2700 && ao_ref_init_from_vn_reference
2701 (&lhs_ref, ao_ref_alias_set (&lhs_ref),
2702 ao_ref_base_alias_set (&lhs_ref), TREE_TYPE (lhs), lhs_ops)
2703 && !refs_may_alias_p_1 (ref, &lhs_ref, data->tbaa_p))
2705 *disambiguate_only = TR_VALUEIZE_AND_DISAMBIGUATE;
2706 return NULL;
2709 /* When the def is a CLOBBER we can optimistically disambiguate
2710 against it since any overlap it would be undefined behavior.
2711 Avoid this for obvious must aliases to save compile-time though.
2712 We also may not do this when the query is used for redundant
2713 store removal. */
2714 if (!data->redundant_store_removal_p
2715 && gimple_clobber_p (def_stmt)
2716 && !operand_equal_p (ao_ref_base (&lhs_ref), base, OEP_ADDRESS_OF))
2718 *disambiguate_only = TR_DISAMBIGUATE;
2719 return NULL;
2722 /* Besides valueizing the LHS we can also use access-path based
2723 disambiguation on the original non-valueized ref. */
2724 if (!ref->ref
2725 && lhs_ref_ok
2726 && data->orig_ref.ref)
2728 /* We want to use the non-valueized LHS for this, but avoid redundant
2729 work. */
2730 ao_ref *lref = &lhs_ref;
2731 ao_ref lref_alt;
2732 if (valueized_anything)
2734 ao_ref_init (&lref_alt, lhs);
2735 lref = &lref_alt;
2737 if (!refs_may_alias_p_1 (&data->orig_ref, lref, data->tbaa_p))
2739 *disambiguate_only = (valueized_anything
2740 ? TR_VALUEIZE_AND_DISAMBIGUATE
2741 : TR_DISAMBIGUATE);
2742 return NULL;
2746 /* If we reach a clobbering statement try to skip it and see if
2747 we find a VN result with exactly the same value as the
2748 possible clobber. In this case we can ignore the clobber
2749 and return the found value. */
2750 if (is_gimple_reg_type (TREE_TYPE (lhs))
2751 && types_compatible_p (TREE_TYPE (lhs), vr->type)
2752 && (ref->ref || data->orig_ref.ref)
2753 && !data->mask
2754 && data->partial_defs.is_empty ()
2755 && multiple_p (get_object_alignment
2756 (ref->ref ? ref->ref : data->orig_ref.ref),
2757 ref->size)
2758 && multiple_p (get_object_alignment (lhs), ref->size))
2760 tree rhs = gimple_assign_rhs1 (def_stmt);
2761 /* ??? We may not compare to ahead values which might be from
2762 a different loop iteration but only to loop invariants. Use
2763 CONSTANT_CLASS_P (unvalueized!) as conservative approximation.
2764 The one-hop lookup below doesn't have this issue since there's
2765 a virtual PHI before we ever reach a backedge to cross.
2766 We can skip multiple defs as long as they are from the same
2767 value though. */
2768 if (data->same_val
2769 && !operand_equal_p (data->same_val, rhs))
2771 else if (CONSTANT_CLASS_P (rhs))
2773 if (dump_file && (dump_flags & TDF_DETAILS))
2775 fprintf (dump_file,
2776 "Skipping possible redundant definition ");
2777 print_gimple_stmt (dump_file, def_stmt, 0);
2779 /* Delay the actual compare of the values to the end of the walk
2780 but do not update last_vuse from here. */
2781 data->last_vuse_ptr = NULL;
2782 data->same_val = rhs;
2783 return NULL;
2785 else
2787 tree *saved_last_vuse_ptr = data->last_vuse_ptr;
2788 /* Do not update last_vuse_ptr in vn_reference_lookup_2. */
2789 data->last_vuse_ptr = NULL;
2790 tree saved_vuse = vr->vuse;
2791 hashval_t saved_hashcode = vr->hashcode;
2792 void *res = vn_reference_lookup_2 (ref, gimple_vuse (def_stmt),
2793 data);
2794 /* Need to restore vr->vuse and vr->hashcode. */
2795 vr->vuse = saved_vuse;
2796 vr->hashcode = saved_hashcode;
2797 data->last_vuse_ptr = saved_last_vuse_ptr;
2798 if (res && res != (void *)-1)
2800 vn_reference_t vnresult = (vn_reference_t) res;
2801 if (TREE_CODE (rhs) == SSA_NAME)
2802 rhs = SSA_VAL (rhs);
2803 if (vnresult->result
2804 && operand_equal_p (vnresult->result, rhs, 0))
2805 return res;
2810 else if (*disambiguate_only <= TR_VALUEIZE_AND_DISAMBIGUATE
2811 && gimple_call_builtin_p (def_stmt, BUILT_IN_NORMAL)
2812 && gimple_call_num_args (def_stmt) <= 4)
2814 /* For builtin calls valueize its arguments and call the
2815 alias oracle again. Valueization may improve points-to
2816 info of pointers and constify size and position arguments.
2817 Originally this was motivated by PR61034 which has
2818 conditional calls to free falsely clobbering ref because
2819 of imprecise points-to info of the argument. */
2820 tree oldargs[4];
2821 bool valueized_anything = false;
2822 for (unsigned i = 0; i < gimple_call_num_args (def_stmt); ++i)
2824 oldargs[i] = gimple_call_arg (def_stmt, i);
2825 tree val = vn_valueize (oldargs[i]);
2826 if (val != oldargs[i])
2828 gimple_call_set_arg (def_stmt, i, val);
2829 valueized_anything = true;
2832 if (valueized_anything)
2834 bool res = call_may_clobber_ref_p_1 (as_a <gcall *> (def_stmt),
2835 ref, data->tbaa_p);
2836 for (unsigned i = 0; i < gimple_call_num_args (def_stmt); ++i)
2837 gimple_call_set_arg (def_stmt, i, oldargs[i]);
2838 if (!res)
2840 *disambiguate_only = TR_VALUEIZE_AND_DISAMBIGUATE;
2841 return NULL;
2846 if (*disambiguate_only > TR_TRANSLATE)
2847 return (void *)-1;
2849 /* If we cannot constrain the size of the reference we cannot
2850 test if anything kills it. */
2851 if (!ref->max_size_known_p ())
2852 return (void *)-1;
2854 poly_int64 offset = ref->offset;
2855 poly_int64 maxsize = ref->max_size;
2857 /* def_stmt may-defs *ref. See if we can derive a value for *ref
2858 from that definition.
2859 1) Memset. */
2860 if (is_gimple_reg_type (vr->type)
2861 && (gimple_call_builtin_p (def_stmt, BUILT_IN_MEMSET)
2862 || gimple_call_builtin_p (def_stmt, BUILT_IN_MEMSET_CHK))
2863 && (integer_zerop (gimple_call_arg (def_stmt, 1))
2864 || ((TREE_CODE (gimple_call_arg (def_stmt, 1)) == INTEGER_CST
2865 || (INTEGRAL_TYPE_P (vr->type) && known_eq (ref->size, 8)))
2866 && CHAR_BIT == 8
2867 && BITS_PER_UNIT == 8
2868 && BYTES_BIG_ENDIAN == WORDS_BIG_ENDIAN
2869 && offset.is_constant (&offseti)
2870 && ref->size.is_constant (&sizei)
2871 && (offseti % BITS_PER_UNIT == 0
2872 || TREE_CODE (gimple_call_arg (def_stmt, 1)) == INTEGER_CST)))
2873 && (poly_int_tree_p (gimple_call_arg (def_stmt, 2))
2874 || (TREE_CODE (gimple_call_arg (def_stmt, 2)) == SSA_NAME
2875 && poly_int_tree_p (SSA_VAL (gimple_call_arg (def_stmt, 2)))))
2876 && (TREE_CODE (gimple_call_arg (def_stmt, 0)) == ADDR_EXPR
2877 || TREE_CODE (gimple_call_arg (def_stmt, 0)) == SSA_NAME))
2879 tree base2;
2880 poly_int64 offset2, size2, maxsize2;
2881 bool reverse;
2882 tree ref2 = gimple_call_arg (def_stmt, 0);
2883 if (TREE_CODE (ref2) == SSA_NAME)
2885 ref2 = SSA_VAL (ref2);
2886 if (TREE_CODE (ref2) == SSA_NAME
2887 && (TREE_CODE (base) != MEM_REF
2888 || TREE_OPERAND (base, 0) != ref2))
2890 gimple *def_stmt = SSA_NAME_DEF_STMT (ref2);
2891 if (gimple_assign_single_p (def_stmt)
2892 && gimple_assign_rhs_code (def_stmt) == ADDR_EXPR)
2893 ref2 = gimple_assign_rhs1 (def_stmt);
2896 if (TREE_CODE (ref2) == ADDR_EXPR)
2898 ref2 = TREE_OPERAND (ref2, 0);
2899 base2 = get_ref_base_and_extent (ref2, &offset2, &size2, &maxsize2,
2900 &reverse);
2901 if (!known_size_p (maxsize2)
2902 || !known_eq (maxsize2, size2)
2903 || !operand_equal_p (base, base2, OEP_ADDRESS_OF))
2904 return (void *)-1;
2906 else if (TREE_CODE (ref2) == SSA_NAME)
2908 poly_int64 soff;
2909 if (TREE_CODE (base) != MEM_REF
2910 || !(mem_ref_offset (base)
2911 << LOG2_BITS_PER_UNIT).to_shwi (&soff))
2912 return (void *)-1;
2913 offset += soff;
2914 offset2 = 0;
2915 if (TREE_OPERAND (base, 0) != ref2)
2917 gimple *def = SSA_NAME_DEF_STMT (ref2);
2918 if (is_gimple_assign (def)
2919 && gimple_assign_rhs_code (def) == POINTER_PLUS_EXPR
2920 && gimple_assign_rhs1 (def) == TREE_OPERAND (base, 0)
2921 && poly_int_tree_p (gimple_assign_rhs2 (def)))
2923 tree rhs2 = gimple_assign_rhs2 (def);
2924 if (!(poly_offset_int::from (wi::to_poly_wide (rhs2),
2925 SIGNED)
2926 << LOG2_BITS_PER_UNIT).to_shwi (&offset2))
2927 return (void *)-1;
2928 ref2 = gimple_assign_rhs1 (def);
2929 if (TREE_CODE (ref2) == SSA_NAME)
2930 ref2 = SSA_VAL (ref2);
2932 else
2933 return (void *)-1;
2936 else
2937 return (void *)-1;
2938 tree len = gimple_call_arg (def_stmt, 2);
2939 HOST_WIDE_INT leni, offset2i;
2940 if (TREE_CODE (len) == SSA_NAME)
2941 len = SSA_VAL (len);
2942 /* Sometimes the above trickery is smarter than alias analysis. Take
2943 advantage of that. */
2944 if (!ranges_maybe_overlap_p (offset, maxsize, offset2,
2945 (wi::to_poly_offset (len)
2946 << LOG2_BITS_PER_UNIT)))
2947 return NULL;
2948 if (data->partial_defs.is_empty ()
2949 && known_subrange_p (offset, maxsize, offset2,
2950 wi::to_poly_offset (len) << LOG2_BITS_PER_UNIT))
2952 tree val;
2953 if (integer_zerop (gimple_call_arg (def_stmt, 1)))
2954 val = build_zero_cst (vr->type);
2955 else if (INTEGRAL_TYPE_P (vr->type)
2956 && known_eq (ref->size, 8)
2957 && offseti % BITS_PER_UNIT == 0)
2959 gimple_match_op res_op (gimple_match_cond::UNCOND, NOP_EXPR,
2960 vr->type, gimple_call_arg (def_stmt, 1));
2961 val = vn_nary_build_or_lookup (&res_op);
2962 if (!val
2963 || (TREE_CODE (val) == SSA_NAME
2964 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (val)))
2965 return (void *)-1;
2967 else
2969 unsigned buflen = TREE_INT_CST_LOW (TYPE_SIZE_UNIT (vr->type)) + 1;
2970 if (INTEGRAL_TYPE_P (vr->type))
2971 buflen = GET_MODE_SIZE (SCALAR_INT_TYPE_MODE (vr->type)) + 1;
2972 unsigned char *buf = XALLOCAVEC (unsigned char, buflen);
2973 memset (buf, TREE_INT_CST_LOW (gimple_call_arg (def_stmt, 1)),
2974 buflen);
2975 if (BYTES_BIG_ENDIAN)
2977 unsigned int amnt
2978 = (((unsigned HOST_WIDE_INT) offseti + sizei)
2979 % BITS_PER_UNIT);
2980 if (amnt)
2982 shift_bytes_in_array_right (buf, buflen,
2983 BITS_PER_UNIT - amnt);
2984 buf++;
2985 buflen--;
2988 else if (offseti % BITS_PER_UNIT != 0)
2990 unsigned int amnt
2991 = BITS_PER_UNIT - ((unsigned HOST_WIDE_INT) offseti
2992 % BITS_PER_UNIT);
2993 shift_bytes_in_array_left (buf, buflen, amnt);
2994 buf++;
2995 buflen--;
2997 val = native_interpret_expr (vr->type, buf, buflen);
2998 if (!val)
2999 return (void *)-1;
3001 return data->finish (0, 0, val);
3003 /* For now handle clearing memory with partial defs. */
3004 else if (known_eq (ref->size, maxsize)
3005 && integer_zerop (gimple_call_arg (def_stmt, 1))
3006 && tree_fits_poly_int64_p (len)
3007 && tree_to_poly_int64 (len).is_constant (&leni)
3008 && leni <= INTTYPE_MAXIMUM (HOST_WIDE_INT) / BITS_PER_UNIT
3009 && offset.is_constant (&offseti)
3010 && offset2.is_constant (&offset2i)
3011 && maxsize.is_constant (&maxsizei)
3012 && ranges_known_overlap_p (offseti, maxsizei, offset2i,
3013 leni << LOG2_BITS_PER_UNIT))
3015 pd_data pd;
3016 pd.rhs = build_constructor (NULL_TREE, NULL);
3017 pd.rhs_off = 0;
3018 pd.offset = offset2i;
3019 pd.size = leni << LOG2_BITS_PER_UNIT;
3020 return data->push_partial_def (pd, 0, 0, offseti, maxsizei);
3024 /* 2) Assignment from an empty CONSTRUCTOR. */
3025 else if (is_gimple_reg_type (vr->type)
3026 && gimple_assign_single_p (def_stmt)
3027 && gimple_assign_rhs_code (def_stmt) == CONSTRUCTOR
3028 && CONSTRUCTOR_NELTS (gimple_assign_rhs1 (def_stmt)) == 0)
3030 tree base2;
3031 poly_int64 offset2, size2, maxsize2;
3032 HOST_WIDE_INT offset2i, size2i;
3033 gcc_assert (lhs_ref_ok);
3034 base2 = ao_ref_base (&lhs_ref);
3035 offset2 = lhs_ref.offset;
3036 size2 = lhs_ref.size;
3037 maxsize2 = lhs_ref.max_size;
3038 if (known_size_p (maxsize2)
3039 && known_eq (maxsize2, size2)
3040 && adjust_offsets_for_equal_base_address (base, &offset,
3041 base2, &offset2))
3043 if (data->partial_defs.is_empty ()
3044 && known_subrange_p (offset, maxsize, offset2, size2))
3046 /* While technically undefined behavior do not optimize
3047 a full read from a clobber. */
3048 if (gimple_clobber_p (def_stmt))
3049 return (void *)-1;
3050 tree val = build_zero_cst (vr->type);
3051 return data->finish (ao_ref_alias_set (&lhs_ref),
3052 ao_ref_base_alias_set (&lhs_ref), val);
3054 else if (known_eq (ref->size, maxsize)
3055 && maxsize.is_constant (&maxsizei)
3056 && offset.is_constant (&offseti)
3057 && offset2.is_constant (&offset2i)
3058 && size2.is_constant (&size2i)
3059 && ranges_known_overlap_p (offseti, maxsizei,
3060 offset2i, size2i))
3062 /* Let clobbers be consumed by the partial-def tracker
3063 which can choose to ignore them if they are shadowed
3064 by a later def. */
3065 pd_data pd;
3066 pd.rhs = gimple_assign_rhs1 (def_stmt);
3067 pd.rhs_off = 0;
3068 pd.offset = offset2i;
3069 pd.size = size2i;
3070 return data->push_partial_def (pd, ao_ref_alias_set (&lhs_ref),
3071 ao_ref_base_alias_set (&lhs_ref),
3072 offseti, maxsizei);
3077 /* 3) Assignment from a constant. We can use folds native encode/interpret
3078 routines to extract the assigned bits. */
3079 else if (known_eq (ref->size, maxsize)
3080 && is_gimple_reg_type (vr->type)
3081 && !reverse_storage_order_for_component_p (vr->operands)
3082 && !contains_storage_order_barrier_p (vr->operands)
3083 && gimple_assign_single_p (def_stmt)
3084 && CHAR_BIT == 8
3085 && BITS_PER_UNIT == 8
3086 && BYTES_BIG_ENDIAN == WORDS_BIG_ENDIAN
3087 /* native_encode and native_decode operate on arrays of bytes
3088 and so fundamentally need a compile-time size and offset. */
3089 && maxsize.is_constant (&maxsizei)
3090 && offset.is_constant (&offseti)
3091 && (is_gimple_min_invariant (gimple_assign_rhs1 (def_stmt))
3092 || (TREE_CODE (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
3093 && is_gimple_min_invariant (SSA_VAL (gimple_assign_rhs1 (def_stmt))))))
3095 tree lhs = gimple_assign_lhs (def_stmt);
3096 tree base2;
3097 poly_int64 offset2, size2, maxsize2;
3098 HOST_WIDE_INT offset2i, size2i;
3099 bool reverse;
3100 gcc_assert (lhs_ref_ok);
3101 base2 = ao_ref_base (&lhs_ref);
3102 offset2 = lhs_ref.offset;
3103 size2 = lhs_ref.size;
3104 maxsize2 = lhs_ref.max_size;
3105 reverse = reverse_storage_order_for_component_p (lhs);
3106 if (base2
3107 && !reverse
3108 && !storage_order_barrier_p (lhs)
3109 && known_eq (maxsize2, size2)
3110 && adjust_offsets_for_equal_base_address (base, &offset,
3111 base2, &offset2)
3112 && offset.is_constant (&offseti)
3113 && offset2.is_constant (&offset2i)
3114 && size2.is_constant (&size2i))
3116 if (data->partial_defs.is_empty ()
3117 && known_subrange_p (offseti, maxsizei, offset2, size2))
3119 /* We support up to 512-bit values (for V8DFmode). */
3120 unsigned char buffer[65];
3121 int len;
3123 tree rhs = gimple_assign_rhs1 (def_stmt);
3124 if (TREE_CODE (rhs) == SSA_NAME)
3125 rhs = SSA_VAL (rhs);
3126 len = native_encode_expr (rhs,
3127 buffer, sizeof (buffer) - 1,
3128 (offseti - offset2i) / BITS_PER_UNIT);
3129 if (len > 0 && len * BITS_PER_UNIT >= maxsizei)
3131 tree type = vr->type;
3132 unsigned char *buf = buffer;
3133 unsigned int amnt = 0;
3134 /* Make sure to interpret in a type that has a range
3135 covering the whole access size. */
3136 if (INTEGRAL_TYPE_P (vr->type)
3137 && maxsizei != TYPE_PRECISION (vr->type))
3138 type = build_nonstandard_integer_type (maxsizei,
3139 TYPE_UNSIGNED (type));
3140 if (BYTES_BIG_ENDIAN)
3142 /* For big-endian native_encode_expr stored the rhs
3143 such that the LSB of it is the LSB of buffer[len - 1].
3144 That bit is stored into memory at position
3145 offset2 + size2 - 1, i.e. in byte
3146 base + (offset2 + size2 - 1) / BITS_PER_UNIT.
3147 E.g. for offset2 1 and size2 14, rhs -1 and memory
3148 previously cleared that is:
3150 01111111|11111110
3151 Now, if we want to extract offset 2 and size 12 from
3152 it using native_interpret_expr (which actually works
3153 for integral bitfield types in terms of byte size of
3154 the mode), the native_encode_expr stored the value
3155 into buffer as
3156 XX111111|11111111
3157 and returned len 2 (the X bits are outside of
3158 precision).
3159 Let sz be maxsize / BITS_PER_UNIT if not extracting
3160 a bitfield, and GET_MODE_SIZE otherwise.
3161 We need to align the LSB of the value we want to
3162 extract as the LSB of buf[sz - 1].
3163 The LSB from memory we need to read is at position
3164 offset + maxsize - 1. */
3165 HOST_WIDE_INT sz = maxsizei / BITS_PER_UNIT;
3166 if (INTEGRAL_TYPE_P (type))
3167 sz = GET_MODE_SIZE (SCALAR_INT_TYPE_MODE (type));
3168 amnt = ((unsigned HOST_WIDE_INT) offset2i + size2i
3169 - offseti - maxsizei) % BITS_PER_UNIT;
3170 if (amnt)
3171 shift_bytes_in_array_right (buffer, len, amnt);
3172 amnt = ((unsigned HOST_WIDE_INT) offset2i + size2i
3173 - offseti - maxsizei - amnt) / BITS_PER_UNIT;
3174 if ((unsigned HOST_WIDE_INT) sz + amnt > (unsigned) len)
3175 len = 0;
3176 else
3178 buf = buffer + len - sz - amnt;
3179 len -= (buf - buffer);
3182 else
3184 amnt = ((unsigned HOST_WIDE_INT) offset2i
3185 - offseti) % BITS_PER_UNIT;
3186 if (amnt)
3188 buffer[len] = 0;
3189 shift_bytes_in_array_left (buffer, len + 1, amnt);
3190 buf = buffer + 1;
3193 tree val = native_interpret_expr (type, buf, len);
3194 /* If we chop off bits because the types precision doesn't
3195 match the memory access size this is ok when optimizing
3196 reads but not when called from the DSE code during
3197 elimination. */
3198 if (val
3199 && type != vr->type)
3201 if (! int_fits_type_p (val, vr->type))
3202 val = NULL_TREE;
3203 else
3204 val = fold_convert (vr->type, val);
3207 if (val)
3208 return data->finish (ao_ref_alias_set (&lhs_ref),
3209 ao_ref_base_alias_set (&lhs_ref), val);
3212 else if (ranges_known_overlap_p (offseti, maxsizei, offset2i,
3213 size2i))
3215 pd_data pd;
3216 tree rhs = gimple_assign_rhs1 (def_stmt);
3217 if (TREE_CODE (rhs) == SSA_NAME)
3218 rhs = SSA_VAL (rhs);
3219 pd.rhs = rhs;
3220 pd.rhs_off = 0;
3221 pd.offset = offset2i;
3222 pd.size = size2i;
3223 return data->push_partial_def (pd, ao_ref_alias_set (&lhs_ref),
3224 ao_ref_base_alias_set (&lhs_ref),
3225 offseti, maxsizei);
3230 /* 4) Assignment from an SSA name which definition we may be able
3231 to access pieces from or we can combine to a larger entity. */
3232 else if (known_eq (ref->size, maxsize)
3233 && is_gimple_reg_type (vr->type)
3234 && !reverse_storage_order_for_component_p (vr->operands)
3235 && !contains_storage_order_barrier_p (vr->operands)
3236 && gimple_assign_single_p (def_stmt)
3237 && TREE_CODE (gimple_assign_rhs1 (def_stmt)) == SSA_NAME)
3239 tree lhs = gimple_assign_lhs (def_stmt);
3240 tree base2;
3241 poly_int64 offset2, size2, maxsize2;
3242 HOST_WIDE_INT offset2i, size2i, offseti;
3243 bool reverse;
3244 gcc_assert (lhs_ref_ok);
3245 base2 = ao_ref_base (&lhs_ref);
3246 offset2 = lhs_ref.offset;
3247 size2 = lhs_ref.size;
3248 maxsize2 = lhs_ref.max_size;
3249 reverse = reverse_storage_order_for_component_p (lhs);
3250 tree def_rhs = gimple_assign_rhs1 (def_stmt);
3251 if (!reverse
3252 && !storage_order_barrier_p (lhs)
3253 && known_size_p (maxsize2)
3254 && known_eq (maxsize2, size2)
3255 && adjust_offsets_for_equal_base_address (base, &offset,
3256 base2, &offset2))
3258 if (data->partial_defs.is_empty ()
3259 && known_subrange_p (offset, maxsize, offset2, size2)
3260 /* ??? We can't handle bitfield precision extracts without
3261 either using an alternate type for the BIT_FIELD_REF and
3262 then doing a conversion or possibly adjusting the offset
3263 according to endianness. */
3264 && (! INTEGRAL_TYPE_P (vr->type)
3265 || known_eq (ref->size, TYPE_PRECISION (vr->type)))
3266 && multiple_p (ref->size, BITS_PER_UNIT))
3268 tree val = NULL_TREE;
3269 if (! INTEGRAL_TYPE_P (TREE_TYPE (def_rhs))
3270 || type_has_mode_precision_p (TREE_TYPE (def_rhs)))
3272 gimple_match_op op (gimple_match_cond::UNCOND,
3273 BIT_FIELD_REF, vr->type,
3274 SSA_VAL (def_rhs),
3275 bitsize_int (ref->size),
3276 bitsize_int (offset - offset2));
3277 val = vn_nary_build_or_lookup (&op);
3279 else if (known_eq (ref->size, size2))
3281 gimple_match_op op (gimple_match_cond::UNCOND,
3282 VIEW_CONVERT_EXPR, vr->type,
3283 SSA_VAL (def_rhs));
3284 val = vn_nary_build_or_lookup (&op);
3286 if (val
3287 && (TREE_CODE (val) != SSA_NAME
3288 || ! SSA_NAME_OCCURS_IN_ABNORMAL_PHI (val)))
3289 return data->finish (ao_ref_alias_set (&lhs_ref),
3290 ao_ref_base_alias_set (&lhs_ref), val);
3292 else if (maxsize.is_constant (&maxsizei)
3293 && offset.is_constant (&offseti)
3294 && offset2.is_constant (&offset2i)
3295 && size2.is_constant (&size2i)
3296 && ranges_known_overlap_p (offset, maxsize, offset2, size2))
3298 pd_data pd;
3299 pd.rhs = SSA_VAL (def_rhs);
3300 pd.rhs_off = 0;
3301 pd.offset = offset2i;
3302 pd.size = size2i;
3303 return data->push_partial_def (pd, ao_ref_alias_set (&lhs_ref),
3304 ao_ref_base_alias_set (&lhs_ref),
3305 offseti, maxsizei);
3310 /* 4b) Assignment done via one of the vectorizer internal store
3311 functions where we may be able to access pieces from or we can
3312 combine to a larger entity. */
3313 else if (known_eq (ref->size, maxsize)
3314 && is_gimple_reg_type (vr->type)
3315 && !reverse_storage_order_for_component_p (vr->operands)
3316 && !contains_storage_order_barrier_p (vr->operands)
3317 && is_gimple_call (def_stmt)
3318 && gimple_call_internal_p (def_stmt)
3319 && internal_store_fn_p (gimple_call_internal_fn (def_stmt)))
3321 gcall *call = as_a <gcall *> (def_stmt);
3322 internal_fn fn = gimple_call_internal_fn (call);
3324 tree mask = NULL_TREE, len = NULL_TREE, bias = NULL_TREE;
3325 switch (fn)
3327 case IFN_MASK_STORE:
3328 mask = gimple_call_arg (call, internal_fn_mask_index (fn));
3329 mask = vn_valueize (mask);
3330 if (TREE_CODE (mask) != VECTOR_CST)
3331 return (void *)-1;
3332 break;
3333 case IFN_LEN_STORE:
3335 int len_index = internal_fn_len_index (fn);
3336 len = gimple_call_arg (call, len_index);
3337 bias = gimple_call_arg (call, len_index + 1);
3338 if (!tree_fits_uhwi_p (len) || !tree_fits_shwi_p (bias))
3339 return (void *) -1;
3340 break;
3342 default:
3343 return (void *)-1;
3345 tree def_rhs = gimple_call_arg (call,
3346 internal_fn_stored_value_index (fn));
3347 def_rhs = vn_valueize (def_rhs);
3348 if (TREE_CODE (def_rhs) != VECTOR_CST)
3349 return (void *)-1;
3351 ao_ref_init_from_ptr_and_size (&lhs_ref,
3352 vn_valueize (gimple_call_arg (call, 0)),
3353 TYPE_SIZE_UNIT (TREE_TYPE (def_rhs)));
3354 tree base2;
3355 poly_int64 offset2, size2, maxsize2;
3356 HOST_WIDE_INT offset2i, size2i, offseti;
3357 base2 = ao_ref_base (&lhs_ref);
3358 offset2 = lhs_ref.offset;
3359 size2 = lhs_ref.size;
3360 maxsize2 = lhs_ref.max_size;
3361 if (known_size_p (maxsize2)
3362 && known_eq (maxsize2, size2)
3363 && adjust_offsets_for_equal_base_address (base, &offset,
3364 base2, &offset2)
3365 && maxsize.is_constant (&maxsizei)
3366 && offset.is_constant (&offseti)
3367 && offset2.is_constant (&offset2i)
3368 && size2.is_constant (&size2i))
3370 if (!ranges_maybe_overlap_p (offset, maxsize, offset2, size2))
3371 /* Poor-mans disambiguation. */
3372 return NULL;
3373 else if (ranges_known_overlap_p (offset, maxsize, offset2, size2))
3375 pd_data pd;
3376 pd.rhs = def_rhs;
3377 tree aa = gimple_call_arg (call, 1);
3378 alias_set_type set = get_deref_alias_set (TREE_TYPE (aa));
3379 tree vectype = TREE_TYPE (def_rhs);
3380 unsigned HOST_WIDE_INT elsz
3381 = tree_to_uhwi (TYPE_SIZE (TREE_TYPE (vectype)));
3382 if (mask)
3384 HOST_WIDE_INT start = 0, length = 0;
3385 unsigned mask_idx = 0;
3388 if (integer_zerop (VECTOR_CST_ELT (mask, mask_idx)))
3390 if (length != 0)
3392 pd.rhs_off = start;
3393 pd.offset = offset2i + start;
3394 pd.size = length;
3395 if (ranges_known_overlap_p
3396 (offset, maxsize, pd.offset, pd.size))
3398 void *res = data->push_partial_def
3399 (pd, set, set, offseti, maxsizei);
3400 if (res != NULL)
3401 return res;
3404 start = (mask_idx + 1) * elsz;
3405 length = 0;
3407 else
3408 length += elsz;
3409 mask_idx++;
3411 while (known_lt (mask_idx, TYPE_VECTOR_SUBPARTS (vectype)));
3412 if (length != 0)
3414 pd.rhs_off = start;
3415 pd.offset = offset2i + start;
3416 pd.size = length;
3417 if (ranges_known_overlap_p (offset, maxsize,
3418 pd.offset, pd.size))
3419 return data->push_partial_def (pd, set, set,
3420 offseti, maxsizei);
3423 else if (fn == IFN_LEN_STORE)
3425 pd.offset = offset2i;
3426 pd.size = (tree_to_uhwi (len)
3427 + -tree_to_shwi (bias)) * BITS_PER_UNIT;
3428 if (BYTES_BIG_ENDIAN)
3429 pd.rhs_off = pd.size - tree_to_uhwi (TYPE_SIZE (vectype));
3430 else
3431 pd.rhs_off = 0;
3432 if (ranges_known_overlap_p (offset, maxsize,
3433 pd.offset, pd.size))
3434 return data->push_partial_def (pd, set, set,
3435 offseti, maxsizei);
3437 else
3438 gcc_unreachable ();
3439 return NULL;
3444 /* 5) For aggregate copies translate the reference through them if
3445 the copy kills ref. */
3446 else if (data->vn_walk_kind == VN_WALKREWRITE
3447 && gimple_assign_single_p (def_stmt)
3448 && (DECL_P (gimple_assign_rhs1 (def_stmt))
3449 || TREE_CODE (gimple_assign_rhs1 (def_stmt)) == MEM_REF
3450 || handled_component_p (gimple_assign_rhs1 (def_stmt))))
3452 tree base2;
3453 int i, j, k;
3454 auto_vec<vn_reference_op_s> rhs;
3455 vn_reference_op_t vro;
3456 ao_ref r;
3458 gcc_assert (lhs_ref_ok);
3460 /* See if the assignment kills REF. */
3461 base2 = ao_ref_base (&lhs_ref);
3462 if (!lhs_ref.max_size_known_p ()
3463 || (base != base2
3464 && (TREE_CODE (base) != MEM_REF
3465 || TREE_CODE (base2) != MEM_REF
3466 || TREE_OPERAND (base, 0) != TREE_OPERAND (base2, 0)
3467 || !tree_int_cst_equal (TREE_OPERAND (base, 1),
3468 TREE_OPERAND (base2, 1))))
3469 || !stmt_kills_ref_p (def_stmt, ref))
3470 return (void *)-1;
3472 /* Find the common base of ref and the lhs. lhs_ops already
3473 contains valueized operands for the lhs. */
3474 i = vr->operands.length () - 1;
3475 j = lhs_ops.length () - 1;
3476 while (j >= 0 && i >= 0
3477 && vn_reference_op_eq (&vr->operands[i], &lhs_ops[j]))
3479 i--;
3480 j--;
3483 /* ??? The innermost op should always be a MEM_REF and we already
3484 checked that the assignment to the lhs kills vr. Thus for
3485 aggregate copies using char[] types the vn_reference_op_eq
3486 may fail when comparing types for compatibility. But we really
3487 don't care here - further lookups with the rewritten operands
3488 will simply fail if we messed up types too badly. */
3489 poly_int64 extra_off = 0;
3490 if (j == 0 && i >= 0
3491 && lhs_ops[0].opcode == MEM_REF
3492 && maybe_ne (lhs_ops[0].off, -1))
3494 if (known_eq (lhs_ops[0].off, vr->operands[i].off))
3495 i--, j--;
3496 else if (vr->operands[i].opcode == MEM_REF
3497 && maybe_ne (vr->operands[i].off, -1))
3499 extra_off = vr->operands[i].off - lhs_ops[0].off;
3500 i--, j--;
3504 /* i now points to the first additional op.
3505 ??? LHS may not be completely contained in VR, one or more
3506 VIEW_CONVERT_EXPRs could be in its way. We could at least
3507 try handling outermost VIEW_CONVERT_EXPRs. */
3508 if (j != -1)
3509 return (void *)-1;
3511 /* Punt if the additional ops contain a storage order barrier. */
3512 for (k = i; k >= 0; k--)
3514 vro = &vr->operands[k];
3515 if (vro->opcode == VIEW_CONVERT_EXPR && vro->reverse)
3516 return (void *)-1;
3519 /* Now re-write REF to be based on the rhs of the assignment. */
3520 tree rhs1 = gimple_assign_rhs1 (def_stmt);
3521 copy_reference_ops_from_ref (rhs1, &rhs);
3523 /* Apply an extra offset to the inner MEM_REF of the RHS. */
3524 bool force_no_tbaa = false;
3525 if (maybe_ne (extra_off, 0))
3527 if (rhs.length () < 2)
3528 return (void *)-1;
3529 int ix = rhs.length () - 2;
3530 if (rhs[ix].opcode != MEM_REF
3531 || known_eq (rhs[ix].off, -1))
3532 return (void *)-1;
3533 rhs[ix].off += extra_off;
3534 rhs[ix].op0 = int_const_binop (PLUS_EXPR, rhs[ix].op0,
3535 build_int_cst (TREE_TYPE (rhs[ix].op0),
3536 extra_off));
3537 /* When we have offsetted the RHS, reading only parts of it,
3538 we can no longer use the original TBAA type, force alias-set
3539 zero. */
3540 force_no_tbaa = true;
3543 /* Save the operands since we need to use the original ones for
3544 the hash entry we use. */
3545 if (!data->saved_operands.exists ())
3546 data->saved_operands = vr->operands.copy ();
3548 /* We need to pre-pend vr->operands[0..i] to rhs. */
3549 vec<vn_reference_op_s> old = vr->operands;
3550 if (i + 1 + rhs.length () > vr->operands.length ())
3551 vr->operands.safe_grow (i + 1 + rhs.length (), true);
3552 else
3553 vr->operands.truncate (i + 1 + rhs.length ());
3554 FOR_EACH_VEC_ELT (rhs, j, vro)
3555 vr->operands[i + 1 + j] = *vro;
3556 valueize_refs (&vr->operands);
3557 if (old == shared_lookup_references)
3558 shared_lookup_references = vr->operands;
3559 vr->hashcode = vn_reference_compute_hash (vr);
3561 /* Try folding the new reference to a constant. */
3562 tree val = fully_constant_vn_reference_p (vr);
3563 if (val)
3565 if (data->partial_defs.is_empty ())
3566 return data->finish (ao_ref_alias_set (&lhs_ref),
3567 ao_ref_base_alias_set (&lhs_ref), val);
3568 /* This is the only interesting case for partial-def handling
3569 coming from targets that like to gimplify init-ctors as
3570 aggregate copies from constant data like aarch64 for
3571 PR83518. */
3572 if (maxsize.is_constant (&maxsizei) && known_eq (ref->size, maxsize))
3574 pd_data pd;
3575 pd.rhs = val;
3576 pd.rhs_off = 0;
3577 pd.offset = 0;
3578 pd.size = maxsizei;
3579 return data->push_partial_def (pd, ao_ref_alias_set (&lhs_ref),
3580 ao_ref_base_alias_set (&lhs_ref),
3581 0, maxsizei);
3585 /* Continuing with partial defs isn't easily possible here, we
3586 have to find a full def from further lookups from here. Probably
3587 not worth the special-casing everywhere. */
3588 if (!data->partial_defs.is_empty ())
3589 return (void *)-1;
3591 /* Adjust *ref from the new operands. */
3592 ao_ref rhs1_ref;
3593 ao_ref_init (&rhs1_ref, rhs1);
3594 if (!ao_ref_init_from_vn_reference (&r,
3595 force_no_tbaa ? 0
3596 : ao_ref_alias_set (&rhs1_ref),
3597 force_no_tbaa ? 0
3598 : ao_ref_base_alias_set (&rhs1_ref),
3599 vr->type, vr->operands))
3600 return (void *)-1;
3601 /* This can happen with bitfields. */
3602 if (maybe_ne (ref->size, r.size))
3604 /* If the access lacks some subsetting simply apply that by
3605 shortening it. That in the end can only be successful
3606 if we can pun the lookup result which in turn requires
3607 exact offsets. */
3608 if (known_eq (r.size, r.max_size)
3609 && known_lt (ref->size, r.size))
3610 r.size = r.max_size = ref->size;
3611 else
3612 return (void *)-1;
3614 *ref = r;
3616 /* Do not update last seen VUSE after translating. */
3617 data->last_vuse_ptr = NULL;
3618 /* Invalidate the original access path since it now contains
3619 the wrong base. */
3620 data->orig_ref.ref = NULL_TREE;
3621 /* Use the alias-set of this LHS for recording an eventual result. */
3622 if (data->first_set == -2)
3624 data->first_set = ao_ref_alias_set (&lhs_ref);
3625 data->first_base_set = ao_ref_base_alias_set (&lhs_ref);
3628 /* Keep looking for the adjusted *REF / VR pair. */
3629 return NULL;
3632 /* 6) For memcpy copies translate the reference through them if the copy
3633 kills ref. But we cannot (easily) do this translation if the memcpy is
3634 a storage order barrier, i.e. is equivalent to a VIEW_CONVERT_EXPR that
3635 can modify the storage order of objects (see storage_order_barrier_p). */
3636 else if (data->vn_walk_kind == VN_WALKREWRITE
3637 && is_gimple_reg_type (vr->type)
3638 /* ??? Handle BCOPY as well. */
3639 && (gimple_call_builtin_p (def_stmt, BUILT_IN_MEMCPY)
3640 || gimple_call_builtin_p (def_stmt, BUILT_IN_MEMCPY_CHK)
3641 || gimple_call_builtin_p (def_stmt, BUILT_IN_MEMPCPY)
3642 || gimple_call_builtin_p (def_stmt, BUILT_IN_MEMPCPY_CHK)
3643 || gimple_call_builtin_p (def_stmt, BUILT_IN_MEMMOVE)
3644 || gimple_call_builtin_p (def_stmt, BUILT_IN_MEMMOVE_CHK))
3645 && (TREE_CODE (gimple_call_arg (def_stmt, 0)) == ADDR_EXPR
3646 || TREE_CODE (gimple_call_arg (def_stmt, 0)) == SSA_NAME)
3647 && (TREE_CODE (gimple_call_arg (def_stmt, 1)) == ADDR_EXPR
3648 || TREE_CODE (gimple_call_arg (def_stmt, 1)) == SSA_NAME)
3649 && (poly_int_tree_p (gimple_call_arg (def_stmt, 2), &copy_size)
3650 || (TREE_CODE (gimple_call_arg (def_stmt, 2)) == SSA_NAME
3651 && poly_int_tree_p (SSA_VAL (gimple_call_arg (def_stmt, 2)),
3652 &copy_size)))
3653 /* Handling this is more complicated, give up for now. */
3654 && data->partial_defs.is_empty ())
3656 tree lhs, rhs;
3657 ao_ref r;
3658 poly_int64 rhs_offset, lhs_offset;
3659 vn_reference_op_s op;
3660 poly_uint64 mem_offset;
3661 poly_int64 at, byte_maxsize;
3663 /* Only handle non-variable, addressable refs. */
3664 if (maybe_ne (ref->size, maxsize)
3665 || !multiple_p (offset, BITS_PER_UNIT, &at)
3666 || !multiple_p (maxsize, BITS_PER_UNIT, &byte_maxsize))
3667 return (void *)-1;
3669 /* Extract a pointer base and an offset for the destination. */
3670 lhs = gimple_call_arg (def_stmt, 0);
3671 lhs_offset = 0;
3672 if (TREE_CODE (lhs) == SSA_NAME)
3674 lhs = vn_valueize (lhs);
3675 if (TREE_CODE (lhs) == SSA_NAME)
3677 gimple *def_stmt = SSA_NAME_DEF_STMT (lhs);
3678 if (gimple_assign_single_p (def_stmt)
3679 && gimple_assign_rhs_code (def_stmt) == ADDR_EXPR)
3680 lhs = gimple_assign_rhs1 (def_stmt);
3683 if (TREE_CODE (lhs) == ADDR_EXPR)
3685 if (AGGREGATE_TYPE_P (TREE_TYPE (TREE_TYPE (lhs)))
3686 && TYPE_REVERSE_STORAGE_ORDER (TREE_TYPE (TREE_TYPE (lhs))))
3687 return (void *)-1;
3688 tree tem = get_addr_base_and_unit_offset (TREE_OPERAND (lhs, 0),
3689 &lhs_offset);
3690 if (!tem)
3691 return (void *)-1;
3692 if (TREE_CODE (tem) == MEM_REF
3693 && poly_int_tree_p (TREE_OPERAND (tem, 1), &mem_offset))
3695 lhs = TREE_OPERAND (tem, 0);
3696 if (TREE_CODE (lhs) == SSA_NAME)
3697 lhs = vn_valueize (lhs);
3698 lhs_offset += mem_offset;
3700 else if (DECL_P (tem))
3701 lhs = build_fold_addr_expr (tem);
3702 else
3703 return (void *)-1;
3705 if (TREE_CODE (lhs) != SSA_NAME
3706 && TREE_CODE (lhs) != ADDR_EXPR)
3707 return (void *)-1;
3709 /* Extract a pointer base and an offset for the source. */
3710 rhs = gimple_call_arg (def_stmt, 1);
3711 rhs_offset = 0;
3712 if (TREE_CODE (rhs) == SSA_NAME)
3713 rhs = vn_valueize (rhs);
3714 if (TREE_CODE (rhs) == ADDR_EXPR)
3716 if (AGGREGATE_TYPE_P (TREE_TYPE (TREE_TYPE (rhs)))
3717 && TYPE_REVERSE_STORAGE_ORDER (TREE_TYPE (TREE_TYPE (rhs))))
3718 return (void *)-1;
3719 tree tem = get_addr_base_and_unit_offset (TREE_OPERAND (rhs, 0),
3720 &rhs_offset);
3721 if (!tem)
3722 return (void *)-1;
3723 if (TREE_CODE (tem) == MEM_REF
3724 && poly_int_tree_p (TREE_OPERAND (tem, 1), &mem_offset))
3726 rhs = TREE_OPERAND (tem, 0);
3727 rhs_offset += mem_offset;
3729 else if (DECL_P (tem)
3730 || TREE_CODE (tem) == STRING_CST)
3731 rhs = build_fold_addr_expr (tem);
3732 else
3733 return (void *)-1;
3735 if (TREE_CODE (rhs) == SSA_NAME)
3736 rhs = SSA_VAL (rhs);
3737 else if (TREE_CODE (rhs) != ADDR_EXPR)
3738 return (void *)-1;
3740 /* The bases of the destination and the references have to agree. */
3741 if (TREE_CODE (base) == MEM_REF)
3743 if (TREE_OPERAND (base, 0) != lhs
3744 || !poly_int_tree_p (TREE_OPERAND (base, 1), &mem_offset))
3745 return (void *) -1;
3746 at += mem_offset;
3748 else if (!DECL_P (base)
3749 || TREE_CODE (lhs) != ADDR_EXPR
3750 || TREE_OPERAND (lhs, 0) != base)
3751 return (void *)-1;
3753 /* If the access is completely outside of the memcpy destination
3754 area there is no aliasing. */
3755 if (!ranges_maybe_overlap_p (lhs_offset, copy_size, at, byte_maxsize))
3756 return NULL;
3757 /* And the access has to be contained within the memcpy destination. */
3758 if (!known_subrange_p (at, byte_maxsize, lhs_offset, copy_size))
3759 return (void *)-1;
3761 /* Save the operands since we need to use the original ones for
3762 the hash entry we use. */
3763 if (!data->saved_operands.exists ())
3764 data->saved_operands = vr->operands.copy ();
3766 /* Make room for 2 operands in the new reference. */
3767 if (vr->operands.length () < 2)
3769 vec<vn_reference_op_s> old = vr->operands;
3770 vr->operands.safe_grow_cleared (2, true);
3771 if (old == shared_lookup_references)
3772 shared_lookup_references = vr->operands;
3774 else
3775 vr->operands.truncate (2);
3777 /* The looked-through reference is a simple MEM_REF. */
3778 memset (&op, 0, sizeof (op));
3779 op.type = vr->type;
3780 op.opcode = MEM_REF;
3781 op.op0 = build_int_cst (ptr_type_node, at - lhs_offset + rhs_offset);
3782 op.off = at - lhs_offset + rhs_offset;
3783 vr->operands[0] = op;
3784 op.type = TREE_TYPE (rhs);
3785 op.opcode = TREE_CODE (rhs);
3786 op.op0 = rhs;
3787 op.off = -1;
3788 vr->operands[1] = op;
3789 vr->hashcode = vn_reference_compute_hash (vr);
3791 /* Try folding the new reference to a constant. */
3792 tree val = fully_constant_vn_reference_p (vr);
3793 if (val)
3794 return data->finish (0, 0, val);
3796 /* Adjust *ref from the new operands. */
3797 if (!ao_ref_init_from_vn_reference (&r, 0, 0, vr->type, vr->operands))
3798 return (void *)-1;
3799 /* This can happen with bitfields. */
3800 if (maybe_ne (ref->size, r.size))
3801 return (void *)-1;
3802 *ref = r;
3804 /* Do not update last seen VUSE after translating. */
3805 data->last_vuse_ptr = NULL;
3806 /* Invalidate the original access path since it now contains
3807 the wrong base. */
3808 data->orig_ref.ref = NULL_TREE;
3809 /* Use the alias-set of this stmt for recording an eventual result. */
3810 if (data->first_set == -2)
3812 data->first_set = 0;
3813 data->first_base_set = 0;
3816 /* Keep looking for the adjusted *REF / VR pair. */
3817 return NULL;
3820 /* Bail out and stop walking. */
3821 return (void *)-1;
3824 /* Return a reference op vector from OP that can be used for
3825 vn_reference_lookup_pieces. The caller is responsible for releasing
3826 the vector. */
3828 vec<vn_reference_op_s>
3829 vn_reference_operands_for_lookup (tree op)
3831 bool valueized;
3832 return valueize_shared_reference_ops_from_ref (op, &valueized).copy ();
3835 /* Lookup a reference operation by it's parts, in the current hash table.
3836 Returns the resulting value number if it exists in the hash table,
3837 NULL_TREE otherwise. VNRESULT will be filled in with the actual
3838 vn_reference_t stored in the hashtable if something is found. */
3840 tree
3841 vn_reference_lookup_pieces (tree vuse, alias_set_type set,
3842 alias_set_type base_set, tree type,
3843 vec<vn_reference_op_s> operands,
3844 vn_reference_t *vnresult, vn_lookup_kind kind)
3846 struct vn_reference_s vr1;
3847 vn_reference_t tmp;
3848 tree cst;
3850 if (!vnresult)
3851 vnresult = &tmp;
3852 *vnresult = NULL;
3854 vr1.vuse = vuse_ssa_val (vuse);
3855 shared_lookup_references.truncate (0);
3856 shared_lookup_references.safe_grow (operands.length (), true);
3857 memcpy (shared_lookup_references.address (),
3858 operands.address (),
3859 sizeof (vn_reference_op_s)
3860 * operands.length ());
3861 bool valueized_p;
3862 valueize_refs_1 (&shared_lookup_references, &valueized_p);
3863 vr1.operands = shared_lookup_references;
3864 vr1.type = type;
3865 vr1.set = set;
3866 vr1.base_set = base_set;
3867 vr1.hashcode = vn_reference_compute_hash (&vr1);
3868 if ((cst = fully_constant_vn_reference_p (&vr1)))
3869 return cst;
3871 vn_reference_lookup_1 (&vr1, vnresult);
3872 if (!*vnresult
3873 && kind != VN_NOWALK
3874 && vr1.vuse)
3876 ao_ref r;
3877 unsigned limit = param_sccvn_max_alias_queries_per_access;
3878 vn_walk_cb_data data (&vr1, NULL_TREE, NULL, kind, true, NULL_TREE,
3879 false);
3880 vec<vn_reference_op_s> ops_for_ref;
3881 if (!valueized_p)
3882 ops_for_ref = vr1.operands;
3883 else
3885 /* For ao_ref_from_mem we have to ensure only available SSA names
3886 end up in base and the only convenient way to make this work
3887 for PRE is to re-valueize with that in mind. */
3888 ops_for_ref.create (operands.length ());
3889 ops_for_ref.quick_grow (operands.length ());
3890 memcpy (ops_for_ref.address (),
3891 operands.address (),
3892 sizeof (vn_reference_op_s)
3893 * operands.length ());
3894 valueize_refs_1 (&ops_for_ref, &valueized_p, true);
3896 if (ao_ref_init_from_vn_reference (&r, set, base_set, type,
3897 ops_for_ref))
3898 *vnresult
3899 = ((vn_reference_t)
3900 walk_non_aliased_vuses (&r, vr1.vuse, true, vn_reference_lookup_2,
3901 vn_reference_lookup_3, vuse_valueize,
3902 limit, &data));
3903 if (ops_for_ref != shared_lookup_references)
3904 ops_for_ref.release ();
3905 gcc_checking_assert (vr1.operands == shared_lookup_references);
3906 if (*vnresult
3907 && data.same_val
3908 && (!(*vnresult)->result
3909 || !operand_equal_p ((*vnresult)->result, data.same_val)))
3911 *vnresult = NULL;
3912 return NULL_TREE;
3916 if (*vnresult)
3917 return (*vnresult)->result;
3919 return NULL_TREE;
3922 /* Lookup OP in the current hash table, and return the resulting value
3923 number if it exists in the hash table. Return NULL_TREE if it does
3924 not exist in the hash table or if the result field of the structure
3925 was NULL.. VNRESULT will be filled in with the vn_reference_t
3926 stored in the hashtable if one exists. When TBAA_P is false assume
3927 we are looking up a store and treat it as having alias-set zero.
3928 *LAST_VUSE_PTR will be updated with the VUSE the value lookup succeeded.
3929 MASK is either NULL_TREE, or can be an INTEGER_CST if the result of the
3930 load is bitwise anded with MASK and so we are only interested in a subset
3931 of the bits and can ignore if the other bits are uninitialized or
3932 not initialized with constants. When doing redundant store removal
3933 the caller has to set REDUNDANT_STORE_REMOVAL_P. */
3935 tree
3936 vn_reference_lookup (tree op, tree vuse, vn_lookup_kind kind,
3937 vn_reference_t *vnresult, bool tbaa_p,
3938 tree *last_vuse_ptr, tree mask,
3939 bool redundant_store_removal_p)
3941 vec<vn_reference_op_s> operands;
3942 struct vn_reference_s vr1;
3943 bool valueized_anything;
3945 if (vnresult)
3946 *vnresult = NULL;
3948 vr1.vuse = vuse_ssa_val (vuse);
3949 vr1.operands = operands
3950 = valueize_shared_reference_ops_from_ref (op, &valueized_anything);
3952 /* Handle &MEM[ptr + 5].b[1].c as POINTER_PLUS_EXPR. Avoid doing
3953 this before the pass folding __builtin_object_size had a chance to run. */
3954 if ((cfun->curr_properties & PROP_objsz)
3955 && operands[0].opcode == ADDR_EXPR
3956 && operands.last ().opcode == SSA_NAME)
3958 poly_int64 off = 0;
3959 vn_reference_op_t vro;
3960 unsigned i;
3961 for (i = 1; operands.iterate (i, &vro); ++i)
3963 if (vro->opcode == SSA_NAME)
3964 break;
3965 else if (known_eq (vro->off, -1))
3966 break;
3967 off += vro->off;
3969 if (i == operands.length () - 1
3970 /* Make sure we the offset we accumulated in a 64bit int
3971 fits the address computation carried out in target
3972 offset precision. */
3973 && (off.coeffs[0]
3974 == sext_hwi (off.coeffs[0], TYPE_PRECISION (sizetype))))
3976 gcc_assert (operands[i-1].opcode == MEM_REF);
3977 tree ops[2];
3978 ops[0] = operands[i].op0;
3979 ops[1] = wide_int_to_tree (sizetype, off);
3980 tree res = vn_nary_op_lookup_pieces (2, POINTER_PLUS_EXPR,
3981 TREE_TYPE (op), ops, NULL);
3982 if (res)
3983 return res;
3984 return NULL_TREE;
3988 vr1.type = TREE_TYPE (op);
3989 ao_ref op_ref;
3990 ao_ref_init (&op_ref, op);
3991 vr1.set = ao_ref_alias_set (&op_ref);
3992 vr1.base_set = ao_ref_base_alias_set (&op_ref);
3993 vr1.hashcode = vn_reference_compute_hash (&vr1);
3994 if (mask == NULL_TREE)
3995 if (tree cst = fully_constant_vn_reference_p (&vr1))
3996 return cst;
3998 if (kind != VN_NOWALK && vr1.vuse)
4000 vn_reference_t wvnresult;
4001 ao_ref r;
4002 unsigned limit = param_sccvn_max_alias_queries_per_access;
4003 auto_vec<vn_reference_op_s> ops_for_ref;
4004 if (valueized_anything)
4006 copy_reference_ops_from_ref (op, &ops_for_ref);
4007 bool tem;
4008 valueize_refs_1 (&ops_for_ref, &tem, true);
4010 /* Make sure to use a valueized reference if we valueized anything.
4011 Otherwise preserve the full reference for advanced TBAA. */
4012 if (!valueized_anything
4013 || !ao_ref_init_from_vn_reference (&r, vr1.set, vr1.base_set,
4014 vr1.type, ops_for_ref))
4015 ao_ref_init (&r, op);
4016 vn_walk_cb_data data (&vr1, r.ref ? NULL_TREE : op,
4017 last_vuse_ptr, kind, tbaa_p, mask,
4018 redundant_store_removal_p);
4020 wvnresult
4021 = ((vn_reference_t)
4022 walk_non_aliased_vuses (&r, vr1.vuse, tbaa_p, vn_reference_lookup_2,
4023 vn_reference_lookup_3, vuse_valueize, limit,
4024 &data));
4025 gcc_checking_assert (vr1.operands == shared_lookup_references);
4026 if (wvnresult)
4028 gcc_assert (mask == NULL_TREE);
4029 if (data.same_val
4030 && (!wvnresult->result
4031 || !operand_equal_p (wvnresult->result, data.same_val)))
4032 return NULL_TREE;
4033 if (vnresult)
4034 *vnresult = wvnresult;
4035 return wvnresult->result;
4037 else if (mask)
4038 return data.masked_result;
4040 return NULL_TREE;
4043 if (last_vuse_ptr)
4044 *last_vuse_ptr = vr1.vuse;
4045 if (mask)
4046 return NULL_TREE;
4047 return vn_reference_lookup_1 (&vr1, vnresult);
4050 /* Lookup CALL in the current hash table and return the entry in
4051 *VNRESULT if found. Populates *VR for the hashtable lookup. */
4053 void
4054 vn_reference_lookup_call (gcall *call, vn_reference_t *vnresult,
4055 vn_reference_t vr)
4057 if (vnresult)
4058 *vnresult = NULL;
4060 tree vuse = gimple_vuse (call);
4062 vr->vuse = vuse ? SSA_VAL (vuse) : NULL_TREE;
4063 vr->operands = valueize_shared_reference_ops_from_call (call);
4064 tree lhs = gimple_call_lhs (call);
4065 /* For non-SSA return values the referece ops contain the LHS. */
4066 vr->type = ((lhs && TREE_CODE (lhs) == SSA_NAME)
4067 ? TREE_TYPE (lhs) : NULL_TREE);
4068 vr->punned = false;
4069 vr->set = 0;
4070 vr->base_set = 0;
4071 vr->hashcode = vn_reference_compute_hash (vr);
4072 vn_reference_lookup_1 (vr, vnresult);
4075 /* Insert OP into the current hash table with a value number of RESULT. */
4077 static void
4078 vn_reference_insert (tree op, tree result, tree vuse, tree vdef)
4080 vn_reference_s **slot;
4081 vn_reference_t vr1;
4082 bool tem;
4084 vec<vn_reference_op_s> operands
4085 = valueize_shared_reference_ops_from_ref (op, &tem);
4086 /* Handle &MEM[ptr + 5].b[1].c as POINTER_PLUS_EXPR. Avoid doing this
4087 before the pass folding __builtin_object_size had a chance to run. */
4088 if ((cfun->curr_properties & PROP_objsz)
4089 && operands[0].opcode == ADDR_EXPR
4090 && operands.last ().opcode == SSA_NAME)
4092 poly_int64 off = 0;
4093 vn_reference_op_t vro;
4094 unsigned i;
4095 for (i = 1; operands.iterate (i, &vro); ++i)
4097 if (vro->opcode == SSA_NAME)
4098 break;
4099 else if (known_eq (vro->off, -1))
4100 break;
4101 off += vro->off;
4103 if (i == operands.length () - 1
4104 /* Make sure we the offset we accumulated in a 64bit int
4105 fits the address computation carried out in target
4106 offset precision. */
4107 && (off.coeffs[0]
4108 == sext_hwi (off.coeffs[0], TYPE_PRECISION (sizetype))))
4110 gcc_assert (operands[i-1].opcode == MEM_REF);
4111 tree ops[2];
4112 ops[0] = operands[i].op0;
4113 ops[1] = wide_int_to_tree (sizetype, off);
4114 vn_nary_op_insert_pieces (2, POINTER_PLUS_EXPR,
4115 TREE_TYPE (op), ops, result,
4116 VN_INFO (result)->value_id);
4117 return;
4121 vr1 = XOBNEW (&vn_tables_obstack, vn_reference_s);
4122 if (TREE_CODE (result) == SSA_NAME)
4123 vr1->value_id = VN_INFO (result)->value_id;
4124 else
4125 vr1->value_id = get_or_alloc_constant_value_id (result);
4126 vr1->vuse = vuse_ssa_val (vuse);
4127 vr1->operands = operands.copy ();
4128 vr1->type = TREE_TYPE (op);
4129 vr1->punned = false;
4130 ao_ref op_ref;
4131 ao_ref_init (&op_ref, op);
4132 vr1->set = ao_ref_alias_set (&op_ref);
4133 vr1->base_set = ao_ref_base_alias_set (&op_ref);
4134 vr1->hashcode = vn_reference_compute_hash (vr1);
4135 vr1->result = TREE_CODE (result) == SSA_NAME ? SSA_VAL (result) : result;
4136 vr1->result_vdef = vdef;
4138 slot = valid_info->references->find_slot_with_hash (vr1, vr1->hashcode,
4139 INSERT);
4141 /* Because IL walking on reference lookup can end up visiting
4142 a def that is only to be visited later in iteration order
4143 when we are about to make an irreducible region reducible
4144 the def can be effectively processed and its ref being inserted
4145 by vn_reference_lookup_3 already. So we cannot assert (!*slot)
4146 but save a lookup if we deal with already inserted refs here. */
4147 if (*slot)
4149 /* We cannot assert that we have the same value either because
4150 when disentangling an irreducible region we may end up visiting
4151 a use before the corresponding def. That's a missed optimization
4152 only though. See gcc.dg/tree-ssa/pr87126.c for example. */
4153 if (dump_file && (dump_flags & TDF_DETAILS)
4154 && !operand_equal_p ((*slot)->result, vr1->result, 0))
4156 fprintf (dump_file, "Keeping old value ");
4157 print_generic_expr (dump_file, (*slot)->result);
4158 fprintf (dump_file, " because of collision\n");
4160 free_reference (vr1);
4161 obstack_free (&vn_tables_obstack, vr1);
4162 return;
4165 *slot = vr1;
4166 vr1->next = last_inserted_ref;
4167 last_inserted_ref = vr1;
4170 /* Insert a reference by it's pieces into the current hash table with
4171 a value number of RESULT. Return the resulting reference
4172 structure we created. */
4174 vn_reference_t
4175 vn_reference_insert_pieces (tree vuse, alias_set_type set,
4176 alias_set_type base_set, tree type,
4177 vec<vn_reference_op_s> operands,
4178 tree result, unsigned int value_id)
4181 vn_reference_s **slot;
4182 vn_reference_t vr1;
4184 vr1 = XOBNEW (&vn_tables_obstack, vn_reference_s);
4185 vr1->value_id = value_id;
4186 vr1->vuse = vuse_ssa_val (vuse);
4187 vr1->operands = operands;
4188 valueize_refs (&vr1->operands);
4189 vr1->type = type;
4190 vr1->punned = false;
4191 vr1->set = set;
4192 vr1->base_set = base_set;
4193 vr1->hashcode = vn_reference_compute_hash (vr1);
4194 if (result && TREE_CODE (result) == SSA_NAME)
4195 result = SSA_VAL (result);
4196 vr1->result = result;
4197 vr1->result_vdef = NULL_TREE;
4199 slot = valid_info->references->find_slot_with_hash (vr1, vr1->hashcode,
4200 INSERT);
4202 /* At this point we should have all the things inserted that we have
4203 seen before, and we should never try inserting something that
4204 already exists. */
4205 gcc_assert (!*slot);
4207 *slot = vr1;
4208 vr1->next = last_inserted_ref;
4209 last_inserted_ref = vr1;
4210 return vr1;
4213 /* Compute and return the hash value for nary operation VBO1. */
4215 hashval_t
4216 vn_nary_op_compute_hash (const vn_nary_op_t vno1)
4218 inchash::hash hstate;
4219 unsigned i;
4221 if (((vno1->length == 2
4222 && commutative_tree_code (vno1->opcode))
4223 || (vno1->length == 3
4224 && commutative_ternary_tree_code (vno1->opcode)))
4225 && tree_swap_operands_p (vno1->op[0], vno1->op[1]))
4226 std::swap (vno1->op[0], vno1->op[1]);
4227 else if (TREE_CODE_CLASS (vno1->opcode) == tcc_comparison
4228 && tree_swap_operands_p (vno1->op[0], vno1->op[1]))
4230 std::swap (vno1->op[0], vno1->op[1]);
4231 vno1->opcode = swap_tree_comparison (vno1->opcode);
4234 hstate.add_int (vno1->opcode);
4235 for (i = 0; i < vno1->length; ++i)
4236 inchash::add_expr (vno1->op[i], hstate);
4238 return hstate.end ();
4241 /* Compare nary operations VNO1 and VNO2 and return true if they are
4242 equivalent. */
4244 bool
4245 vn_nary_op_eq (const_vn_nary_op_t const vno1, const_vn_nary_op_t const vno2)
4247 unsigned i;
4249 if (vno1->hashcode != vno2->hashcode)
4250 return false;
4252 if (vno1->length != vno2->length)
4253 return false;
4255 if (vno1->opcode != vno2->opcode
4256 || !types_compatible_p (vno1->type, vno2->type))
4257 return false;
4259 for (i = 0; i < vno1->length; ++i)
4260 if (!expressions_equal_p (vno1->op[i], vno2->op[i]))
4261 return false;
4263 /* BIT_INSERT_EXPR has an implict operand as the type precision
4264 of op1. Need to check to make sure they are the same. */
4265 if (vno1->opcode == BIT_INSERT_EXPR
4266 && TREE_CODE (vno1->op[1]) == INTEGER_CST
4267 && TYPE_PRECISION (TREE_TYPE (vno1->op[1]))
4268 != TYPE_PRECISION (TREE_TYPE (vno2->op[1])))
4269 return false;
4271 return true;
4274 /* Initialize VNO from the pieces provided. */
4276 static void
4277 init_vn_nary_op_from_pieces (vn_nary_op_t vno, unsigned int length,
4278 enum tree_code code, tree type, tree *ops)
4280 vno->opcode = code;
4281 vno->length = length;
4282 vno->type = type;
4283 memcpy (&vno->op[0], ops, sizeof (tree) * length);
4286 /* Return the number of operands for a vn_nary ops structure from STMT. */
4288 unsigned int
4289 vn_nary_length_from_stmt (gimple *stmt)
4291 switch (gimple_assign_rhs_code (stmt))
4293 case REALPART_EXPR:
4294 case IMAGPART_EXPR:
4295 case VIEW_CONVERT_EXPR:
4296 return 1;
4298 case BIT_FIELD_REF:
4299 return 3;
4301 case CONSTRUCTOR:
4302 return CONSTRUCTOR_NELTS (gimple_assign_rhs1 (stmt));
4304 default:
4305 return gimple_num_ops (stmt) - 1;
4309 /* Initialize VNO from STMT. */
4311 void
4312 init_vn_nary_op_from_stmt (vn_nary_op_t vno, gassign *stmt)
4314 unsigned i;
4316 vno->opcode = gimple_assign_rhs_code (stmt);
4317 vno->type = TREE_TYPE (gimple_assign_lhs (stmt));
4318 switch (vno->opcode)
4320 case REALPART_EXPR:
4321 case IMAGPART_EXPR:
4322 case VIEW_CONVERT_EXPR:
4323 vno->length = 1;
4324 vno->op[0] = TREE_OPERAND (gimple_assign_rhs1 (stmt), 0);
4325 break;
4327 case BIT_FIELD_REF:
4328 vno->length = 3;
4329 vno->op[0] = TREE_OPERAND (gimple_assign_rhs1 (stmt), 0);
4330 vno->op[1] = TREE_OPERAND (gimple_assign_rhs1 (stmt), 1);
4331 vno->op[2] = TREE_OPERAND (gimple_assign_rhs1 (stmt), 2);
4332 break;
4334 case CONSTRUCTOR:
4335 vno->length = CONSTRUCTOR_NELTS (gimple_assign_rhs1 (stmt));
4336 for (i = 0; i < vno->length; ++i)
4337 vno->op[i] = CONSTRUCTOR_ELT (gimple_assign_rhs1 (stmt), i)->value;
4338 break;
4340 default:
4341 gcc_checking_assert (!gimple_assign_single_p (stmt));
4342 vno->length = gimple_num_ops (stmt) - 1;
4343 for (i = 0; i < vno->length; ++i)
4344 vno->op[i] = gimple_op (stmt, i + 1);
4348 /* Compute the hashcode for VNO and look for it in the hash table;
4349 return the resulting value number if it exists in the hash table.
4350 Return NULL_TREE if it does not exist in the hash table or if the
4351 result field of the operation is NULL. VNRESULT will contain the
4352 vn_nary_op_t from the hashtable if it exists. */
4354 static tree
4355 vn_nary_op_lookup_1 (vn_nary_op_t vno, vn_nary_op_t *vnresult)
4357 vn_nary_op_s **slot;
4359 if (vnresult)
4360 *vnresult = NULL;
4362 for (unsigned i = 0; i < vno->length; ++i)
4363 if (TREE_CODE (vno->op[i]) == SSA_NAME)
4364 vno->op[i] = SSA_VAL (vno->op[i]);
4366 vno->hashcode = vn_nary_op_compute_hash (vno);
4367 slot = valid_info->nary->find_slot_with_hash (vno, vno->hashcode, NO_INSERT);
4368 if (!slot)
4369 return NULL_TREE;
4370 if (vnresult)
4371 *vnresult = *slot;
4372 return (*slot)->predicated_values ? NULL_TREE : (*slot)->u.result;
4375 /* Lookup a n-ary operation by its pieces and return the resulting value
4376 number if it exists in the hash table. Return NULL_TREE if it does
4377 not exist in the hash table or if the result field of the operation
4378 is NULL. VNRESULT will contain the vn_nary_op_t from the hashtable
4379 if it exists. */
4381 tree
4382 vn_nary_op_lookup_pieces (unsigned int length, enum tree_code code,
4383 tree type, tree *ops, vn_nary_op_t *vnresult)
4385 vn_nary_op_t vno1 = XALLOCAVAR (struct vn_nary_op_s,
4386 sizeof_vn_nary_op (length));
4387 init_vn_nary_op_from_pieces (vno1, length, code, type, ops);
4388 return vn_nary_op_lookup_1 (vno1, vnresult);
4391 /* Lookup the rhs of STMT in the current hash table, and return the resulting
4392 value number if it exists in the hash table. Return NULL_TREE if
4393 it does not exist in the hash table. VNRESULT will contain the
4394 vn_nary_op_t from the hashtable if it exists. */
4396 tree
4397 vn_nary_op_lookup_stmt (gimple *stmt, vn_nary_op_t *vnresult)
4399 vn_nary_op_t vno1
4400 = XALLOCAVAR (struct vn_nary_op_s,
4401 sizeof_vn_nary_op (vn_nary_length_from_stmt (stmt)));
4402 init_vn_nary_op_from_stmt (vno1, as_a <gassign *> (stmt));
4403 return vn_nary_op_lookup_1 (vno1, vnresult);
4406 /* Allocate a vn_nary_op_t with LENGTH operands on STACK. */
4408 vn_nary_op_t
4409 alloc_vn_nary_op_noinit (unsigned int length, struct obstack *stack)
4411 return (vn_nary_op_t) obstack_alloc (stack, sizeof_vn_nary_op (length));
4414 /* Allocate and initialize a vn_nary_op_t on CURRENT_INFO's
4415 obstack. */
4417 static vn_nary_op_t
4418 alloc_vn_nary_op (unsigned int length, tree result, unsigned int value_id)
4420 vn_nary_op_t vno1 = alloc_vn_nary_op_noinit (length, &vn_tables_obstack);
4422 vno1->value_id = value_id;
4423 vno1->length = length;
4424 vno1->predicated_values = 0;
4425 vno1->u.result = result;
4427 return vno1;
4430 /* Insert VNO into TABLE. */
4432 static vn_nary_op_t
4433 vn_nary_op_insert_into (vn_nary_op_t vno, vn_nary_op_table_type *table)
4435 vn_nary_op_s **slot;
4437 gcc_assert (! vno->predicated_values
4438 || (! vno->u.values->next
4439 && vno->u.values->n == 1));
4441 for (unsigned i = 0; i < vno->length; ++i)
4442 if (TREE_CODE (vno->op[i]) == SSA_NAME)
4443 vno->op[i] = SSA_VAL (vno->op[i]);
4445 vno->hashcode = vn_nary_op_compute_hash (vno);
4446 slot = table->find_slot_with_hash (vno, vno->hashcode, INSERT);
4447 vno->unwind_to = *slot;
4448 if (*slot)
4450 /* Prefer non-predicated values.
4451 ??? Only if those are constant, otherwise, with constant predicated
4452 value, turn them into predicated values with entry-block validity
4453 (??? but we always find the first valid result currently). */
4454 if ((*slot)->predicated_values
4455 && ! vno->predicated_values)
4457 /* ??? We cannot remove *slot from the unwind stack list.
4458 For the moment we deal with this by skipping not found
4459 entries but this isn't ideal ... */
4460 *slot = vno;
4461 /* ??? Maintain a stack of states we can unwind in
4462 vn_nary_op_s? But how far do we unwind? In reality
4463 we need to push change records somewhere... Or not
4464 unwind vn_nary_op_s and linking them but instead
4465 unwind the results "list", linking that, which also
4466 doesn't move on hashtable resize. */
4467 /* We can also have a ->unwind_to recording *slot there.
4468 That way we can make u.values a fixed size array with
4469 recording the number of entries but of course we then
4470 have always N copies for each unwind_to-state. Or we
4471 make sure to only ever append and each unwinding will
4472 pop off one entry (but how to deal with predicated
4473 replaced with non-predicated here?) */
4474 vno->next = last_inserted_nary;
4475 last_inserted_nary = vno;
4476 return vno;
4478 else if (vno->predicated_values
4479 && ! (*slot)->predicated_values)
4480 return *slot;
4481 else if (vno->predicated_values
4482 && (*slot)->predicated_values)
4484 /* ??? Factor this all into a insert_single_predicated_value
4485 routine. */
4486 gcc_assert (!vno->u.values->next && vno->u.values->n == 1);
4487 basic_block vno_bb
4488 = BASIC_BLOCK_FOR_FN (cfun, vno->u.values->valid_dominated_by_p[0]);
4489 vn_pval *nval = vno->u.values;
4490 vn_pval **next = &vno->u.values;
4491 bool found = false;
4492 for (vn_pval *val = (*slot)->u.values; val; val = val->next)
4494 if (expressions_equal_p (val->result, nval->result))
4496 found = true;
4497 for (unsigned i = 0; i < val->n; ++i)
4499 basic_block val_bb
4500 = BASIC_BLOCK_FOR_FN (cfun,
4501 val->valid_dominated_by_p[i]);
4502 if (dominated_by_p (CDI_DOMINATORS, vno_bb, val_bb))
4503 /* Value registered with more generic predicate. */
4504 return *slot;
4505 else if (flag_checking)
4506 /* Shouldn't happen, we insert in RPO order. */
4507 gcc_assert (!dominated_by_p (CDI_DOMINATORS,
4508 val_bb, vno_bb));
4510 /* Append value. */
4511 *next = (vn_pval *) obstack_alloc (&vn_tables_obstack,
4512 sizeof (vn_pval)
4513 + val->n * sizeof (int));
4514 (*next)->next = NULL;
4515 (*next)->result = val->result;
4516 (*next)->n = val->n + 1;
4517 memcpy ((*next)->valid_dominated_by_p,
4518 val->valid_dominated_by_p,
4519 val->n * sizeof (int));
4520 (*next)->valid_dominated_by_p[val->n] = vno_bb->index;
4521 next = &(*next)->next;
4522 if (dump_file && (dump_flags & TDF_DETAILS))
4523 fprintf (dump_file, "Appending predicate to value.\n");
4524 continue;
4526 /* Copy other predicated values. */
4527 *next = (vn_pval *) obstack_alloc (&vn_tables_obstack,
4528 sizeof (vn_pval)
4529 + (val->n-1) * sizeof (int));
4530 memcpy (*next, val, sizeof (vn_pval) + (val->n-1) * sizeof (int));
4531 (*next)->next = NULL;
4532 next = &(*next)->next;
4534 if (!found)
4535 *next = nval;
4537 *slot = vno;
4538 vno->next = last_inserted_nary;
4539 last_inserted_nary = vno;
4540 return vno;
4543 /* While we do not want to insert things twice it's awkward to
4544 avoid it in the case where visit_nary_op pattern-matches stuff
4545 and ends up simplifying the replacement to itself. We then
4546 get two inserts, one from visit_nary_op and one from
4547 vn_nary_build_or_lookup.
4548 So allow inserts with the same value number. */
4549 if ((*slot)->u.result == vno->u.result)
4550 return *slot;
4553 /* ??? There's also optimistic vs. previous commited state merging
4554 that is problematic for the case of unwinding. */
4556 /* ??? We should return NULL if we do not use 'vno' and have the
4557 caller release it. */
4558 gcc_assert (!*slot);
4560 *slot = vno;
4561 vno->next = last_inserted_nary;
4562 last_inserted_nary = vno;
4563 return vno;
4566 /* Insert a n-ary operation into the current hash table using it's
4567 pieces. Return the vn_nary_op_t structure we created and put in
4568 the hashtable. */
4570 vn_nary_op_t
4571 vn_nary_op_insert_pieces (unsigned int length, enum tree_code code,
4572 tree type, tree *ops,
4573 tree result, unsigned int value_id)
4575 vn_nary_op_t vno1 = alloc_vn_nary_op (length, result, value_id);
4576 init_vn_nary_op_from_pieces (vno1, length, code, type, ops);
4577 return vn_nary_op_insert_into (vno1, valid_info->nary);
4580 /* Return whether we can track a predicate valid when PRED_E is executed. */
4582 static bool
4583 can_track_predicate_on_edge (edge pred_e)
4585 /* ??? As we are currently recording the destination basic-block index in
4586 vn_pval.valid_dominated_by_p and using dominance for the
4587 validity check we cannot track predicates on all edges. */
4588 if (single_pred_p (pred_e->dest))
4589 return true;
4590 /* Never record for backedges. */
4591 if (pred_e->flags & EDGE_DFS_BACK)
4592 return false;
4593 /* When there's more than one predecessor we cannot track
4594 predicate validity based on the destination block. The
4595 exception is when all other incoming edges sources are
4596 dominated by the destination block. */
4597 edge_iterator ei;
4598 edge e;
4599 FOR_EACH_EDGE (e, ei, pred_e->dest->preds)
4600 if (e != pred_e && ! dominated_by_p (CDI_DOMINATORS, e->src, e->dest))
4601 return false;
4602 return true;
4605 static vn_nary_op_t
4606 vn_nary_op_insert_pieces_predicated (unsigned int length, enum tree_code code,
4607 tree type, tree *ops,
4608 tree result, unsigned int value_id,
4609 edge pred_e)
4611 gcc_assert (can_track_predicate_on_edge (pred_e));
4613 if (dump_file && (dump_flags & TDF_DETAILS)
4614 /* ??? Fix dumping, but currently we only get comparisons. */
4615 && TREE_CODE_CLASS (code) == tcc_comparison)
4617 fprintf (dump_file, "Recording on edge %d->%d ", pred_e->src->index,
4618 pred_e->dest->index);
4619 print_generic_expr (dump_file, ops[0], TDF_SLIM);
4620 fprintf (dump_file, " %s ", get_tree_code_name (code));
4621 print_generic_expr (dump_file, ops[1], TDF_SLIM);
4622 fprintf (dump_file, " == %s\n",
4623 integer_zerop (result) ? "false" : "true");
4625 vn_nary_op_t vno1 = alloc_vn_nary_op (length, NULL_TREE, value_id);
4626 init_vn_nary_op_from_pieces (vno1, length, code, type, ops);
4627 vno1->predicated_values = 1;
4628 vno1->u.values = (vn_pval *) obstack_alloc (&vn_tables_obstack,
4629 sizeof (vn_pval));
4630 vno1->u.values->next = NULL;
4631 vno1->u.values->result = result;
4632 vno1->u.values->n = 1;
4633 vno1->u.values->valid_dominated_by_p[0] = pred_e->dest->index;
4634 return vn_nary_op_insert_into (vno1, valid_info->nary);
4637 static bool
4638 dominated_by_p_w_unex (basic_block bb1, basic_block bb2, bool);
4640 static tree
4641 vn_nary_op_get_predicated_value (vn_nary_op_t vno, basic_block bb,
4642 edge e = NULL)
4644 if (! vno->predicated_values)
4645 return vno->u.result;
4646 for (vn_pval *val = vno->u.values; val; val = val->next)
4647 for (unsigned i = 0; i < val->n; ++i)
4649 basic_block cand
4650 = BASIC_BLOCK_FOR_FN (cfun, val->valid_dominated_by_p[i]);
4651 /* Do not handle backedge executability optimistically since
4652 when figuring out whether to iterate we do not consider
4653 changed predication.
4654 When asking for predicated values on an edge avoid looking
4655 at edge executability for edges forward in our iteration
4656 as well. */
4657 if (e && (e->flags & EDGE_DFS_BACK))
4659 if (dominated_by_p (CDI_DOMINATORS, bb, cand))
4660 return val->result;
4662 else if (dominated_by_p_w_unex (bb, cand, false))
4663 return val->result;
4665 return NULL_TREE;
4668 static tree
4669 vn_nary_op_get_predicated_value (vn_nary_op_t vno, edge e)
4671 return vn_nary_op_get_predicated_value (vno, e->src, e);
4674 /* Insert the rhs of STMT into the current hash table with a value number of
4675 RESULT. */
4677 static vn_nary_op_t
4678 vn_nary_op_insert_stmt (gimple *stmt, tree result)
4680 vn_nary_op_t vno1
4681 = alloc_vn_nary_op (vn_nary_length_from_stmt (stmt),
4682 result, VN_INFO (result)->value_id);
4683 init_vn_nary_op_from_stmt (vno1, as_a <gassign *> (stmt));
4684 return vn_nary_op_insert_into (vno1, valid_info->nary);
4687 /* Compute a hashcode for PHI operation VP1 and return it. */
4689 static inline hashval_t
4690 vn_phi_compute_hash (vn_phi_t vp1)
4692 inchash::hash hstate;
4693 tree phi1op;
4694 tree type;
4695 edge e;
4696 edge_iterator ei;
4698 hstate.add_int (EDGE_COUNT (vp1->block->preds));
4699 switch (EDGE_COUNT (vp1->block->preds))
4701 case 1:
4702 break;
4703 case 2:
4704 /* When this is a PHI node subject to CSE for different blocks
4705 avoid hashing the block index. */
4706 if (vp1->cclhs)
4707 break;
4708 /* Fallthru. */
4709 default:
4710 hstate.add_int (vp1->block->index);
4713 /* If all PHI arguments are constants we need to distinguish
4714 the PHI node via its type. */
4715 type = vp1->type;
4716 hstate.merge_hash (vn_hash_type (type));
4718 FOR_EACH_EDGE (e, ei, vp1->block->preds)
4720 /* Don't hash backedge values they need to be handled as VN_TOP
4721 for optimistic value-numbering. */
4722 if (e->flags & EDGE_DFS_BACK)
4723 continue;
4725 phi1op = vp1->phiargs[e->dest_idx];
4726 if (phi1op == VN_TOP)
4727 continue;
4728 inchash::add_expr (phi1op, hstate);
4731 return hstate.end ();
4735 /* Return true if COND1 and COND2 represent the same condition, set
4736 *INVERTED_P if one needs to be inverted to make it the same as
4737 the other. */
4739 static bool
4740 cond_stmts_equal_p (gcond *cond1, tree lhs1, tree rhs1,
4741 gcond *cond2, tree lhs2, tree rhs2, bool *inverted_p)
4743 enum tree_code code1 = gimple_cond_code (cond1);
4744 enum tree_code code2 = gimple_cond_code (cond2);
4746 *inverted_p = false;
4747 if (code1 == code2)
4749 else if (code1 == swap_tree_comparison (code2))
4750 std::swap (lhs2, rhs2);
4751 else if (code1 == invert_tree_comparison (code2, HONOR_NANS (lhs2)))
4752 *inverted_p = true;
4753 else if (code1 == invert_tree_comparison
4754 (swap_tree_comparison (code2), HONOR_NANS (lhs2)))
4756 std::swap (lhs2, rhs2);
4757 *inverted_p = true;
4759 else
4760 return false;
4762 return ((expressions_equal_p (lhs1, lhs2)
4763 && expressions_equal_p (rhs1, rhs2))
4764 || (commutative_tree_code (code1)
4765 && expressions_equal_p (lhs1, rhs2)
4766 && expressions_equal_p (rhs1, lhs2)));
4769 /* Compare two phi entries for equality, ignoring VN_TOP arguments. */
4771 static int
4772 vn_phi_eq (const_vn_phi_t const vp1, const_vn_phi_t const vp2)
4774 if (vp1->hashcode != vp2->hashcode)
4775 return false;
4777 if (vp1->block != vp2->block)
4779 if (EDGE_COUNT (vp1->block->preds) != EDGE_COUNT (vp2->block->preds))
4780 return false;
4782 switch (EDGE_COUNT (vp1->block->preds))
4784 case 1:
4785 /* Single-arg PHIs are just copies. */
4786 break;
4788 case 2:
4790 /* Make sure both PHIs are classified as CSEable. */
4791 if (! vp1->cclhs || ! vp2->cclhs)
4792 return false;
4794 /* Rule out backedges into the PHI. */
4795 gcc_checking_assert
4796 (vp1->block->loop_father->header != vp1->block
4797 && vp2->block->loop_father->header != vp2->block);
4799 /* If the PHI nodes do not have compatible types
4800 they are not the same. */
4801 if (!types_compatible_p (vp1->type, vp2->type))
4802 return false;
4804 /* If the immediate dominator end in switch stmts multiple
4805 values may end up in the same PHI arg via intermediate
4806 CFG merges. */
4807 basic_block idom1
4808 = get_immediate_dominator (CDI_DOMINATORS, vp1->block);
4809 basic_block idom2
4810 = get_immediate_dominator (CDI_DOMINATORS, vp2->block);
4811 gcc_checking_assert (EDGE_COUNT (idom1->succs) == 2
4812 && EDGE_COUNT (idom2->succs) == 2);
4814 /* Verify the controlling stmt is the same. */
4815 gcond *last1 = as_a <gcond *> (*gsi_last_bb (idom1));
4816 gcond *last2 = as_a <gcond *> (*gsi_last_bb (idom2));
4817 bool inverted_p;
4818 if (! cond_stmts_equal_p (last1, vp1->cclhs, vp1->ccrhs,
4819 last2, vp2->cclhs, vp2->ccrhs,
4820 &inverted_p))
4821 return false;
4823 /* Get at true/false controlled edges into the PHI. */
4824 edge te1, te2, fe1, fe2;
4825 if (! extract_true_false_controlled_edges (idom1, vp1->block,
4826 &te1, &fe1)
4827 || ! extract_true_false_controlled_edges (idom2, vp2->block,
4828 &te2, &fe2))
4829 return false;
4831 /* Swap edges if the second condition is the inverted of the
4832 first. */
4833 if (inverted_p)
4834 std::swap (te2, fe2);
4836 /* Since we do not know which edge will be executed we have
4837 to be careful when matching VN_TOP. Be conservative and
4838 only match VN_TOP == VN_TOP for now, we could allow
4839 VN_TOP on the not prevailing PHI though. See for example
4840 PR102920. */
4841 if (! expressions_equal_p (vp1->phiargs[te1->dest_idx],
4842 vp2->phiargs[te2->dest_idx], false)
4843 || ! expressions_equal_p (vp1->phiargs[fe1->dest_idx],
4844 vp2->phiargs[fe2->dest_idx], false))
4845 return false;
4847 return true;
4850 default:
4851 return false;
4855 /* If the PHI nodes do not have compatible types
4856 they are not the same. */
4857 if (!types_compatible_p (vp1->type, vp2->type))
4858 return false;
4860 /* Any phi in the same block will have it's arguments in the
4861 same edge order, because of how we store phi nodes. */
4862 unsigned nargs = EDGE_COUNT (vp1->block->preds);
4863 for (unsigned i = 0; i < nargs; ++i)
4865 tree phi1op = vp1->phiargs[i];
4866 tree phi2op = vp2->phiargs[i];
4867 if (phi1op == phi2op)
4868 continue;
4869 if (!expressions_equal_p (phi1op, phi2op, false))
4870 return false;
4873 return true;
4876 /* Lookup PHI in the current hash table, and return the resulting
4877 value number if it exists in the hash table. Return NULL_TREE if
4878 it does not exist in the hash table. */
4880 static tree
4881 vn_phi_lookup (gimple *phi, bool backedges_varying_p)
4883 vn_phi_s **slot;
4884 struct vn_phi_s *vp1;
4885 edge e;
4886 edge_iterator ei;
4888 vp1 = XALLOCAVAR (struct vn_phi_s,
4889 sizeof (struct vn_phi_s)
4890 + (gimple_phi_num_args (phi) - 1) * sizeof (tree));
4892 /* Canonicalize the SSA_NAME's to their value number. */
4893 FOR_EACH_EDGE (e, ei, gimple_bb (phi)->preds)
4895 tree def = PHI_ARG_DEF_FROM_EDGE (phi, e);
4896 if (TREE_CODE (def) == SSA_NAME
4897 && (!backedges_varying_p || !(e->flags & EDGE_DFS_BACK)))
4899 if (!virtual_operand_p (def)
4900 && ssa_undefined_value_p (def, false))
4901 def = VN_TOP;
4902 else
4903 def = SSA_VAL (def);
4905 vp1->phiargs[e->dest_idx] = def;
4907 vp1->type = TREE_TYPE (gimple_phi_result (phi));
4908 vp1->block = gimple_bb (phi);
4909 /* Extract values of the controlling condition. */
4910 vp1->cclhs = NULL_TREE;
4911 vp1->ccrhs = NULL_TREE;
4912 if (EDGE_COUNT (vp1->block->preds) == 2
4913 && vp1->block->loop_father->header != vp1->block)
4915 basic_block idom1 = get_immediate_dominator (CDI_DOMINATORS, vp1->block);
4916 if (EDGE_COUNT (idom1->succs) == 2)
4917 if (gcond *last1 = safe_dyn_cast <gcond *> (*gsi_last_bb (idom1)))
4919 /* ??? We want to use SSA_VAL here. But possibly not
4920 allow VN_TOP. */
4921 vp1->cclhs = vn_valueize (gimple_cond_lhs (last1));
4922 vp1->ccrhs = vn_valueize (gimple_cond_rhs (last1));
4925 vp1->hashcode = vn_phi_compute_hash (vp1);
4926 slot = valid_info->phis->find_slot_with_hash (vp1, vp1->hashcode, NO_INSERT);
4927 if (!slot)
4928 return NULL_TREE;
4929 return (*slot)->result;
4932 /* Insert PHI into the current hash table with a value number of
4933 RESULT. */
4935 static vn_phi_t
4936 vn_phi_insert (gimple *phi, tree result, bool backedges_varying_p)
4938 vn_phi_s **slot;
4939 vn_phi_t vp1 = (vn_phi_t) obstack_alloc (&vn_tables_obstack,
4940 sizeof (vn_phi_s)
4941 + ((gimple_phi_num_args (phi) - 1)
4942 * sizeof (tree)));
4943 edge e;
4944 edge_iterator ei;
4946 /* Canonicalize the SSA_NAME's to their value number. */
4947 FOR_EACH_EDGE (e, ei, gimple_bb (phi)->preds)
4949 tree def = PHI_ARG_DEF_FROM_EDGE (phi, e);
4950 if (TREE_CODE (def) == SSA_NAME
4951 && (!backedges_varying_p || !(e->flags & EDGE_DFS_BACK)))
4953 if (!virtual_operand_p (def)
4954 && ssa_undefined_value_p (def, false))
4955 def = VN_TOP;
4956 else
4957 def = SSA_VAL (def);
4959 vp1->phiargs[e->dest_idx] = def;
4961 vp1->value_id = VN_INFO (result)->value_id;
4962 vp1->type = TREE_TYPE (gimple_phi_result (phi));
4963 vp1->block = gimple_bb (phi);
4964 /* Extract values of the controlling condition. */
4965 vp1->cclhs = NULL_TREE;
4966 vp1->ccrhs = NULL_TREE;
4967 if (EDGE_COUNT (vp1->block->preds) == 2
4968 && vp1->block->loop_father->header != vp1->block)
4970 basic_block idom1 = get_immediate_dominator (CDI_DOMINATORS, vp1->block);
4971 if (EDGE_COUNT (idom1->succs) == 2)
4972 if (gcond *last1 = safe_dyn_cast <gcond *> (*gsi_last_bb (idom1)))
4974 /* ??? We want to use SSA_VAL here. But possibly not
4975 allow VN_TOP. */
4976 vp1->cclhs = vn_valueize (gimple_cond_lhs (last1));
4977 vp1->ccrhs = vn_valueize (gimple_cond_rhs (last1));
4980 vp1->result = result;
4981 vp1->hashcode = vn_phi_compute_hash (vp1);
4983 slot = valid_info->phis->find_slot_with_hash (vp1, vp1->hashcode, INSERT);
4984 gcc_assert (!*slot);
4986 *slot = vp1;
4987 vp1->next = last_inserted_phi;
4988 last_inserted_phi = vp1;
4989 return vp1;
4993 /* Return true if BB1 is dominated by BB2 taking into account edges
4994 that are not executable. When ALLOW_BACK is false consider not
4995 executable backedges as executable. */
4997 static bool
4998 dominated_by_p_w_unex (basic_block bb1, basic_block bb2, bool allow_back)
5000 edge_iterator ei;
5001 edge e;
5003 if (dominated_by_p (CDI_DOMINATORS, bb1, bb2))
5004 return true;
5006 /* Before iterating we'd like to know if there exists a
5007 (executable) path from bb2 to bb1 at all, if not we can
5008 directly return false. For now simply iterate once. */
5010 /* Iterate to the single executable bb1 predecessor. */
5011 if (EDGE_COUNT (bb1->preds) > 1)
5013 edge prede = NULL;
5014 FOR_EACH_EDGE (e, ei, bb1->preds)
5015 if ((e->flags & EDGE_EXECUTABLE)
5016 || (!allow_back && (e->flags & EDGE_DFS_BACK)))
5018 if (prede)
5020 prede = NULL;
5021 break;
5023 prede = e;
5025 if (prede)
5027 bb1 = prede->src;
5029 /* Re-do the dominance check with changed bb1. */
5030 if (dominated_by_p (CDI_DOMINATORS, bb1, bb2))
5031 return true;
5035 /* Iterate to the single executable bb2 successor. */
5036 if (EDGE_COUNT (bb2->succs) > 1)
5038 edge succe = NULL;
5039 FOR_EACH_EDGE (e, ei, bb2->succs)
5040 if ((e->flags & EDGE_EXECUTABLE)
5041 || (!allow_back && (e->flags & EDGE_DFS_BACK)))
5043 if (succe)
5045 succe = NULL;
5046 break;
5048 succe = e;
5050 if (succe)
5052 /* Verify the reached block is only reached through succe.
5053 If there is only one edge we can spare us the dominator
5054 check and iterate directly. */
5055 if (EDGE_COUNT (succe->dest->preds) > 1)
5057 FOR_EACH_EDGE (e, ei, succe->dest->preds)
5058 if (e != succe
5059 && ((e->flags & EDGE_EXECUTABLE)
5060 || (!allow_back && (e->flags & EDGE_DFS_BACK))))
5062 succe = NULL;
5063 break;
5066 if (succe)
5068 bb2 = succe->dest;
5070 /* Re-do the dominance check with changed bb2. */
5071 if (dominated_by_p (CDI_DOMINATORS, bb1, bb2))
5072 return true;
5077 /* We could now iterate updating bb1 / bb2. */
5078 return false;
5081 /* Set the value number of FROM to TO, return true if it has changed
5082 as a result. */
5084 static inline bool
5085 set_ssa_val_to (tree from, tree to)
5087 vn_ssa_aux_t from_info = VN_INFO (from);
5088 tree currval = from_info->valnum; // SSA_VAL (from)
5089 poly_int64 toff, coff;
5090 bool curr_undefined = false;
5091 bool curr_invariant = false;
5093 /* The only thing we allow as value numbers are ssa_names
5094 and invariants. So assert that here. We don't allow VN_TOP
5095 as visiting a stmt should produce a value-number other than
5096 that.
5097 ??? Still VN_TOP can happen for unreachable code, so force
5098 it to varying in that case. Not all code is prepared to
5099 get VN_TOP on valueization. */
5100 if (to == VN_TOP)
5102 /* ??? When iterating and visiting PHI <undef, backedge-value>
5103 for the first time we rightfully get VN_TOP and we need to
5104 preserve that to optimize for example gcc.dg/tree-ssa/ssa-sccvn-2.c.
5105 With SCCVN we were simply lucky we iterated the other PHI
5106 cycles first and thus visited the backedge-value DEF. */
5107 if (currval == VN_TOP)
5108 goto set_and_exit;
5109 if (dump_file && (dump_flags & TDF_DETAILS))
5110 fprintf (dump_file, "Forcing value number to varying on "
5111 "receiving VN_TOP\n");
5112 to = from;
5115 gcc_checking_assert (to != NULL_TREE
5116 && ((TREE_CODE (to) == SSA_NAME
5117 && (to == from || SSA_VAL (to) == to))
5118 || is_gimple_min_invariant (to)));
5120 if (from != to)
5122 if (currval == from)
5124 if (dump_file && (dump_flags & TDF_DETAILS))
5126 fprintf (dump_file, "Not changing value number of ");
5127 print_generic_expr (dump_file, from);
5128 fprintf (dump_file, " from VARYING to ");
5129 print_generic_expr (dump_file, to);
5130 fprintf (dump_file, "\n");
5132 return false;
5134 curr_invariant = is_gimple_min_invariant (currval);
5135 curr_undefined = (TREE_CODE (currval) == SSA_NAME
5136 && !virtual_operand_p (currval)
5137 && ssa_undefined_value_p (currval, false));
5138 if (currval != VN_TOP
5139 && !curr_invariant
5140 && !curr_undefined
5141 && is_gimple_min_invariant (to))
5143 if (dump_file && (dump_flags & TDF_DETAILS))
5145 fprintf (dump_file, "Forcing VARYING instead of changing "
5146 "value number of ");
5147 print_generic_expr (dump_file, from);
5148 fprintf (dump_file, " from ");
5149 print_generic_expr (dump_file, currval);
5150 fprintf (dump_file, " (non-constant) to ");
5151 print_generic_expr (dump_file, to);
5152 fprintf (dump_file, " (constant)\n");
5154 to = from;
5156 else if (currval != VN_TOP
5157 && !curr_undefined
5158 && TREE_CODE (to) == SSA_NAME
5159 && !virtual_operand_p (to)
5160 && ssa_undefined_value_p (to, false))
5162 if (dump_file && (dump_flags & TDF_DETAILS))
5164 fprintf (dump_file, "Forcing VARYING instead of changing "
5165 "value number of ");
5166 print_generic_expr (dump_file, from);
5167 fprintf (dump_file, " from ");
5168 print_generic_expr (dump_file, currval);
5169 fprintf (dump_file, " (non-undefined) to ");
5170 print_generic_expr (dump_file, to);
5171 fprintf (dump_file, " (undefined)\n");
5173 to = from;
5175 else if (TREE_CODE (to) == SSA_NAME
5176 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (to))
5177 to = from;
5180 set_and_exit:
5181 if (dump_file && (dump_flags & TDF_DETAILS))
5183 fprintf (dump_file, "Setting value number of ");
5184 print_generic_expr (dump_file, from);
5185 fprintf (dump_file, " to ");
5186 print_generic_expr (dump_file, to);
5189 if (currval != to
5190 && !operand_equal_p (currval, to, 0)
5191 /* Different undefined SSA names are not actually different. See
5192 PR82320 for a testcase were we'd otherwise not terminate iteration. */
5193 && !(curr_undefined
5194 && TREE_CODE (to) == SSA_NAME
5195 && !virtual_operand_p (to)
5196 && ssa_undefined_value_p (to, false))
5197 /* ??? For addresses involving volatile objects or types operand_equal_p
5198 does not reliably detect ADDR_EXPRs as equal. We know we are only
5199 getting invariant gimple addresses here, so can use
5200 get_addr_base_and_unit_offset to do this comparison. */
5201 && !(TREE_CODE (currval) == ADDR_EXPR
5202 && TREE_CODE (to) == ADDR_EXPR
5203 && (get_addr_base_and_unit_offset (TREE_OPERAND (currval, 0), &coff)
5204 == get_addr_base_and_unit_offset (TREE_OPERAND (to, 0), &toff))
5205 && known_eq (coff, toff)))
5207 if (to != from
5208 && currval != VN_TOP
5209 && !curr_undefined
5210 /* We do not want to allow lattice transitions from one value
5211 to another since that may lead to not terminating iteration
5212 (see PR95049). Since there's no convenient way to check
5213 for the allowed transition of VAL -> PHI (loop entry value,
5214 same on two PHIs, to same PHI result) we restrict the check
5215 to invariants. */
5216 && curr_invariant
5217 && is_gimple_min_invariant (to))
5219 if (dump_file && (dump_flags & TDF_DETAILS))
5220 fprintf (dump_file, " forced VARYING");
5221 to = from;
5223 if (dump_file && (dump_flags & TDF_DETAILS))
5224 fprintf (dump_file, " (changed)\n");
5225 from_info->valnum = to;
5226 return true;
5228 if (dump_file && (dump_flags & TDF_DETAILS))
5229 fprintf (dump_file, "\n");
5230 return false;
5233 /* Set all definitions in STMT to value number to themselves.
5234 Return true if a value number changed. */
5236 static bool
5237 defs_to_varying (gimple *stmt)
5239 bool changed = false;
5240 ssa_op_iter iter;
5241 def_operand_p defp;
5243 FOR_EACH_SSA_DEF_OPERAND (defp, stmt, iter, SSA_OP_ALL_DEFS)
5245 tree def = DEF_FROM_PTR (defp);
5246 changed |= set_ssa_val_to (def, def);
5248 return changed;
5251 /* Visit a copy between LHS and RHS, return true if the value number
5252 changed. */
5254 static bool
5255 visit_copy (tree lhs, tree rhs)
5257 /* Valueize. */
5258 rhs = SSA_VAL (rhs);
5260 return set_ssa_val_to (lhs, rhs);
5263 /* Lookup a value for OP in type WIDE_TYPE where the value in type of OP
5264 is the same. */
5266 static tree
5267 valueized_wider_op (tree wide_type, tree op, bool allow_truncate)
5269 if (TREE_CODE (op) == SSA_NAME)
5270 op = vn_valueize (op);
5272 /* Either we have the op widened available. */
5273 tree ops[3] = {};
5274 ops[0] = op;
5275 tree tem = vn_nary_op_lookup_pieces (1, NOP_EXPR,
5276 wide_type, ops, NULL);
5277 if (tem)
5278 return tem;
5280 /* Or the op is truncated from some existing value. */
5281 if (allow_truncate && TREE_CODE (op) == SSA_NAME)
5283 gimple *def = SSA_NAME_DEF_STMT (op);
5284 if (is_gimple_assign (def)
5285 && CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def)))
5287 tem = gimple_assign_rhs1 (def);
5288 if (useless_type_conversion_p (wide_type, TREE_TYPE (tem)))
5290 if (TREE_CODE (tem) == SSA_NAME)
5291 tem = vn_valueize (tem);
5292 return tem;
5297 /* For constants simply extend it. */
5298 if (TREE_CODE (op) == INTEGER_CST)
5299 return wide_int_to_tree (wide_type, wi::to_widest (op));
5301 return NULL_TREE;
5304 /* Visit a nary operator RHS, value number it, and return true if the
5305 value number of LHS has changed as a result. */
5307 static bool
5308 visit_nary_op (tree lhs, gassign *stmt)
5310 vn_nary_op_t vnresult;
5311 tree result = vn_nary_op_lookup_stmt (stmt, &vnresult);
5312 if (! result && vnresult)
5313 result = vn_nary_op_get_predicated_value (vnresult, gimple_bb (stmt));
5314 if (result)
5315 return set_ssa_val_to (lhs, result);
5317 /* Do some special pattern matching for redundancies of operations
5318 in different types. */
5319 enum tree_code code = gimple_assign_rhs_code (stmt);
5320 tree type = TREE_TYPE (lhs);
5321 tree rhs1 = gimple_assign_rhs1 (stmt);
5322 switch (code)
5324 CASE_CONVERT:
5325 /* Match arithmetic done in a different type where we can easily
5326 substitute the result from some earlier sign-changed or widened
5327 operation. */
5328 if (INTEGRAL_TYPE_P (type)
5329 && TREE_CODE (rhs1) == SSA_NAME
5330 /* We only handle sign-changes, zero-extension -> & mask or
5331 sign-extension if we know the inner operation doesn't
5332 overflow. */
5333 && (((TYPE_UNSIGNED (TREE_TYPE (rhs1))
5334 || (INTEGRAL_TYPE_P (TREE_TYPE (rhs1))
5335 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (rhs1))))
5336 && TYPE_PRECISION (type) > TYPE_PRECISION (TREE_TYPE (rhs1)))
5337 || TYPE_PRECISION (type) == TYPE_PRECISION (TREE_TYPE (rhs1))))
5339 gassign *def = dyn_cast <gassign *> (SSA_NAME_DEF_STMT (rhs1));
5340 if (def
5341 && (gimple_assign_rhs_code (def) == PLUS_EXPR
5342 || gimple_assign_rhs_code (def) == MINUS_EXPR
5343 || gimple_assign_rhs_code (def) == MULT_EXPR))
5345 tree ops[3] = {};
5346 /* When requiring a sign-extension we cannot model a
5347 previous truncation with a single op so don't bother. */
5348 bool allow_truncate = TYPE_UNSIGNED (TREE_TYPE (rhs1));
5349 /* Either we have the op widened available. */
5350 ops[0] = valueized_wider_op (type, gimple_assign_rhs1 (def),
5351 allow_truncate);
5352 if (ops[0])
5353 ops[1] = valueized_wider_op (type, gimple_assign_rhs2 (def),
5354 allow_truncate);
5355 if (ops[0] && ops[1])
5357 ops[0] = vn_nary_op_lookup_pieces
5358 (2, gimple_assign_rhs_code (def), type, ops, NULL);
5359 /* We have wider operation available. */
5360 if (ops[0]
5361 /* If the leader is a wrapping operation we can
5362 insert it for code hoisting w/o introducing
5363 undefined overflow. If it is not it has to
5364 be available. See PR86554. */
5365 && (TYPE_OVERFLOW_WRAPS (TREE_TYPE (ops[0]))
5366 || (rpo_avail && vn_context_bb
5367 && rpo_avail->eliminate_avail (vn_context_bb,
5368 ops[0]))))
5370 unsigned lhs_prec = TYPE_PRECISION (type);
5371 unsigned rhs_prec = TYPE_PRECISION (TREE_TYPE (rhs1));
5372 if (lhs_prec == rhs_prec
5373 || (INTEGRAL_TYPE_P (TREE_TYPE (rhs1))
5374 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (rhs1))))
5376 gimple_match_op match_op (gimple_match_cond::UNCOND,
5377 NOP_EXPR, type, ops[0]);
5378 result = vn_nary_build_or_lookup (&match_op);
5379 if (result)
5381 bool changed = set_ssa_val_to (lhs, result);
5382 vn_nary_op_insert_stmt (stmt, result);
5383 return changed;
5386 else
5388 tree mask = wide_int_to_tree
5389 (type, wi::mask (rhs_prec, false, lhs_prec));
5390 gimple_match_op match_op (gimple_match_cond::UNCOND,
5391 BIT_AND_EXPR,
5392 TREE_TYPE (lhs),
5393 ops[0], mask);
5394 result = vn_nary_build_or_lookup (&match_op);
5395 if (result)
5397 bool changed = set_ssa_val_to (lhs, result);
5398 vn_nary_op_insert_stmt (stmt, result);
5399 return changed;
5406 break;
5407 case BIT_AND_EXPR:
5408 if (INTEGRAL_TYPE_P (type)
5409 && TREE_CODE (rhs1) == SSA_NAME
5410 && TREE_CODE (gimple_assign_rhs2 (stmt)) == INTEGER_CST
5411 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (rhs1)
5412 && default_vn_walk_kind != VN_NOWALK
5413 && CHAR_BIT == 8
5414 && BITS_PER_UNIT == 8
5415 && BYTES_BIG_ENDIAN == WORDS_BIG_ENDIAN
5416 && !integer_all_onesp (gimple_assign_rhs2 (stmt))
5417 && !integer_zerop (gimple_assign_rhs2 (stmt)))
5419 gassign *ass = dyn_cast <gassign *> (SSA_NAME_DEF_STMT (rhs1));
5420 if (ass
5421 && !gimple_has_volatile_ops (ass)
5422 && vn_get_stmt_kind (ass) == VN_REFERENCE)
5424 tree last_vuse = gimple_vuse (ass);
5425 tree op = gimple_assign_rhs1 (ass);
5426 tree result = vn_reference_lookup (op, gimple_vuse (ass),
5427 default_vn_walk_kind,
5428 NULL, true, &last_vuse,
5429 gimple_assign_rhs2 (stmt));
5430 if (result
5431 && useless_type_conversion_p (TREE_TYPE (result),
5432 TREE_TYPE (op)))
5433 return set_ssa_val_to (lhs, result);
5436 break;
5437 case TRUNC_DIV_EXPR:
5438 if (TYPE_UNSIGNED (type))
5439 break;
5440 /* Fallthru. */
5441 case RDIV_EXPR:
5442 case MULT_EXPR:
5443 /* Match up ([-]a){/,*}([-])b with v=a{/,*}b, replacing it with -v. */
5444 if (! HONOR_SIGN_DEPENDENT_ROUNDING (type))
5446 tree rhs[2];
5447 rhs[0] = rhs1;
5448 rhs[1] = gimple_assign_rhs2 (stmt);
5449 for (unsigned i = 0; i <= 1; ++i)
5451 unsigned j = i == 0 ? 1 : 0;
5452 tree ops[2];
5453 gimple_match_op match_op (gimple_match_cond::UNCOND,
5454 NEGATE_EXPR, type, rhs[i]);
5455 ops[i] = vn_nary_build_or_lookup_1 (&match_op, false, true);
5456 ops[j] = rhs[j];
5457 if (ops[i]
5458 && (ops[0] = vn_nary_op_lookup_pieces (2, code,
5459 type, ops, NULL)))
5461 gimple_match_op match_op (gimple_match_cond::UNCOND,
5462 NEGATE_EXPR, type, ops[0]);
5463 result = vn_nary_build_or_lookup_1 (&match_op, true, false);
5464 if (result)
5466 bool changed = set_ssa_val_to (lhs, result);
5467 vn_nary_op_insert_stmt (stmt, result);
5468 return changed;
5473 break;
5474 case LSHIFT_EXPR:
5475 /* For X << C, use the value number of X * (1 << C). */
5476 if (INTEGRAL_TYPE_P (type)
5477 && TYPE_OVERFLOW_WRAPS (type)
5478 && !TYPE_SATURATING (type))
5480 tree rhs2 = gimple_assign_rhs2 (stmt);
5481 if (TREE_CODE (rhs2) == INTEGER_CST
5482 && tree_fits_uhwi_p (rhs2)
5483 && tree_to_uhwi (rhs2) < TYPE_PRECISION (type))
5485 wide_int w = wi::set_bit_in_zero (tree_to_uhwi (rhs2),
5486 TYPE_PRECISION (type));
5487 gimple_match_op match_op (gimple_match_cond::UNCOND,
5488 MULT_EXPR, type, rhs1,
5489 wide_int_to_tree (type, w));
5490 result = vn_nary_build_or_lookup (&match_op);
5491 if (result)
5493 bool changed = set_ssa_val_to (lhs, result);
5494 if (TREE_CODE (result) == SSA_NAME)
5495 vn_nary_op_insert_stmt (stmt, result);
5496 return changed;
5500 break;
5501 default:
5502 break;
5505 bool changed = set_ssa_val_to (lhs, lhs);
5506 vn_nary_op_insert_stmt (stmt, lhs);
5507 return changed;
5510 /* Visit a call STMT storing into LHS. Return true if the value number
5511 of the LHS has changed as a result. */
5513 static bool
5514 visit_reference_op_call (tree lhs, gcall *stmt)
5516 bool changed = false;
5517 struct vn_reference_s vr1;
5518 vn_reference_t vnresult = NULL;
5519 tree vdef = gimple_vdef (stmt);
5520 modref_summary *summary;
5522 /* Non-ssa lhs is handled in copy_reference_ops_from_call. */
5523 if (lhs && TREE_CODE (lhs) != SSA_NAME)
5524 lhs = NULL_TREE;
5526 vn_reference_lookup_call (stmt, &vnresult, &vr1);
5528 /* If the lookup did not succeed for pure functions try to use
5529 modref info to find a candidate to CSE to. */
5530 const unsigned accesses_limit = 8;
5531 if (!vnresult
5532 && !vdef
5533 && lhs
5534 && gimple_vuse (stmt)
5535 && (((summary = get_modref_function_summary (stmt, NULL))
5536 && !summary->global_memory_read
5537 && summary->load_accesses < accesses_limit)
5538 || gimple_call_flags (stmt) & ECF_CONST))
5540 /* First search if we can do someting useful and build a
5541 vector of all loads we have to check. */
5542 bool unknown_memory_access = false;
5543 auto_vec<ao_ref, accesses_limit> accesses;
5544 unsigned load_accesses = summary ? summary->load_accesses : 0;
5545 if (!unknown_memory_access)
5546 /* Add loads done as part of setting up the call arguments.
5547 That's also necessary for CONST functions which will
5548 not have a modref summary. */
5549 for (unsigned i = 0; i < gimple_call_num_args (stmt); ++i)
5551 tree arg = gimple_call_arg (stmt, i);
5552 if (TREE_CODE (arg) != SSA_NAME
5553 && !is_gimple_min_invariant (arg))
5555 if (accesses.length () >= accesses_limit - load_accesses)
5557 unknown_memory_access = true;
5558 break;
5560 accesses.quick_grow (accesses.length () + 1);
5561 ao_ref_init (&accesses.last (), arg);
5564 if (summary && !unknown_memory_access)
5566 /* Add loads as analyzed by IPA modref. */
5567 for (auto base_node : summary->loads->bases)
5568 if (unknown_memory_access)
5569 break;
5570 else for (auto ref_node : base_node->refs)
5571 if (unknown_memory_access)
5572 break;
5573 else for (auto access_node : ref_node->accesses)
5575 accesses.quick_grow (accesses.length () + 1);
5576 ao_ref *r = &accesses.last ();
5577 if (!access_node.get_ao_ref (stmt, r))
5579 /* Initialize a ref based on the argument and
5580 unknown offset if possible. */
5581 tree arg = access_node.get_call_arg (stmt);
5582 if (arg && TREE_CODE (arg) == SSA_NAME)
5583 arg = SSA_VAL (arg);
5584 if (arg
5585 && TREE_CODE (arg) == ADDR_EXPR
5586 && (arg = get_base_address (arg))
5587 && DECL_P (arg))
5589 ao_ref_init (r, arg);
5590 r->ref = NULL_TREE;
5591 r->base = arg;
5593 else
5595 unknown_memory_access = true;
5596 break;
5599 r->base_alias_set = base_node->base;
5600 r->ref_alias_set = ref_node->ref;
5604 /* Walk the VUSE->VDEF chain optimistically trying to find an entry
5605 for the call in the hashtable. */
5606 unsigned limit = (unknown_memory_access
5608 : (param_sccvn_max_alias_queries_per_access
5609 / (accesses.length () + 1)));
5610 tree saved_vuse = vr1.vuse;
5611 hashval_t saved_hashcode = vr1.hashcode;
5612 while (limit > 0 && !vnresult && !SSA_NAME_IS_DEFAULT_DEF (vr1.vuse))
5614 vr1.hashcode = vr1.hashcode - SSA_NAME_VERSION (vr1.vuse);
5615 gimple *def = SSA_NAME_DEF_STMT (vr1.vuse);
5616 /* ??? We could use fancy stuff like in walk_non_aliased_vuses, but
5617 do not bother for now. */
5618 if (is_a <gphi *> (def))
5619 break;
5620 vr1.vuse = vuse_ssa_val (gimple_vuse (def));
5621 vr1.hashcode = vr1.hashcode + SSA_NAME_VERSION (vr1.vuse);
5622 vn_reference_lookup_1 (&vr1, &vnresult);
5623 limit--;
5626 /* If we found a candidate to CSE to verify it is valid. */
5627 if (vnresult && !accesses.is_empty ())
5629 tree vuse = vuse_ssa_val (gimple_vuse (stmt));
5630 while (vnresult && vuse != vr1.vuse)
5632 gimple *def = SSA_NAME_DEF_STMT (vuse);
5633 for (auto &ref : accesses)
5635 /* ??? stmt_may_clobber_ref_p_1 does per stmt constant
5636 analysis overhead that we might be able to cache. */
5637 if (stmt_may_clobber_ref_p_1 (def, &ref, true))
5639 vnresult = NULL;
5640 break;
5643 vuse = vuse_ssa_val (gimple_vuse (def));
5646 vr1.vuse = saved_vuse;
5647 vr1.hashcode = saved_hashcode;
5650 if (vnresult)
5652 if (vdef)
5654 if (vnresult->result_vdef)
5655 changed |= set_ssa_val_to (vdef, vnresult->result_vdef);
5656 else if (!lhs && gimple_call_lhs (stmt))
5657 /* If stmt has non-SSA_NAME lhs, value number the vdef to itself,
5658 as the call still acts as a lhs store. */
5659 changed |= set_ssa_val_to (vdef, vdef);
5660 else
5661 /* If the call was discovered to be pure or const reflect
5662 that as far as possible. */
5663 changed |= set_ssa_val_to (vdef,
5664 vuse_ssa_val (gimple_vuse (stmt)));
5667 if (!vnresult->result && lhs)
5668 vnresult->result = lhs;
5670 if (vnresult->result && lhs)
5671 changed |= set_ssa_val_to (lhs, vnresult->result);
5673 else
5675 vn_reference_t vr2;
5676 vn_reference_s **slot;
5677 tree vdef_val = vdef;
5678 if (vdef)
5680 /* If we value numbered an indirect functions function to
5681 one not clobbering memory value number its VDEF to its
5682 VUSE. */
5683 tree fn = gimple_call_fn (stmt);
5684 if (fn && TREE_CODE (fn) == SSA_NAME)
5686 fn = SSA_VAL (fn);
5687 if (TREE_CODE (fn) == ADDR_EXPR
5688 && TREE_CODE (TREE_OPERAND (fn, 0)) == FUNCTION_DECL
5689 && (flags_from_decl_or_type (TREE_OPERAND (fn, 0))
5690 & (ECF_CONST | ECF_PURE))
5691 /* If stmt has non-SSA_NAME lhs, value number the
5692 vdef to itself, as the call still acts as a lhs
5693 store. */
5694 && (lhs || gimple_call_lhs (stmt) == NULL_TREE))
5695 vdef_val = vuse_ssa_val (gimple_vuse (stmt));
5697 changed |= set_ssa_val_to (vdef, vdef_val);
5699 if (lhs)
5700 changed |= set_ssa_val_to (lhs, lhs);
5701 vr2 = XOBNEW (&vn_tables_obstack, vn_reference_s);
5702 vr2->vuse = vr1.vuse;
5703 /* As we are not walking the virtual operand chain we know the
5704 shared_lookup_references are still original so we can re-use
5705 them here. */
5706 vr2->operands = vr1.operands.copy ();
5707 vr2->type = vr1.type;
5708 vr2->punned = vr1.punned;
5709 vr2->set = vr1.set;
5710 vr2->base_set = vr1.base_set;
5711 vr2->hashcode = vr1.hashcode;
5712 vr2->result = lhs;
5713 vr2->result_vdef = vdef_val;
5714 vr2->value_id = 0;
5715 slot = valid_info->references->find_slot_with_hash (vr2, vr2->hashcode,
5716 INSERT);
5717 gcc_assert (!*slot);
5718 *slot = vr2;
5719 vr2->next = last_inserted_ref;
5720 last_inserted_ref = vr2;
5723 return changed;
5726 /* Visit a load from a reference operator RHS, part of STMT, value number it,
5727 and return true if the value number of the LHS has changed as a result. */
5729 static bool
5730 visit_reference_op_load (tree lhs, tree op, gimple *stmt)
5732 bool changed = false;
5733 tree result;
5734 vn_reference_t res;
5736 tree vuse = gimple_vuse (stmt);
5737 tree last_vuse = vuse;
5738 result = vn_reference_lookup (op, vuse, default_vn_walk_kind, &res, true, &last_vuse);
5740 /* We handle type-punning through unions by value-numbering based
5741 on offset and size of the access. Be prepared to handle a
5742 type-mismatch here via creating a VIEW_CONVERT_EXPR. */
5743 if (result
5744 && !useless_type_conversion_p (TREE_TYPE (result), TREE_TYPE (op)))
5746 /* Avoid the type punning in case the result mode has padding where
5747 the op we lookup has not. */
5748 if (maybe_lt (GET_MODE_PRECISION (TYPE_MODE (TREE_TYPE (result))),
5749 GET_MODE_PRECISION (TYPE_MODE (TREE_TYPE (op)))))
5750 result = NULL_TREE;
5751 else
5753 /* We will be setting the value number of lhs to the value number
5754 of VIEW_CONVERT_EXPR <TREE_TYPE (result)> (result).
5755 So first simplify and lookup this expression to see if it
5756 is already available. */
5757 gimple_match_op res_op (gimple_match_cond::UNCOND,
5758 VIEW_CONVERT_EXPR, TREE_TYPE (op), result);
5759 result = vn_nary_build_or_lookup (&res_op);
5760 if (result
5761 && TREE_CODE (result) == SSA_NAME
5762 && VN_INFO (result)->needs_insertion)
5763 /* Track whether this is the canonical expression for different
5764 typed loads. We use that as a stopgap measure for code
5765 hoisting when dealing with floating point loads. */
5766 res->punned = true;
5769 /* When building the conversion fails avoid inserting the reference
5770 again. */
5771 if (!result)
5772 return set_ssa_val_to (lhs, lhs);
5775 if (result)
5776 changed = set_ssa_val_to (lhs, result);
5777 else
5779 changed = set_ssa_val_to (lhs, lhs);
5780 vn_reference_insert (op, lhs, last_vuse, NULL_TREE);
5781 if (vuse && SSA_VAL (last_vuse) != SSA_VAL (vuse))
5783 if (dump_file && (dump_flags & TDF_DETAILS))
5785 fprintf (dump_file, "Using extra use virtual operand ");
5786 print_generic_expr (dump_file, last_vuse);
5787 fprintf (dump_file, "\n");
5789 vn_reference_insert (op, lhs, vuse, NULL_TREE);
5793 return changed;
5797 /* Visit a store to a reference operator LHS, part of STMT, value number it,
5798 and return true if the value number of the LHS has changed as a result. */
5800 static bool
5801 visit_reference_op_store (tree lhs, tree op, gimple *stmt)
5803 bool changed = false;
5804 vn_reference_t vnresult = NULL;
5805 tree assign;
5806 bool resultsame = false;
5807 tree vuse = gimple_vuse (stmt);
5808 tree vdef = gimple_vdef (stmt);
5810 if (TREE_CODE (op) == SSA_NAME)
5811 op = SSA_VAL (op);
5813 /* First we want to lookup using the *vuses* from the store and see
5814 if there the last store to this location with the same address
5815 had the same value.
5817 The vuses represent the memory state before the store. If the
5818 memory state, address, and value of the store is the same as the
5819 last store to this location, then this store will produce the
5820 same memory state as that store.
5822 In this case the vdef versions for this store are value numbered to those
5823 vuse versions, since they represent the same memory state after
5824 this store.
5826 Otherwise, the vdefs for the store are used when inserting into
5827 the table, since the store generates a new memory state. */
5829 vn_reference_lookup (lhs, vuse, VN_NOWALK, &vnresult, false);
5830 if (vnresult
5831 && vnresult->result)
5833 tree result = vnresult->result;
5834 gcc_checking_assert (TREE_CODE (result) != SSA_NAME
5835 || result == SSA_VAL (result));
5836 resultsame = expressions_equal_p (result, op);
5837 if (resultsame)
5839 /* If the TBAA state isn't compatible for downstream reads
5840 we cannot value-number the VDEFs the same. */
5841 ao_ref lhs_ref;
5842 ao_ref_init (&lhs_ref, lhs);
5843 alias_set_type set = ao_ref_alias_set (&lhs_ref);
5844 alias_set_type base_set = ao_ref_base_alias_set (&lhs_ref);
5845 if ((vnresult->set != set
5846 && ! alias_set_subset_of (set, vnresult->set))
5847 || (vnresult->base_set != base_set
5848 && ! alias_set_subset_of (base_set, vnresult->base_set)))
5849 resultsame = false;
5853 if (!resultsame)
5855 if (dump_file && (dump_flags & TDF_DETAILS))
5857 fprintf (dump_file, "No store match\n");
5858 fprintf (dump_file, "Value numbering store ");
5859 print_generic_expr (dump_file, lhs);
5860 fprintf (dump_file, " to ");
5861 print_generic_expr (dump_file, op);
5862 fprintf (dump_file, "\n");
5864 /* Have to set value numbers before insert, since insert is
5865 going to valueize the references in-place. */
5866 if (vdef)
5867 changed |= set_ssa_val_to (vdef, vdef);
5869 /* Do not insert structure copies into the tables. */
5870 if (is_gimple_min_invariant (op)
5871 || is_gimple_reg (op))
5872 vn_reference_insert (lhs, op, vdef, NULL);
5874 /* Only perform the following when being called from PRE
5875 which embeds tail merging. */
5876 if (default_vn_walk_kind == VN_WALK)
5878 assign = build2 (MODIFY_EXPR, TREE_TYPE (lhs), lhs, op);
5879 vn_reference_lookup (assign, vuse, VN_NOWALK, &vnresult, false);
5880 if (!vnresult)
5881 vn_reference_insert (assign, lhs, vuse, vdef);
5884 else
5886 /* We had a match, so value number the vdef to have the value
5887 number of the vuse it came from. */
5889 if (dump_file && (dump_flags & TDF_DETAILS))
5890 fprintf (dump_file, "Store matched earlier value, "
5891 "value numbering store vdefs to matching vuses.\n");
5893 changed |= set_ssa_val_to (vdef, SSA_VAL (vuse));
5896 return changed;
5899 /* Visit and value number PHI, return true if the value number
5900 changed. When BACKEDGES_VARYING_P is true then assume all
5901 backedge values are varying. When INSERTED is not NULL then
5902 this is just a ahead query for a possible iteration, set INSERTED
5903 to true if we'd insert into the hashtable. */
5905 static bool
5906 visit_phi (gimple *phi, bool *inserted, bool backedges_varying_p)
5908 tree result, sameval = VN_TOP, seen_undef = NULL_TREE;
5909 tree backedge_val = NULL_TREE;
5910 bool seen_non_backedge = false;
5911 tree sameval_base = NULL_TREE;
5912 poly_int64 soff, doff;
5913 unsigned n_executable = 0;
5914 edge_iterator ei;
5915 edge e, sameval_e = NULL;
5917 /* TODO: We could check for this in initialization, and replace this
5918 with a gcc_assert. */
5919 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (PHI_RESULT (phi)))
5920 return set_ssa_val_to (PHI_RESULT (phi), PHI_RESULT (phi));
5922 /* We track whether a PHI was CSEd to to avoid excessive iterations
5923 that would be necessary only because the PHI changed arguments
5924 but not value. */
5925 if (!inserted)
5926 gimple_set_plf (phi, GF_PLF_1, false);
5928 /* See if all non-TOP arguments have the same value. TOP is
5929 equivalent to everything, so we can ignore it. */
5930 basic_block bb = gimple_bb (phi);
5931 FOR_EACH_EDGE (e, ei, bb->preds)
5932 if (e->flags & EDGE_EXECUTABLE)
5934 tree def = PHI_ARG_DEF_FROM_EDGE (phi, e);
5936 if (def == PHI_RESULT (phi))
5937 continue;
5938 ++n_executable;
5939 if (TREE_CODE (def) == SSA_NAME)
5941 if (!backedges_varying_p || !(e->flags & EDGE_DFS_BACK))
5942 def = SSA_VAL (def);
5943 if (e->flags & EDGE_DFS_BACK)
5944 backedge_val = def;
5946 if (!(e->flags & EDGE_DFS_BACK))
5947 seen_non_backedge = true;
5948 if (def == VN_TOP)
5950 /* Ignore undefined defs for sameval but record one. */
5951 else if (TREE_CODE (def) == SSA_NAME
5952 && ! virtual_operand_p (def)
5953 && ssa_undefined_value_p (def, false))
5954 seen_undef = def;
5955 else if (sameval == VN_TOP)
5957 sameval = def;
5958 sameval_e = e;
5960 else if (expressions_equal_p (def, sameval))
5961 sameval_e = NULL;
5962 else if (virtual_operand_p (def))
5964 sameval = NULL_TREE;
5965 break;
5967 else
5969 /* We know we're arriving only with invariant addresses here,
5970 try harder comparing them. We can do some caching here
5971 which we cannot do in expressions_equal_p. */
5972 if (TREE_CODE (def) == ADDR_EXPR
5973 && TREE_CODE (sameval) == ADDR_EXPR
5974 && sameval_base != (void *)-1)
5976 if (!sameval_base)
5977 sameval_base = get_addr_base_and_unit_offset
5978 (TREE_OPERAND (sameval, 0), &soff);
5979 if (!sameval_base)
5980 sameval_base = (tree)(void *)-1;
5981 else if ((get_addr_base_and_unit_offset
5982 (TREE_OPERAND (def, 0), &doff) == sameval_base)
5983 && known_eq (soff, doff))
5984 continue;
5986 /* There's also the possibility to use equivalences. */
5987 if (!FLOAT_TYPE_P (TREE_TYPE (def))
5988 /* But only do this if we didn't force any of sameval or
5989 val to VARYING because of backedge processing rules. */
5990 && (TREE_CODE (sameval) != SSA_NAME
5991 || SSA_VAL (sameval) == sameval)
5992 && (TREE_CODE (def) != SSA_NAME || SSA_VAL (def) == def))
5994 vn_nary_op_t vnresult;
5995 tree ops[2];
5996 ops[0] = def;
5997 ops[1] = sameval;
5998 tree val = vn_nary_op_lookup_pieces (2, EQ_EXPR,
5999 boolean_type_node,
6000 ops, &vnresult);
6001 if (! val && vnresult && vnresult->predicated_values)
6003 val = vn_nary_op_get_predicated_value (vnresult, e);
6004 if (val && integer_truep (val)
6005 && !(sameval_e && (sameval_e->flags & EDGE_DFS_BACK)))
6007 if (dump_file && (dump_flags & TDF_DETAILS))
6009 fprintf (dump_file, "Predication says ");
6010 print_generic_expr (dump_file, def, TDF_NONE);
6011 fprintf (dump_file, " and ");
6012 print_generic_expr (dump_file, sameval, TDF_NONE);
6013 fprintf (dump_file, " are equal on edge %d -> %d\n",
6014 e->src->index, e->dest->index);
6016 continue;
6018 /* If on all previous edges the value was equal to def
6019 we can change sameval to def. */
6020 if (EDGE_COUNT (bb->preds) == 2
6021 && (val = vn_nary_op_get_predicated_value
6022 (vnresult, EDGE_PRED (bb, 0)))
6023 && integer_truep (val)
6024 && !(e->flags & EDGE_DFS_BACK))
6026 if (dump_file && (dump_flags & TDF_DETAILS))
6028 fprintf (dump_file, "Predication says ");
6029 print_generic_expr (dump_file, def, TDF_NONE);
6030 fprintf (dump_file, " and ");
6031 print_generic_expr (dump_file, sameval, TDF_NONE);
6032 fprintf (dump_file, " are equal on edge %d -> %d\n",
6033 EDGE_PRED (bb, 0)->src->index,
6034 EDGE_PRED (bb, 0)->dest->index);
6036 sameval = def;
6037 continue;
6041 sameval = NULL_TREE;
6042 break;
6046 /* If the value we want to use is flowing over the backedge and we
6047 should take it as VARYING but it has a non-VARYING value drop to
6048 VARYING.
6049 If we value-number a virtual operand never value-number to the
6050 value from the backedge as that confuses the alias-walking code.
6051 See gcc.dg/torture/pr87176.c. If the value is the same on a
6052 non-backedge everything is OK though. */
6053 bool visited_p;
6054 if ((backedge_val
6055 && !seen_non_backedge
6056 && TREE_CODE (backedge_val) == SSA_NAME
6057 && sameval == backedge_val
6058 && (SSA_NAME_IS_VIRTUAL_OPERAND (backedge_val)
6059 || SSA_VAL (backedge_val) != backedge_val))
6060 /* Do not value-number a virtual operand to sth not visited though
6061 given that allows us to escape a region in alias walking. */
6062 || (sameval
6063 && TREE_CODE (sameval) == SSA_NAME
6064 && !SSA_NAME_IS_DEFAULT_DEF (sameval)
6065 && SSA_NAME_IS_VIRTUAL_OPERAND (sameval)
6066 && (SSA_VAL (sameval, &visited_p), !visited_p)))
6067 /* Note this just drops to VARYING without inserting the PHI into
6068 the hashes. */
6069 result = PHI_RESULT (phi);
6070 /* If none of the edges was executable keep the value-number at VN_TOP,
6071 if only a single edge is exectuable use its value. */
6072 else if (n_executable <= 1)
6073 result = seen_undef ? seen_undef : sameval;
6074 /* If we saw only undefined values and VN_TOP use one of the
6075 undefined values. */
6076 else if (sameval == VN_TOP)
6077 result = seen_undef ? seen_undef : sameval;
6078 /* First see if it is equivalent to a phi node in this block. We prefer
6079 this as it allows IV elimination - see PRs 66502 and 67167. */
6080 else if ((result = vn_phi_lookup (phi, backedges_varying_p)))
6082 if (!inserted
6083 && TREE_CODE (result) == SSA_NAME
6084 && gimple_code (SSA_NAME_DEF_STMT (result)) == GIMPLE_PHI)
6086 gimple_set_plf (SSA_NAME_DEF_STMT (result), GF_PLF_1, true);
6087 if (dump_file && (dump_flags & TDF_DETAILS))
6089 fprintf (dump_file, "Marking CSEd to PHI node ");
6090 print_gimple_expr (dump_file, SSA_NAME_DEF_STMT (result),
6091 0, TDF_SLIM);
6092 fprintf (dump_file, "\n");
6096 /* If all values are the same use that, unless we've seen undefined
6097 values as well and the value isn't constant.
6098 CCP/copyprop have the same restriction to not remove uninit warnings. */
6099 else if (sameval
6100 && (! seen_undef || is_gimple_min_invariant (sameval)))
6101 result = sameval;
6102 else
6104 result = PHI_RESULT (phi);
6105 /* Only insert PHIs that are varying, for constant value numbers
6106 we mess up equivalences otherwise as we are only comparing
6107 the immediate controlling predicates. */
6108 vn_phi_insert (phi, result, backedges_varying_p);
6109 if (inserted)
6110 *inserted = true;
6113 return set_ssa_val_to (PHI_RESULT (phi), result);
6116 /* Try to simplify RHS using equivalences and constant folding. */
6118 static tree
6119 try_to_simplify (gassign *stmt)
6121 enum tree_code code = gimple_assign_rhs_code (stmt);
6122 tree tem;
6124 /* For stores we can end up simplifying a SSA_NAME rhs. Just return
6125 in this case, there is no point in doing extra work. */
6126 if (code == SSA_NAME)
6127 return NULL_TREE;
6129 /* First try constant folding based on our current lattice. */
6130 mprts_hook = vn_lookup_simplify_result;
6131 tem = gimple_fold_stmt_to_constant_1 (stmt, vn_valueize, vn_valueize);
6132 mprts_hook = NULL;
6133 if (tem
6134 && (TREE_CODE (tem) == SSA_NAME
6135 || is_gimple_min_invariant (tem)))
6136 return tem;
6138 return NULL_TREE;
6141 /* Visit and value number STMT, return true if the value number
6142 changed. */
6144 static bool
6145 visit_stmt (gimple *stmt, bool backedges_varying_p = false)
6147 bool changed = false;
6149 if (dump_file && (dump_flags & TDF_DETAILS))
6151 fprintf (dump_file, "Value numbering stmt = ");
6152 print_gimple_stmt (dump_file, stmt, 0);
6155 if (gimple_code (stmt) == GIMPLE_PHI)
6156 changed = visit_phi (stmt, NULL, backedges_varying_p);
6157 else if (gimple_has_volatile_ops (stmt))
6158 changed = defs_to_varying (stmt);
6159 else if (gassign *ass = dyn_cast <gassign *> (stmt))
6161 enum tree_code code = gimple_assign_rhs_code (ass);
6162 tree lhs = gimple_assign_lhs (ass);
6163 tree rhs1 = gimple_assign_rhs1 (ass);
6164 tree simplified;
6166 /* Shortcut for copies. Simplifying copies is pointless,
6167 since we copy the expression and value they represent. */
6168 if (code == SSA_NAME
6169 && TREE_CODE (lhs) == SSA_NAME)
6171 changed = visit_copy (lhs, rhs1);
6172 goto done;
6174 simplified = try_to_simplify (ass);
6175 if (simplified)
6177 if (dump_file && (dump_flags & TDF_DETAILS))
6179 fprintf (dump_file, "RHS ");
6180 print_gimple_expr (dump_file, ass, 0);
6181 fprintf (dump_file, " simplified to ");
6182 print_generic_expr (dump_file, simplified);
6183 fprintf (dump_file, "\n");
6186 /* Setting value numbers to constants will occasionally
6187 screw up phi congruence because constants are not
6188 uniquely associated with a single ssa name that can be
6189 looked up. */
6190 if (simplified
6191 && is_gimple_min_invariant (simplified)
6192 && TREE_CODE (lhs) == SSA_NAME)
6194 changed = set_ssa_val_to (lhs, simplified);
6195 goto done;
6197 else if (simplified
6198 && TREE_CODE (simplified) == SSA_NAME
6199 && TREE_CODE (lhs) == SSA_NAME)
6201 changed = visit_copy (lhs, simplified);
6202 goto done;
6205 if ((TREE_CODE (lhs) == SSA_NAME
6206 /* We can substitute SSA_NAMEs that are live over
6207 abnormal edges with their constant value. */
6208 && !(gimple_assign_copy_p (ass)
6209 && is_gimple_min_invariant (rhs1))
6210 && !(simplified
6211 && is_gimple_min_invariant (simplified))
6212 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
6213 /* Stores or copies from SSA_NAMEs that are live over
6214 abnormal edges are a problem. */
6215 || (code == SSA_NAME
6216 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (rhs1)))
6217 changed = defs_to_varying (ass);
6218 else if (REFERENCE_CLASS_P (lhs)
6219 || DECL_P (lhs))
6220 changed = visit_reference_op_store (lhs, rhs1, ass);
6221 else if (TREE_CODE (lhs) == SSA_NAME)
6223 if ((gimple_assign_copy_p (ass)
6224 && is_gimple_min_invariant (rhs1))
6225 || (simplified
6226 && is_gimple_min_invariant (simplified)))
6228 if (simplified)
6229 changed = set_ssa_val_to (lhs, simplified);
6230 else
6231 changed = set_ssa_val_to (lhs, rhs1);
6233 else
6235 /* Visit the original statement. */
6236 switch (vn_get_stmt_kind (ass))
6238 case VN_NARY:
6239 changed = visit_nary_op (lhs, ass);
6240 break;
6241 case VN_REFERENCE:
6242 changed = visit_reference_op_load (lhs, rhs1, ass);
6243 break;
6244 default:
6245 changed = defs_to_varying (ass);
6246 break;
6250 else
6251 changed = defs_to_varying (ass);
6253 else if (gcall *call_stmt = dyn_cast <gcall *> (stmt))
6255 tree lhs = gimple_call_lhs (call_stmt);
6256 if (lhs && TREE_CODE (lhs) == SSA_NAME)
6258 /* Try constant folding based on our current lattice. */
6259 tree simplified = gimple_fold_stmt_to_constant_1 (call_stmt,
6260 vn_valueize);
6261 if (simplified)
6263 if (dump_file && (dump_flags & TDF_DETAILS))
6265 fprintf (dump_file, "call ");
6266 print_gimple_expr (dump_file, call_stmt, 0);
6267 fprintf (dump_file, " simplified to ");
6268 print_generic_expr (dump_file, simplified);
6269 fprintf (dump_file, "\n");
6272 /* Setting value numbers to constants will occasionally
6273 screw up phi congruence because constants are not
6274 uniquely associated with a single ssa name that can be
6275 looked up. */
6276 if (simplified
6277 && is_gimple_min_invariant (simplified))
6279 changed = set_ssa_val_to (lhs, simplified);
6280 if (gimple_vdef (call_stmt))
6281 changed |= set_ssa_val_to (gimple_vdef (call_stmt),
6282 SSA_VAL (gimple_vuse (call_stmt)));
6283 goto done;
6285 else if (simplified
6286 && TREE_CODE (simplified) == SSA_NAME)
6288 changed = visit_copy (lhs, simplified);
6289 if (gimple_vdef (call_stmt))
6290 changed |= set_ssa_val_to (gimple_vdef (call_stmt),
6291 SSA_VAL (gimple_vuse (call_stmt)));
6292 goto done;
6294 else if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
6296 changed = defs_to_varying (call_stmt);
6297 goto done;
6301 /* Pick up flags from a devirtualization target. */
6302 tree fn = gimple_call_fn (stmt);
6303 int extra_fnflags = 0;
6304 if (fn && TREE_CODE (fn) == SSA_NAME)
6306 fn = SSA_VAL (fn);
6307 if (TREE_CODE (fn) == ADDR_EXPR
6308 && TREE_CODE (TREE_OPERAND (fn, 0)) == FUNCTION_DECL)
6309 extra_fnflags = flags_from_decl_or_type (TREE_OPERAND (fn, 0));
6311 if ((/* Calls to the same function with the same vuse
6312 and the same operands do not necessarily return the same
6313 value, unless they're pure or const. */
6314 ((gimple_call_flags (call_stmt) | extra_fnflags)
6315 & (ECF_PURE | ECF_CONST))
6316 /* If calls have a vdef, subsequent calls won't have
6317 the same incoming vuse. So, if 2 calls with vdef have the
6318 same vuse, we know they're not subsequent.
6319 We can value number 2 calls to the same function with the
6320 same vuse and the same operands which are not subsequent
6321 the same, because there is no code in the program that can
6322 compare the 2 values... */
6323 || (gimple_vdef (call_stmt)
6324 /* ... unless the call returns a pointer which does
6325 not alias with anything else. In which case the
6326 information that the values are distinct are encoded
6327 in the IL. */
6328 && !(gimple_call_return_flags (call_stmt) & ERF_NOALIAS)
6329 /* Only perform the following when being called from PRE
6330 which embeds tail merging. */
6331 && default_vn_walk_kind == VN_WALK))
6332 /* Do not process .DEFERRED_INIT since that confuses uninit
6333 analysis. */
6334 && !gimple_call_internal_p (call_stmt, IFN_DEFERRED_INIT))
6335 changed = visit_reference_op_call (lhs, call_stmt);
6336 else
6337 changed = defs_to_varying (call_stmt);
6339 else
6340 changed = defs_to_varying (stmt);
6341 done:
6342 return changed;
6346 /* Allocate a value number table. */
6348 static void
6349 allocate_vn_table (vn_tables_t table, unsigned size)
6351 table->phis = new vn_phi_table_type (size);
6352 table->nary = new vn_nary_op_table_type (size);
6353 table->references = new vn_reference_table_type (size);
6356 /* Free a value number table. */
6358 static void
6359 free_vn_table (vn_tables_t table)
6361 /* Walk over elements and release vectors. */
6362 vn_reference_iterator_type hir;
6363 vn_reference_t vr;
6364 FOR_EACH_HASH_TABLE_ELEMENT (*table->references, vr, vn_reference_t, hir)
6365 vr->operands.release ();
6366 delete table->phis;
6367 table->phis = NULL;
6368 delete table->nary;
6369 table->nary = NULL;
6370 delete table->references;
6371 table->references = NULL;
6374 /* Set *ID according to RESULT. */
6376 static void
6377 set_value_id_for_result (tree result, unsigned int *id)
6379 if (result && TREE_CODE (result) == SSA_NAME)
6380 *id = VN_INFO (result)->value_id;
6381 else if (result && is_gimple_min_invariant (result))
6382 *id = get_or_alloc_constant_value_id (result);
6383 else
6384 *id = get_next_value_id ();
6387 /* Set the value ids in the valid hash tables. */
6389 static void
6390 set_hashtable_value_ids (void)
6392 vn_nary_op_iterator_type hin;
6393 vn_phi_iterator_type hip;
6394 vn_reference_iterator_type hir;
6395 vn_nary_op_t vno;
6396 vn_reference_t vr;
6397 vn_phi_t vp;
6399 /* Now set the value ids of the things we had put in the hash
6400 table. */
6402 FOR_EACH_HASH_TABLE_ELEMENT (*valid_info->nary, vno, vn_nary_op_t, hin)
6403 if (! vno->predicated_values)
6404 set_value_id_for_result (vno->u.result, &vno->value_id);
6406 FOR_EACH_HASH_TABLE_ELEMENT (*valid_info->phis, vp, vn_phi_t, hip)
6407 set_value_id_for_result (vp->result, &vp->value_id);
6409 FOR_EACH_HASH_TABLE_ELEMENT (*valid_info->references, vr, vn_reference_t,
6410 hir)
6411 set_value_id_for_result (vr->result, &vr->value_id);
6414 /* Return the maximum value id we have ever seen. */
6416 unsigned int
6417 get_max_value_id (void)
6419 return next_value_id;
6422 /* Return the maximum constant value id we have ever seen. */
6424 unsigned int
6425 get_max_constant_value_id (void)
6427 return -next_constant_value_id;
6430 /* Return the next unique value id. */
6432 unsigned int
6433 get_next_value_id (void)
6435 gcc_checking_assert ((int)next_value_id > 0);
6436 return next_value_id++;
6439 /* Return the next unique value id for constants. */
6441 unsigned int
6442 get_next_constant_value_id (void)
6444 gcc_checking_assert (next_constant_value_id < 0);
6445 return next_constant_value_id--;
6449 /* Compare two expressions E1 and E2 and return true if they are equal.
6450 If match_vn_top_optimistically is true then VN_TOP is equal to anything,
6451 otherwise VN_TOP only matches VN_TOP. */
6453 bool
6454 expressions_equal_p (tree e1, tree e2, bool match_vn_top_optimistically)
6456 /* The obvious case. */
6457 if (e1 == e2)
6458 return true;
6460 /* If either one is VN_TOP consider them equal. */
6461 if (match_vn_top_optimistically
6462 && (e1 == VN_TOP || e2 == VN_TOP))
6463 return true;
6465 /* If only one of them is null, they cannot be equal. While in general
6466 this should not happen for operations like TARGET_MEM_REF some
6467 operands are optional and an identity value we could substitute
6468 has differing semantics. */
6469 if (!e1 || !e2)
6470 return false;
6472 /* SSA_NAME compare pointer equal. */
6473 if (TREE_CODE (e1) == SSA_NAME || TREE_CODE (e2) == SSA_NAME)
6474 return false;
6476 /* Now perform the actual comparison. */
6477 if (TREE_CODE (e1) == TREE_CODE (e2)
6478 && operand_equal_p (e1, e2, OEP_PURE_SAME))
6479 return true;
6481 return false;
6485 /* Return true if the nary operation NARY may trap. This is a copy
6486 of stmt_could_throw_1_p adjusted to the SCCVN IL. */
6488 bool
6489 vn_nary_may_trap (vn_nary_op_t nary)
6491 tree type;
6492 tree rhs2 = NULL_TREE;
6493 bool honor_nans = false;
6494 bool honor_snans = false;
6495 bool fp_operation = false;
6496 bool honor_trapv = false;
6497 bool handled, ret;
6498 unsigned i;
6500 if (TREE_CODE_CLASS (nary->opcode) == tcc_comparison
6501 || TREE_CODE_CLASS (nary->opcode) == tcc_unary
6502 || TREE_CODE_CLASS (nary->opcode) == tcc_binary)
6504 type = nary->type;
6505 fp_operation = FLOAT_TYPE_P (type);
6506 if (fp_operation)
6508 honor_nans = flag_trapping_math && !flag_finite_math_only;
6509 honor_snans = flag_signaling_nans != 0;
6511 else if (INTEGRAL_TYPE_P (type) && TYPE_OVERFLOW_TRAPS (type))
6512 honor_trapv = true;
6514 if (nary->length >= 2)
6515 rhs2 = nary->op[1];
6516 ret = operation_could_trap_helper_p (nary->opcode, fp_operation,
6517 honor_trapv, honor_nans, honor_snans,
6518 rhs2, &handled);
6519 if (handled && ret)
6520 return true;
6522 for (i = 0; i < nary->length; ++i)
6523 if (tree_could_trap_p (nary->op[i]))
6524 return true;
6526 return false;
6529 /* Return true if the reference operation REF may trap. */
6531 bool
6532 vn_reference_may_trap (vn_reference_t ref)
6534 switch (ref->operands[0].opcode)
6536 case MODIFY_EXPR:
6537 case CALL_EXPR:
6538 /* We do not handle calls. */
6539 return true;
6540 case ADDR_EXPR:
6541 /* And toplevel address computations never trap. */
6542 return false;
6543 default:;
6546 vn_reference_op_t op;
6547 unsigned i;
6548 FOR_EACH_VEC_ELT (ref->operands, i, op)
6550 switch (op->opcode)
6552 case WITH_SIZE_EXPR:
6553 case TARGET_MEM_REF:
6554 /* Always variable. */
6555 return true;
6556 case COMPONENT_REF:
6557 if (op->op1 && TREE_CODE (op->op1) == SSA_NAME)
6558 return true;
6559 break;
6560 case ARRAY_RANGE_REF:
6561 if (TREE_CODE (op->op0) == SSA_NAME)
6562 return true;
6563 break;
6564 case ARRAY_REF:
6566 if (TREE_CODE (op->op0) != INTEGER_CST)
6567 return true;
6569 /* !in_array_bounds */
6570 tree domain_type = TYPE_DOMAIN (ref->operands[i+1].type);
6571 if (!domain_type)
6572 return true;
6574 tree min = op->op1;
6575 tree max = TYPE_MAX_VALUE (domain_type);
6576 if (!min
6577 || !max
6578 || TREE_CODE (min) != INTEGER_CST
6579 || TREE_CODE (max) != INTEGER_CST)
6580 return true;
6582 if (tree_int_cst_lt (op->op0, min)
6583 || tree_int_cst_lt (max, op->op0))
6584 return true;
6586 break;
6588 case MEM_REF:
6589 /* Nothing interesting in itself, the base is separate. */
6590 break;
6591 /* The following are the address bases. */
6592 case SSA_NAME:
6593 return true;
6594 case ADDR_EXPR:
6595 if (op->op0)
6596 return tree_could_trap_p (TREE_OPERAND (op->op0, 0));
6597 return false;
6598 default:;
6601 return false;
6604 eliminate_dom_walker::eliminate_dom_walker (cdi_direction direction,
6605 bitmap inserted_exprs_)
6606 : dom_walker (direction), do_pre (inserted_exprs_ != NULL),
6607 el_todo (0), eliminations (0), insertions (0),
6608 inserted_exprs (inserted_exprs_)
6610 need_eh_cleanup = BITMAP_ALLOC (NULL);
6611 need_ab_cleanup = BITMAP_ALLOC (NULL);
6614 eliminate_dom_walker::~eliminate_dom_walker ()
6616 BITMAP_FREE (need_eh_cleanup);
6617 BITMAP_FREE (need_ab_cleanup);
6620 /* Return a leader for OP that is available at the current point of the
6621 eliminate domwalk. */
6623 tree
6624 eliminate_dom_walker::eliminate_avail (basic_block, tree op)
6626 tree valnum = VN_INFO (op)->valnum;
6627 if (TREE_CODE (valnum) == SSA_NAME)
6629 if (SSA_NAME_IS_DEFAULT_DEF (valnum))
6630 return valnum;
6631 if (avail.length () > SSA_NAME_VERSION (valnum))
6633 tree av = avail[SSA_NAME_VERSION (valnum)];
6634 /* When PRE discovers a new redundancy there's no way to unite
6635 the value classes so it instead inserts a copy old-val = new-val.
6636 Look through such copies here, providing one more level of
6637 simplification at elimination time. */
6638 gassign *ass;
6639 if (av && (ass = dyn_cast <gassign *> (SSA_NAME_DEF_STMT (av))))
6640 if (gimple_assign_rhs_class (ass) == GIMPLE_SINGLE_RHS)
6642 tree rhs1 = gimple_assign_rhs1 (ass);
6643 if (CONSTANT_CLASS_P (rhs1)
6644 || (TREE_CODE (rhs1) == SSA_NAME
6645 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (rhs1)))
6646 av = rhs1;
6648 return av;
6651 else if (is_gimple_min_invariant (valnum))
6652 return valnum;
6653 return NULL_TREE;
6656 /* At the current point of the eliminate domwalk make OP available. */
6658 void
6659 eliminate_dom_walker::eliminate_push_avail (basic_block, tree op)
6661 tree valnum = VN_INFO (op)->valnum;
6662 if (TREE_CODE (valnum) == SSA_NAME)
6664 if (avail.length () <= SSA_NAME_VERSION (valnum))
6665 avail.safe_grow_cleared (SSA_NAME_VERSION (valnum) + 1, true);
6666 tree pushop = op;
6667 if (avail[SSA_NAME_VERSION (valnum)])
6668 pushop = avail[SSA_NAME_VERSION (valnum)];
6669 avail_stack.safe_push (pushop);
6670 avail[SSA_NAME_VERSION (valnum)] = op;
6674 /* Insert the expression recorded by SCCVN for VAL at *GSI. Returns
6675 the leader for the expression if insertion was successful. */
6677 tree
6678 eliminate_dom_walker::eliminate_insert (basic_block bb,
6679 gimple_stmt_iterator *gsi, tree val)
6681 /* We can insert a sequence with a single assignment only. */
6682 gimple_seq stmts = VN_INFO (val)->expr;
6683 if (!gimple_seq_singleton_p (stmts))
6684 return NULL_TREE;
6685 gassign *stmt = dyn_cast <gassign *> (gimple_seq_first_stmt (stmts));
6686 if (!stmt
6687 || (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt))
6688 && gimple_assign_rhs_code (stmt) != VIEW_CONVERT_EXPR
6689 && gimple_assign_rhs_code (stmt) != NEGATE_EXPR
6690 && gimple_assign_rhs_code (stmt) != BIT_FIELD_REF
6691 && (gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
6692 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)))
6693 return NULL_TREE;
6695 tree op = gimple_assign_rhs1 (stmt);
6696 if (gimple_assign_rhs_code (stmt) == VIEW_CONVERT_EXPR
6697 || gimple_assign_rhs_code (stmt) == BIT_FIELD_REF)
6698 op = TREE_OPERAND (op, 0);
6699 tree leader = TREE_CODE (op) == SSA_NAME ? eliminate_avail (bb, op) : op;
6700 if (!leader)
6701 return NULL_TREE;
6703 tree res;
6704 stmts = NULL;
6705 if (gimple_assign_rhs_code (stmt) == BIT_FIELD_REF)
6706 res = gimple_build (&stmts, BIT_FIELD_REF,
6707 TREE_TYPE (val), leader,
6708 TREE_OPERAND (gimple_assign_rhs1 (stmt), 1),
6709 TREE_OPERAND (gimple_assign_rhs1 (stmt), 2));
6710 else if (gimple_assign_rhs_code (stmt) == BIT_AND_EXPR)
6711 res = gimple_build (&stmts, BIT_AND_EXPR,
6712 TREE_TYPE (val), leader, gimple_assign_rhs2 (stmt));
6713 else
6714 res = gimple_build (&stmts, gimple_assign_rhs_code (stmt),
6715 TREE_TYPE (val), leader);
6716 if (TREE_CODE (res) != SSA_NAME
6717 || SSA_NAME_IS_DEFAULT_DEF (res)
6718 || gimple_bb (SSA_NAME_DEF_STMT (res)))
6720 gimple_seq_discard (stmts);
6722 /* During propagation we have to treat SSA info conservatively
6723 and thus we can end up simplifying the inserted expression
6724 at elimination time to sth not defined in stmts. */
6725 /* But then this is a redundancy we failed to detect. Which means
6726 res now has two values. That doesn't play well with how
6727 we track availability here, so give up. */
6728 if (dump_file && (dump_flags & TDF_DETAILS))
6730 if (TREE_CODE (res) == SSA_NAME)
6731 res = eliminate_avail (bb, res);
6732 if (res)
6734 fprintf (dump_file, "Failed to insert expression for value ");
6735 print_generic_expr (dump_file, val);
6736 fprintf (dump_file, " which is really fully redundant to ");
6737 print_generic_expr (dump_file, res);
6738 fprintf (dump_file, "\n");
6742 return NULL_TREE;
6744 else
6746 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
6747 vn_ssa_aux_t vn_info = VN_INFO (res);
6748 vn_info->valnum = val;
6749 vn_info->visited = true;
6752 insertions++;
6753 if (dump_file && (dump_flags & TDF_DETAILS))
6755 fprintf (dump_file, "Inserted ");
6756 print_gimple_stmt (dump_file, SSA_NAME_DEF_STMT (res), 0);
6759 return res;
6762 void
6763 eliminate_dom_walker::eliminate_stmt (basic_block b, gimple_stmt_iterator *gsi)
6765 tree sprime = NULL_TREE;
6766 gimple *stmt = gsi_stmt (*gsi);
6767 tree lhs = gimple_get_lhs (stmt);
6768 if (lhs && TREE_CODE (lhs) == SSA_NAME
6769 && !gimple_has_volatile_ops (stmt)
6770 /* See PR43491. Do not replace a global register variable when
6771 it is a the RHS of an assignment. Do replace local register
6772 variables since gcc does not guarantee a local variable will
6773 be allocated in register.
6774 ??? The fix isn't effective here. This should instead
6775 be ensured by not value-numbering them the same but treating
6776 them like volatiles? */
6777 && !(gimple_assign_single_p (stmt)
6778 && (TREE_CODE (gimple_assign_rhs1 (stmt)) == VAR_DECL
6779 && DECL_HARD_REGISTER (gimple_assign_rhs1 (stmt))
6780 && is_global_var (gimple_assign_rhs1 (stmt)))))
6782 sprime = eliminate_avail (b, lhs);
6783 if (!sprime)
6785 /* If there is no existing usable leader but SCCVN thinks
6786 it has an expression it wants to use as replacement,
6787 insert that. */
6788 tree val = VN_INFO (lhs)->valnum;
6789 vn_ssa_aux_t vn_info;
6790 if (val != VN_TOP
6791 && TREE_CODE (val) == SSA_NAME
6792 && (vn_info = VN_INFO (val), true)
6793 && vn_info->needs_insertion
6794 && vn_info->expr != NULL
6795 && (sprime = eliminate_insert (b, gsi, val)) != NULL_TREE)
6796 eliminate_push_avail (b, sprime);
6799 /* If this now constitutes a copy duplicate points-to
6800 and range info appropriately. This is especially
6801 important for inserted code. See tree-ssa-copy.cc
6802 for similar code. */
6803 if (sprime
6804 && TREE_CODE (sprime) == SSA_NAME)
6806 basic_block sprime_b = gimple_bb (SSA_NAME_DEF_STMT (sprime));
6807 if (POINTER_TYPE_P (TREE_TYPE (lhs))
6808 && SSA_NAME_PTR_INFO (lhs)
6809 && ! SSA_NAME_PTR_INFO (sprime))
6811 duplicate_ssa_name_ptr_info (sprime,
6812 SSA_NAME_PTR_INFO (lhs));
6813 if (b != sprime_b)
6814 reset_flow_sensitive_info (sprime);
6816 else if (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
6817 && SSA_NAME_RANGE_INFO (lhs)
6818 && ! SSA_NAME_RANGE_INFO (sprime)
6819 && b == sprime_b)
6820 duplicate_ssa_name_range_info (sprime, lhs);
6823 /* Inhibit the use of an inserted PHI on a loop header when
6824 the address of the memory reference is a simple induction
6825 variable. In other cases the vectorizer won't do anything
6826 anyway (either it's loop invariant or a complicated
6827 expression). */
6828 if (sprime
6829 && TREE_CODE (sprime) == SSA_NAME
6830 && do_pre
6831 && (flag_tree_loop_vectorize || flag_tree_parallelize_loops > 1)
6832 && loop_outer (b->loop_father)
6833 && has_zero_uses (sprime)
6834 && bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (sprime))
6835 && gimple_assign_load_p (stmt))
6837 gimple *def_stmt = SSA_NAME_DEF_STMT (sprime);
6838 basic_block def_bb = gimple_bb (def_stmt);
6839 if (gimple_code (def_stmt) == GIMPLE_PHI
6840 && def_bb->loop_father->header == def_bb)
6842 loop_p loop = def_bb->loop_father;
6843 ssa_op_iter iter;
6844 tree op;
6845 bool found = false;
6846 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
6848 affine_iv iv;
6849 def_bb = gimple_bb (SSA_NAME_DEF_STMT (op));
6850 if (def_bb
6851 && flow_bb_inside_loop_p (loop, def_bb)
6852 && simple_iv (loop, loop, op, &iv, true))
6854 found = true;
6855 break;
6858 if (found)
6860 if (dump_file && (dump_flags & TDF_DETAILS))
6862 fprintf (dump_file, "Not replacing ");
6863 print_gimple_expr (dump_file, stmt, 0);
6864 fprintf (dump_file, " with ");
6865 print_generic_expr (dump_file, sprime);
6866 fprintf (dump_file, " which would add a loop"
6867 " carried dependence to loop %d\n",
6868 loop->num);
6870 /* Don't keep sprime available. */
6871 sprime = NULL_TREE;
6876 if (sprime)
6878 /* If we can propagate the value computed for LHS into
6879 all uses don't bother doing anything with this stmt. */
6880 if (may_propagate_copy (lhs, sprime))
6882 /* Mark it for removal. */
6883 to_remove.safe_push (stmt);
6885 /* ??? Don't count copy/constant propagations. */
6886 if (gimple_assign_single_p (stmt)
6887 && (TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME
6888 || gimple_assign_rhs1 (stmt) == sprime))
6889 return;
6891 if (dump_file && (dump_flags & TDF_DETAILS))
6893 fprintf (dump_file, "Replaced ");
6894 print_gimple_expr (dump_file, stmt, 0);
6895 fprintf (dump_file, " with ");
6896 print_generic_expr (dump_file, sprime);
6897 fprintf (dump_file, " in all uses of ");
6898 print_gimple_stmt (dump_file, stmt, 0);
6901 eliminations++;
6902 return;
6905 /* If this is an assignment from our leader (which
6906 happens in the case the value-number is a constant)
6907 then there is nothing to do. Likewise if we run into
6908 inserted code that needed a conversion because of
6909 our type-agnostic value-numbering of loads. */
6910 if ((gimple_assign_single_p (stmt)
6911 || (is_gimple_assign (stmt)
6912 && (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt))
6913 || gimple_assign_rhs_code (stmt) == VIEW_CONVERT_EXPR)))
6914 && sprime == gimple_assign_rhs1 (stmt))
6915 return;
6917 /* Else replace its RHS. */
6918 if (dump_file && (dump_flags & TDF_DETAILS))
6920 fprintf (dump_file, "Replaced ");
6921 print_gimple_expr (dump_file, stmt, 0);
6922 fprintf (dump_file, " with ");
6923 print_generic_expr (dump_file, sprime);
6924 fprintf (dump_file, " in ");
6925 print_gimple_stmt (dump_file, stmt, 0);
6927 eliminations++;
6929 bool can_make_abnormal_goto = (is_gimple_call (stmt)
6930 && stmt_can_make_abnormal_goto (stmt));
6931 gimple *orig_stmt = stmt;
6932 if (!useless_type_conversion_p (TREE_TYPE (lhs),
6933 TREE_TYPE (sprime)))
6935 /* We preserve conversions to but not from function or method
6936 types. This asymmetry makes it necessary to re-instantiate
6937 conversions here. */
6938 if (POINTER_TYPE_P (TREE_TYPE (lhs))
6939 && FUNC_OR_METHOD_TYPE_P (TREE_TYPE (TREE_TYPE (lhs))))
6940 sprime = fold_convert (TREE_TYPE (lhs), sprime);
6941 else
6942 gcc_unreachable ();
6944 tree vdef = gimple_vdef (stmt);
6945 tree vuse = gimple_vuse (stmt);
6946 propagate_tree_value_into_stmt (gsi, sprime);
6947 stmt = gsi_stmt (*gsi);
6948 update_stmt (stmt);
6949 /* In case the VDEF on the original stmt was released, value-number
6950 it to the VUSE. This is to make vuse_ssa_val able to skip
6951 released virtual operands. */
6952 if (vdef != gimple_vdef (stmt))
6954 gcc_assert (SSA_NAME_IN_FREE_LIST (vdef));
6955 VN_INFO (vdef)->valnum = vuse;
6958 /* If we removed EH side-effects from the statement, clean
6959 its EH information. */
6960 if (maybe_clean_or_replace_eh_stmt (orig_stmt, stmt))
6962 bitmap_set_bit (need_eh_cleanup,
6963 gimple_bb (stmt)->index);
6964 if (dump_file && (dump_flags & TDF_DETAILS))
6965 fprintf (dump_file, " Removed EH side-effects.\n");
6968 /* Likewise for AB side-effects. */
6969 if (can_make_abnormal_goto
6970 && !stmt_can_make_abnormal_goto (stmt))
6972 bitmap_set_bit (need_ab_cleanup,
6973 gimple_bb (stmt)->index);
6974 if (dump_file && (dump_flags & TDF_DETAILS))
6975 fprintf (dump_file, " Removed AB side-effects.\n");
6978 return;
6982 /* If the statement is a scalar store, see if the expression
6983 has the same value number as its rhs. If so, the store is
6984 dead. */
6985 if (gimple_assign_single_p (stmt)
6986 && !gimple_has_volatile_ops (stmt)
6987 && !is_gimple_reg (gimple_assign_lhs (stmt))
6988 && (TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME
6989 || is_gimple_min_invariant (gimple_assign_rhs1 (stmt))))
6991 tree rhs = gimple_assign_rhs1 (stmt);
6992 vn_reference_t vnresult;
6993 /* ??? gcc.dg/torture/pr91445.c shows that we lookup a boolean
6994 typed load of a byte known to be 0x11 as 1 so a store of
6995 a boolean 1 is detected as redundant. Because of this we
6996 have to make sure to lookup with a ref where its size
6997 matches the precision. */
6998 tree lookup_lhs = lhs;
6999 if (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
7000 && (TREE_CODE (lhs) != COMPONENT_REF
7001 || !DECL_BIT_FIELD_TYPE (TREE_OPERAND (lhs, 1)))
7002 && !type_has_mode_precision_p (TREE_TYPE (lhs)))
7004 if (TREE_CODE (lhs) == COMPONENT_REF
7005 || TREE_CODE (lhs) == MEM_REF)
7007 tree ltype = build_nonstandard_integer_type
7008 (TREE_INT_CST_LOW (TYPE_SIZE (TREE_TYPE (lhs))),
7009 TYPE_UNSIGNED (TREE_TYPE (lhs)));
7010 if (TREE_CODE (lhs) == COMPONENT_REF)
7012 tree foff = component_ref_field_offset (lhs);
7013 tree f = TREE_OPERAND (lhs, 1);
7014 if (!poly_int_tree_p (foff))
7015 lookup_lhs = NULL_TREE;
7016 else
7017 lookup_lhs = build3 (BIT_FIELD_REF, ltype,
7018 TREE_OPERAND (lhs, 0),
7019 TYPE_SIZE (TREE_TYPE (lhs)),
7020 bit_from_pos
7021 (foff, DECL_FIELD_BIT_OFFSET (f)));
7023 else
7024 lookup_lhs = build2 (MEM_REF, ltype,
7025 TREE_OPERAND (lhs, 0),
7026 TREE_OPERAND (lhs, 1));
7028 else
7029 lookup_lhs = NULL_TREE;
7031 tree val = NULL_TREE;
7032 if (lookup_lhs)
7033 val = vn_reference_lookup (lookup_lhs, gimple_vuse (stmt),
7034 VN_WALKREWRITE, &vnresult, false,
7035 NULL, NULL_TREE, true);
7036 if (TREE_CODE (rhs) == SSA_NAME)
7037 rhs = VN_INFO (rhs)->valnum;
7038 if (val
7039 && (operand_equal_p (val, rhs, 0)
7040 /* Due to the bitfield lookups above we can get bit
7041 interpretations of the same RHS as values here. Those
7042 are redundant as well. */
7043 || (TREE_CODE (val) == SSA_NAME
7044 && gimple_assign_single_p (SSA_NAME_DEF_STMT (val))
7045 && (val = gimple_assign_rhs1 (SSA_NAME_DEF_STMT (val)))
7046 && TREE_CODE (val) == VIEW_CONVERT_EXPR
7047 && TREE_OPERAND (val, 0) == rhs)))
7049 /* We can only remove the later store if the former aliases
7050 at least all accesses the later one does or if the store
7051 was to readonly memory storing the same value. */
7052 ao_ref lhs_ref;
7053 ao_ref_init (&lhs_ref, lhs);
7054 alias_set_type set = ao_ref_alias_set (&lhs_ref);
7055 alias_set_type base_set = ao_ref_base_alias_set (&lhs_ref);
7056 if (! vnresult
7057 || ((vnresult->set == set
7058 || alias_set_subset_of (set, vnresult->set))
7059 && (vnresult->base_set == base_set
7060 || alias_set_subset_of (base_set, vnresult->base_set))))
7062 if (dump_file && (dump_flags & TDF_DETAILS))
7064 fprintf (dump_file, "Deleted redundant store ");
7065 print_gimple_stmt (dump_file, stmt, 0);
7068 /* Queue stmt for removal. */
7069 to_remove.safe_push (stmt);
7070 return;
7075 /* If this is a control statement value numbering left edges
7076 unexecuted on force the condition in a way consistent with
7077 that. */
7078 if (gcond *cond = dyn_cast <gcond *> (stmt))
7080 if ((EDGE_SUCC (b, 0)->flags & EDGE_EXECUTABLE)
7081 ^ (EDGE_SUCC (b, 1)->flags & EDGE_EXECUTABLE))
7083 if (dump_file && (dump_flags & TDF_DETAILS))
7085 fprintf (dump_file, "Removing unexecutable edge from ");
7086 print_gimple_stmt (dump_file, stmt, 0);
7088 if (((EDGE_SUCC (b, 0)->flags & EDGE_TRUE_VALUE) != 0)
7089 == ((EDGE_SUCC (b, 0)->flags & EDGE_EXECUTABLE) != 0))
7090 gimple_cond_make_true (cond);
7091 else
7092 gimple_cond_make_false (cond);
7093 update_stmt (cond);
7094 el_todo |= TODO_cleanup_cfg;
7095 return;
7099 bool can_make_abnormal_goto = stmt_can_make_abnormal_goto (stmt);
7100 bool was_noreturn = (is_gimple_call (stmt)
7101 && gimple_call_noreturn_p (stmt));
7102 tree vdef = gimple_vdef (stmt);
7103 tree vuse = gimple_vuse (stmt);
7105 /* If we didn't replace the whole stmt (or propagate the result
7106 into all uses), replace all uses on this stmt with their
7107 leaders. */
7108 bool modified = false;
7109 use_operand_p use_p;
7110 ssa_op_iter iter;
7111 FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_USE)
7113 tree use = USE_FROM_PTR (use_p);
7114 /* ??? The call code above leaves stmt operands un-updated. */
7115 if (TREE_CODE (use) != SSA_NAME)
7116 continue;
7117 tree sprime;
7118 if (SSA_NAME_IS_DEFAULT_DEF (use))
7119 /* ??? For default defs BB shouldn't matter, but we have to
7120 solve the inconsistency between rpo eliminate and
7121 dom eliminate avail valueization first. */
7122 sprime = eliminate_avail (b, use);
7123 else
7124 /* Look for sth available at the definition block of the argument.
7125 This avoids inconsistencies between availability there which
7126 decides if the stmt can be removed and availability at the
7127 use site. The SSA property ensures that things available
7128 at the definition are also available at uses. */
7129 sprime = eliminate_avail (gimple_bb (SSA_NAME_DEF_STMT (use)), use);
7130 if (sprime && sprime != use
7131 && may_propagate_copy (use, sprime, true)
7132 /* We substitute into debug stmts to avoid excessive
7133 debug temporaries created by removed stmts, but we need
7134 to avoid doing so for inserted sprimes as we never want
7135 to create debug temporaries for them. */
7136 && (!inserted_exprs
7137 || TREE_CODE (sprime) != SSA_NAME
7138 || !is_gimple_debug (stmt)
7139 || !bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (sprime))))
7141 propagate_value (use_p, sprime);
7142 modified = true;
7146 /* Fold the stmt if modified, this canonicalizes MEM_REFs we propagated
7147 into which is a requirement for the IPA devirt machinery. */
7148 gimple *old_stmt = stmt;
7149 if (modified)
7151 /* If a formerly non-invariant ADDR_EXPR is turned into an
7152 invariant one it was on a separate stmt. */
7153 if (gimple_assign_single_p (stmt)
7154 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ADDR_EXPR)
7155 recompute_tree_invariant_for_addr_expr (gimple_assign_rhs1 (stmt));
7156 gimple_stmt_iterator prev = *gsi;
7157 gsi_prev (&prev);
7158 if (fold_stmt (gsi, follow_all_ssa_edges))
7160 /* fold_stmt may have created new stmts inbetween
7161 the previous stmt and the folded stmt. Mark
7162 all defs created there as varying to not confuse
7163 the SCCVN machinery as we're using that even during
7164 elimination. */
7165 if (gsi_end_p (prev))
7166 prev = gsi_start_bb (b);
7167 else
7168 gsi_next (&prev);
7169 if (gsi_stmt (prev) != gsi_stmt (*gsi))
7172 tree def;
7173 ssa_op_iter dit;
7174 FOR_EACH_SSA_TREE_OPERAND (def, gsi_stmt (prev),
7175 dit, SSA_OP_ALL_DEFS)
7176 /* As existing DEFs may move between stmts
7177 only process new ones. */
7178 if (! has_VN_INFO (def))
7180 vn_ssa_aux_t vn_info = VN_INFO (def);
7181 vn_info->valnum = def;
7182 vn_info->visited = true;
7184 if (gsi_stmt (prev) == gsi_stmt (*gsi))
7185 break;
7186 gsi_next (&prev);
7188 while (1);
7190 stmt = gsi_stmt (*gsi);
7191 /* In case we folded the stmt away schedule the NOP for removal. */
7192 if (gimple_nop_p (stmt))
7193 to_remove.safe_push (stmt);
7196 /* Visit indirect calls and turn them into direct calls if
7197 possible using the devirtualization machinery. Do this before
7198 checking for required EH/abnormal/noreturn cleanup as devird
7199 may expose more of those. */
7200 if (gcall *call_stmt = dyn_cast <gcall *> (stmt))
7202 tree fn = gimple_call_fn (call_stmt);
7203 if (fn
7204 && flag_devirtualize
7205 && virtual_method_call_p (fn))
7207 tree otr_type = obj_type_ref_class (fn);
7208 unsigned HOST_WIDE_INT otr_tok
7209 = tree_to_uhwi (OBJ_TYPE_REF_TOKEN (fn));
7210 tree instance;
7211 ipa_polymorphic_call_context context (current_function_decl,
7212 fn, stmt, &instance);
7213 context.get_dynamic_type (instance, OBJ_TYPE_REF_OBJECT (fn),
7214 otr_type, stmt, NULL);
7215 bool final;
7216 vec <cgraph_node *> targets
7217 = possible_polymorphic_call_targets (obj_type_ref_class (fn),
7218 otr_tok, context, &final);
7219 if (dump_file)
7220 dump_possible_polymorphic_call_targets (dump_file,
7221 obj_type_ref_class (fn),
7222 otr_tok, context);
7223 if (final && targets.length () <= 1 && dbg_cnt (devirt))
7225 tree fn;
7226 if (targets.length () == 1)
7227 fn = targets[0]->decl;
7228 else
7229 fn = builtin_decl_unreachable ();
7230 if (dump_enabled_p ())
7232 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, stmt,
7233 "converting indirect call to "
7234 "function %s\n",
7235 lang_hooks.decl_printable_name (fn, 2));
7237 gimple_call_set_fndecl (call_stmt, fn);
7238 /* If changing the call to __builtin_unreachable
7239 or similar noreturn function, adjust gimple_call_fntype
7240 too. */
7241 if (gimple_call_noreturn_p (call_stmt)
7242 && VOID_TYPE_P (TREE_TYPE (TREE_TYPE (fn)))
7243 && TYPE_ARG_TYPES (TREE_TYPE (fn))
7244 && (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (fn)))
7245 == void_type_node))
7246 gimple_call_set_fntype (call_stmt, TREE_TYPE (fn));
7247 maybe_remove_unused_call_args (cfun, call_stmt);
7248 modified = true;
7253 if (modified)
7255 /* When changing a call into a noreturn call, cfg cleanup
7256 is needed to fix up the noreturn call. */
7257 if (!was_noreturn
7258 && is_gimple_call (stmt) && gimple_call_noreturn_p (stmt))
7259 to_fixup.safe_push (stmt);
7260 /* When changing a condition or switch into one we know what
7261 edge will be executed, schedule a cfg cleanup. */
7262 if ((gimple_code (stmt) == GIMPLE_COND
7263 && (gimple_cond_true_p (as_a <gcond *> (stmt))
7264 || gimple_cond_false_p (as_a <gcond *> (stmt))))
7265 || (gimple_code (stmt) == GIMPLE_SWITCH
7266 && TREE_CODE (gimple_switch_index
7267 (as_a <gswitch *> (stmt))) == INTEGER_CST))
7268 el_todo |= TODO_cleanup_cfg;
7269 /* If we removed EH side-effects from the statement, clean
7270 its EH information. */
7271 if (maybe_clean_or_replace_eh_stmt (old_stmt, stmt))
7273 bitmap_set_bit (need_eh_cleanup,
7274 gimple_bb (stmt)->index);
7275 if (dump_file && (dump_flags & TDF_DETAILS))
7276 fprintf (dump_file, " Removed EH side-effects.\n");
7278 /* Likewise for AB side-effects. */
7279 if (can_make_abnormal_goto
7280 && !stmt_can_make_abnormal_goto (stmt))
7282 bitmap_set_bit (need_ab_cleanup,
7283 gimple_bb (stmt)->index);
7284 if (dump_file && (dump_flags & TDF_DETAILS))
7285 fprintf (dump_file, " Removed AB side-effects.\n");
7287 update_stmt (stmt);
7288 /* In case the VDEF on the original stmt was released, value-number
7289 it to the VUSE. This is to make vuse_ssa_val able to skip
7290 released virtual operands. */
7291 if (vdef && SSA_NAME_IN_FREE_LIST (vdef))
7292 VN_INFO (vdef)->valnum = vuse;
7295 /* Make new values available - for fully redundant LHS we
7296 continue with the next stmt above and skip this.
7297 But avoid picking up dead defs. */
7298 tree def;
7299 FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
7300 if (! has_zero_uses (def)
7301 || (inserted_exprs
7302 && bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (def))))
7303 eliminate_push_avail (b, def);
7306 /* Perform elimination for the basic-block B during the domwalk. */
7308 edge
7309 eliminate_dom_walker::before_dom_children (basic_block b)
7311 /* Mark new bb. */
7312 avail_stack.safe_push (NULL_TREE);
7314 /* Skip unreachable blocks marked unreachable during the SCCVN domwalk. */
7315 if (!(b->flags & BB_EXECUTABLE))
7316 return NULL;
7318 vn_context_bb = b;
7320 for (gphi_iterator gsi = gsi_start_phis (b); !gsi_end_p (gsi);)
7322 gphi *phi = gsi.phi ();
7323 tree res = PHI_RESULT (phi);
7325 if (virtual_operand_p (res))
7327 gsi_next (&gsi);
7328 continue;
7331 tree sprime = eliminate_avail (b, res);
7332 if (sprime
7333 && sprime != res)
7335 if (dump_file && (dump_flags & TDF_DETAILS))
7337 fprintf (dump_file, "Replaced redundant PHI node defining ");
7338 print_generic_expr (dump_file, res);
7339 fprintf (dump_file, " with ");
7340 print_generic_expr (dump_file, sprime);
7341 fprintf (dump_file, "\n");
7344 /* If we inserted this PHI node ourself, it's not an elimination. */
7345 if (! inserted_exprs
7346 || ! bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (res)))
7347 eliminations++;
7349 /* If we will propagate into all uses don't bother to do
7350 anything. */
7351 if (may_propagate_copy (res, sprime))
7353 /* Mark the PHI for removal. */
7354 to_remove.safe_push (phi);
7355 gsi_next (&gsi);
7356 continue;
7359 remove_phi_node (&gsi, false);
7361 if (!useless_type_conversion_p (TREE_TYPE (res), TREE_TYPE (sprime)))
7362 sprime = fold_convert (TREE_TYPE (res), sprime);
7363 gimple *stmt = gimple_build_assign (res, sprime);
7364 gimple_stmt_iterator gsi2 = gsi_after_labels (b);
7365 gsi_insert_before (&gsi2, stmt, GSI_NEW_STMT);
7366 continue;
7369 eliminate_push_avail (b, res);
7370 gsi_next (&gsi);
7373 for (gimple_stmt_iterator gsi = gsi_start_bb (b);
7374 !gsi_end_p (gsi);
7375 gsi_next (&gsi))
7376 eliminate_stmt (b, &gsi);
7378 /* Replace destination PHI arguments. */
7379 edge_iterator ei;
7380 edge e;
7381 FOR_EACH_EDGE (e, ei, b->succs)
7382 if (e->flags & EDGE_EXECUTABLE)
7383 for (gphi_iterator gsi = gsi_start_phis (e->dest);
7384 !gsi_end_p (gsi);
7385 gsi_next (&gsi))
7387 gphi *phi = gsi.phi ();
7388 use_operand_p use_p = PHI_ARG_DEF_PTR_FROM_EDGE (phi, e);
7389 tree arg = USE_FROM_PTR (use_p);
7390 if (TREE_CODE (arg) != SSA_NAME
7391 || virtual_operand_p (arg))
7392 continue;
7393 tree sprime = eliminate_avail (b, arg);
7394 if (sprime && may_propagate_copy (arg, sprime))
7395 propagate_value (use_p, sprime);
7398 vn_context_bb = NULL;
7400 return NULL;
7403 /* Make no longer available leaders no longer available. */
7405 void
7406 eliminate_dom_walker::after_dom_children (basic_block)
7408 tree entry;
7409 while ((entry = avail_stack.pop ()) != NULL_TREE)
7411 tree valnum = VN_INFO (entry)->valnum;
7412 tree old = avail[SSA_NAME_VERSION (valnum)];
7413 if (old == entry)
7414 avail[SSA_NAME_VERSION (valnum)] = NULL_TREE;
7415 else
7416 avail[SSA_NAME_VERSION (valnum)] = entry;
7420 /* Remove queued stmts and perform delayed cleanups. */
7422 unsigned
7423 eliminate_dom_walker::eliminate_cleanup (bool region_p)
7425 statistics_counter_event (cfun, "Eliminated", eliminations);
7426 statistics_counter_event (cfun, "Insertions", insertions);
7428 /* We cannot remove stmts during BB walk, especially not release SSA
7429 names there as this confuses the VN machinery. The stmts ending
7430 up in to_remove are either stores or simple copies.
7431 Remove stmts in reverse order to make debug stmt creation possible. */
7432 while (!to_remove.is_empty ())
7434 bool do_release_defs = true;
7435 gimple *stmt = to_remove.pop ();
7437 /* When we are value-numbering a region we do not require exit PHIs to
7438 be present so we have to make sure to deal with uses outside of the
7439 region of stmts that we thought are eliminated.
7440 ??? Note we may be confused by uses in dead regions we didn't run
7441 elimination on. Rather than checking individual uses we accept
7442 dead copies to be generated here (gcc.c-torture/execute/20060905-1.c
7443 contains such example). */
7444 if (region_p)
7446 if (gphi *phi = dyn_cast <gphi *> (stmt))
7448 tree lhs = gimple_phi_result (phi);
7449 if (!has_zero_uses (lhs))
7451 if (dump_file && (dump_flags & TDF_DETAILS))
7452 fprintf (dump_file, "Keeping eliminated stmt live "
7453 "as copy because of out-of-region uses\n");
7454 tree sprime = eliminate_avail (gimple_bb (stmt), lhs);
7455 gimple *copy = gimple_build_assign (lhs, sprime);
7456 gimple_stmt_iterator gsi
7457 = gsi_after_labels (gimple_bb (stmt));
7458 gsi_insert_before (&gsi, copy, GSI_SAME_STMT);
7459 do_release_defs = false;
7462 else if (tree lhs = gimple_get_lhs (stmt))
7463 if (TREE_CODE (lhs) == SSA_NAME
7464 && !has_zero_uses (lhs))
7466 if (dump_file && (dump_flags & TDF_DETAILS))
7467 fprintf (dump_file, "Keeping eliminated stmt live "
7468 "as copy because of out-of-region uses\n");
7469 tree sprime = eliminate_avail (gimple_bb (stmt), lhs);
7470 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
7471 if (is_gimple_assign (stmt))
7473 gimple_assign_set_rhs_from_tree (&gsi, sprime);
7474 stmt = gsi_stmt (gsi);
7475 update_stmt (stmt);
7476 if (maybe_clean_or_replace_eh_stmt (stmt, stmt))
7477 bitmap_set_bit (need_eh_cleanup, gimple_bb (stmt)->index);
7478 continue;
7480 else
7482 gimple *copy = gimple_build_assign (lhs, sprime);
7483 gsi_insert_before (&gsi, copy, GSI_SAME_STMT);
7484 do_release_defs = false;
7489 if (dump_file && (dump_flags & TDF_DETAILS))
7491 fprintf (dump_file, "Removing dead stmt ");
7492 print_gimple_stmt (dump_file, stmt, 0, TDF_NONE);
7495 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
7496 if (gimple_code (stmt) == GIMPLE_PHI)
7497 remove_phi_node (&gsi, do_release_defs);
7498 else
7500 basic_block bb = gimple_bb (stmt);
7501 unlink_stmt_vdef (stmt);
7502 if (gsi_remove (&gsi, true))
7503 bitmap_set_bit (need_eh_cleanup, bb->index);
7504 if (is_gimple_call (stmt) && stmt_can_make_abnormal_goto (stmt))
7505 bitmap_set_bit (need_ab_cleanup, bb->index);
7506 if (do_release_defs)
7507 release_defs (stmt);
7510 /* Removing a stmt may expose a forwarder block. */
7511 el_todo |= TODO_cleanup_cfg;
7514 /* Fixup stmts that became noreturn calls. This may require splitting
7515 blocks and thus isn't possible during the dominator walk. Do this
7516 in reverse order so we don't inadvertedly remove a stmt we want to
7517 fixup by visiting a dominating now noreturn call first. */
7518 while (!to_fixup.is_empty ())
7520 gimple *stmt = to_fixup.pop ();
7522 if (dump_file && (dump_flags & TDF_DETAILS))
7524 fprintf (dump_file, "Fixing up noreturn call ");
7525 print_gimple_stmt (dump_file, stmt, 0);
7528 if (fixup_noreturn_call (stmt))
7529 el_todo |= TODO_cleanup_cfg;
7532 bool do_eh_cleanup = !bitmap_empty_p (need_eh_cleanup);
7533 bool do_ab_cleanup = !bitmap_empty_p (need_ab_cleanup);
7535 if (do_eh_cleanup)
7536 gimple_purge_all_dead_eh_edges (need_eh_cleanup);
7538 if (do_ab_cleanup)
7539 gimple_purge_all_dead_abnormal_call_edges (need_ab_cleanup);
7541 if (do_eh_cleanup || do_ab_cleanup)
7542 el_todo |= TODO_cleanup_cfg;
7544 return el_todo;
7547 /* Eliminate fully redundant computations. */
7549 unsigned
7550 eliminate_with_rpo_vn (bitmap inserted_exprs)
7552 eliminate_dom_walker walker (CDI_DOMINATORS, inserted_exprs);
7554 eliminate_dom_walker *saved_rpo_avail = rpo_avail;
7555 rpo_avail = &walker;
7556 walker.walk (cfun->cfg->x_entry_block_ptr);
7557 rpo_avail = saved_rpo_avail;
7559 return walker.eliminate_cleanup ();
7562 static unsigned
7563 do_rpo_vn_1 (function *fn, edge entry, bitmap exit_bbs,
7564 bool iterate, bool eliminate, vn_lookup_kind kind);
7566 void
7567 run_rpo_vn (vn_lookup_kind kind)
7569 do_rpo_vn_1 (cfun, NULL, NULL, true, false, kind);
7571 /* ??? Prune requirement of these. */
7572 constant_to_value_id = new hash_table<vn_constant_hasher> (23);
7574 /* Initialize the value ids and prune out remaining VN_TOPs
7575 from dead code. */
7576 tree name;
7577 unsigned i;
7578 FOR_EACH_SSA_NAME (i, name, cfun)
7580 vn_ssa_aux_t info = VN_INFO (name);
7581 if (!info->visited
7582 || info->valnum == VN_TOP)
7583 info->valnum = name;
7584 if (info->valnum == name)
7585 info->value_id = get_next_value_id ();
7586 else if (is_gimple_min_invariant (info->valnum))
7587 info->value_id = get_or_alloc_constant_value_id (info->valnum);
7590 /* Propagate. */
7591 FOR_EACH_SSA_NAME (i, name, cfun)
7593 vn_ssa_aux_t info = VN_INFO (name);
7594 if (TREE_CODE (info->valnum) == SSA_NAME
7595 && info->valnum != name
7596 && info->value_id != VN_INFO (info->valnum)->value_id)
7597 info->value_id = VN_INFO (info->valnum)->value_id;
7600 set_hashtable_value_ids ();
7602 if (dump_file && (dump_flags & TDF_DETAILS))
7604 fprintf (dump_file, "Value numbers:\n");
7605 FOR_EACH_SSA_NAME (i, name, cfun)
7607 if (VN_INFO (name)->visited
7608 && SSA_VAL (name) != name)
7610 print_generic_expr (dump_file, name);
7611 fprintf (dump_file, " = ");
7612 print_generic_expr (dump_file, SSA_VAL (name));
7613 fprintf (dump_file, " (%04d)\n", VN_INFO (name)->value_id);
7619 /* Free VN associated data structures. */
7621 void
7622 free_rpo_vn (void)
7624 free_vn_table (valid_info);
7625 XDELETE (valid_info);
7626 obstack_free (&vn_tables_obstack, NULL);
7627 obstack_free (&vn_tables_insert_obstack, NULL);
7629 vn_ssa_aux_iterator_type it;
7630 vn_ssa_aux_t info;
7631 FOR_EACH_HASH_TABLE_ELEMENT (*vn_ssa_aux_hash, info, vn_ssa_aux_t, it)
7632 if (info->needs_insertion)
7633 release_ssa_name (info->name);
7634 obstack_free (&vn_ssa_aux_obstack, NULL);
7635 delete vn_ssa_aux_hash;
7637 delete constant_to_value_id;
7638 constant_to_value_id = NULL;
7641 /* Hook for maybe_push_res_to_seq, lookup the expression in the VN tables. */
7643 static tree
7644 vn_lookup_simplify_result (gimple_match_op *res_op)
7646 if (!res_op->code.is_tree_code ())
7647 return NULL_TREE;
7648 tree *ops = res_op->ops;
7649 unsigned int length = res_op->num_ops;
7650 if (res_op->code == CONSTRUCTOR
7651 /* ??? We're arriving here with SCCVNs view, decomposed CONSTRUCTOR
7652 and GIMPLEs / match-and-simplifies, CONSTRUCTOR as GENERIC tree. */
7653 && TREE_CODE (res_op->ops[0]) == CONSTRUCTOR)
7655 length = CONSTRUCTOR_NELTS (res_op->ops[0]);
7656 ops = XALLOCAVEC (tree, length);
7657 for (unsigned i = 0; i < length; ++i)
7658 ops[i] = CONSTRUCTOR_ELT (res_op->ops[0], i)->value;
7660 vn_nary_op_t vnresult = NULL;
7661 tree res = vn_nary_op_lookup_pieces (length, (tree_code) res_op->code,
7662 res_op->type, ops, &vnresult);
7663 /* If this is used from expression simplification make sure to
7664 return an available expression. */
7665 if (res && TREE_CODE (res) == SSA_NAME && mprts_hook && rpo_avail)
7666 res = rpo_avail->eliminate_avail (vn_context_bb, res);
7667 return res;
7670 /* Return a leader for OPs value that is valid at BB. */
7672 tree
7673 rpo_elim::eliminate_avail (basic_block bb, tree op)
7675 bool visited;
7676 tree valnum = SSA_VAL (op, &visited);
7677 /* If we didn't visit OP then it must be defined outside of the
7678 region we process and also dominate it. So it is available. */
7679 if (!visited)
7680 return op;
7681 if (TREE_CODE (valnum) == SSA_NAME)
7683 if (SSA_NAME_IS_DEFAULT_DEF (valnum))
7684 return valnum;
7685 vn_avail *av = VN_INFO (valnum)->avail;
7686 if (!av)
7687 return NULL_TREE;
7688 if (av->location == bb->index)
7689 /* On tramp3d 90% of the cases are here. */
7690 return ssa_name (av->leader);
7693 basic_block abb = BASIC_BLOCK_FOR_FN (cfun, av->location);
7694 /* ??? During elimination we have to use availability at the
7695 definition site of a use we try to replace. This
7696 is required to not run into inconsistencies because
7697 of dominated_by_p_w_unex behavior and removing a definition
7698 while not replacing all uses.
7699 ??? We could try to consistently walk dominators
7700 ignoring non-executable regions. The nearest common
7701 dominator of bb and abb is where we can stop walking. We
7702 may also be able to "pre-compute" (bits of) the next immediate
7703 (non-)dominator during the RPO walk when marking edges as
7704 executable. */
7705 if (dominated_by_p_w_unex (bb, abb, true))
7707 tree leader = ssa_name (av->leader);
7708 /* Prevent eliminations that break loop-closed SSA. */
7709 if (loops_state_satisfies_p (LOOP_CLOSED_SSA)
7710 && ! SSA_NAME_IS_DEFAULT_DEF (leader)
7711 && ! flow_bb_inside_loop_p (gimple_bb (SSA_NAME_DEF_STMT
7712 (leader))->loop_father,
7713 bb))
7714 return NULL_TREE;
7715 if (dump_file && (dump_flags & TDF_DETAILS))
7717 print_generic_expr (dump_file, leader);
7718 fprintf (dump_file, " is available for ");
7719 print_generic_expr (dump_file, valnum);
7720 fprintf (dump_file, "\n");
7722 /* On tramp3d 99% of the _remaining_ cases succeed at
7723 the first enty. */
7724 return leader;
7726 /* ??? Can we somehow skip to the immediate dominator
7727 RPO index (bb_to_rpo)? Again, maybe not worth, on
7728 tramp3d the worst number of elements in the vector is 9. */
7729 av = av->next;
7731 while (av);
7733 else if (valnum != VN_TOP)
7734 /* valnum is is_gimple_min_invariant. */
7735 return valnum;
7736 return NULL_TREE;
7739 /* Make LEADER a leader for its value at BB. */
7741 void
7742 rpo_elim::eliminate_push_avail (basic_block bb, tree leader)
7744 tree valnum = VN_INFO (leader)->valnum;
7745 if (valnum == VN_TOP
7746 || is_gimple_min_invariant (valnum))
7747 return;
7748 if (dump_file && (dump_flags & TDF_DETAILS))
7750 fprintf (dump_file, "Making available beyond BB%d ", bb->index);
7751 print_generic_expr (dump_file, leader);
7752 fprintf (dump_file, " for value ");
7753 print_generic_expr (dump_file, valnum);
7754 fprintf (dump_file, "\n");
7756 vn_ssa_aux_t value = VN_INFO (valnum);
7757 vn_avail *av;
7758 if (m_avail_freelist)
7760 av = m_avail_freelist;
7761 m_avail_freelist = m_avail_freelist->next;
7763 else
7764 av = XOBNEW (&vn_ssa_aux_obstack, vn_avail);
7765 av->location = bb->index;
7766 av->leader = SSA_NAME_VERSION (leader);
7767 av->next = value->avail;
7768 av->next_undo = last_pushed_avail;
7769 last_pushed_avail = value;
7770 value->avail = av;
7773 /* Valueization hook for RPO VN plus required state. */
7775 tree
7776 rpo_vn_valueize (tree name)
7778 if (TREE_CODE (name) == SSA_NAME)
7780 vn_ssa_aux_t val = VN_INFO (name);
7781 if (val)
7783 tree tem = val->valnum;
7784 if (tem != VN_TOP && tem != name)
7786 if (TREE_CODE (tem) != SSA_NAME)
7787 return tem;
7788 /* For all values we only valueize to an available leader
7789 which means we can use SSA name info without restriction. */
7790 tem = rpo_avail->eliminate_avail (vn_context_bb, tem);
7791 if (tem)
7792 return tem;
7796 return name;
7799 /* Insert on PRED_E predicates derived from CODE OPS being true besides the
7800 inverted condition. */
7802 static void
7803 insert_related_predicates_on_edge (enum tree_code code, tree *ops, edge pred_e)
7805 switch (code)
7807 case LT_EXPR:
7808 /* a < b -> a {!,<}= b */
7809 vn_nary_op_insert_pieces_predicated (2, NE_EXPR, boolean_type_node,
7810 ops, boolean_true_node, 0, pred_e);
7811 vn_nary_op_insert_pieces_predicated (2, LE_EXPR, boolean_type_node,
7812 ops, boolean_true_node, 0, pred_e);
7813 /* a < b -> ! a {>,=} b */
7814 vn_nary_op_insert_pieces_predicated (2, GT_EXPR, boolean_type_node,
7815 ops, boolean_false_node, 0, pred_e);
7816 vn_nary_op_insert_pieces_predicated (2, EQ_EXPR, boolean_type_node,
7817 ops, boolean_false_node, 0, pred_e);
7818 break;
7819 case GT_EXPR:
7820 /* a > b -> a {!,>}= b */
7821 vn_nary_op_insert_pieces_predicated (2, NE_EXPR, boolean_type_node,
7822 ops, boolean_true_node, 0, pred_e);
7823 vn_nary_op_insert_pieces_predicated (2, GE_EXPR, boolean_type_node,
7824 ops, boolean_true_node, 0, pred_e);
7825 /* a > b -> ! a {<,=} b */
7826 vn_nary_op_insert_pieces_predicated (2, LT_EXPR, boolean_type_node,
7827 ops, boolean_false_node, 0, pred_e);
7828 vn_nary_op_insert_pieces_predicated (2, EQ_EXPR, boolean_type_node,
7829 ops, boolean_false_node, 0, pred_e);
7830 break;
7831 case EQ_EXPR:
7832 /* a == b -> ! a {<,>} b */
7833 vn_nary_op_insert_pieces_predicated (2, LT_EXPR, boolean_type_node,
7834 ops, boolean_false_node, 0, pred_e);
7835 vn_nary_op_insert_pieces_predicated (2, GT_EXPR, boolean_type_node,
7836 ops, boolean_false_node, 0, pred_e);
7837 break;
7838 case LE_EXPR:
7839 case GE_EXPR:
7840 case NE_EXPR:
7841 /* Nothing besides inverted condition. */
7842 break;
7843 default:;
7847 /* Main stmt worker for RPO VN, process BB. */
7849 static unsigned
7850 process_bb (rpo_elim &avail, basic_block bb,
7851 bool bb_visited, bool iterate_phis, bool iterate, bool eliminate,
7852 bool do_region, bitmap exit_bbs, bool skip_phis)
7854 unsigned todo = 0;
7855 edge_iterator ei;
7856 edge e;
7858 vn_context_bb = bb;
7860 /* If we are in loop-closed SSA preserve this state. This is
7861 relevant when called on regions from outside of FRE/PRE. */
7862 bool lc_phi_nodes = false;
7863 if (!skip_phis
7864 && loops_state_satisfies_p (LOOP_CLOSED_SSA))
7865 FOR_EACH_EDGE (e, ei, bb->preds)
7866 if (e->src->loop_father != e->dest->loop_father
7867 && flow_loop_nested_p (e->dest->loop_father,
7868 e->src->loop_father))
7870 lc_phi_nodes = true;
7871 break;
7874 /* When we visit a loop header substitute into loop info. */
7875 if (!iterate && eliminate && bb->loop_father->header == bb)
7877 /* Keep fields in sync with substitute_in_loop_info. */
7878 if (bb->loop_father->nb_iterations)
7879 bb->loop_father->nb_iterations
7880 = simplify_replace_tree (bb->loop_father->nb_iterations,
7881 NULL_TREE, NULL_TREE, &vn_valueize_for_srt);
7884 /* Value-number all defs in the basic-block. */
7885 if (!skip_phis)
7886 for (gphi_iterator gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
7887 gsi_next (&gsi))
7889 gphi *phi = gsi.phi ();
7890 tree res = PHI_RESULT (phi);
7891 vn_ssa_aux_t res_info = VN_INFO (res);
7892 if (!bb_visited)
7894 gcc_assert (!res_info->visited);
7895 res_info->valnum = VN_TOP;
7896 res_info->visited = true;
7899 /* When not iterating force backedge values to varying. */
7900 visit_stmt (phi, !iterate_phis);
7901 if (virtual_operand_p (res))
7902 continue;
7904 /* Eliminate */
7905 /* The interesting case is gcc.dg/tree-ssa/pr22230.c for correctness
7906 how we handle backedges and availability.
7907 And gcc.dg/tree-ssa/ssa-sccvn-2.c for optimization. */
7908 tree val = res_info->valnum;
7909 if (res != val && !iterate && eliminate)
7911 if (tree leader = avail.eliminate_avail (bb, res))
7913 if (leader != res
7914 /* Preserve loop-closed SSA form. */
7915 && (! lc_phi_nodes
7916 || is_gimple_min_invariant (leader)))
7918 if (dump_file && (dump_flags & TDF_DETAILS))
7920 fprintf (dump_file, "Replaced redundant PHI node "
7921 "defining ");
7922 print_generic_expr (dump_file, res);
7923 fprintf (dump_file, " with ");
7924 print_generic_expr (dump_file, leader);
7925 fprintf (dump_file, "\n");
7927 avail.eliminations++;
7929 if (may_propagate_copy (res, leader))
7931 /* Schedule for removal. */
7932 avail.to_remove.safe_push (phi);
7933 continue;
7935 /* ??? Else generate a copy stmt. */
7939 /* Only make defs available that not already are. But make
7940 sure loop-closed SSA PHI node defs are picked up for
7941 downstream uses. */
7942 if (lc_phi_nodes
7943 || res == val
7944 || ! avail.eliminate_avail (bb, res))
7945 avail.eliminate_push_avail (bb, res);
7948 /* For empty BBs mark outgoing edges executable. For non-empty BBs
7949 we do this when processing the last stmt as we have to do this
7950 before elimination which otherwise forces GIMPLE_CONDs to
7951 if (1 != 0) style when seeing non-executable edges. */
7952 if (gsi_end_p (gsi_start_bb (bb)))
7954 FOR_EACH_EDGE (e, ei, bb->succs)
7956 if (!(e->flags & EDGE_EXECUTABLE))
7958 if (dump_file && (dump_flags & TDF_DETAILS))
7959 fprintf (dump_file,
7960 "marking outgoing edge %d -> %d executable\n",
7961 e->src->index, e->dest->index);
7962 e->flags |= EDGE_EXECUTABLE;
7963 e->dest->flags |= BB_EXECUTABLE;
7965 else if (!(e->dest->flags & BB_EXECUTABLE))
7967 if (dump_file && (dump_flags & TDF_DETAILS))
7968 fprintf (dump_file,
7969 "marking destination block %d reachable\n",
7970 e->dest->index);
7971 e->dest->flags |= BB_EXECUTABLE;
7975 for (gimple_stmt_iterator gsi = gsi_start_bb (bb);
7976 !gsi_end_p (gsi); gsi_next (&gsi))
7978 ssa_op_iter i;
7979 tree op;
7980 if (!bb_visited)
7982 FOR_EACH_SSA_TREE_OPERAND (op, gsi_stmt (gsi), i, SSA_OP_ALL_DEFS)
7984 vn_ssa_aux_t op_info = VN_INFO (op);
7985 gcc_assert (!op_info->visited);
7986 op_info->valnum = VN_TOP;
7987 op_info->visited = true;
7990 /* We somehow have to deal with uses that are not defined
7991 in the processed region. Forcing unvisited uses to
7992 varying here doesn't play well with def-use following during
7993 expression simplification, so we deal with this by checking
7994 the visited flag in SSA_VAL. */
7997 visit_stmt (gsi_stmt (gsi));
7999 gimple *last = gsi_stmt (gsi);
8000 e = NULL;
8001 switch (gimple_code (last))
8003 case GIMPLE_SWITCH:
8004 e = find_taken_edge (bb, vn_valueize (gimple_switch_index
8005 (as_a <gswitch *> (last))));
8006 break;
8007 case GIMPLE_COND:
8009 tree lhs = vn_valueize (gimple_cond_lhs (last));
8010 tree rhs = vn_valueize (gimple_cond_rhs (last));
8011 tree val = gimple_simplify (gimple_cond_code (last),
8012 boolean_type_node, lhs, rhs,
8013 NULL, vn_valueize);
8014 /* If the condition didn't simplfy see if we have recorded
8015 an expression from sofar taken edges. */
8016 if (! val || TREE_CODE (val) != INTEGER_CST)
8018 vn_nary_op_t vnresult;
8019 tree ops[2];
8020 ops[0] = lhs;
8021 ops[1] = rhs;
8022 val = vn_nary_op_lookup_pieces (2, gimple_cond_code (last),
8023 boolean_type_node, ops,
8024 &vnresult);
8025 /* Did we get a predicated value? */
8026 if (! val && vnresult && vnresult->predicated_values)
8028 val = vn_nary_op_get_predicated_value (vnresult, bb);
8029 if (val && dump_file && (dump_flags & TDF_DETAILS))
8031 fprintf (dump_file, "Got predicated value ");
8032 print_generic_expr (dump_file, val, TDF_NONE);
8033 fprintf (dump_file, " for ");
8034 print_gimple_stmt (dump_file, last, TDF_SLIM);
8038 if (val)
8039 e = find_taken_edge (bb, val);
8040 if (! e)
8042 /* If we didn't manage to compute the taken edge then
8043 push predicated expressions for the condition itself
8044 and related conditions to the hashtables. This allows
8045 simplification of redundant conditions which is
8046 important as early cleanup. */
8047 edge true_e, false_e;
8048 extract_true_false_edges_from_block (bb, &true_e, &false_e);
8049 enum tree_code code = gimple_cond_code (last);
8050 enum tree_code icode
8051 = invert_tree_comparison (code, HONOR_NANS (lhs));
8052 tree ops[2];
8053 ops[0] = lhs;
8054 ops[1] = rhs;
8055 if ((do_region && bitmap_bit_p (exit_bbs, true_e->dest->index))
8056 || !can_track_predicate_on_edge (true_e))
8057 true_e = NULL;
8058 if ((do_region && bitmap_bit_p (exit_bbs, false_e->dest->index))
8059 || !can_track_predicate_on_edge (false_e))
8060 false_e = NULL;
8061 if (true_e)
8062 vn_nary_op_insert_pieces_predicated
8063 (2, code, boolean_type_node, ops,
8064 boolean_true_node, 0, true_e);
8065 if (false_e)
8066 vn_nary_op_insert_pieces_predicated
8067 (2, code, boolean_type_node, ops,
8068 boolean_false_node, 0, false_e);
8069 if (icode != ERROR_MARK)
8071 if (true_e)
8072 vn_nary_op_insert_pieces_predicated
8073 (2, icode, boolean_type_node, ops,
8074 boolean_false_node, 0, true_e);
8075 if (false_e)
8076 vn_nary_op_insert_pieces_predicated
8077 (2, icode, boolean_type_node, ops,
8078 boolean_true_node, 0, false_e);
8080 /* Relax for non-integers, inverted condition handled
8081 above. */
8082 if (INTEGRAL_TYPE_P (TREE_TYPE (lhs)))
8084 if (true_e)
8085 insert_related_predicates_on_edge (code, ops, true_e);
8086 if (false_e)
8087 insert_related_predicates_on_edge (icode, ops, false_e);
8090 break;
8092 case GIMPLE_GOTO:
8093 e = find_taken_edge (bb, vn_valueize (gimple_goto_dest (last)));
8094 break;
8095 default:
8096 e = NULL;
8098 if (e)
8100 todo = TODO_cleanup_cfg;
8101 if (!(e->flags & EDGE_EXECUTABLE))
8103 if (dump_file && (dump_flags & TDF_DETAILS))
8104 fprintf (dump_file,
8105 "marking known outgoing %sedge %d -> %d executable\n",
8106 e->flags & EDGE_DFS_BACK ? "back-" : "",
8107 e->src->index, e->dest->index);
8108 e->flags |= EDGE_EXECUTABLE;
8109 e->dest->flags |= BB_EXECUTABLE;
8111 else if (!(e->dest->flags & BB_EXECUTABLE))
8113 if (dump_file && (dump_flags & TDF_DETAILS))
8114 fprintf (dump_file,
8115 "marking destination block %d reachable\n",
8116 e->dest->index);
8117 e->dest->flags |= BB_EXECUTABLE;
8120 else if (gsi_one_before_end_p (gsi))
8122 FOR_EACH_EDGE (e, ei, bb->succs)
8124 if (!(e->flags & EDGE_EXECUTABLE))
8126 if (dump_file && (dump_flags & TDF_DETAILS))
8127 fprintf (dump_file,
8128 "marking outgoing edge %d -> %d executable\n",
8129 e->src->index, e->dest->index);
8130 e->flags |= EDGE_EXECUTABLE;
8131 e->dest->flags |= BB_EXECUTABLE;
8133 else if (!(e->dest->flags & BB_EXECUTABLE))
8135 if (dump_file && (dump_flags & TDF_DETAILS))
8136 fprintf (dump_file,
8137 "marking destination block %d reachable\n",
8138 e->dest->index);
8139 e->dest->flags |= BB_EXECUTABLE;
8144 /* Eliminate. That also pushes to avail. */
8145 if (eliminate && ! iterate)
8146 avail.eliminate_stmt (bb, &gsi);
8147 else
8148 /* If not eliminating, make all not already available defs
8149 available. But avoid picking up dead defs. */
8150 FOR_EACH_SSA_TREE_OPERAND (op, gsi_stmt (gsi), i, SSA_OP_DEF)
8151 if (! has_zero_uses (op)
8152 && ! avail.eliminate_avail (bb, op))
8153 avail.eliminate_push_avail (bb, op);
8156 /* Eliminate in destination PHI arguments. Always substitute in dest
8157 PHIs, even for non-executable edges. This handles region
8158 exits PHIs. */
8159 if (!iterate && eliminate)
8160 FOR_EACH_EDGE (e, ei, bb->succs)
8161 for (gphi_iterator gsi = gsi_start_phis (e->dest);
8162 !gsi_end_p (gsi); gsi_next (&gsi))
8164 gphi *phi = gsi.phi ();
8165 use_operand_p use_p = PHI_ARG_DEF_PTR_FROM_EDGE (phi, e);
8166 tree arg = USE_FROM_PTR (use_p);
8167 if (TREE_CODE (arg) != SSA_NAME
8168 || virtual_operand_p (arg))
8169 continue;
8170 tree sprime;
8171 if (SSA_NAME_IS_DEFAULT_DEF (arg))
8173 sprime = SSA_VAL (arg);
8174 gcc_assert (TREE_CODE (sprime) != SSA_NAME
8175 || SSA_NAME_IS_DEFAULT_DEF (sprime));
8177 else
8178 /* Look for sth available at the definition block of the argument.
8179 This avoids inconsistencies between availability there which
8180 decides if the stmt can be removed and availability at the
8181 use site. The SSA property ensures that things available
8182 at the definition are also available at uses. */
8183 sprime = avail.eliminate_avail (gimple_bb (SSA_NAME_DEF_STMT (arg)),
8184 arg);
8185 if (sprime
8186 && sprime != arg
8187 && may_propagate_copy (arg, sprime))
8188 propagate_value (use_p, sprime);
8191 vn_context_bb = NULL;
8192 return todo;
8195 /* Unwind state per basic-block. */
8197 struct unwind_state
8199 /* Times this block has been visited. */
8200 unsigned visited;
8201 /* Whether to handle this as iteration point or whether to treat
8202 incoming backedge PHI values as varying. */
8203 bool iterate;
8204 /* Maximum RPO index this block is reachable from. */
8205 int max_rpo;
8206 /* Unwind state. */
8207 void *ob_top;
8208 vn_reference_t ref_top;
8209 vn_phi_t phi_top;
8210 vn_nary_op_t nary_top;
8211 vn_avail *avail_top;
8214 /* Unwind the RPO VN state for iteration. */
8216 static void
8217 do_unwind (unwind_state *to, rpo_elim &avail)
8219 gcc_assert (to->iterate);
8220 for (; last_inserted_nary != to->nary_top;
8221 last_inserted_nary = last_inserted_nary->next)
8223 vn_nary_op_t *slot;
8224 slot = valid_info->nary->find_slot_with_hash
8225 (last_inserted_nary, last_inserted_nary->hashcode, NO_INSERT);
8226 /* Predication causes the need to restore previous state. */
8227 if ((*slot)->unwind_to)
8228 *slot = (*slot)->unwind_to;
8229 else
8230 valid_info->nary->clear_slot (slot);
8232 for (; last_inserted_phi != to->phi_top;
8233 last_inserted_phi = last_inserted_phi->next)
8235 vn_phi_t *slot;
8236 slot = valid_info->phis->find_slot_with_hash
8237 (last_inserted_phi, last_inserted_phi->hashcode, NO_INSERT);
8238 valid_info->phis->clear_slot (slot);
8240 for (; last_inserted_ref != to->ref_top;
8241 last_inserted_ref = last_inserted_ref->next)
8243 vn_reference_t *slot;
8244 slot = valid_info->references->find_slot_with_hash
8245 (last_inserted_ref, last_inserted_ref->hashcode, NO_INSERT);
8246 (*slot)->operands.release ();
8247 valid_info->references->clear_slot (slot);
8249 obstack_free (&vn_tables_obstack, to->ob_top);
8251 /* Prune [rpo_idx, ] from avail. */
8252 for (; last_pushed_avail && last_pushed_avail->avail != to->avail_top;)
8254 vn_ssa_aux_t val = last_pushed_avail;
8255 vn_avail *av = val->avail;
8256 val->avail = av->next;
8257 last_pushed_avail = av->next_undo;
8258 av->next = avail.m_avail_freelist;
8259 avail.m_avail_freelist = av;
8263 /* Do VN on a SEME region specified by ENTRY and EXIT_BBS in FN.
8264 If ITERATE is true then treat backedges optimistically as not
8265 executed and iterate. If ELIMINATE is true then perform
8266 elimination, otherwise leave that to the caller. */
8268 static unsigned
8269 do_rpo_vn_1 (function *fn, edge entry, bitmap exit_bbs,
8270 bool iterate, bool eliminate, vn_lookup_kind kind)
8272 unsigned todo = 0;
8273 default_vn_walk_kind = kind;
8275 /* We currently do not support region-based iteration when
8276 elimination is requested. */
8277 gcc_assert (!entry || !iterate || !eliminate);
8278 /* When iterating we need loop info up-to-date. */
8279 gcc_assert (!iterate || !loops_state_satisfies_p (LOOPS_NEED_FIXUP));
8281 bool do_region = entry != NULL;
8282 if (!do_region)
8284 entry = single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (fn));
8285 exit_bbs = BITMAP_ALLOC (NULL);
8286 bitmap_set_bit (exit_bbs, EXIT_BLOCK);
8289 /* Clear EDGE_DFS_BACK on "all" entry edges, RPO order compute will
8290 re-mark those that are contained in the region. */
8291 edge_iterator ei;
8292 edge e;
8293 FOR_EACH_EDGE (e, ei, entry->dest->preds)
8294 e->flags &= ~EDGE_DFS_BACK;
8296 int *rpo = XNEWVEC (int, n_basic_blocks_for_fn (fn) - NUM_FIXED_BLOCKS);
8297 auto_vec<std::pair<int, int> > toplevel_scc_extents;
8298 int n = rev_post_order_and_mark_dfs_back_seme
8299 (fn, entry, exit_bbs, true, rpo, !iterate ? &toplevel_scc_extents : NULL);
8301 if (!do_region)
8302 BITMAP_FREE (exit_bbs);
8304 /* If there are any non-DFS_BACK edges into entry->dest skip
8305 processing PHI nodes for that block. This supports
8306 value-numbering loop bodies w/o the actual loop. */
8307 FOR_EACH_EDGE (e, ei, entry->dest->preds)
8308 if (e != entry
8309 && !(e->flags & EDGE_DFS_BACK))
8310 break;
8311 bool skip_entry_phis = e != NULL;
8312 if (skip_entry_phis && dump_file && (dump_flags & TDF_DETAILS))
8313 fprintf (dump_file, "Region does not contain all edges into "
8314 "the entry block, skipping its PHIs.\n");
8316 int *bb_to_rpo = XNEWVEC (int, last_basic_block_for_fn (fn));
8317 for (int i = 0; i < n; ++i)
8318 bb_to_rpo[rpo[i]] = i;
8320 unwind_state *rpo_state = XNEWVEC (unwind_state, n);
8322 rpo_elim avail (entry->dest);
8323 rpo_avail = &avail;
8325 /* Verify we have no extra entries into the region. */
8326 if (flag_checking && do_region)
8328 auto_bb_flag bb_in_region (fn);
8329 for (int i = 0; i < n; ++i)
8331 basic_block bb = BASIC_BLOCK_FOR_FN (fn, rpo[i]);
8332 bb->flags |= bb_in_region;
8334 /* We can't merge the first two loops because we cannot rely
8335 on EDGE_DFS_BACK for edges not within the region. But if
8336 we decide to always have the bb_in_region flag we can
8337 do the checking during the RPO walk itself (but then it's
8338 also easy to handle MEME conservatively). */
8339 for (int i = 0; i < n; ++i)
8341 basic_block bb = BASIC_BLOCK_FOR_FN (fn, rpo[i]);
8342 edge e;
8343 edge_iterator ei;
8344 FOR_EACH_EDGE (e, ei, bb->preds)
8345 gcc_assert (e == entry
8346 || (skip_entry_phis && bb == entry->dest)
8347 || (e->src->flags & bb_in_region));
8349 for (int i = 0; i < n; ++i)
8351 basic_block bb = BASIC_BLOCK_FOR_FN (fn, rpo[i]);
8352 bb->flags &= ~bb_in_region;
8356 /* Create the VN state. For the initial size of the various hashtables
8357 use a heuristic based on region size and number of SSA names. */
8358 unsigned region_size = (((unsigned HOST_WIDE_INT)n * num_ssa_names)
8359 / (n_basic_blocks_for_fn (fn) - NUM_FIXED_BLOCKS));
8360 VN_TOP = create_tmp_var_raw (void_type_node, "vn_top");
8361 next_value_id = 1;
8362 next_constant_value_id = -1;
8364 vn_ssa_aux_hash = new hash_table <vn_ssa_aux_hasher> (region_size * 2);
8365 gcc_obstack_init (&vn_ssa_aux_obstack);
8367 gcc_obstack_init (&vn_tables_obstack);
8368 gcc_obstack_init (&vn_tables_insert_obstack);
8369 valid_info = XCNEW (struct vn_tables_s);
8370 allocate_vn_table (valid_info, region_size);
8371 last_inserted_ref = NULL;
8372 last_inserted_phi = NULL;
8373 last_inserted_nary = NULL;
8374 last_pushed_avail = NULL;
8376 vn_valueize = rpo_vn_valueize;
8378 /* Initialize the unwind state and edge/BB executable state. */
8379 unsigned curr_scc = 0;
8380 for (int i = 0; i < n; ++i)
8382 basic_block bb = BASIC_BLOCK_FOR_FN (fn, rpo[i]);
8383 rpo_state[i].visited = 0;
8384 rpo_state[i].max_rpo = i;
8385 if (!iterate && curr_scc < toplevel_scc_extents.length ())
8387 if (i >= toplevel_scc_extents[curr_scc].first
8388 && i <= toplevel_scc_extents[curr_scc].second)
8389 rpo_state[i].max_rpo = toplevel_scc_extents[curr_scc].second;
8390 if (i == toplevel_scc_extents[curr_scc].second)
8391 curr_scc++;
8393 bb->flags &= ~BB_EXECUTABLE;
8394 bool has_backedges = false;
8395 edge e;
8396 edge_iterator ei;
8397 FOR_EACH_EDGE (e, ei, bb->preds)
8399 if (e->flags & EDGE_DFS_BACK)
8400 has_backedges = true;
8401 e->flags &= ~EDGE_EXECUTABLE;
8402 if (iterate || e == entry || (skip_entry_phis && bb == entry->dest))
8403 continue;
8405 rpo_state[i].iterate = iterate && has_backedges;
8407 entry->flags |= EDGE_EXECUTABLE;
8408 entry->dest->flags |= BB_EXECUTABLE;
8410 /* As heuristic to improve compile-time we handle only the N innermost
8411 loops and the outermost one optimistically. */
8412 if (iterate)
8414 unsigned max_depth = param_rpo_vn_max_loop_depth;
8415 for (auto loop : loops_list (cfun, LI_ONLY_INNERMOST))
8416 if (loop_depth (loop) > max_depth)
8417 for (unsigned i = 2;
8418 i < loop_depth (loop) - max_depth; ++i)
8420 basic_block header = superloop_at_depth (loop, i)->header;
8421 bool non_latch_backedge = false;
8422 edge e;
8423 edge_iterator ei;
8424 FOR_EACH_EDGE (e, ei, header->preds)
8425 if (e->flags & EDGE_DFS_BACK)
8427 /* There can be a non-latch backedge into the header
8428 which is part of an outer irreducible region. We
8429 cannot avoid iterating this block then. */
8430 if (!dominated_by_p (CDI_DOMINATORS,
8431 e->src, e->dest))
8433 if (dump_file && (dump_flags & TDF_DETAILS))
8434 fprintf (dump_file, "non-latch backedge %d -> %d "
8435 "forces iteration of loop %d\n",
8436 e->src->index, e->dest->index, loop->num);
8437 non_latch_backedge = true;
8439 else
8440 e->flags |= EDGE_EXECUTABLE;
8442 rpo_state[bb_to_rpo[header->index]].iterate = non_latch_backedge;
8446 uint64_t nblk = 0;
8447 int idx = 0;
8448 if (iterate)
8449 /* Go and process all blocks, iterating as necessary. */
8452 basic_block bb = BASIC_BLOCK_FOR_FN (fn, rpo[idx]);
8454 /* If the block has incoming backedges remember unwind state. This
8455 is required even for non-executable blocks since in irreducible
8456 regions we might reach them via the backedge and re-start iterating
8457 from there.
8458 Note we can individually mark blocks with incoming backedges to
8459 not iterate where we then handle PHIs conservatively. We do that
8460 heuristically to reduce compile-time for degenerate cases. */
8461 if (rpo_state[idx].iterate)
8463 rpo_state[idx].ob_top = obstack_alloc (&vn_tables_obstack, 0);
8464 rpo_state[idx].ref_top = last_inserted_ref;
8465 rpo_state[idx].phi_top = last_inserted_phi;
8466 rpo_state[idx].nary_top = last_inserted_nary;
8467 rpo_state[idx].avail_top
8468 = last_pushed_avail ? last_pushed_avail->avail : NULL;
8471 if (!(bb->flags & BB_EXECUTABLE))
8473 if (dump_file && (dump_flags & TDF_DETAILS))
8474 fprintf (dump_file, "Block %d: BB%d found not executable\n",
8475 idx, bb->index);
8476 idx++;
8477 continue;
8480 if (dump_file && (dump_flags & TDF_DETAILS))
8481 fprintf (dump_file, "Processing block %d: BB%d\n", idx, bb->index);
8482 nblk++;
8483 todo |= process_bb (avail, bb,
8484 rpo_state[idx].visited != 0,
8485 rpo_state[idx].iterate,
8486 iterate, eliminate, do_region, exit_bbs, false);
8487 rpo_state[idx].visited++;
8489 /* Verify if changed values flow over executable outgoing backedges
8490 and those change destination PHI values (that's the thing we
8491 can easily verify). Reduce over all such edges to the farthest
8492 away PHI. */
8493 int iterate_to = -1;
8494 edge_iterator ei;
8495 edge e;
8496 FOR_EACH_EDGE (e, ei, bb->succs)
8497 if ((e->flags & (EDGE_DFS_BACK|EDGE_EXECUTABLE))
8498 == (EDGE_DFS_BACK|EDGE_EXECUTABLE)
8499 && rpo_state[bb_to_rpo[e->dest->index]].iterate)
8501 int destidx = bb_to_rpo[e->dest->index];
8502 if (!rpo_state[destidx].visited)
8504 if (dump_file && (dump_flags & TDF_DETAILS))
8505 fprintf (dump_file, "Unvisited destination %d\n",
8506 e->dest->index);
8507 if (iterate_to == -1 || destidx < iterate_to)
8508 iterate_to = destidx;
8509 continue;
8511 if (dump_file && (dump_flags & TDF_DETAILS))
8512 fprintf (dump_file, "Looking for changed values of backedge"
8513 " %d->%d destination PHIs\n",
8514 e->src->index, e->dest->index);
8515 vn_context_bb = e->dest;
8516 gphi_iterator gsi;
8517 for (gsi = gsi_start_phis (e->dest);
8518 !gsi_end_p (gsi); gsi_next (&gsi))
8520 bool inserted = false;
8521 /* While we'd ideally just iterate on value changes
8522 we CSE PHIs and do that even across basic-block
8523 boundaries. So even hashtable state changes can
8524 be important (which is roughly equivalent to
8525 PHI argument value changes). To not excessively
8526 iterate because of that we track whether a PHI
8527 was CSEd to with GF_PLF_1. */
8528 bool phival_changed;
8529 if ((phival_changed = visit_phi (gsi.phi (),
8530 &inserted, false))
8531 || (inserted && gimple_plf (gsi.phi (), GF_PLF_1)))
8533 if (!phival_changed
8534 && dump_file && (dump_flags & TDF_DETAILS))
8535 fprintf (dump_file, "PHI was CSEd and hashtable "
8536 "state (changed)\n");
8537 if (iterate_to == -1 || destidx < iterate_to)
8538 iterate_to = destidx;
8539 break;
8542 vn_context_bb = NULL;
8544 if (iterate_to != -1)
8546 do_unwind (&rpo_state[iterate_to], avail);
8547 idx = iterate_to;
8548 if (dump_file && (dump_flags & TDF_DETAILS))
8549 fprintf (dump_file, "Iterating to %d BB%d\n",
8550 iterate_to, rpo[iterate_to]);
8551 continue;
8554 idx++;
8556 while (idx < n);
8558 else /* !iterate */
8560 /* Process all blocks greedily with a worklist that enforces RPO
8561 processing of reachable blocks. */
8562 auto_bitmap worklist;
8563 bitmap_set_bit (worklist, 0);
8564 while (!bitmap_empty_p (worklist))
8566 int idx = bitmap_clear_first_set_bit (worklist);
8567 basic_block bb = BASIC_BLOCK_FOR_FN (fn, rpo[idx]);
8568 gcc_assert ((bb->flags & BB_EXECUTABLE)
8569 && !rpo_state[idx].visited);
8571 if (dump_file && (dump_flags & TDF_DETAILS))
8572 fprintf (dump_file, "Processing block %d: BB%d\n", idx, bb->index);
8574 /* When we run into predecessor edges where we cannot trust its
8575 executable state mark them executable so PHI processing will
8576 be conservative.
8577 ??? Do we need to force arguments flowing over that edge
8578 to be varying or will they even always be? */
8579 edge_iterator ei;
8580 edge e;
8581 FOR_EACH_EDGE (e, ei, bb->preds)
8582 if (!(e->flags & EDGE_EXECUTABLE)
8583 && (bb == entry->dest
8584 || (!rpo_state[bb_to_rpo[e->src->index]].visited
8585 && (rpo_state[bb_to_rpo[e->src->index]].max_rpo
8586 >= (int)idx))))
8588 if (dump_file && (dump_flags & TDF_DETAILS))
8589 fprintf (dump_file, "Cannot trust state of predecessor "
8590 "edge %d -> %d, marking executable\n",
8591 e->src->index, e->dest->index);
8592 e->flags |= EDGE_EXECUTABLE;
8595 nblk++;
8596 todo |= process_bb (avail, bb, false, false, false, eliminate,
8597 do_region, exit_bbs,
8598 skip_entry_phis && bb == entry->dest);
8599 rpo_state[idx].visited++;
8601 FOR_EACH_EDGE (e, ei, bb->succs)
8602 if ((e->flags & EDGE_EXECUTABLE)
8603 && e->dest->index != EXIT_BLOCK
8604 && (!do_region || !bitmap_bit_p (exit_bbs, e->dest->index))
8605 && !rpo_state[bb_to_rpo[e->dest->index]].visited)
8606 bitmap_set_bit (worklist, bb_to_rpo[e->dest->index]);
8610 /* If statistics or dump file active. */
8611 int nex = 0;
8612 unsigned max_visited = 1;
8613 for (int i = 0; i < n; ++i)
8615 basic_block bb = BASIC_BLOCK_FOR_FN (fn, rpo[i]);
8616 if (bb->flags & BB_EXECUTABLE)
8617 nex++;
8618 statistics_histogram_event (cfun, "RPO block visited times",
8619 rpo_state[i].visited);
8620 if (rpo_state[i].visited > max_visited)
8621 max_visited = rpo_state[i].visited;
8623 unsigned nvalues = 0, navail = 0;
8624 for (hash_table<vn_ssa_aux_hasher>::iterator i = vn_ssa_aux_hash->begin ();
8625 i != vn_ssa_aux_hash->end (); ++i)
8627 nvalues++;
8628 vn_avail *av = (*i)->avail;
8629 while (av)
8631 navail++;
8632 av = av->next;
8635 statistics_counter_event (cfun, "RPO blocks", n);
8636 statistics_counter_event (cfun, "RPO blocks visited", nblk);
8637 statistics_counter_event (cfun, "RPO blocks executable", nex);
8638 statistics_histogram_event (cfun, "RPO iterations", 10*nblk / nex);
8639 statistics_histogram_event (cfun, "RPO num values", nvalues);
8640 statistics_histogram_event (cfun, "RPO num avail", navail);
8641 statistics_histogram_event (cfun, "RPO num lattice",
8642 vn_ssa_aux_hash->elements ());
8643 if (dump_file && (dump_flags & (TDF_DETAILS|TDF_STATS)))
8645 fprintf (dump_file, "RPO iteration over %d blocks visited %" PRIu64
8646 " blocks in total discovering %d executable blocks iterating "
8647 "%d.%d times, a block was visited max. %u times\n",
8648 n, nblk, nex,
8649 (int)((10*nblk / nex)/10), (int)((10*nblk / nex)%10),
8650 max_visited);
8651 fprintf (dump_file, "RPO tracked %d values available at %d locations "
8652 "and %" PRIu64 " lattice elements\n",
8653 nvalues, navail, (uint64_t) vn_ssa_aux_hash->elements ());
8656 if (eliminate)
8658 /* When !iterate we already performed elimination during the RPO
8659 walk. */
8660 if (iterate)
8662 /* Elimination for region-based VN needs to be done within the
8663 RPO walk. */
8664 gcc_assert (! do_region);
8665 /* Note we can't use avail.walk here because that gets confused
8666 by the existing availability and it will be less efficient
8667 as well. */
8668 todo |= eliminate_with_rpo_vn (NULL);
8670 else
8671 todo |= avail.eliminate_cleanup (do_region);
8674 vn_valueize = NULL;
8675 rpo_avail = NULL;
8677 XDELETEVEC (bb_to_rpo);
8678 XDELETEVEC (rpo);
8679 XDELETEVEC (rpo_state);
8681 return todo;
8684 /* Region-based entry for RPO VN. Performs value-numbering and elimination
8685 on the SEME region specified by ENTRY and EXIT_BBS. If ENTRY is not
8686 the only edge into the region at ENTRY->dest PHI nodes in ENTRY->dest
8687 are not considered.
8688 If ITERATE is true then treat backedges optimistically as not
8689 executed and iterate. If ELIMINATE is true then perform
8690 elimination, otherwise leave that to the caller.
8691 KIND specifies the amount of work done for handling memory operations. */
8693 unsigned
8694 do_rpo_vn (function *fn, edge entry, bitmap exit_bbs,
8695 bool iterate, bool eliminate, vn_lookup_kind kind)
8697 auto_timevar tv (TV_TREE_RPO_VN);
8698 unsigned todo = do_rpo_vn_1 (fn, entry, exit_bbs, iterate, eliminate, kind);
8699 free_rpo_vn ();
8700 return todo;
8704 namespace {
8706 const pass_data pass_data_fre =
8708 GIMPLE_PASS, /* type */
8709 "fre", /* name */
8710 OPTGROUP_NONE, /* optinfo_flags */
8711 TV_TREE_FRE, /* tv_id */
8712 ( PROP_cfg | PROP_ssa ), /* properties_required */
8713 0, /* properties_provided */
8714 0, /* properties_destroyed */
8715 0, /* todo_flags_start */
8716 0, /* todo_flags_finish */
8719 class pass_fre : public gimple_opt_pass
8721 public:
8722 pass_fre (gcc::context *ctxt)
8723 : gimple_opt_pass (pass_data_fre, ctxt), may_iterate (true)
8726 /* opt_pass methods: */
8727 opt_pass * clone () final override { return new pass_fre (m_ctxt); }
8728 void set_pass_param (unsigned int n, bool param) final override
8730 gcc_assert (n == 0);
8731 may_iterate = param;
8733 bool gate (function *) final override
8735 return flag_tree_fre != 0 && (may_iterate || optimize > 1);
8737 unsigned int execute (function *) final override;
8739 private:
8740 bool may_iterate;
8741 }; // class pass_fre
8743 unsigned int
8744 pass_fre::execute (function *fun)
8746 unsigned todo = 0;
8748 /* At -O[1g] use the cheap non-iterating mode. */
8749 bool iterate_p = may_iterate && (optimize > 1);
8750 calculate_dominance_info (CDI_DOMINATORS);
8751 if (iterate_p)
8752 loop_optimizer_init (AVOID_CFG_MODIFICATIONS);
8754 todo = do_rpo_vn_1 (fun, NULL, NULL, iterate_p, true, VN_WALKREWRITE);
8755 free_rpo_vn ();
8757 if (iterate_p)
8758 loop_optimizer_finalize ();
8760 if (scev_initialized_p ())
8761 scev_reset_htab ();
8763 /* For late FRE after IVOPTs and unrolling, see if we can
8764 remove some TREE_ADDRESSABLE and rewrite stuff into SSA. */
8765 if (!may_iterate)
8766 todo |= TODO_update_address_taken;
8768 return todo;
8771 } // anon namespace
8773 gimple_opt_pass *
8774 make_pass_fre (gcc::context *ctxt)
8776 return new pass_fre (ctxt);
8779 #undef BB_EXECUTABLE