Debian Codegraph @

gcc/tree-ssa-sccvn.cc

raw
1 /* SCC value numbering for trees
2 Copyright (C) 2006-2025 Free Software Foundation, Inc.
3 Contributed by Daniel Berlin <[email protected]>
4
5 This file is part of GCC.
6
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.
11
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.
16
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/>. */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "backend.h"
25 #include "rtl.h"
26 #include "tree.h"
27 #include "gimple.h"
28 #include "ssa.h"
29 #include "expmed.h"
30 #include "insn-config.h"
31 #include "memmodel.h"
32 #include "emit-rtl.h"
33 #include "cgraph.h"
34 #include "gimple-pretty-print.h"
35 #include "splay-tree-utils.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 "sreal.h"
80 #include "ipa-cp.h"
81 #include "ipa-prop.h"
82 #include "target.h"
83
84 /* This algorithm is based on the SCC algorithm presented by Keith
85 Cooper and L. Taylor Simpson in "SCC-Based Value numbering"
86 (http://citeseer.ist.psu.edu/41805.html). In
87 straight line code, it is equivalent to a regular hash based value
88 numbering that is performed in reverse postorder.
89
90 For code with cycles, there are two alternatives, both of which
91 require keeping the hashtables separate from the actual list of
92 value numbers for SSA names.
93
94 1. Iterate value numbering in an RPO walk of the blocks, removing
95 all the entries from the hashtable after each iteration (but
96 keeping the SSA name->value number mapping between iterations).
97 Iterate until it does not change.
98
99 2. Perform value numbering as part of an SCC walk on the SSA graph,
100 iterating only the cycles in the SSA graph until they do not change
101 (using a separate, optimistic hashtable for value numbering the SCC
102 operands).
103
104 The second is not just faster in practice (because most SSA graph
105 cycles do not involve all the variables in the graph), it also has
106 some nice properties.
107
108 One of these nice properties is that when we pop an SCC off the
109 stack, we are guaranteed to have processed all the operands coming from
110 *outside of that SCC*, so we do not need to do anything special to
111 ensure they have value numbers.
112
113 Another nice property is that the SCC walk is done as part of a DFS
114 of the SSA graph, which makes it easy to perform combining and
115 simplifying operations at the same time.
116
117 The code below is deliberately written in a way that makes it easy
118 to separate the SCC walk from the other work it does.
119
120 In order to propagate constants through the code, we track which
121 expressions contain constants, and use those while folding. In
122 theory, we could also track expressions whose value numbers are
123 replaced, in case we end up folding based on expression
124 identities.
125
126 In order to value number memory, we assign value numbers to vuses.
127 This enables us to note that, for example, stores to the same
128 address of the same value from the same starting memory states are
129 equivalent.
130 TODO:
131
132 1. We can iterate only the changing portions of the SCC's, but
133 I have not seen an SCC big enough for this to be a win.
134 2. If you differentiate between phi nodes for loops and phi nodes
135 for if-then-else, you can properly consider phi nodes in different
136 blocks for equivalence.
137 3. We could value number vuses in more cases, particularly, whole
138 structure copies.
139 */
140
141 /* There's no BB_EXECUTABLE but we can use BB_VISITED. */
142 #define BB_EXECUTABLE BB_VISITED
143
144 static vn_lookup_kind default_vn_walk_kind;
145
146 /* vn_nary_op hashtable helpers. */
147
148 struct vn_nary_op_hasher : nofree_ptr_hash <vn_nary_op_s>
149 {
150 typedef vn_nary_op_s *compare_type;
151 static inline hashval_t hash (const vn_nary_op_s *);
152 static inline bool equal (const vn_nary_op_s *, const vn_nary_op_s *);
153 };
154
155 /* Return the computed hashcode for nary operation P1. */
156
157 inline hashval_t
158 vn_nary_op_hasher::hash (const vn_nary_op_s *vno1)
159 {
160 return vno1->hashcode;
161 }
162
163 /* Compare nary operations P1 and P2 and return true if they are
164 equivalent. */
165
166 inline bool
167 vn_nary_op_hasher::equal (const vn_nary_op_s *vno1, const vn_nary_op_s *vno2)
168 {
169 return vno1 == vno2 || vn_nary_op_eq (vno1, vno2);
170 }
171
172 typedef hash_table<vn_nary_op_hasher> vn_nary_op_table_type;
173 typedef vn_nary_op_table_type::iterator vn_nary_op_iterator_type;
174
175
176 /* vn_phi hashtable helpers. */
177
178 static int
179 vn_phi_eq (const_vn_phi_t const vp1, const_vn_phi_t const vp2);
180
181 struct vn_phi_hasher : nofree_ptr_hash <vn_phi_s>
182 {
183 static inline hashval_t hash (const vn_phi_s *);
184 static inline bool equal (const vn_phi_s *, const vn_phi_s *);
185 };
186
187 /* Return the computed hashcode for phi operation P1. */
188
189 inline hashval_t
190 vn_phi_hasher::hash (const vn_phi_s *vp1)
191 {
192 return vp1->hashcode;
193 }
194
195 /* Compare two phi entries for equality, ignoring VN_TOP arguments. */
196
197 inline bool
198 vn_phi_hasher::equal (const vn_phi_s *vp1, const vn_phi_s *vp2)
199 {
200 return vp1 == vp2 || vn_phi_eq (vp1, vp2);
201 }
202
203 typedef hash_table<vn_phi_hasher> vn_phi_table_type;
204 typedef vn_phi_table_type::iterator vn_phi_iterator_type;
205
206
207 /* Compare two reference operands P1 and P2 for equality. Return true if
208 they are equal, and false otherwise. */
209
210 static int
211 vn_reference_op_eq (const void *p1, const void *p2)
212 {
213 const_vn_reference_op_t const vro1 = (const_vn_reference_op_t) p1;
214 const_vn_reference_op_t const vro2 = (const_vn_reference_op_t) p2;
215
216 return (vro1->opcode == vro2->opcode
217 /* We do not care for differences in type qualification. */
218 && (vro1->type == vro2->type
219 || (vro1->type && vro2->type
220 && types_compatible_p (TYPE_MAIN_VARIANT (vro1->type),
221 TYPE_MAIN_VARIANT (vro2->type))))
222 && expressions_equal_p (vro1->op0, vro2->op0)
223 && expressions_equal_p (vro1->op1, vro2->op1)
224 && expressions_equal_p (vro1->op2, vro2->op2)
225 && (vro1->opcode != CALL_EXPR || vro1->clique == vro2->clique));
226 }
227
228 /* Free a reference operation structure VP. */
229
230 static inline void
231 free_reference (vn_reference_s *vr)
232 {
233 vr->operands.release ();
234 }
235
236
237 /* vn_reference hashtable helpers. */
238
239 struct vn_reference_hasher : nofree_ptr_hash <vn_reference_s>
240 {
241 static inline hashval_t hash (const vn_reference_s *);
242 static inline bool equal (const vn_reference_s *, const vn_reference_s *);
243 };
244
245 /* Return the hashcode for a given reference operation P1. */
246
247 inline hashval_t
248 vn_reference_hasher::hash (const vn_reference_s *vr1)
249 {
250 return vr1->hashcode;
251 }
252
253 inline bool
254 vn_reference_hasher::equal (const vn_reference_s *v, const vn_reference_s *c)
255 {
256 return v == c || vn_reference_eq (v, c);
257 }
258
259 typedef hash_table<vn_reference_hasher> vn_reference_table_type;
260 typedef vn_reference_table_type::iterator vn_reference_iterator_type;
261
262 /* Pretty-print OPS to OUTFILE. */
263
264 void
265 print_vn_reference_ops (FILE *outfile, const vec<vn_reference_op_s> ops)
266 {
267 vn_reference_op_t vro;
268 unsigned int i;
269 fprintf (outfile, "{");
270 for (i = 0; ops.iterate (i, &vro); i++)
271 {
272 bool closebrace = false;
273 if (vro->opcode != SSA_NAME
274 && TREE_CODE_CLASS (vro->opcode) != tcc_declaration)
275 {
276 fprintf (outfile, "%s", get_tree_code_name (vro->opcode));
277 if (vro->op0 || vro->opcode == CALL_EXPR)
278 {
279 fprintf (outfile, "<");
280 closebrace = true;
281 }
282 }
283 if (vro->op0 || vro->opcode == CALL_EXPR)
284 {
285 if (!vro->op0)
286 fprintf (outfile, internal_fn_name ((internal_fn)vro->clique));
287 else
288 print_generic_expr (outfile, vro->op0);
289 if (vro->op1)
290 {
291 fprintf (outfile, ",");
292 print_generic_expr (outfile, vro->op1);
293 }
294 if (vro->op2)
295 {
296 fprintf (outfile, ",");
297 print_generic_expr (outfile, vro->op2);
298 }
299 }
300 if (closebrace)
301 fprintf (outfile, ">");
302 if (i != ops.length () - 1)
303 fprintf (outfile, ",");
304 }
305 fprintf (outfile, "}");
306 }
307
308 DEBUG_FUNCTION void
309 debug_vn_reference_ops (const vec<vn_reference_op_s> ops)
310 {
311 print_vn_reference_ops (stderr, ops);
312 fputc ('\n', stderr);
313 }
314
315 /* The set of VN hashtables. */
316
317 typedef struct vn_tables_s
318 {
319 vn_nary_op_table_type *nary;
320 vn_phi_table_type *phis;
321 vn_reference_table_type *references;
322 } *vn_tables_t;
323
324
325 /* vn_constant hashtable helpers. */
326
327 struct vn_constant_hasher : free_ptr_hash <vn_constant_s>
328 {
329 static inline hashval_t hash (const vn_constant_s *);
330 static inline bool equal (const vn_constant_s *, const vn_constant_s *);
331 };
332
333 /* Hash table hash function for vn_constant_t. */
334
335 inline hashval_t
336 vn_constant_hasher::hash (const vn_constant_s *vc1)
337 {
338 return vc1->hashcode;
339 }
340
341 /* Hash table equality function for vn_constant_t. */
342
343 inline bool
344 vn_constant_hasher::equal (const vn_constant_s *vc1, const vn_constant_s *vc2)
345 {
346 if (vc1->hashcode != vc2->hashcode)
347 return false;
348
349 return vn_constant_eq_with_type (vc1->constant, vc2->constant);
350 }
351
352 static hash_table<vn_constant_hasher> *constant_to_value_id;
353
354
355 /* Obstack we allocate the vn-tables elements from. */
356 static obstack vn_tables_obstack;
357 /* Special obstack we never unwind. */
358 static obstack vn_tables_insert_obstack;
359
360 static vn_reference_t last_inserted_ref;
361 static vn_phi_t last_inserted_phi;
362 static vn_nary_op_t last_inserted_nary;
363 static vn_ssa_aux_t last_pushed_avail;
364
365 /* Valid hashtables storing information we have proven to be
366 correct. */
367 static vn_tables_t valid_info;
368
369 /* Global RPO state for access from hooks. */
370 static class eliminate_dom_walker *rpo_avail;
371 basic_block vn_context_bb;
372 int *vn_bb_to_rpo;
373
374
375 /* Valueization hook for simplify_replace_tree. Valueize NAME if it is
376 an SSA name, otherwise just return it. */
377 tree (*vn_valueize) (tree);
378 static tree
379 vn_valueize_for_srt (tree t, void* context ATTRIBUTE_UNUSED)
380 {
381 basic_block saved_vn_context_bb = vn_context_bb;
382 /* Look for sth available at the definition block of the argument.
383 This avoids inconsistencies between availability there which
384 decides if the stmt can be removed and availability at the
385 use site. The SSA property ensures that things available
386 at the definition are also available at uses. */
387 if (!SSA_NAME_IS_DEFAULT_DEF (t))
388 vn_context_bb = gimple_bb (SSA_NAME_DEF_STMT (t));
389 tree res = vn_valueize (t);
390 vn_context_bb = saved_vn_context_bb;
391 return res;
392 }
393
394
395 /* This represents the top of the VN lattice, which is the universal
396 value. */
397
398 tree VN_TOP;
399
400 /* Unique counter for our value ids. */
401
402 static unsigned int next_value_id;
403 static int next_constant_value_id;
404
405
406 /* Table of vn_ssa_aux_t's, one per ssa_name. The vn_ssa_aux_t objects
407 are allocated on an obstack for locality reasons, and to free them
408 without looping over the vec. */
409
410 struct vn_ssa_aux_hasher : typed_noop_remove <vn_ssa_aux_t>
411 {
412 typedef vn_ssa_aux_t value_type;
413 typedef tree compare_type;
414 static inline hashval_t hash (const value_type &);
415 static inline bool equal (const value_type &, const compare_type &);
416 static inline void mark_deleted (value_type &) {}
417 static const bool empty_zero_p = true;
418 static inline void mark_empty (value_type &e) { e = NULL; }
419 static inline bool is_deleted (value_type &) { return false; }
420 static inline bool is_empty (value_type &e) { return e == NULL; }
421 };
422
423 hashval_t
424 vn_ssa_aux_hasher::hash (const value_type &entry)
425 {
426 return SSA_NAME_VERSION (entry->name);
427 }
428
429 bool
430 vn_ssa_aux_hasher::equal (const value_type &entry, const compare_type &name)
431 {
432 return name == entry->name;
433 }
434
435 static hash_table<vn_ssa_aux_hasher> *vn_ssa_aux_hash;
436 typedef hash_table<vn_ssa_aux_hasher>::iterator vn_ssa_aux_iterator_type;
437 static struct obstack vn_ssa_aux_obstack;
438
439 static vn_nary_op_t vn_nary_op_insert_stmt (gimple *, tree);
440 static vn_nary_op_t vn_nary_op_insert_into (vn_nary_op_t,
441 vn_nary_op_table_type *);
442 static void init_vn_nary_op_from_pieces (vn_nary_op_t, unsigned int,
443 enum tree_code, tree, tree *);
444 static tree vn_lookup_simplify_result (gimple_match_op *);
445 static vn_reference_t vn_reference_lookup_or_insert_for_pieces
446 (tree, alias_set_type, alias_set_type, poly_int64, poly_int64, tree,
447 vec<vn_reference_op_s, va_heap>, tree);
448
449 /* Return whether there is value numbering information for a given SSA name. */
450
451 bool
452 has_VN_INFO (tree name)
453 {
454 return vn_ssa_aux_hash->find_with_hash (name, SSA_NAME_VERSION (name));
455 }
456
457 vn_ssa_aux_t
458 VN_INFO (tree name)
459 {
460 vn_ssa_aux_t *res
461 = vn_ssa_aux_hash->find_slot_with_hash (name, SSA_NAME_VERSION (name),
462 INSERT);
463 if (*res != NULL)
464 return *res;
465
466 vn_ssa_aux_t newinfo = *res = XOBNEW (&vn_ssa_aux_obstack, struct vn_ssa_aux);
467 memset (newinfo, 0, sizeof (struct vn_ssa_aux));
468 newinfo->name = name;
469 newinfo->valnum = VN_TOP;
470 /* We are using the visited flag to handle uses with defs not within the
471 region being value-numbered. */
472 newinfo->visited = false;
473
474 /* Given we create the VN_INFOs on-demand now we have to do initialization
475 different than VN_TOP here. */
476 if (SSA_NAME_IS_DEFAULT_DEF (name))
477 switch (TREE_CODE (SSA_NAME_VAR (name)))
478 {
479 case VAR_DECL:
480 /* All undefined vars are VARYING. */
481 newinfo->valnum = name;
482 newinfo->visited = true;
483 break;
484
485 case PARM_DECL:
486 /* Parameters are VARYING but we can record a condition
487 if we know it is a non-NULL pointer. */
488 newinfo->visited = true;
489 newinfo->valnum = name;
490 if (POINTER_TYPE_P (TREE_TYPE (name))
491 && nonnull_arg_p (SSA_NAME_VAR (name)))
492 {
493 tree ops[2];
494 ops[0] = name;
495 ops[1] = build_int_cst (TREE_TYPE (name), 0);
496 vn_nary_op_t nary;
497 /* Allocate from non-unwinding stack. */
498 nary = alloc_vn_nary_op_noinit (2, &vn_tables_insert_obstack);
499 init_vn_nary_op_from_pieces (nary, 2, NE_EXPR,
500 boolean_type_node, ops);
501 nary->predicated_values = 0;
502 nary->u.result = boolean_true_node;
503 vn_nary_op_insert_into (nary, valid_info->nary);
504 gcc_assert (nary->unwind_to == NULL);
505 /* Also do not link it into the undo chain. */
506 last_inserted_nary = nary->next;
507 nary->next = (vn_nary_op_t)(void *)-1;
508 nary = alloc_vn_nary_op_noinit (2, &vn_tables_insert_obstack);
509 init_vn_nary_op_from_pieces (nary, 2, EQ_EXPR,
510 boolean_type_node, ops);
511 nary->predicated_values = 0;
512 nary->u.result = boolean_false_node;
513 vn_nary_op_insert_into (nary, valid_info->nary);
514 gcc_assert (nary->unwind_to == NULL);
515 last_inserted_nary = nary->next;
516 nary->next = (vn_nary_op_t)(void *)-1;
517 if (dump_file && (dump_flags & TDF_DETAILS))
518 {
519 fprintf (dump_file, "Recording ");
520 print_generic_expr (dump_file, name, TDF_SLIM);
521 fprintf (dump_file, " != 0\n");
522 }
523 }
524 break;
525
526 case RESULT_DECL:
527 /* If the result is passed by invisible reference the default
528 def is initialized, otherwise it's uninitialized. Still
529 undefined is varying. */
530 newinfo->visited = true;
531 newinfo->valnum = name;
532 break;
533
534 default:
535 gcc_unreachable ();
536 }
537 return newinfo;
538 }
539
540 /* Return the SSA value of X. */
541
542 inline tree
543 SSA_VAL (tree x, bool *visited = NULL)
544 {
545 vn_ssa_aux_t tem = vn_ssa_aux_hash->find_with_hash (x, SSA_NAME_VERSION (x));
546 if (visited)
547 *visited = tem && tem->visited;
548 return tem && tem->visited ? tem->valnum : x;
549 }
550
551 /* Return the SSA value of the VUSE x, supporting released VDEFs
552 during elimination which will value-number the VDEF to the
553 associated VUSE (but not substitute in the whole lattice). */
554
555 static inline tree
556 vuse_ssa_val (tree x)
557 {
558 if (!x)
559 return NULL_TREE;
560
561 do
562 {
563 x = SSA_VAL (x);
564 gcc_assert (x != VN_TOP);
565 }
566 while (SSA_NAME_IN_FREE_LIST (x));
567
568 return x;
569 }
570
571 /* Similar to the above but used as callback for walk_non_aliased_vuses
572 and thus should stop at unvisited VUSE to not walk across region
573 boundaries. */
574
575 static tree
576 vuse_valueize (tree vuse)
577 {
578 do
579 {
580 bool visited;
581 vuse = SSA_VAL (vuse, &visited);
582 if (!visited)
583 return NULL_TREE;
584 gcc_assert (vuse != VN_TOP);
585 }
586 while (SSA_NAME_IN_FREE_LIST (vuse));
587 return vuse;
588 }
589
590
591 /* Return the vn_kind the expression computed by the stmt should be
592 associated with. */
593
594 enum vn_kind
595 vn_get_stmt_kind (gimple *stmt)
596 {
597 switch (gimple_code (stmt))
598 {
599 case GIMPLE_CALL:
600 return VN_REFERENCE;
601 case GIMPLE_PHI:
602 return VN_PHI;
603 case GIMPLE_ASSIGN:
604 {
605 enum tree_code code = gimple_assign_rhs_code (stmt);
606 tree rhs1 = gimple_assign_rhs1 (stmt);
607 switch (get_gimple_rhs_class (code))
608 {
609 case GIMPLE_UNARY_RHS:
610 case GIMPLE_BINARY_RHS:
611 case GIMPLE_TERNARY_RHS:
612 return VN_NARY;
613 case GIMPLE_SINGLE_RHS:
614 switch (TREE_CODE_CLASS (code))
615 {
616 case tcc_reference:
617 /* VOP-less references can go through unary case. */
618 if ((code == REALPART_EXPR
619 || code == IMAGPART_EXPR
620 || code == VIEW_CONVERT_EXPR
621 || code == BIT_FIELD_REF)
622 && (TREE_CODE (TREE_OPERAND (rhs1, 0)) == SSA_NAME
623 || is_gimple_min_invariant (TREE_OPERAND (rhs1, 0))))
624 return VN_NARY;
625
626 /* Fallthrough. */
627 case tcc_declaration:
628 return VN_REFERENCE;
629
630 case tcc_constant:
631 return VN_CONSTANT;
632
633 default:
634 if (code == ADDR_EXPR)
635 return (is_gimple_min_invariant (rhs1)
636 ? VN_CONSTANT : VN_REFERENCE);
637 else if (code == CONSTRUCTOR)
638 return VN_NARY;
639 return VN_NONE;
640 }
641 default:
642 return VN_NONE;
643 }
644 }
645 default:
646 return VN_NONE;
647 }
648 }
649
650 /* Lookup a value id for CONSTANT and return it. If it does not
651 exist returns 0. */
652
653 unsigned int
654 get_constant_value_id (tree constant)
655 {
656 vn_constant_s **slot;
657 struct vn_constant_s vc;
658
659 vc.hashcode = vn_hash_constant_with_type (constant);
660 vc.constant = constant;
661 slot = constant_to_value_id->find_slot (&vc, NO_INSERT);
662 if (slot)
663 return (*slot)->value_id;
664 return 0;
665 }
666
667 /* Lookup a value id for CONSTANT, and if it does not exist, create a
668 new one and return it. If it does exist, return it. */
669
670 unsigned int
671 get_or_alloc_constant_value_id (tree constant)
672 {
673 vn_constant_s **slot;
674 struct vn_constant_s vc;
675 vn_constant_t vcp;
676
677 /* If the hashtable isn't initialized we're not running from PRE and thus
678 do not need value-ids. */
679 if (!constant_to_value_id)
680 return 0;
681
682 vc.hashcode = vn_hash_constant_with_type (constant);
683 vc.constant = constant;
684 slot = constant_to_value_id->find_slot (&vc, INSERT);
685 if (*slot)
686 return (*slot)->value_id;
687
688 vcp = XNEW (struct vn_constant_s);
689 vcp->hashcode = vc.hashcode;
690 vcp->constant = constant;
691 vcp->value_id = get_next_constant_value_id ();
692 *slot = vcp;
693 return vcp->value_id;
694 }
695
696 /* Compute the hash for a reference operand VRO1. */
697
698 static void
699 vn_reference_op_compute_hash (const vn_reference_op_t vro1, inchash::hash &hstate)
700 {
701 hstate.add_int (vro1->opcode);
702 if (vro1->opcode == CALL_EXPR && !vro1->op0)
703 hstate.add_int (vro1->clique);
704 if (vro1->op0)
705 inchash::add_expr (vro1->op0, hstate);
706 if (vro1->op1)
707 inchash::add_expr (vro1->op1, hstate);
708 if (vro1->op2)
709 inchash::add_expr (vro1->op2, hstate);
710 }
711
712 /* Compute a hash for the reference operation VR1 and return it. */
713
714 static hashval_t
715 vn_reference_compute_hash (const vn_reference_t vr1)
716 {
717 inchash::hash hstate;
718 hashval_t result;
719 int i;
720 vn_reference_op_t vro;
721 poly_int64 off = -1;
722 bool deref = false;
723
724 FOR_EACH_VEC_ELT (vr1->operands, i, vro)
725 {
726 if (vro->opcode == MEM_REF)
727 deref = true;
728 else if (vro->opcode != ADDR_EXPR)
729 deref = false;
730 if (maybe_ne (vro->off, -1))
731 {
732 if (known_eq (off, -1))
733 off = 0;
734 off += vro->off;
735 }
736 else
737 {
738 if (maybe_ne (off, -1)
739 && maybe_ne (off, 0))
740 hstate.add_poly_int (off);
741 off = -1;
742 if (deref
743 && vro->opcode == ADDR_EXPR)
744 {
745 if (vro->op0)
746 {
747 tree op = TREE_OPERAND (vro->op0, 0);
748 hstate.add_int (TREE_CODE (op));
749 inchash::add_expr (op, hstate);
750 }
751 }
752 else
753 vn_reference_op_compute_hash (vro, hstate);
754 }
755 }
756 /* Do not hash vr1->offset or vr1->max_size, we want to get collisions
757 to be able to identify compatible results. */
758 result = hstate.end ();
759 /* ??? We would ICE later if we hash instead of adding that in. */
760 if (vr1->vuse)
761 result += SSA_NAME_VERSION (vr1->vuse);
762
763 return result;
764 }
765
766 /* Return true if reference operations VR1 and VR2 are equivalent. This
767 means they have the same set of operands and vuses. */
768
769 bool
770 vn_reference_eq (const_vn_reference_t const vr1, const_vn_reference_t const vr2)
771 {
772 unsigned i, j;
773
774 /* Early out if this is not a hash collision. */
775 if (vr1->hashcode != vr2->hashcode)
776 return false;
777
778 /* The VOP needs to be the same. */
779 if (vr1->vuse != vr2->vuse)
780 return false;
781
782 /* The offset/max_size used for the ao_ref during lookup has to be
783 the same. */
784 if (maybe_ne (vr1->offset, vr2->offset)
785 || maybe_ne (vr1->max_size, vr2->max_size))
786 {
787 /* But nothing known in the prevailing entry is OK to be used. */
788 if (maybe_ne (vr1->offset, 0) || known_size_p (vr1->max_size))
789 return false;
790 }
791
792 /* If the operands are the same we are done. */
793 if (vr1->operands == vr2->operands)
794 return true;
795
796 if (!vr1->type || !vr2->type)
797 {
798 if (vr1->type != vr2->type)
799 return false;
800 }
801 else if (vr1->type == vr2->type)
802 ;
803 else if (COMPLETE_TYPE_P (vr1->type) != COMPLETE_TYPE_P (vr2->type)
804 || (COMPLETE_TYPE_P (vr1->type)
805 && !expressions_equal_p (TYPE_SIZE (vr1->type),
806 TYPE_SIZE (vr2->type))))
807 return false;
808 else if (vr1->operands[0].opcode == CALL_EXPR
809 && !types_compatible_p (vr1->type, vr2->type))
810 return false;
811 else if (INTEGRAL_TYPE_P (vr1->type)
812 && INTEGRAL_TYPE_P (vr2->type))
813 {
814 if (TYPE_PRECISION (vr1->type) != TYPE_PRECISION (vr2->type))
815 return false;
816 }
817 else if (INTEGRAL_TYPE_P (vr1->type)
818 && (TYPE_PRECISION (vr1->type)
819 != TREE_INT_CST_LOW (TYPE_SIZE (vr1->type))))
820 return false;
821 else if (INTEGRAL_TYPE_P (vr2->type)
822 && (TYPE_PRECISION (vr2->type)
823 != TREE_INT_CST_LOW (TYPE_SIZE (vr2->type))))
824 return false;
825 else if (VECTOR_BOOLEAN_TYPE_P (vr1->type)
826 && VECTOR_BOOLEAN_TYPE_P (vr2->type))
827 {
828 /* Vector boolean types can have padding, verify we are dealing with
829 the same number of elements, aka the precision of the types.
830 For example, In most architecture the precision_size of vbool*_t
831 types are caculated like below:
832 precision_size = type_size * 8
833
834 Unfortunately, the RISC-V will adjust the precision_size for the
835 vbool*_t in order to align the ISA as below:
836 type_size = [1, 1, 1, 1, 2, 4, 8]
837 precision_size = [1, 2, 4, 8, 16, 32, 64]
838
839 Then the precision_size of RISC-V vbool*_t will not be the multiple
840 of the type_size. We take care of this case consolidated here. */
841 if (maybe_ne (TYPE_VECTOR_SUBPARTS (vr1->type),
842 TYPE_VECTOR_SUBPARTS (vr2->type)))
843 return false;
844 }
845 else if (TYPE_MODE (vr1->type) != TYPE_MODE (vr2->type)
846 && (!mode_can_transfer_bits (TYPE_MODE (vr1->type))
847 || !mode_can_transfer_bits (TYPE_MODE (vr2->type))))
848 return false;
849
850 i = 0;
851 j = 0;
852 do
853 {
854 poly_int64 off1 = 0, off2 = 0;
855 vn_reference_op_t vro1, vro2;
856 vn_reference_op_s tem1, tem2;
857 bool deref1 = false, deref2 = false;
858 bool reverse1 = false, reverse2 = false;
859 for (; vr1->operands.iterate (i, &vro1); i++)
860 {
861 if (vro1->opcode == MEM_REF)
862 deref1 = true;
863 /* Do not look through a storage order barrier. */
864 else if (vro1->opcode == VIEW_CONVERT_EXPR && vro1->reverse)
865 return false;
866 reverse1 |= vro1->reverse;
867 if (known_eq (vro1->off, -1))
868 break;
869 off1 += vro1->off;
870 }
871 for (; vr2->operands.iterate (j, &vro2); j++)
872 {
873 if (vro2->opcode == MEM_REF)
874 deref2 = true;
875 /* Do not look through a storage order barrier. */
876 else if (vro2->opcode == VIEW_CONVERT_EXPR && vro2->reverse)
877 return false;
878 reverse2 |= vro2->reverse;
879 if (known_eq (vro2->off, -1))
880 break;
881 off2 += vro2->off;
882 }
883 if (maybe_ne (off1, off2) || reverse1 != reverse2)
884 return false;
885 if (deref1 && vro1->opcode == ADDR_EXPR)
886 {
887 memset (&tem1, 0, sizeof (tem1));
888 tem1.op0 = TREE_OPERAND (vro1->op0, 0);
889 tem1.type = TREE_TYPE (tem1.op0);
890 tem1.opcode = TREE_CODE (tem1.op0);
891 vro1 = &tem1;
892 deref1 = false;
893 }
894 if (deref2 && vro2->opcode == ADDR_EXPR)
895 {
896 memset (&tem2, 0, sizeof (tem2));
897 tem2.op0 = TREE_OPERAND (vro2->op0, 0);
898 tem2.type = TREE_TYPE (tem2.op0);
899 tem2.opcode = TREE_CODE (tem2.op0);
900 vro2 = &tem2;
901 deref2 = false;
902 }
903 if (deref1 != deref2)
904 return false;
905 if (!vn_reference_op_eq (vro1, vro2))
906 return false;
907 ++j;
908 ++i;
909 }
910 while (vr1->operands.length () != i
911 || vr2->operands.length () != j);
912
913 return true;
914 }
915
916 /* Copy the operations present in load/store REF into RESULT, a vector of
917 vn_reference_op_s's. */
918
919 static void
920 copy_reference_ops_from_ref (tree ref, vec<vn_reference_op_s> *result)
921 {
922 /* For non-calls, store the information that makes up the address. */
923 tree orig = ref;
924 while (ref)
925 {
926 vn_reference_op_s temp;
927
928 memset (&temp, 0, sizeof (temp));
929 temp.type = TREE_TYPE (ref);
930 temp.opcode = TREE_CODE (ref);
931 temp.off = -1;
932
933 switch (temp.opcode)
934 {
935 case MODIFY_EXPR:
936 temp.op0 = TREE_OPERAND (ref, 1);
937 break;
938 case WITH_SIZE_EXPR:
939 temp.op0 = TREE_OPERAND (ref, 1);
940 temp.off = 0;
941 break;
942 case MEM_REF:
943 /* The base address gets its own vn_reference_op_s structure. */
944 temp.op0 = TREE_OPERAND (ref, 1);
945 if (!mem_ref_offset (ref).to_shwi (&temp.off))
946 temp.off = -1;
947 temp.clique = MR_DEPENDENCE_CLIQUE (ref);
948 temp.base = MR_DEPENDENCE_BASE (ref);
949 temp.reverse = REF_REVERSE_STORAGE_ORDER (ref);
950 break;
951 case TARGET_MEM_REF:
952 /* The base address gets its own vn_reference_op_s structure. */
953 temp.op0 = TMR_INDEX (ref);
954 temp.op1 = TMR_STEP (ref);
955 temp.op2 = TMR_OFFSET (ref);
956 temp.clique = MR_DEPENDENCE_CLIQUE (ref);
957 temp.base = MR_DEPENDENCE_BASE (ref);
958 result->safe_push (temp);
959 memset (&temp, 0, sizeof (temp));
960 temp.type = NULL_TREE;
961 temp.opcode = ERROR_MARK;
962 temp.op0 = TMR_INDEX2 (ref);
963 temp.off = -1;
964 break;
965 case BIT_FIELD_REF:
966 /* Record bits, position and storage order. */
967 temp.op0 = TREE_OPERAND (ref, 1);
968 temp.op1 = TREE_OPERAND (ref, 2);
969 if (!multiple_p (bit_field_offset (ref), BITS_PER_UNIT, &temp.off))
970 temp.off = -1;
971 temp.reverse = REF_REVERSE_STORAGE_ORDER (ref);
972 break;
973 case COMPONENT_REF:
974 /* The field decl is enough to unambiguously specify the field,
975 so use its type here. */
976 temp.type = TREE_TYPE (TREE_OPERAND (ref, 1));
977 temp.op0 = TREE_OPERAND (ref, 1);
978 temp.op1 = TREE_OPERAND (ref, 2);
979 temp.reverse = (AGGREGATE_TYPE_P (TREE_TYPE (TREE_OPERAND (ref, 0)))
980 && TYPE_REVERSE_STORAGE_ORDER
981 (TREE_TYPE (TREE_OPERAND (ref, 0))));
982 {
983 tree this_offset = component_ref_field_offset (ref);
984 if (this_offset
985 && poly_int_tree_p (this_offset))
986 {
987 tree bit_offset = DECL_FIELD_BIT_OFFSET (TREE_OPERAND (ref, 1));
988 if (TREE_INT_CST_LOW (bit_offset) % BITS_PER_UNIT == 0)
989 {
990 poly_offset_int off
991 = (wi::to_poly_offset (this_offset)
992 + (wi::to_offset (bit_offset) >> LOG2_BITS_PER_UNIT));
993 /* Prohibit value-numbering zero offset components
994 of addresses the same before the pass folding
995 __builtin_object_size had a chance to run. Likewise
996 for components of zero size at arbitrary offset. */
997 if (TREE_CODE (orig) != ADDR_EXPR
998 || (TYPE_SIZE (temp.type)
999 && integer_nonzerop (TYPE_SIZE (temp.type))
1000 && maybe_ne (off, 0))
1001 || (cfun->curr_properties & PROP_objsz))
1002 off.to_shwi (&temp.off);
1003 }
1004 }
1005 }
1006 break;
1007 case ARRAY_RANGE_REF:
1008 case ARRAY_REF:
1009 {
1010 tree eltype = TREE_TYPE (TREE_TYPE (TREE_OPERAND (ref, 0)));
1011 /* Record index as operand. */
1012 temp.op0 = TREE_OPERAND (ref, 1);
1013 /* Always record lower bounds and element size. */
1014 temp.op1 = array_ref_low_bound (ref);
1015 /* But record element size in units of the type alignment. */
1016 temp.op2 = TREE_OPERAND (ref, 3);
1017 temp.align = eltype->type_common.align;
1018 if (! temp.op2)
1019 temp.op2 = size_binop (EXACT_DIV_EXPR, TYPE_SIZE_UNIT (eltype),
1020 size_int (TYPE_ALIGN_UNIT (eltype)));
1021 /* Prohibit value-numbering addresses of one-after-the-last
1022 element ARRAY_REFs the same as addresses of other components
1023 before the pass folding __builtin_object_size had a chance
1024 to run. */
1025 bool avoid_oob = true;
1026 if (TREE_CODE (orig) != ADDR_EXPR
1027 || cfun->curr_properties & PROP_objsz)
1028 avoid_oob = false;
1029 else if (poly_int_tree_p (temp.op0))
1030 {
1031 tree ub = array_ref_up_bound (ref);
1032 if (ub
1033 && poly_int_tree_p (ub)
1034 /* ??? The C frontend for T[0] uses [0:] and the
1035 C++ frontend [0:-1U]. See layout_type for how
1036 awkward this is. */
1037 && !integer_minus_onep (ub)
1038 && known_le (wi::to_poly_offset (temp.op0),
1039 wi::to_poly_offset (ub)))
1040 avoid_oob = false;
1041 }
1042 if (poly_int_tree_p (temp.op0)
1043 && poly_int_tree_p (temp.op1)
1044 && TREE_CODE (temp.op2) == INTEGER_CST
1045 && !avoid_oob)
1046 {
1047 poly_offset_int off = ((wi::to_poly_offset (temp.op0)
1048 - wi::to_poly_offset (temp.op1))
1049 * wi::to_offset (temp.op2)
1050 * vn_ref_op_align_unit (&temp));
1051 off.to_shwi (&temp.off);
1052 }
1053 temp.reverse = (AGGREGATE_TYPE_P (TREE_TYPE (TREE_OPERAND (ref, 0)))
1054 && TYPE_REVERSE_STORAGE_ORDER
1055 (TREE_TYPE (TREE_OPERAND (ref, 0))));
1056 }
1057 break;
1058 case VAR_DECL:
1059 if (DECL_HARD_REGISTER (ref))
1060 {
1061 temp.op0 = ref;
1062 break;
1063 }
1064 /* Fallthru. */
1065 case PARM_DECL:
1066 case CONST_DECL:
1067 case RESULT_DECL:
1068 /* Canonicalize decls to MEM[&decl] which is what we end up with
1069 when valueizing MEM[ptr] with ptr = &decl. */
1070 temp.opcode = MEM_REF;
1071 temp.op0 = build_int_cst (build_pointer_type (TREE_TYPE (ref)), 0);
1072 temp.off = 0;
1073 result->safe_push (temp);
1074 temp.opcode = ADDR_EXPR;
1075 temp.op0 = build1 (ADDR_EXPR, TREE_TYPE (temp.op0), ref);
1076 temp.type = TREE_TYPE (temp.op0);
1077 temp.off = -1;
1078 break;
1079 case STRING_CST:
1080 case INTEGER_CST:
1081 case POLY_INT_CST:
1082 case COMPLEX_CST:
1083 case VECTOR_CST:
1084 case REAL_CST:
1085 case FIXED_CST:
1086 case CONSTRUCTOR:
1087 case SSA_NAME:
1088 temp.op0 = ref;
1089 break;
1090 case ADDR_EXPR:
1091 if (is_gimple_min_invariant (ref))
1092 {
1093 temp.op0 = ref;
1094 break;
1095 }
1096 break;
1097 /* These are only interesting for their operands, their
1098 existence, and their type. They will never be the last
1099 ref in the chain of references (IE they require an
1100 operand), so we don't have to put anything
1101 for op* as it will be handled by the iteration */
1102 case REALPART_EXPR:
1103 temp.off = 0;
1104 break;
1105 case VIEW_CONVERT_EXPR:
1106 temp.off = 0;
1107 temp.reverse = storage_order_barrier_p (ref);
1108 break;
1109 case IMAGPART_EXPR:
1110 /* This is only interesting for its constant offset. */
1111 temp.off = TREE_INT_CST_LOW (TYPE_SIZE_UNIT (TREE_TYPE (ref)));
1112 break;
1113 default:
1114 gcc_unreachable ();
1115 }
1116 result->safe_push (temp);
1117
1118 if (REFERENCE_CLASS_P (ref)
1119 || TREE_CODE (ref) == MODIFY_EXPR
1120 || TREE_CODE (ref) == WITH_SIZE_EXPR
1121 || (TREE_CODE (ref) == ADDR_EXPR
1122 && !is_gimple_min_invariant (ref)))
1123 ref = TREE_OPERAND (ref, 0);
1124 else
1125 ref = NULL_TREE;
1126 }
1127 }
1128
1129 /* Build a alias-oracle reference abstraction in *REF from the vn_reference
1130 operands in *OPS, the reference alias set SET and the reference type TYPE.
1131 Return true if something useful was produced. */
1132
1133 bool
1134 ao_ref_init_from_vn_reference (ao_ref *ref,
1135 alias_set_type set, alias_set_type base_set,
1136 tree type, const vec<vn_reference_op_s> &ops)
1137 {
1138 unsigned i;
1139 tree base = NULL_TREE;
1140 tree *op0_p = &base;
1141 poly_offset_int offset = 0;
1142 poly_offset_int max_size;
1143 poly_offset_int size = -1;
1144 tree size_tree = NULL_TREE;
1145
1146 /* We don't handle calls. */
1147 if (!type)
1148 return false;
1149
1150 machine_mode mode = TYPE_MODE (type);
1151 if (mode == BLKmode)
1152 size_tree = TYPE_SIZE (type);
1153 else
1154 size = GET_MODE_BITSIZE (mode);
1155 if (size_tree != NULL_TREE
1156 && poly_int_tree_p (size_tree))
1157 size = wi::to_poly_offset (size_tree);
1158
1159 /* Lower the final access size from the outermost expression. */
1160 const_vn_reference_op_t cst_op = &ops[0];
1161 /* Cast away constness for the sake of the const-unsafe
1162 FOR_EACH_VEC_ELT(). */
1163 vn_reference_op_t op = const_cast<vn_reference_op_t>(cst_op);
1164 size_tree = NULL_TREE;
1165 if (op->opcode == COMPONENT_REF)
1166 size_tree = DECL_SIZE (op->op0);
1167 else if (op->opcode == BIT_FIELD_REF)
1168 size_tree = op->op0;
1169 if (size_tree != NULL_TREE
1170 && poly_int_tree_p (size_tree)
1171 && (!known_size_p (size)
1172 || known_lt (wi::to_poly_offset (size_tree), size)))
1173 size = wi::to_poly_offset (size_tree);
1174
1175 /* Initially, maxsize is the same as the accessed element size.
1176 In the following it will only grow (or become -1). */
1177 max_size = size;
1178
1179 /* Compute cumulative bit-offset for nested component-refs and array-refs,
1180 and find the ultimate containing object. */
1181 FOR_EACH_VEC_ELT (ops, i, op)
1182 {
1183 switch (op->opcode)
1184 {
1185 case CALL_EXPR:
1186 return false;
1187
1188 /* Record the base objects. */
1189 case MEM_REF:
1190 *op0_p = build2 (MEM_REF, op->type,
1191 NULL_TREE, op->op0);
1192 MR_DEPENDENCE_CLIQUE (*op0_p) = op->clique;
1193 MR_DEPENDENCE_BASE (*op0_p) = op->base;
1194 op0_p = &TREE_OPERAND (*op0_p, 0);
1195 break;
1196
1197 case TARGET_MEM_REF:
1198 *op0_p = build5 (TARGET_MEM_REF, op->type,
1199 NULL_TREE, op->op2, op->op0,
1200 op->op1, ops[i+1].op0);
1201 MR_DEPENDENCE_CLIQUE (*op0_p) = op->clique;
1202 MR_DEPENDENCE_BASE (*op0_p) = op->base;
1203 op0_p = &TREE_OPERAND (*op0_p, 0);
1204 ++i;
1205 break;
1206
1207 /* Unwrap some of the wrapped decls. */
1208 case ADDR_EXPR:
1209 /* Apart from ADDR_EXPR arguments to MEM_REF. */
1210 if (base != NULL_TREE
1211 && TREE_CODE (base) == MEM_REF
1212 && op->op0
1213 && DECL_P (TREE_OPERAND (op->op0, 0)))
1214 {
1215 const_vn_reference_op_t pop = &ops[i-1];
1216 base = TREE_OPERAND (op->op0, 0);
1217 if (known_eq (pop->off, -1))
1218 {
1219 max_size = -1;
1220 offset = 0;
1221 }
1222 else
1223 offset += poly_offset_int (pop->off) * BITS_PER_UNIT;
1224 op0_p = NULL;
1225 break;
1226 }
1227 /* Fallthru. */
1228 case PARM_DECL:
1229 case CONST_DECL:
1230 case RESULT_DECL:
1231 /* ??? We shouldn't see these, but un-canonicalize what
1232 copy_reference_ops_from_ref does when visiting MEM_REF. */
1233 case VAR_DECL:
1234 /* ??? And for this only have DECL_HARD_REGISTER. */
1235 case STRING_CST:
1236 /* This can show up in ARRAY_REF bases. */
1237 case INTEGER_CST:
1238 case SSA_NAME:
1239 *op0_p = op->op0;
1240 op0_p = NULL;
1241 break;
1242
1243 /* And now the usual component-reference style ops. */
1244 case BIT_FIELD_REF:
1245 offset += wi::to_poly_offset (op->op1);
1246 break;
1247
1248 case COMPONENT_REF:
1249 {
1250 tree field = op->op0;
1251 /* We do not have a complete COMPONENT_REF tree here so we
1252 cannot use component_ref_field_offset. Do the interesting
1253 parts manually. */
1254 tree this_offset = DECL_FIELD_OFFSET (field);
1255
1256 if (op->op1 || !poly_int_tree_p (this_offset))
1257 max_size = -1;
1258 else
1259 {
1260 poly_offset_int woffset = (wi::to_poly_offset (this_offset)
1261 << LOG2_BITS_PER_UNIT);
1262 woffset += wi::to_offset (DECL_FIELD_BIT_OFFSET (field));
1263 offset += woffset;
1264 }
1265 break;
1266 }
1267
1268 case ARRAY_RANGE_REF:
1269 case ARRAY_REF:
1270 /* Use the recorded constant offset. */
1271 if (maybe_eq (op->off, -1))
1272 max_size = -1;
1273 else
1274 offset += poly_offset_int (op->off) * BITS_PER_UNIT;
1275 break;
1276
1277 case REALPART_EXPR:
1278 break;
1279
1280 case IMAGPART_EXPR:
1281 offset += size;
1282 break;
1283
1284 case VIEW_CONVERT_EXPR:
1285 break;
1286
1287 case POLY_INT_CST:
1288 case COMPLEX_CST:
1289 case VECTOR_CST:
1290 case REAL_CST:
1291 case FIXED_CST:
1292 case CONSTRUCTOR:
1293 return false;
1294
1295 default:
1296 return false;
1297 }
1298 }
1299
1300 if (base == NULL_TREE)
1301 return false;
1302
1303 ref->ref = NULL_TREE;
1304 ref->base = base;
1305 ref->ref_alias_set = set;
1306 ref->base_alias_set = base_set;
1307 /* We discount volatiles from value-numbering elsewhere. */
1308 ref->volatile_p = false;
1309
1310 if (!size.to_shwi (&ref->size) || maybe_lt (ref->size, 0))
1311 {
1312 ref->offset = 0;
1313 ref->size = -1;
1314 ref->max_size = -1;
1315 return true;
1316 }
1317
1318 if (!offset.to_shwi (&ref->offset))
1319 {
1320 ref->offset = 0;
1321 ref->max_size = -1;
1322 return true;
1323 }
1324
1325 if (!max_size.to_shwi (&ref->max_size) || maybe_lt (ref->max_size, 0))
1326 ref->max_size = -1;
1327
1328 return true;
1329 }
1330
1331 /* Copy the operations present in load/store/call REF into RESULT, a vector of
1332 vn_reference_op_s's. */
1333
1334 static void
1335 copy_reference_ops_from_call (gcall *call,
1336 vec<vn_reference_op_s> *result)
1337 {
1338 vn_reference_op_s temp;
1339 unsigned i;
1340 tree lhs = gimple_call_lhs (call);
1341 int lr;
1342
1343 /* If 2 calls have a different non-ssa lhs, vdef value numbers should be
1344 different. By adding the lhs here in the vector, we ensure that the
1345 hashcode is different, guaranteeing a different value number. */
1346 if (lhs && TREE_CODE (lhs) != SSA_NAME)
1347 {
1348 memset (&temp, 0, sizeof (temp));
1349 temp.opcode = MODIFY_EXPR;
1350 temp.type = TREE_TYPE (lhs);
1351 temp.op0 = lhs;
1352 temp.off = -1;
1353 result->safe_push (temp);
1354 }
1355
1356 /* Copy the type, opcode, function, static chain and EH region, if any. */
1357 memset (&temp, 0, sizeof (temp));
1358 temp.type = gimple_call_fntype (call);
1359 temp.opcode = CALL_EXPR;
1360 temp.op0 = gimple_call_fn (call);
1361 if (gimple_call_internal_p (call))
1362 temp.clique = gimple_call_internal_fn (call);
1363 temp.op1 = gimple_call_chain (call);
1364 if (stmt_could_throw_p (cfun, call) && (lr = lookup_stmt_eh_lp (call)) > 0)
1365 temp.op2 = size_int (lr);
1366 temp.off = -1;
1367 result->safe_push (temp);
1368
1369 /* Copy the call arguments. As they can be references as well,
1370 just chain them together. */
1371 for (i = 0; i < gimple_call_num_args (call); ++i)
1372 {
1373 tree callarg = gimple_call_arg (call, i);
1374 copy_reference_ops_from_ref (callarg, result);
1375 }
1376 }
1377
1378 /* Fold *& at position *I_P in a vn_reference_op_s vector *OPS. Updates
1379 *I_P to point to the last element of the replacement. */
1380 static bool
1381 vn_reference_fold_indirect (vec<vn_reference_op_s> *ops,
1382 unsigned int *i_p)
1383 {
1384 unsigned int i = *i_p;
1385 vn_reference_op_t op = &(*ops)[i];
1386 vn_reference_op_t mem_op = &(*ops)[i - 1];
1387 tree addr_base;
1388 poly_int64 addr_offset = 0;
1389
1390 /* The only thing we have to do is from &OBJ.foo.bar add the offset
1391 from .foo.bar to the preceding MEM_REF offset and replace the
1392 address with &OBJ. */
1393 addr_base = get_addr_base_and_unit_offset_1 (TREE_OPERAND (op->op0, 0),
1394 &addr_offset, vn_valueize);
1395 gcc_checking_assert (addr_base && TREE_CODE (addr_base) != MEM_REF);
1396 if (addr_base != TREE_OPERAND (op->op0, 0))
1397 {
1398 poly_offset_int off
1399 = (poly_offset_int::from (wi::to_poly_wide (mem_op->op0),
1400 SIGNED)
1401 + addr_offset);
1402 mem_op->op0 = wide_int_to_tree (TREE_TYPE (mem_op->op0), off);
1403 op->op0 = build_fold_addr_expr (addr_base);
1404 if (tree_fits_shwi_p (mem_op->op0))
1405 mem_op->off = tree_to_shwi (mem_op->op0);
1406 else
1407 mem_op->off = -1;
1408 return true;
1409 }
1410 return false;
1411 }
1412
1413 /* Fold *& at position *I_P in a vn_reference_op_s vector *OPS. Updates
1414 *I_P to point to the last element of the replacement. */
1415 static bool
1416 vn_reference_maybe_forwprop_address (vec<vn_reference_op_s> *ops,
1417 unsigned int *i_p)
1418 {
1419 bool changed = false;
1420 vn_reference_op_t op;
1421
1422 do
1423 {
1424 unsigned int i = *i_p;
1425 op = &(*ops)[i];
1426 vn_reference_op_t mem_op = &(*ops)[i - 1];
1427 gimple *def_stmt;
1428 enum tree_code code;
1429 poly_offset_int off;
1430
1431 def_stmt = SSA_NAME_DEF_STMT (op->op0);
1432 if (!is_gimple_assign (def_stmt))
1433 return changed;
1434
1435 code = gimple_assign_rhs_code (def_stmt);
1436 if (code != ADDR_EXPR
1437 && code != POINTER_PLUS_EXPR)
1438 return changed;
1439
1440 off = poly_offset_int::from (wi::to_poly_wide (mem_op->op0), SIGNED);
1441
1442 /* The only thing we have to do is from &OBJ.foo.bar add the offset
1443 from .foo.bar to the preceding MEM_REF offset and replace the
1444 address with &OBJ. */
1445 if (code == ADDR_EXPR)
1446 {
1447 tree addr, addr_base;
1448 poly_int64 addr_offset;
1449
1450 addr = gimple_assign_rhs1 (def_stmt);
1451 addr_base = get_addr_base_and_unit_offset_1 (TREE_OPERAND (addr, 0),
1452 &addr_offset,
1453 vn_valueize);
1454 /* If that didn't work because the address isn't invariant propagate
1455 the reference tree from the address operation in case the current
1456 dereference isn't offsetted. */
1457 if (!addr_base
1458 && *i_p == ops->length () - 1
1459 && known_eq (off, 0)
1460 /* This makes us disable this transform for PRE where the
1461 reference ops might be also used for code insertion which
1462 is invalid. */
1463 && default_vn_walk_kind == VN_WALKREWRITE)
1464 {
1465 auto_vec<vn_reference_op_s, 32> tem;
1466 copy_reference_ops_from_ref (TREE_OPERAND (addr, 0), &tem);
1467 /* Make sure to preserve TBAA info. The only objects not
1468 wrapped in MEM_REFs that can have their address taken are
1469 STRING_CSTs. */
1470 if (tem.length () >= 2
1471 && tem[tem.length () - 2].opcode == MEM_REF)
1472 {
1473 vn_reference_op_t new_mem_op = &tem[tem.length () - 2];
1474 new_mem_op->op0
1475 = wide_int_to_tree (TREE_TYPE (mem_op->op0),
1476 wi::to_poly_wide (new_mem_op->op0));
1477 }
1478 else
1479 gcc_assert (tem.last ().opcode == STRING_CST);
1480 ops->pop ();
1481 ops->pop ();
1482 ops->safe_splice (tem);
1483 --*i_p;
1484 return true;
1485 }
1486 if (!addr_base
1487 || TREE_CODE (addr_base) != MEM_REF
1488 || (TREE_CODE (TREE_OPERAND (addr_base, 0)) == SSA_NAME
1489 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (TREE_OPERAND (addr_base,
1490 0))))
1491 return changed;
1492
1493 off += addr_offset;
1494 off += mem_ref_offset (addr_base);
1495 op->op0 = TREE_OPERAND (addr_base, 0);
1496 }
1497 else
1498 {
1499 tree ptr, ptroff;
1500 ptr = gimple_assign_rhs1 (def_stmt);
1501 ptroff = gimple_assign_rhs2 (def_stmt);
1502 if (TREE_CODE (ptr) != SSA_NAME
1503 || SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ptr)
1504 /* Make sure to not endlessly recurse.
1505 See gcc.dg/tree-ssa/20040408-1.c for an example. Can easily
1506 happen when we value-number a PHI to its backedge value. */
1507 || SSA_VAL (ptr) == op->op0
1508 || !poly_int_tree_p (ptroff))
1509 return changed;
1510
1511 off += wi::to_poly_offset (ptroff);
1512 op->op0 = ptr;
1513 }
1514
1515 mem_op->op0 = wide_int_to_tree (TREE_TYPE (mem_op->op0), off);
1516 if (tree_fits_shwi_p (mem_op->op0))
1517 mem_op->off = tree_to_shwi (mem_op->op0);
1518 else
1519 mem_op->off = -1;
1520 /* ??? Can end up with endless recursion here!?
1521 gcc.c-torture/execute/strcmp-1.c */
1522 if (TREE_CODE (op->op0) == SSA_NAME)
1523 op->op0 = SSA_VAL (op->op0);
1524 if (TREE_CODE (op->op0) != SSA_NAME)
1525 op->opcode = TREE_CODE (op->op0);
1526
1527 changed = true;
1528 }
1529 /* Tail-recurse. */
1530 while (TREE_CODE (op->op0) == SSA_NAME);
1531
1532 /* Fold a remaining *&. */
1533 if (TREE_CODE (op->op0) == ADDR_EXPR)
1534 vn_reference_fold_indirect (ops, i_p);
1535
1536 return changed;
1537 }
1538
1539 /* Optimize the reference REF to a constant if possible or return
1540 NULL_TREE if not. */
1541
1542 tree
1543 fully_constant_vn_reference_p (vn_reference_t ref)
1544 {
1545 vec<vn_reference_op_s> operands = ref->operands;
1546 vn_reference_op_t op;
1547
1548 /* Try to simplify the translated expression if it is
1549 a call to a builtin function with at most two arguments. */
1550 op = &operands[0];
1551 if (op->opcode == CALL_EXPR
1552 && (!op->op0
1553 || (TREE_CODE (op->op0) == ADDR_EXPR
1554 && TREE_CODE (TREE_OPERAND (op->op0, 0)) == FUNCTION_DECL
1555 && fndecl_built_in_p (TREE_OPERAND (op->op0, 0),
1556 BUILT_IN_NORMAL)))
1557 && operands.length () >= 2
1558 && operands.length () <= 3)
1559 {
1560 vn_reference_op_t arg0, arg1 = NULL;
1561 bool anyconst = false;
1562 arg0 = &operands[1];
1563 if (operands.length () > 2)
1564 arg1 = &operands[2];
1565 if (TREE_CODE_CLASS (arg0->opcode) == tcc_constant
1566 || (arg0->opcode == ADDR_EXPR
1567 && is_gimple_min_invariant (arg0->op0)))
1568 anyconst = true;
1569 if (arg1
1570 && (TREE_CODE_CLASS (arg1->opcode) == tcc_constant
1571 || (arg1->opcode == ADDR_EXPR
1572 && is_gimple_min_invariant (arg1->op0))))
1573 anyconst = true;
1574 if (anyconst)
1575 {
1576 combined_fn fn;
1577 if (op->op0)
1578 fn = as_combined_fn (DECL_FUNCTION_CODE
1579 (TREE_OPERAND (op->op0, 0)));
1580 else
1581 fn = as_combined_fn ((internal_fn) op->clique);
1582 tree folded;
1583 if (arg1)
1584 folded = fold_const_call (fn, ref->type, arg0->op0, arg1->op0);
1585 else
1586 folded = fold_const_call (fn, ref->type, arg0->op0);
1587 if (folded
1588 && is_gimple_min_invariant (folded))
1589 return folded;
1590 }
1591 }
1592
1593 /* Simplify reads from constants or constant initializers. */
1594 else if (BITS_PER_UNIT == 8
1595 && ref->type
1596 && COMPLETE_TYPE_P (ref->type)
1597 && is_gimple_reg_type (ref->type))
1598 {
1599 poly_int64 off = 0;
1600 HOST_WIDE_INT size;
1601 if (INTEGRAL_TYPE_P (ref->type))
1602 size = TYPE_PRECISION (ref->type);
1603 else if (tree_fits_shwi_p (TYPE_SIZE (ref->type)))
1604 size = tree_to_shwi (TYPE_SIZE (ref->type));
1605 else
1606 return NULL_TREE;
1607 if (size % BITS_PER_UNIT != 0
1608 || size > MAX_BITSIZE_MODE_ANY_MODE)
1609 return NULL_TREE;
1610 size /= BITS_PER_UNIT;
1611 unsigned i;
1612 for (i = 0; i < operands.length (); ++i)
1613 {
1614 if (TREE_CODE_CLASS (operands[i].opcode) == tcc_constant)
1615 {
1616 ++i;
1617 break;
1618 }
1619 if (operands[i].reverse)
1620 return NULL_TREE;
1621 if (known_eq (operands[i].off, -1))
1622 return NULL_TREE;
1623 off += operands[i].off;
1624 if (operands[i].opcode == MEM_REF)
1625 {
1626 ++i;
1627 break;
1628 }
1629 }
1630 vn_reference_op_t base = &operands[--i];
1631 tree ctor = error_mark_node;
1632 tree decl = NULL_TREE;
1633 if (TREE_CODE_CLASS (base->opcode) == tcc_constant)
1634 ctor = base->op0;
1635 else if (base->opcode == MEM_REF
1636 && base[1].opcode == ADDR_EXPR
1637 && (VAR_P (TREE_OPERAND (base[1].op0, 0))
1638 || TREE_CODE (TREE_OPERAND (base[1].op0, 0)) == CONST_DECL
1639 || TREE_CODE (TREE_OPERAND (base[1].op0, 0)) == STRING_CST))
1640 {
1641 decl = TREE_OPERAND (base[1].op0, 0);
1642 if (TREE_CODE (decl) == STRING_CST)
1643 ctor = decl;
1644 else
1645 ctor = ctor_for_folding (decl);
1646 }
1647 if (ctor == NULL_TREE)
1648 return build_zero_cst (ref->type);
1649 else if (ctor != error_mark_node)
1650 {
1651 HOST_WIDE_INT const_off;
1652 if (decl)
1653 {
1654 tree res = fold_ctor_reference (ref->type, ctor,
1655 off * BITS_PER_UNIT,
1656 size * BITS_PER_UNIT, decl);
1657 if (res)
1658 {
1659 STRIP_USELESS_TYPE_CONVERSION (res);
1660 if (is_gimple_min_invariant (res))
1661 return res;
1662 }
1663 }
1664 else if (off.is_constant (&const_off))
1665 {
1666 unsigned char buf[MAX_BITSIZE_MODE_ANY_MODE / BITS_PER_UNIT];
1667 int len = native_encode_expr (ctor, buf, size, const_off);
1668 if (len > 0)
1669 return native_interpret_expr (ref->type, buf, len);
1670 }
1671 }
1672 }
1673
1674 return NULL_TREE;
1675 }
1676
1677 /* Return true if OPS contain a storage order barrier. */
1678
1679 static bool
1680 contains_storage_order_barrier_p (vec<vn_reference_op_s> ops)
1681 {
1682 vn_reference_op_t op;
1683 unsigned i;
1684
1685 FOR_EACH_VEC_ELT (ops, i, op)
1686 if (op->opcode == VIEW_CONVERT_EXPR && op->reverse)
1687 return true;
1688
1689 return false;
1690 }
1691
1692 /* Return true if OPS represent an access with reverse storage order. */
1693
1694 static bool
1695 reverse_storage_order_for_component_p (vec<vn_reference_op_s> ops)
1696 {
1697 unsigned i = 0;
1698 if (ops[i].opcode == REALPART_EXPR || ops[i].opcode == IMAGPART_EXPR)
1699 ++i;
1700 switch (ops[i].opcode)
1701 {
1702 case ARRAY_REF:
1703 case COMPONENT_REF:
1704 case BIT_FIELD_REF:
1705 case MEM_REF:
1706 return ops[i].reverse;
1707 default:
1708 return false;
1709 }
1710 }
1711
1712 /* Transform any SSA_NAME's in a vector of vn_reference_op_s
1713 structures into their value numbers. This is done in-place, and
1714 the vector passed in is returned. *VALUEIZED_ANYTHING will specify
1715 whether any operands were valueized. */
1716
1717 static void
1718 valueize_refs_1 (vec<vn_reference_op_s> *orig, bool *valueized_anything,
1719 bool with_avail = false)
1720 {
1721 *valueized_anything = false;
1722
1723 for (unsigned i = 0; i < orig->length (); ++i)
1724 {
1725 re_valueize:
1726 vn_reference_op_t vro = &(*orig)[i];
1727 if (vro->opcode == SSA_NAME
1728 || (vro->op0 && TREE_CODE (vro->op0) == SSA_NAME))
1729 {
1730 tree tem = with_avail ? vn_valueize (vro->op0) : SSA_VAL (vro->op0);
1731 if (tem != vro->op0)
1732 {
1733 *valueized_anything = true;
1734 vro->op0 = tem;
1735 }
1736 /* If it transforms from an SSA_NAME to a constant, update
1737 the opcode. */
1738 if (TREE_CODE (vro->op0) != SSA_NAME && vro->opcode == SSA_NAME)
1739 vro->opcode = TREE_CODE (vro->op0);
1740 }
1741 if (vro->op1 && TREE_CODE (vro->op1) == SSA_NAME)
1742 {
1743 tree tem = with_avail ? vn_valueize (vro->op1) : SSA_VAL (vro->op1);
1744 if (tem != vro->op1)
1745 {
1746 *valueized_anything = true;
1747 vro->op1 = tem;
1748 }
1749 }
1750 if (vro->op2 && TREE_CODE (vro->op2) == SSA_NAME)
1751 {
1752 tree tem = with_avail ? vn_valueize (vro->op2) : SSA_VAL (vro->op2);
1753 if (tem != vro->op2)
1754 {
1755 *valueized_anything = true;
1756 vro->op2 = tem;
1757 }
1758 }
1759 /* If it transforms from an SSA_NAME to an address, fold with
1760 a preceding indirect reference. */
1761 if (i > 0
1762 && vro->op0
1763 && TREE_CODE (vro->op0) == ADDR_EXPR
1764 && (*orig)[i - 1].opcode == MEM_REF)
1765 {
1766 if (vn_reference_fold_indirect (orig, &i))
1767 *valueized_anything = true;
1768 }
1769 else if (i > 0
1770 && vro->opcode == SSA_NAME
1771 && (*orig)[i - 1].opcode == MEM_REF)
1772 {
1773 if (vn_reference_maybe_forwprop_address (orig, &i))
1774 {
1775 *valueized_anything = true;
1776 /* Re-valueize the current operand. */
1777 goto re_valueize;
1778 }
1779 }
1780 /* If it transforms a non-constant ARRAY_REF into a constant
1781 one, adjust the constant offset. */
1782 else if ((vro->opcode == ARRAY_REF
1783 || vro->opcode == ARRAY_RANGE_REF)
1784 && known_eq (vro->off, -1)
1785 && poly_int_tree_p (vro->op0)
1786 && poly_int_tree_p (vro->op1)
1787 && TREE_CODE (vro->op2) == INTEGER_CST)
1788 {
1789 /* Prohibit value-numbering addresses of one-after-the-last
1790 element ARRAY_REFs the same as addresses of other components
1791 before the pass folding __builtin_object_size had a chance
1792 to run. */
1793 if (!(cfun->curr_properties & PROP_objsz)
1794 && (*orig)[0].opcode == ADDR_EXPR)
1795 {
1796 tree dom = TYPE_DOMAIN ((*orig)[i + 1].type);
1797 if (!dom
1798 || !TYPE_MAX_VALUE (dom)
1799 || !poly_int_tree_p (TYPE_MAX_VALUE (dom))
1800 || integer_minus_onep (TYPE_MAX_VALUE (dom)))
1801 continue;
1802 if (!known_le (wi::to_poly_offset (vro->op0),
1803 wi::to_poly_offset (TYPE_MAX_VALUE (dom))))
1804 continue;
1805 }
1806
1807 poly_offset_int off = ((wi::to_poly_offset (vro->op0)
1808 - wi::to_poly_offset (vro->op1))
1809 * wi::to_offset (vro->op2)
1810 * vn_ref_op_align_unit (vro));
1811 off.to_shwi (&vro->off);
1812 }
1813 }
1814 }
1815
1816 static void
1817 valueize_refs (vec<vn_reference_op_s> *orig)
1818 {
1819 bool tem;
1820 valueize_refs_1 (orig, &tem);
1821 }
1822
1823 static vec<vn_reference_op_s> shared_lookup_references;
1824
1825 /* Create a vector of vn_reference_op_s structures from REF, a
1826 REFERENCE_CLASS_P tree. The vector is shared among all callers of
1827 this function. *VALUEIZED_ANYTHING will specify whether any
1828 operands were valueized. */
1829
1830 static vec<vn_reference_op_s>
1831 valueize_shared_reference_ops_from_ref (tree ref, bool *valueized_anything)
1832 {
1833 if (!ref)
1834 return vNULL;
1835 shared_lookup_references.truncate (0);
1836 copy_reference_ops_from_ref (ref, &shared_lookup_references);
1837 valueize_refs_1 (&shared_lookup_references, valueized_anything);
1838 return shared_lookup_references;
1839 }
1840
1841 /* Create a vector of vn_reference_op_s structures from CALL, a
1842 call statement. The vector is shared among all callers of
1843 this function. */
1844
1845 static vec<vn_reference_op_s>
1846 valueize_shared_reference_ops_from_call (gcall *call)
1847 {
1848 if (!call)
1849 return vNULL;
1850 shared_lookup_references.truncate (0);
1851 copy_reference_ops_from_call (call, &shared_lookup_references);
1852 valueize_refs (&shared_lookup_references);
1853 return shared_lookup_references;
1854 }
1855
1856 /* Lookup a SCCVN reference operation VR in the current hash table.
1857 Returns the resulting value number if it exists in the hash table,
1858 NULL_TREE otherwise. VNRESULT will be filled in with the actual
1859 vn_reference_t stored in the hashtable if something is found. */
1860
1861 static tree
1862 vn_reference_lookup_1 (vn_reference_t vr, vn_reference_t *vnresult)
1863 {
1864 vn_reference_s **slot;
1865 hashval_t hash;
1866
1867 hash = vr->hashcode;
1868 slot = valid_info->references->find_slot_with_hash (vr, hash, NO_INSERT);
1869 if (slot)
1870 {
1871 if (vnresult)
1872 *vnresult = (vn_reference_t)*slot;
1873 return ((vn_reference_t)*slot)->result;
1874 }
1875
1876 return NULL_TREE;
1877 }
1878
1879
1880 /* Partial definition tracking support. */
1881
1882 struct pd_range
1883 {
1884 HOST_WIDE_INT offset;
1885 HOST_WIDE_INT size;
1886 pd_range *m_children[2];
1887 };
1888
1889 struct pd_data
1890 {
1891 tree rhs;
1892 HOST_WIDE_INT rhs_off;
1893 HOST_WIDE_INT offset;
1894 HOST_WIDE_INT size;
1895 };
1896
1897 /* Context for alias walking. */
1898
1899 struct vn_walk_cb_data
1900 {
1901 vn_walk_cb_data (vn_reference_t vr_, tree orig_ref_, tree *last_vuse_ptr_,
1902 vn_lookup_kind vn_walk_kind_, bool tbaa_p_, tree mask_,
1903 bool redundant_store_removal_p_)
1904 : vr (vr_), last_vuse_ptr (last_vuse_ptr_), last_vuse (NULL_TREE),
1905 mask (mask_), masked_result (NULL_TREE), same_val (NULL_TREE),
1906 vn_walk_kind (vn_walk_kind_),
1907 tbaa_p (tbaa_p_), redundant_store_removal_p (redundant_store_removal_p_),
1908 saved_operands (vNULL), first_range (), first_set (-2),
1909 first_base_set (-2)
1910 {
1911 if (!last_vuse_ptr)
1912 last_vuse_ptr = &last_vuse;
1913 ao_ref_init (&orig_ref, orig_ref_);
1914 if (mask)
1915 {
1916 wide_int w = wi::to_wide (mask);
1917 unsigned int pos = 0, prec = w.get_precision ();
1918 pd_data pd;
1919 pd.rhs = build_constructor (NULL_TREE, NULL);
1920 pd.rhs_off = 0;
1921 /* When bitwise and with a constant is done on a memory load,
1922 we don't really need all the bits to be defined or defined
1923 to constants, we don't really care what is in the position
1924 corresponding to 0 bits in the mask.
1925 So, push the ranges of those 0 bits in the mask as artificial
1926 zero stores and let the partial def handling code do the
1927 rest. */
1928 while (pos < prec)
1929 {
1930 int tz = wi::ctz (w);
1931 if (pos + tz > prec)
1932 tz = prec - pos;
1933 if (tz)
1934 {
1935 if (BYTES_BIG_ENDIAN)
1936 pd.offset = prec - pos - tz;
1937 else
1938 pd.offset = pos;
1939 pd.size = tz;
1940 void *r = push_partial_def (pd, 0, 0, 0, prec);
1941 gcc_assert (r == NULL_TREE);
1942 }
1943 pos += tz;
1944 if (pos == prec)
1945 break;
1946 w = wi::lrshift (w, tz);
1947 tz = wi::ctz (wi::bit_not (w));
1948 if (pos + tz > prec)
1949 tz = prec - pos;
1950 pos += tz;
1951 w = wi::lrshift (w, tz);
1952 }
1953 }
1954 }
1955 ~vn_walk_cb_data ();
1956 void *finish (alias_set_type, alias_set_type, tree);
1957 void *push_partial_def (pd_data pd,
1958 alias_set_type, alias_set_type, HOST_WIDE_INT,
1959 HOST_WIDE_INT);
1960
1961 vn_reference_t vr;
1962 ao_ref orig_ref;
1963 tree *last_vuse_ptr;
1964 tree last_vuse;
1965 tree mask;
1966 tree masked_result;
1967 tree same_val;
1968 vn_lookup_kind vn_walk_kind;
1969 bool tbaa_p;
1970 bool redundant_store_removal_p;
1971 vec<vn_reference_op_s> saved_operands;
1972
1973 /* The VDEFs of partial defs we come along. */
1974 auto_vec<pd_data, 2> partial_defs;
1975 /* The first defs range to avoid splay tree setup in most cases. */
1976 pd_range first_range;
1977 alias_set_type first_set;
1978 alias_set_type first_base_set;
1979 default_splay_tree<pd_range *> known_ranges;
1980 obstack ranges_obstack;
1981 static constexpr HOST_WIDE_INT bufsize = 64;
1982 };
1983
1984 vn_walk_cb_data::~vn_walk_cb_data ()
1985 {
1986 if (known_ranges)
1987 obstack_free (&ranges_obstack, NULL);
1988 saved_operands.release ();
1989 }
1990
1991 void *
1992 vn_walk_cb_data::finish (alias_set_type set, alias_set_type base_set, tree val)
1993 {
1994 if (first_set != -2)
1995 {
1996 set = first_set;
1997 base_set = first_base_set;
1998 }
1999 if (mask)
2000 {
2001 masked_result = val;
2002 return (void *) -1;
2003 }
2004 if (same_val && !operand_equal_p (val, same_val))
2005 return (void *) -1;
2006 vec<vn_reference_op_s> &operands
2007 = saved_operands.exists () ? saved_operands : vr->operands;
2008 return vn_reference_lookup_or_insert_for_pieces (last_vuse, set, base_set,
2009 vr->offset, vr->max_size,
2010 vr->type, operands, val);
2011 }
2012
2013 /* Push PD to the vector of partial definitions returning a
2014 value when we are ready to combine things with VUSE, SET and MAXSIZEI,
2015 NULL when we want to continue looking for partial defs or -1
2016 on failure. */
2017
2018 void *
2019 vn_walk_cb_data::push_partial_def (pd_data pd,
2020 alias_set_type set, alias_set_type base_set,
2021 HOST_WIDE_INT offseti,
2022 HOST_WIDE_INT maxsizei)
2023 {
2024 /* We're using a fixed buffer for encoding so fail early if the object
2025 we want to interpret is bigger. */
2026 if (maxsizei > bufsize * BITS_PER_UNIT
2027 || CHAR_BIT != 8
2028 || BITS_PER_UNIT != 8
2029 /* Not prepared to handle PDP endian. */
2030 || BYTES_BIG_ENDIAN != WORDS_BIG_ENDIAN)
2031 return (void *)-1;
2032
2033 /* Turn too large constant stores into non-constant stores. */
2034 if (CONSTANT_CLASS_P (pd.rhs) && pd.size > bufsize * BITS_PER_UNIT)
2035 pd.rhs = error_mark_node;
2036
2037 /* And for non-constant or CONSTRUCTOR stores shrink them to only keep at
2038 most a partial byte before and/or after the region. */
2039 if (!CONSTANT_CLASS_P (pd.rhs))
2040 {
2041 if (pd.offset < offseti)
2042 {
2043 HOST_WIDE_INT o = ROUND_DOWN (offseti - pd.offset, BITS_PER_UNIT);
2044 gcc_assert (pd.size > o);
2045 pd.size -= o;
2046 pd.offset += o;
2047 }
2048 if (pd.size > maxsizei)
2049 pd.size = maxsizei + ((pd.size - maxsizei) % BITS_PER_UNIT);
2050 }
2051
2052 pd.offset -= offseti;
2053
2054 bool pd_constant_p = (TREE_CODE (pd.rhs) == CONSTRUCTOR
2055 || CONSTANT_CLASS_P (pd.rhs));
2056 pd_range *r;
2057 if (partial_defs.is_empty ())
2058 {
2059 /* If we get a clobber upfront, fail. */
2060 if (TREE_CLOBBER_P (pd.rhs))
2061 return (void *)-1;
2062 if (!pd_constant_p)
2063 return (void *)-1;
2064 partial_defs.safe_push (pd);
2065 first_range.offset = pd.offset;
2066 first_range.size = pd.size;
2067 first_set = set;
2068 first_base_set = base_set;
2069 last_vuse_ptr = NULL;
2070 r = &first_range;
2071 /* Go check if the first partial definition was a full one in case
2072 the caller didn't optimize for this. */
2073 }
2074 else
2075 {
2076 if (!known_ranges)
2077 {
2078 /* ??? Optimize the case where the 2nd partial def completes
2079 things. */
2080 gcc_obstack_init (&ranges_obstack);
2081 known_ranges.insert_max_node (&first_range);
2082 }
2083 /* Lookup the offset and see if we need to merge. */
2084 int comparison = known_ranges.lookup_le
2085 ([&] (pd_range *r) { return pd.offset < r->offset; },
2086 [&] (pd_range *r) { return pd.offset > r->offset; });
2087 r = known_ranges.root ();
2088 if (comparison >= 0
2089 && ranges_known_overlap_p (r->offset, r->size + 1,
2090 pd.offset, pd.size))
2091 {
2092 /* Ignore partial defs already covered. Here we also drop shadowed
2093 clobbers arriving here at the floor. */
2094 if (known_subrange_p (pd.offset, pd.size, r->offset, r->size))
2095 return NULL;
2096 r->size = MAX (r->offset + r->size, pd.offset + pd.size) - r->offset;
2097 }
2098 else
2099 {
2100 /* pd.offset wasn't covered yet, insert the range. */
2101 void *addr = XOBNEW (&ranges_obstack, pd_range);
2102 r = new (addr) pd_range { pd.offset, pd.size, {} };
2103 known_ranges.insert_relative (comparison, r);
2104 }
2105 /* Merge r which now contains pd's range and is a member of the splay
2106 tree with adjacent overlapping ranges. */
2107 if (known_ranges.splay_next_node ())
2108 do
2109 {
2110 pd_range *rafter = known_ranges.root ();
2111 if (!ranges_known_overlap_p (r->offset, r->size + 1,
2112 rafter->offset, rafter->size))
2113 break;
2114 r->size = MAX (r->offset + r->size,
2115 rafter->offset + rafter->size) - r->offset;
2116 }
2117 while (known_ranges.remove_root_and_splay_next ());
2118 /* If we get a clobber, fail. */
2119 if (TREE_CLOBBER_P (pd.rhs))
2120 return (void *)-1;
2121 /* Non-constants are OK as long as they are shadowed by a constant. */
2122 if (!pd_constant_p)
2123 return (void *)-1;
2124 partial_defs.safe_push (pd);
2125 }
2126
2127 /* Now we have merged pd's range into the range tree. When we have covered
2128 [offseti, sizei] then the tree will contain exactly one node which has
2129 the desired properties and it will be 'r'. */
2130 if (!known_subrange_p (0, maxsizei, r->offset, r->size))
2131 /* Continue looking for partial defs. */
2132 return NULL;
2133
2134 /* Now simply native encode all partial defs in reverse order. */
2135 unsigned ndefs = partial_defs.length ();
2136 /* We support up to 512-bit values (for V8DFmode). */
2137 unsigned char buffer[bufsize + 1];
2138 unsigned char this_buffer[bufsize + 1];
2139 int len;
2140
2141 memset (buffer, 0, bufsize + 1);
2142 unsigned needed_len = ROUND_UP (maxsizei, BITS_PER_UNIT) / BITS_PER_UNIT;
2143 while (!partial_defs.is_empty ())
2144 {
2145 pd_data pd = partial_defs.pop ();
2146 unsigned int amnt;
2147 if (TREE_CODE (pd.rhs) == CONSTRUCTOR)
2148 {
2149 /* Empty CONSTRUCTOR. */
2150 if (pd.size >= needed_len * BITS_PER_UNIT)
2151 len = needed_len;
2152 else
2153 len = ROUND_UP (pd.size, BITS_PER_UNIT) / BITS_PER_UNIT;
2154 memset (this_buffer, 0, len);
2155 }
2156 else if (pd.rhs_off >= 0)
2157 {
2158 len = native_encode_expr (pd.rhs, this_buffer, bufsize,
2159 (MAX (0, -pd.offset)
2160 + pd.rhs_off) / BITS_PER_UNIT);
2161 if (len <= 0
2162 || len < (ROUND_UP (pd.size, BITS_PER_UNIT) / BITS_PER_UNIT
2163 - MAX (0, -pd.offset) / BITS_PER_UNIT))
2164 {
2165 if (dump_file && (dump_flags & TDF_DETAILS))
2166 fprintf (dump_file, "Failed to encode %u "
2167 "partial definitions\n", ndefs);
2168 return (void *)-1;
2169 }
2170 }
2171 else /* negative pd.rhs_off indicates we want to chop off first bits */
2172 {
2173 if (-pd.rhs_off >= bufsize)
2174 return (void *)-1;
2175 len = native_encode_expr (pd.rhs,
2176 this_buffer + -pd.rhs_off / BITS_PER_UNIT,
2177 bufsize - -pd.rhs_off / BITS_PER_UNIT,
2178 MAX (0, -pd.offset) / BITS_PER_UNIT);
2179 if (len <= 0
2180 || len < (ROUND_UP (pd.size, BITS_PER_UNIT) / BITS_PER_UNIT
2181 - MAX (0, -pd.offset) / BITS_PER_UNIT))
2182 {
2183 if (dump_file && (dump_flags & TDF_DETAILS))
2184 fprintf (dump_file, "Failed to encode %u "
2185 "partial definitions\n", ndefs);
2186 return (void *)-1;
2187 }
2188 }
2189
2190 unsigned char *p = buffer;
2191 HOST_WIDE_INT size = pd.size;
2192 if (pd.offset < 0)
2193 size -= ROUND_DOWN (-pd.offset, BITS_PER_UNIT);
2194 this_buffer[len] = 0;
2195 if (BYTES_BIG_ENDIAN)
2196 {
2197 /* LSB of this_buffer[len - 1] byte should be at
2198 pd.offset + pd.size - 1 bits in buffer. */
2199 amnt = ((unsigned HOST_WIDE_INT) pd.offset
2200 + pd.size) % BITS_PER_UNIT;
2201 if (amnt)
2202 shift_bytes_in_array_right (this_buffer, len + 1, amnt);
2203 unsigned char *q = this_buffer;
2204 unsigned int off = 0;
2205 if (pd.offset >= 0)
2206 {
2207 unsigned int msk;
2208 off = pd.offset / BITS_PER_UNIT;
2209 gcc_assert (off < needed_len);
2210 p = buffer + off;
2211 if (size <= amnt)
2212 {
2213 msk = ((1 << size) - 1) << (BITS_PER_UNIT - amnt);
2214 *p = (*p & ~msk) | (this_buffer[len] & msk);
2215 size = 0;
2216 }
2217 else
2218 {
2219 if (TREE_CODE (pd.rhs) != CONSTRUCTOR)
2220 q = (this_buffer + len
2221 - (ROUND_UP (size - amnt, BITS_PER_UNIT)
2222 / BITS_PER_UNIT));
2223 if (pd.offset % BITS_PER_UNIT)
2224 {
2225 msk = -1U << (BITS_PER_UNIT
2226 - (pd.offset % BITS_PER_UNIT));
2227 *p = (*p & msk) | (*q & ~msk);
2228 p++;
2229 q++;
2230 off++;
2231 size -= BITS_PER_UNIT - (pd.offset % BITS_PER_UNIT);
2232 gcc_assert (size >= 0);
2233 }
2234 }
2235 }
2236 else if (TREE_CODE (pd.rhs) != CONSTRUCTOR)
2237 {
2238 q = (this_buffer + len
2239 - (ROUND_UP (size - amnt, BITS_PER_UNIT)
2240 / BITS_PER_UNIT));
2241 if (pd.offset % BITS_PER_UNIT)
2242 {
2243 q++;
2244 size -= BITS_PER_UNIT - ((unsigned HOST_WIDE_INT) pd.offset
2245 % BITS_PER_UNIT);
2246 gcc_assert (size >= 0);
2247 }
2248 }
2249 if ((unsigned HOST_WIDE_INT) size / BITS_PER_UNIT + off
2250 > needed_len)
2251 size = (needed_len - off) * BITS_PER_UNIT;
2252 memcpy (p, q, size / BITS_PER_UNIT);
2253 if (size % BITS_PER_UNIT)
2254 {
2255 unsigned int msk
2256 = -1U << (BITS_PER_UNIT - (size % BITS_PER_UNIT));
2257 p += size / BITS_PER_UNIT;
2258 q += size / BITS_PER_UNIT;
2259 *p = (*q & msk) | (*p & ~msk);
2260 }
2261 }
2262 else
2263 {
2264 if (pd.offset >= 0)
2265 {
2266 /* LSB of this_buffer[0] byte should be at pd.offset bits
2267 in buffer. */
2268 unsigned int msk;
2269 size = MIN (size, (HOST_WIDE_INT) needed_len * BITS_PER_UNIT);
2270 amnt = pd.offset % BITS_PER_UNIT;
2271 if (amnt)
2272 shift_bytes_in_array_left (this_buffer, len + 1, amnt);
2273 unsigned int off = pd.offset / BITS_PER_UNIT;
2274 gcc_assert (off < needed_len);
2275 size = MIN (size,
2276 (HOST_WIDE_INT) (needed_len - off) * BITS_PER_UNIT);
2277 p = buffer + off;
2278 if (amnt + size < BITS_PER_UNIT)
2279 {
2280 /* Low amnt bits come from *p, then size bits
2281 from this_buffer[0] and the remaining again from
2282 *p. */
2283 msk = ((1 << size) - 1) << amnt;
2284 *p = (*p & ~msk) | (this_buffer[0] & msk);
2285 size = 0;
2286 }
2287 else if (amnt)
2288 {
2289 msk = -1U << amnt;
2290 *p = (*p & ~msk) | (this_buffer[0] & msk);
2291 p++;
2292 size -= (BITS_PER_UNIT - amnt);
2293 }
2294 }
2295 else
2296 {
2297 amnt = (unsigned HOST_WIDE_INT) pd.offset % BITS_PER_UNIT;
2298 if (amnt)
2299 size -= BITS_PER_UNIT - amnt;
2300 size = MIN (size, (HOST_WIDE_INT) needed_len * BITS_PER_UNIT);
2301 if (amnt)
2302 shift_bytes_in_array_left (this_buffer, len + 1, amnt);
2303 }
2304 memcpy (p, this_buffer + (amnt != 0), size / BITS_PER_UNIT);
2305 p += size / BITS_PER_UNIT;
2306 if (size % BITS_PER_UNIT)
2307 {
2308 unsigned int msk = -1U << (size % BITS_PER_UNIT);
2309 *p = (this_buffer[(amnt != 0) + size / BITS_PER_UNIT]
2310 & ~msk) | (*p & msk);
2311 }
2312 }
2313 }
2314
2315 tree type = vr->type;
2316 /* Make sure to interpret in a type that has a range covering the whole
2317 access size. */
2318 if (INTEGRAL_TYPE_P (vr->type) && maxsizei != TYPE_PRECISION (vr->type))
2319 type = build_nonstandard_integer_type (maxsizei, TYPE_UNSIGNED (type));
2320 tree val;
2321 if (BYTES_BIG_ENDIAN)
2322 {
2323 unsigned sz = needed_len;
2324 if (maxsizei % BITS_PER_UNIT)
2325 shift_bytes_in_array_right (buffer, needed_len,
2326 BITS_PER_UNIT
2327 - (maxsizei % BITS_PER_UNIT));
2328 if (INTEGRAL_TYPE_P (type))
2329 {
2330 if (TYPE_MODE (type) != BLKmode)
2331 sz = GET_MODE_SIZE (SCALAR_INT_TYPE_MODE (type));
2332 else
2333 sz = TREE_INT_CST_LOW (TYPE_SIZE_UNIT (type));
2334 }
2335 if (sz > needed_len)
2336 {
2337 memcpy (this_buffer + (sz - needed_len), buffer, needed_len);
2338 val = native_interpret_expr (type, this_buffer, sz);
2339 }
2340 else
2341 val = native_interpret_expr (type, buffer, needed_len);
2342 }
2343 else
2344 val = native_interpret_expr (type, buffer, bufsize);
2345 /* If we chop off bits because the types precision doesn't match the memory
2346 access size this is ok when optimizing reads but not when called from
2347 the DSE code during elimination. */
2348 if (val && type != vr->type)
2349 {
2350 if (! int_fits_type_p (val, vr->type))
2351 val = NULL_TREE;
2352 else
2353 val = fold_convert (vr->type, val);
2354 }
2355
2356 if (val)
2357 {
2358 if (dump_file && (dump_flags & TDF_DETAILS))
2359 fprintf (dump_file,
2360 "Successfully combined %u partial definitions\n", ndefs);
2361 /* We are using the alias-set of the first store we encounter which
2362 should be appropriate here. */
2363 return finish (first_set, first_base_set, val);
2364 }
2365 else
2366 {
2367 if (dump_file && (dump_flags & TDF_DETAILS))
2368 fprintf (dump_file,
2369 "Failed to interpret %u encoded partial definitions\n", ndefs);
2370 return (void *)-1;
2371 }
2372 }
2373
2374 /* Callback for walk_non_aliased_vuses. Adjusts the vn_reference_t VR_
2375 with the current VUSE and performs the expression lookup. */
2376
2377 static void *
2378 vn_reference_lookup_2 (ao_ref *op, tree vuse, void *data_)
2379 {
2380 vn_walk_cb_data *data = (vn_walk_cb_data *)data_;
2381 vn_reference_t vr = data->vr;
2382 vn_reference_s **slot;
2383 hashval_t hash;
2384
2385 /* If we have partial definitions recorded we have to go through
2386 vn_reference_lookup_3. */
2387 if (!data->partial_defs.is_empty ())
2388 return NULL;
2389
2390 if (data->last_vuse_ptr)
2391 {
2392 *data->last_vuse_ptr = vuse;
2393 data->last_vuse = vuse;
2394 }
2395
2396 /* Fixup vuse and hash. */
2397 if (vr->vuse)
2398 vr->hashcode = vr->hashcode - SSA_NAME_VERSION (vr->vuse);
2399 vr->vuse = vuse_ssa_val (vuse);
2400 if (vr->vuse)
2401 vr->hashcode = vr->hashcode + SSA_NAME_VERSION (vr->vuse);
2402
2403 hash = vr->hashcode;
2404 slot = valid_info->references->find_slot_with_hash (vr, hash, NO_INSERT);
2405 if (slot)
2406 {
2407 if ((*slot)->result && data->saved_operands.exists ())
2408 return data->finish (vr->set, vr->base_set, (*slot)->result);
2409 return *slot;
2410 }
2411
2412 if (SSA_NAME_IS_DEFAULT_DEF (vuse))
2413 {
2414 HOST_WIDE_INT op_offset, op_size;
2415 tree v = NULL_TREE;
2416 tree base = ao_ref_base (op);
2417
2418 if (base
2419 && op->offset.is_constant (&op_offset)
2420 && op->size.is_constant (&op_size)
2421 && op->max_size_known_p ()
2422 && known_eq (op->size, op->max_size))
2423 {
2424 if (TREE_CODE (base) == PARM_DECL)
2425 v = ipcp_get_aggregate_const (cfun, base, false, op_offset,
2426 op_size);
2427 else if (TREE_CODE (base) == MEM_REF
2428 && integer_zerop (TREE_OPERAND (base, 1))
2429 && TREE_CODE (TREE_OPERAND (base, 0)) == SSA_NAME
2430 && SSA_NAME_IS_DEFAULT_DEF (TREE_OPERAND (base, 0))
2431 && (TREE_CODE (SSA_NAME_VAR (TREE_OPERAND (base, 0)))
2432 == PARM_DECL))
2433 v = ipcp_get_aggregate_const (cfun,
2434 SSA_NAME_VAR (TREE_OPERAND (base, 0)),
2435 true, op_offset, op_size);
2436 }
2437 if (v)
2438 return data->finish (vr->set, vr->base_set, v);
2439 }
2440
2441 return NULL;
2442 }
2443
2444 /* Lookup an existing or insert a new vn_reference entry into the
2445 value table for the VUSE, SET, TYPE, OPERANDS reference which
2446 has the value VALUE which is either a constant or an SSA name. */
2447
2448 static vn_reference_t
2449 vn_reference_lookup_or_insert_for_pieces (tree vuse,
2450 alias_set_type set,
2451 alias_set_type base_set,
2452 poly_int64 offset,
2453 poly_int64 max_size,
2454 tree type,
2455 vec<vn_reference_op_s,
2456 va_heap> operands,
2457 tree value)
2458 {
2459 vn_reference_s vr1;
2460 vn_reference_t result;
2461 unsigned value_id;
2462 vr1.vuse = vuse ? SSA_VAL (vuse) : NULL_TREE;
2463 vr1.operands = operands;
2464 vr1.type = type;
2465 vr1.set = set;
2466 vr1.base_set = base_set;
2467 vr1.offset = offset;
2468 vr1.max_size = max_size;
2469 vr1.hashcode = vn_reference_compute_hash (&vr1);
2470 if (vn_reference_lookup_1 (&vr1, &result))
2471 return result;
2472
2473 if (TREE_CODE (value) == SSA_NAME)
2474 value_id = VN_INFO (value)->value_id;
2475 else
2476 value_id = get_or_alloc_constant_value_id (value);
2477 return vn_reference_insert_pieces (vuse, set, base_set, offset, max_size,
2478 type, operands.copy (), value, value_id);
2479 }
2480
2481 /* Return a value-number for RCODE OPS... either by looking up an existing
2482 value-number for the possibly simplified result or by inserting the
2483 operation if INSERT is true. If SIMPLIFY is false, return a value
2484 number for the unsimplified expression. */
2485
2486 static tree
2487 vn_nary_build_or_lookup_1 (gimple_match_op *res_op, bool insert,
2488 bool simplify)
2489 {
2490 tree result = NULL_TREE;
2491 /* We will be creating a value number for
2492 RCODE (OPS...).
2493 So first simplify and lookup this expression to see if it
2494 is already available. */
2495 /* For simplification valueize. */
2496 unsigned i = 0;
2497 if (simplify)
2498 for (i = 0; i < res_op->num_ops; ++i)
2499 if (TREE_CODE (res_op->ops[i]) == SSA_NAME)
2500 {
2501 tree tem = vn_valueize (res_op->ops[i]);
2502 if (!tem)
2503 break;
2504 res_op->ops[i] = tem;
2505 }
2506 /* If valueization of an operand fails (it is not available), skip
2507 simplification. */
2508 bool res = false;
2509 if (i == res_op->num_ops)
2510 {
2511 /* Do not leak not available operands into the simplified expression
2512 when called from PRE context. */
2513 if (rpo_avail)
2514 mprts_hook = vn_lookup_simplify_result;
2515 res = res_op->resimplify (NULL, vn_valueize);
2516 mprts_hook = NULL;
2517 }
2518 gimple *new_stmt = NULL;
2519 if (res
2520 && gimple_simplified_result_is_gimple_val (res_op))
2521 {
2522 /* The expression is already available. */
2523 result = res_op->ops[0];
2524 /* Valueize it, simplification returns sth in AVAIL only. */
2525 if (TREE_CODE (result) == SSA_NAME)
2526 result = SSA_VAL (result);
2527 }
2528 else
2529 {
2530 tree val = vn_lookup_simplify_result (res_op);
2531 /* ??? In weird cases we can end up with internal-fn calls,
2532 but this isn't expected so throw the result away. See
2533 PR123040 for an example. */
2534 if (!val && insert && res_op->code.is_tree_code ())
2535 {
2536 gimple_seq stmts = NULL;
2537 result = maybe_push_res_to_seq (res_op, &stmts);
2538 if (result)
2539 {
2540 gcc_assert (gimple_seq_singleton_p (stmts));
2541 new_stmt = gimple_seq_first_stmt (stmts);
2542 }
2543 }
2544 else
2545 /* The expression is already available. */
2546 result = val;
2547 }
2548 if (new_stmt)
2549 {
2550 /* The expression is not yet available, value-number lhs to
2551 the new SSA_NAME we created. */
2552 /* Initialize value-number information properly. */
2553 vn_ssa_aux_t result_info = VN_INFO (result);
2554 result_info->valnum = result;
2555 result_info->value_id = get_next_value_id ();
2556 result_info->visited = 1;
2557 gimple_seq_add_stmt_without_update (&VN_INFO (result)->expr,
2558 new_stmt);
2559 result_info->needs_insertion = true;
2560 /* ??? PRE phi-translation inserts NARYs without corresponding
2561 SSA name result. Re-use those but set their result according
2562 to the stmt we just built. */
2563 vn_nary_op_t nary = NULL;
2564 vn_nary_op_lookup_stmt (new_stmt, &nary);
2565 if (nary)
2566 {
2567 gcc_assert (! nary->predicated_values && nary->u.result == NULL_TREE);
2568 nary->u.result = gimple_assign_lhs (new_stmt);
2569 }
2570 /* As all "inserted" statements are singleton SCCs, insert
2571 to the valid table. This is strictly needed to
2572 avoid re-generating new value SSA_NAMEs for the same
2573 expression during SCC iteration over and over (the
2574 optimistic table gets cleared after each iteration).
2575 We do not need to insert into the optimistic table, as
2576 lookups there will fall back to the valid table. */
2577 else
2578 {
2579 unsigned int length = vn_nary_length_from_stmt (new_stmt);
2580 vn_nary_op_t vno1
2581 = alloc_vn_nary_op_noinit (length, &vn_tables_insert_obstack);
2582 vno1->value_id = result_info->value_id;
2583 vno1->length = length;
2584 vno1->predicated_values = 0;
2585 vno1->u.result = result;
2586 init_vn_nary_op_from_stmt (vno1, as_a <gassign *> (new_stmt));
2587 vn_nary_op_insert_into (vno1, valid_info->nary);
2588 /* Also do not link it into the undo chain. */
2589 last_inserted_nary = vno1->next;
2590 vno1->next = (vn_nary_op_t)(void *)-1;
2591 }
2592 if (dump_file && (dump_flags & TDF_DETAILS))
2593 {
2594 fprintf (dump_file, "Inserting name ");
2595 print_generic_expr (dump_file, result);
2596 fprintf (dump_file, " for expression ");
2597 print_gimple_expr (dump_file, new_stmt, 0, TDF_SLIM);
2598 fprintf (dump_file, "\n");
2599 }
2600 }
2601 return result;
2602 }
2603
2604 /* Return a value-number for RCODE OPS... either by looking up an existing
2605 value-number for the simplified result or by inserting the operation. */
2606
2607 static tree
2608 vn_nary_build_or_lookup (gimple_match_op *res_op)
2609 {
2610 return vn_nary_build_or_lookup_1 (res_op, true, true);
2611 }
2612
2613 /* Try to simplify the expression RCODE OPS... of type TYPE and return
2614 its value if present. Update NARY with a simplified expression if
2615 it fits. */
2616
2617 tree
2618 vn_nary_simplify (vn_nary_op_t nary)
2619 {
2620 if (nary->length > gimple_match_op::MAX_NUM_OPS
2621 /* For CONSTRUCTOR the vn_nary_op_t and gimple_match_op representation
2622 does not match. */
2623 || nary->opcode == CONSTRUCTOR)
2624 return NULL_TREE;
2625 gimple_match_op op (gimple_match_cond::UNCOND, nary->opcode,
2626 nary->type, nary->length);
2627 memcpy (op.ops, nary->op, sizeof (tree) * nary->length);
2628 tree res = vn_nary_build_or_lookup_1 (&op, false, true);
2629 /* Do not update *NARY with a simplified result that contains abnormals.
2630 This matches what maybe_push_res_to_seq does when requesting insertion. */
2631 for (unsigned i = 0; i < op.num_ops; ++i)
2632 if (TREE_CODE (op.ops[i]) == SSA_NAME
2633 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (op.ops[i]))
2634 return res;
2635 if (op.code.is_tree_code ()
2636 && op.num_ops <= nary->length
2637 && (tree_code) op.code != CONSTRUCTOR)
2638 {
2639 nary->opcode = (tree_code) op.code;
2640 nary->length = op.num_ops;
2641 for (unsigned i = 0; i < op.num_ops; ++i)
2642 nary->op[i] = op.ops[i];
2643 }
2644 return res;
2645 }
2646
2647 /* Elimination engine. */
2648
2649 class eliminate_dom_walker : public dom_walker
2650 {
2651 public:
2652 eliminate_dom_walker (cdi_direction, bitmap);
2653 ~eliminate_dom_walker ();
2654
2655 edge before_dom_children (basic_block) final override;
2656 void after_dom_children (basic_block) final override;
2657
2658 virtual tree eliminate_avail (basic_block, tree op);
2659 virtual void eliminate_push_avail (basic_block, tree op);
2660 tree eliminate_insert (basic_block, gimple_stmt_iterator *gsi, tree val);
2661
2662 void eliminate_stmt (basic_block, gimple_stmt_iterator *);
2663
2664 unsigned eliminate_cleanup (bool region_p = false);
2665
2666 bool do_pre;
2667 unsigned int el_todo;
2668 unsigned int eliminations;
2669 unsigned int insertions;
2670
2671 /* SSA names that had their defs inserted by PRE if do_pre. */
2672 bitmap inserted_exprs;
2673
2674 /* Blocks with statements that have had their EH properties changed. */
2675 bitmap need_eh_cleanup;
2676
2677 /* Blocks with statements that have had their AB properties changed. */
2678 bitmap need_ab_cleanup;
2679
2680 /* Local state for the eliminate domwalk. */
2681 auto_vec<gimple *> to_remove;
2682 auto_vec<gimple *> to_fixup;
2683 auto_vec<tree> avail;
2684 auto_vec<tree> avail_stack;
2685 };
2686
2687 /* Adaptor to the elimination engine using RPO availability. */
2688
2689 class rpo_elim : public eliminate_dom_walker
2690 {
2691 public:
2692 rpo_elim(basic_block entry_)
2693 : eliminate_dom_walker (CDI_DOMINATORS, NULL), entry (entry_),
2694 m_avail_freelist (NULL) {}
2695
2696 tree eliminate_avail (basic_block, tree op) final override;
2697
2698 void eliminate_push_avail (basic_block, tree) final override;
2699
2700 basic_block entry;
2701 /* Freelist of avail entries which are allocated from the vn_ssa_aux
2702 obstack. */
2703 vn_avail *m_avail_freelist;
2704 };
2705
2706 /* Return true if BASE1 and BASE2 can be adjusted so they have the
2707 same address and adjust *OFFSET1 and *OFFSET2 accordingly.
2708 Otherwise return false. */
2709
2710 static bool
2711 adjust_offsets_for_equal_base_address (tree base1, poly_int64 *offset1,
2712 tree base2, poly_int64 *offset2)
2713 {
2714 poly_int64 soff;
2715 if (TREE_CODE (base1) == MEM_REF
2716 && TREE_CODE (base2) == MEM_REF)
2717 {
2718 if (mem_ref_offset (base1).to_shwi (&soff))
2719 {
2720 base1 = TREE_OPERAND (base1, 0);
2721 *offset1 += soff * BITS_PER_UNIT;
2722 }
2723 if (mem_ref_offset (base2).to_shwi (&soff))
2724 {
2725 base2 = TREE_OPERAND (base2, 0);
2726 *offset2 += soff * BITS_PER_UNIT;
2727 }
2728 return operand_equal_p (base1, base2, 0);
2729 }
2730 return operand_equal_p (base1, base2, OEP_ADDRESS_OF);
2731 }
2732
2733 /* Callback for walk_non_aliased_vuses. Tries to perform a lookup
2734 from the statement defining VUSE and if not successful tries to
2735 translate *REFP and VR_ through an aggregate copy at the definition
2736 of VUSE. If *DISAMBIGUATE_ONLY is true then do not perform translation
2737 of *REF and *VR. If only disambiguation was performed then
2738 *DISAMBIGUATE_ONLY is set to true. */
2739
2740 static void *
2741 vn_reference_lookup_3 (ao_ref *ref, tree vuse, void *data_,
2742 translate_flags *disambiguate_only)
2743 {
2744 vn_walk_cb_data *data = (vn_walk_cb_data *)data_;
2745 vn_reference_t vr = data->vr;
2746 gimple *def_stmt = SSA_NAME_DEF_STMT (vuse);
2747 tree base = ao_ref_base (ref);
2748 HOST_WIDE_INT offseti = 0, maxsizei, sizei = 0;
2749 static vec<vn_reference_op_s> lhs_ops;
2750 ao_ref lhs_ref;
2751 bool lhs_ref_ok = false;
2752 poly_int64 copy_size;
2753
2754 /* First try to disambiguate after value-replacing in the definitions LHS. */
2755 if (is_gimple_assign (def_stmt))
2756 {
2757 tree lhs = gimple_assign_lhs (def_stmt);
2758 bool valueized_anything = false;
2759 /* Avoid re-allocation overhead. */
2760 lhs_ops.truncate (0);
2761 basic_block saved_rpo_bb = vn_context_bb;
2762 vn_context_bb = gimple_bb (def_stmt);
2763 if (*disambiguate_only <= TR_VALUEIZE_AND_DISAMBIGUATE)
2764 {
2765 copy_reference_ops_from_ref (lhs, &lhs_ops);
2766 valueize_refs_1 (&lhs_ops, &valueized_anything, true);
2767 }
2768 vn_context_bb = saved_rpo_bb;
2769 ao_ref_init (&lhs_ref, lhs);
2770 lhs_ref_ok = true;
2771 if (valueized_anything
2772 && ao_ref_init_from_vn_reference
2773 (&lhs_ref, ao_ref_alias_set (&lhs_ref),
2774 ao_ref_base_alias_set (&lhs_ref), TREE_TYPE (lhs), lhs_ops)
2775 && !refs_may_alias_p_1 (ref, &lhs_ref, data->tbaa_p))
2776 {
2777 *disambiguate_only = TR_VALUEIZE_AND_DISAMBIGUATE;
2778 return NULL;
2779 }
2780
2781 /* When the def is a CLOBBER we can optimistically disambiguate
2782 against it since any overlap it would be undefined behavior.
2783 Avoid this for obvious must aliases to save compile-time though.
2784 We also may not do this when the query is used for redundant
2785 store removal. */
2786 if (!data->redundant_store_removal_p
2787 && gimple_clobber_p (def_stmt)
2788 && !operand_equal_p (ao_ref_base (&lhs_ref), base, OEP_ADDRESS_OF))
2789 {
2790 *disambiguate_only = TR_DISAMBIGUATE;
2791 return NULL;
2792 }
2793
2794 /* Besides valueizing the LHS we can also use access-path based
2795 disambiguation on the original non-valueized ref. */
2796 if (!ref->ref
2797 && lhs_ref_ok
2798 && data->orig_ref.ref)
2799 {
2800 /* We want to use the non-valueized LHS for this, but avoid redundant
2801 work. */
2802 ao_ref *lref = &lhs_ref;
2803 ao_ref lref_alt;
2804 if (valueized_anything)
2805 {
2806 ao_ref_init (&lref_alt, lhs);
2807 lref = &lref_alt;
2808 }
2809 if (!refs_may_alias_p_1 (&data->orig_ref, lref, data->tbaa_p))
2810 {
2811 *disambiguate_only = (valueized_anything
2812 ? TR_VALUEIZE_AND_DISAMBIGUATE
2813 : TR_DISAMBIGUATE);
2814 return NULL;
2815 }
2816 }
2817
2818 /* If we reach a clobbering statement try to skip it and see if
2819 we find a VN result with exactly the same value as the
2820 possible clobber. In this case we can ignore the clobber
2821 and return the found value. */
2822 if (!gimple_has_volatile_ops (def_stmt)
2823 && is_gimple_reg_type (TREE_TYPE (lhs))
2824 && types_compatible_p (TREE_TYPE (lhs), vr->type)
2825 && (ref->ref || data->orig_ref.ref)
2826 && !data->mask
2827 && data->partial_defs.is_empty ()
2828 && multiple_p (get_object_alignment
2829 (ref->ref ? ref->ref : data->orig_ref.ref),
2830 ref->size)
2831 && multiple_p (get_object_alignment (lhs), ref->size))
2832 {
2833 tree rhs = gimple_assign_rhs1 (def_stmt);
2834 /* ??? We may not compare to ahead values which might be from
2835 a different loop iteration but only to loop invariants. Use
2836 CONSTANT_CLASS_P (unvalueized!) as conservative approximation.
2837 The one-hop lookup below doesn't have this issue since there's
2838 a virtual PHI before we ever reach a backedge to cross.
2839 We can skip multiple defs as long as they are from the same
2840 value though. */
2841 if (data->same_val
2842 && !operand_equal_p (data->same_val, rhs))
2843 ;
2844 else if (CONSTANT_CLASS_P (rhs))
2845 {
2846 if (dump_file && (dump_flags & TDF_DETAILS))
2847 {
2848 fprintf (dump_file,
2849 "Skipping possible redundant definition ");
2850 print_gimple_stmt (dump_file, def_stmt, 0);
2851 }
2852 /* Delay the actual compare of the values to the end of the walk
2853 but do not update last_vuse from here. */
2854 data->last_vuse_ptr = NULL;
2855 data->same_val = rhs;
2856 return NULL;
2857 }
2858 else
2859 {
2860 tree saved_vuse = vr->vuse;
2861 hashval_t saved_hashcode = vr->hashcode;
2862 if (vr->vuse)
2863 vr->hashcode = vr->hashcode - SSA_NAME_VERSION (vr->vuse);
2864 vr->vuse = vuse_ssa_val (gimple_vuse (def_stmt));
2865 if (vr->vuse)
2866 vr->hashcode = vr->hashcode + SSA_NAME_VERSION (vr->vuse);
2867 vn_reference_t vnresult = NULL;
2868 /* Do not use vn_reference_lookup_2 since that might perform
2869 expression hashtable insertion but this lookup crosses
2870 a possible may-alias making such insertion conditionally
2871 invalid. */
2872 vn_reference_lookup_1 (vr, &vnresult);
2873 /* Need to restore vr->vuse and vr->hashcode. */
2874 vr->vuse = saved_vuse;
2875 vr->hashcode = saved_hashcode;
2876 if (vnresult)
2877 {
2878 if (TREE_CODE (rhs) == SSA_NAME)
2879 rhs = SSA_VAL (rhs);
2880 if (vnresult->result
2881 && operand_equal_p (vnresult->result, rhs, 0))
2882 return vnresult;
2883 }
2884 }
2885 }
2886 }
2887 else if (*disambiguate_only <= TR_VALUEIZE_AND_DISAMBIGUATE
2888 && gimple_call_builtin_p (def_stmt, BUILT_IN_NORMAL)
2889 && gimple_call_num_args (def_stmt) <= 4)
2890 {
2891 /* For builtin calls valueize its arguments and call the
2892 alias oracle again. Valueization may improve points-to
2893 info of pointers and constify size and position arguments.
2894 Originally this was motivated by PR61034 which has
2895 conditional calls to free falsely clobbering ref because
2896 of imprecise points-to info of the argument. */
2897 tree oldargs[4];
2898 bool valueized_anything = false;
2899 for (unsigned i = 0; i < gimple_call_num_args (def_stmt); ++i)
2900 {
2901 oldargs[i] = gimple_call_arg (def_stmt, i);
2902 tree val = vn_valueize (oldargs[i]);
2903 if (val != oldargs[i])
2904 {
2905 gimple_call_set_arg (def_stmt, i, val);
2906 valueized_anything = true;
2907 }
2908 }
2909 if (valueized_anything)
2910 {
2911 bool res = call_may_clobber_ref_p_1 (as_a <gcall *> (def_stmt),
2912 ref, data->tbaa_p);
2913 for (unsigned i = 0; i < gimple_call_num_args (def_stmt); ++i)
2914 gimple_call_set_arg (def_stmt, i, oldargs[i]);
2915 if (!res)
2916 {
2917 *disambiguate_only = TR_VALUEIZE_AND_DISAMBIGUATE;
2918 return NULL;
2919 }
2920 }
2921 }
2922
2923 if (*disambiguate_only > TR_TRANSLATE)
2924 return (void *)-1;
2925
2926 /* If we cannot constrain the size of the reference we cannot
2927 test if anything kills it. */
2928 if (!ref->max_size_known_p ())
2929 return (void *)-1;
2930
2931 poly_int64 offset = ref->offset;
2932 poly_int64 maxsize = ref->max_size;
2933
2934 /* def_stmt may-defs *ref. See if we can derive a value for *ref
2935 from that definition.
2936 1) Memset. */
2937 if (is_gimple_reg_type (vr->type)
2938 && (gimple_call_builtin_p (def_stmt, BUILT_IN_MEMSET)
2939 || gimple_call_builtin_p (def_stmt, BUILT_IN_MEMSET_CHK))
2940 && (integer_zerop (gimple_call_arg (def_stmt, 1))
2941 || ((TREE_CODE (gimple_call_arg (def_stmt, 1)) == INTEGER_CST
2942 || (INTEGRAL_TYPE_P (vr->type) && known_eq (ref->size, 8)))
2943 && CHAR_BIT == 8
2944 && BITS_PER_UNIT == 8
2945 && BYTES_BIG_ENDIAN == WORDS_BIG_ENDIAN
2946 && offset.is_constant (&offseti)
2947 && ref->size.is_constant (&sizei)
2948 && (offseti % BITS_PER_UNIT == 0
2949 || TREE_CODE (gimple_call_arg (def_stmt, 1)) == INTEGER_CST)))
2950 && (poly_int_tree_p (gimple_call_arg (def_stmt, 2))
2951 || (TREE_CODE (gimple_call_arg (def_stmt, 2)) == SSA_NAME
2952 && poly_int_tree_p (SSA_VAL (gimple_call_arg (def_stmt, 2)))))
2953 && (TREE_CODE (gimple_call_arg (def_stmt, 0)) == ADDR_EXPR
2954 || TREE_CODE (gimple_call_arg (def_stmt, 0)) == SSA_NAME))
2955 {
2956 tree base2;
2957 poly_int64 offset2, size2, maxsize2;
2958 bool reverse;
2959 tree ref2 = gimple_call_arg (def_stmt, 0);
2960 if (TREE_CODE (ref2) == SSA_NAME)
2961 {
2962 ref2 = SSA_VAL (ref2);
2963 if (TREE_CODE (ref2) == SSA_NAME
2964 && (TREE_CODE (base) != MEM_REF
2965 || TREE_OPERAND (base, 0) != ref2))
2966 {
2967 gimple *def_stmt = SSA_NAME_DEF_STMT (ref2);
2968 if (gimple_assign_single_p (def_stmt)
2969 && gimple_assign_rhs_code (def_stmt) == ADDR_EXPR)
2970 ref2 = gimple_assign_rhs1 (def_stmt);
2971 }
2972 }
2973 if (TREE_CODE (ref2) == ADDR_EXPR)
2974 {
2975 ref2 = TREE_OPERAND (ref2, 0);
2976 base2 = get_ref_base_and_extent (ref2, &offset2, &size2, &maxsize2,
2977 &reverse);
2978 if (!known_size_p (maxsize2)
2979 || !known_eq (maxsize2, size2)
2980 || !operand_equal_p (base, base2, OEP_ADDRESS_OF))
2981 return (void *)-1;
2982 }
2983 else if (TREE_CODE (ref2) == SSA_NAME)
2984 {
2985 poly_int64 soff;
2986 if (TREE_CODE (base) != MEM_REF
2987 || !(mem_ref_offset (base)
2988 << LOG2_BITS_PER_UNIT).to_shwi (&soff))
2989 return (void *)-1;
2990 offset += soff;
2991 offset2 = 0;
2992 if (TREE_OPERAND (base, 0) != ref2)
2993 {
2994 gimple *def = SSA_NAME_DEF_STMT (ref2);
2995 if (is_gimple_assign (def)
2996 && gimple_assign_rhs_code (def) == POINTER_PLUS_EXPR
2997 && gimple_assign_rhs1 (def) == TREE_OPERAND (base, 0)
2998 && poly_int_tree_p (gimple_assign_rhs2 (def)))
2999 {
3000 tree rhs2 = gimple_assign_rhs2 (def);
3001 if (!(poly_offset_int::from (wi::to_poly_wide (rhs2),
3002 SIGNED)
3003 << LOG2_BITS_PER_UNIT).to_shwi (&offset2))
3004 return (void *)-1;
3005 ref2 = gimple_assign_rhs1 (def);
3006 if (TREE_CODE (ref2) == SSA_NAME)
3007 ref2 = SSA_VAL (ref2);
3008 }
3009 else
3010 return (void *)-1;
3011 }
3012 }
3013 else
3014 return (void *)-1;
3015 tree len = gimple_call_arg (def_stmt, 2);
3016 HOST_WIDE_INT leni, offset2i;
3017 if (TREE_CODE (len) == SSA_NAME)
3018 len = SSA_VAL (len);
3019 /* Sometimes the above trickery is smarter than alias analysis. Take
3020 advantage of that. */
3021 if (!ranges_maybe_overlap_p (offset, maxsize, offset2,
3022 (wi::to_poly_offset (len)
3023 << LOG2_BITS_PER_UNIT)))
3024 return NULL;
3025 if (data->partial_defs.is_empty ()
3026 && known_subrange_p (offset, maxsize, offset2,
3027 wi::to_poly_offset (len) << LOG2_BITS_PER_UNIT))
3028 {
3029 tree val;
3030 if (integer_zerop (gimple_call_arg (def_stmt, 1)))
3031 val = build_zero_cst (vr->type);
3032 else if (INTEGRAL_TYPE_P (vr->type)
3033 && known_eq (ref->size, 8)
3034 && offseti % BITS_PER_UNIT == 0)
3035 {
3036 gimple_match_op res_op (gimple_match_cond::UNCOND, NOP_EXPR,
3037 vr->type, gimple_call_arg (def_stmt, 1));
3038 val = vn_nary_build_or_lookup (&res_op);
3039 if (!val
3040 || (TREE_CODE (val) == SSA_NAME
3041 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (val)))
3042 return (void *)-1;
3043 }
3044 else
3045 {
3046 unsigned buflen
3047 = TREE_INT_CST_LOW (TYPE_SIZE_UNIT (vr->type)) + 1;
3048 if (INTEGRAL_TYPE_P (vr->type)
3049 && TYPE_MODE (vr->type) != BLKmode)
3050 buflen = GET_MODE_SIZE (SCALAR_INT_TYPE_MODE (vr->type)) + 1;
3051 unsigned char *buf = XALLOCAVEC (unsigned char, buflen);
3052 memset (buf, TREE_INT_CST_LOW (gimple_call_arg (def_stmt, 1)),
3053 buflen);
3054 if (BYTES_BIG_ENDIAN)
3055 {
3056 unsigned int amnt
3057 = (((unsigned HOST_WIDE_INT) offseti + sizei)
3058 % BITS_PER_UNIT);
3059 if (amnt)
3060 {
3061 shift_bytes_in_array_right (buf, buflen,
3062 BITS_PER_UNIT - amnt);
3063 buf++;
3064 buflen--;
3065 }
3066 }
3067 else if (offseti % BITS_PER_UNIT != 0)
3068 {
3069 unsigned int amnt
3070 = BITS_PER_UNIT - ((unsigned HOST_WIDE_INT) offseti
3071 % BITS_PER_UNIT);
3072 shift_bytes_in_array_left (buf, buflen, amnt);
3073 buf++;
3074 buflen--;
3075 }
3076 val = native_interpret_expr (vr->type, buf, buflen);
3077 if (!val)
3078 return (void *)-1;
3079 }
3080 return data->finish (0, 0, val);
3081 }
3082 /* For now handle clearing memory with partial defs. */
3083 else if (known_eq (ref->size, maxsize)
3084 && integer_zerop (gimple_call_arg (def_stmt, 1))
3085 && tree_fits_poly_int64_p (len)
3086 && tree_to_poly_int64 (len).is_constant (&leni)
3087 && leni <= INTTYPE_MAXIMUM (HOST_WIDE_INT) / BITS_PER_UNIT
3088 && offset.is_constant (&offseti)
3089 && offset2.is_constant (&offset2i)
3090 && maxsize.is_constant (&maxsizei)
3091 && ranges_known_overlap_p (offseti, maxsizei, offset2i,
3092 leni << LOG2_BITS_PER_UNIT))
3093 {
3094 pd_data pd;
3095 pd.rhs = build_constructor (NULL_TREE, NULL);
3096 pd.rhs_off = 0;
3097 pd.offset = offset2i;
3098 pd.size = leni << LOG2_BITS_PER_UNIT;
3099 return data->push_partial_def (pd, 0, 0, offseti, maxsizei);
3100 }
3101 }
3102
3103 /* 2) Assignment from an empty CONSTRUCTOR. */
3104 else if (is_gimple_reg_type (vr->type)
3105 && gimple_assign_single_p (def_stmt)
3106 && gimple_assign_rhs_code (def_stmt) == CONSTRUCTOR
3107 && CONSTRUCTOR_NELTS (gimple_assign_rhs1 (def_stmt)) == 0
3108 && !TREE_THIS_VOLATILE (gimple_assign_lhs (def_stmt)))
3109 {
3110 tree base2;
3111 poly_int64 offset2, size2, maxsize2;
3112 HOST_WIDE_INT offset2i, size2i;
3113 gcc_assert (lhs_ref_ok);
3114 base2 = ao_ref_base (&lhs_ref);
3115 offset2 = lhs_ref.offset;
3116 size2 = lhs_ref.size;
3117 maxsize2 = lhs_ref.max_size;
3118 if (known_size_p (maxsize2)
3119 && known_eq (maxsize2, size2)
3120 && adjust_offsets_for_equal_base_address (base, &offset,
3121 base2, &offset2))
3122 {
3123 if (data->partial_defs.is_empty ()
3124 && known_subrange_p (offset, maxsize, offset2, size2))
3125 {
3126 /* While technically undefined behavior do not optimize
3127 a full read from a clobber. */
3128 if (gimple_clobber_p (def_stmt))
3129 return (void *)-1;
3130 tree val = build_zero_cst (vr->type);
3131 return data->finish (ao_ref_alias_set (&lhs_ref),
3132 ao_ref_base_alias_set (&lhs_ref), val);
3133 }
3134 else if (known_eq (ref->size, maxsize)
3135 && maxsize.is_constant (&maxsizei)
3136 && offset.is_constant (&offseti)
3137 && offset2.is_constant (&offset2i)
3138 && size2.is_constant (&size2i)
3139 && ranges_known_overlap_p (offseti, maxsizei,
3140 offset2i, size2i))
3141 {
3142 /* Let clobbers be consumed by the partial-def tracker
3143 which can choose to ignore them if they are shadowed
3144 by a later def. */
3145 pd_data pd;
3146 pd.rhs = gimple_assign_rhs1 (def_stmt);
3147 pd.rhs_off = 0;
3148 pd.offset = offset2i;
3149 pd.size = size2i;
3150 return data->push_partial_def (pd, ao_ref_alias_set (&lhs_ref),
3151 ao_ref_base_alias_set (&lhs_ref),
3152 offseti, maxsizei);
3153 }
3154 }
3155 }
3156
3157 /* 3) Assignment from a constant. We can use folds native encode/interpret
3158 routines to extract the assigned bits. */
3159 else if (known_eq (ref->size, maxsize)
3160 && is_gimple_reg_type (vr->type)
3161 && !reverse_storage_order_for_component_p (vr->operands)
3162 && !contains_storage_order_barrier_p (vr->operands)
3163 && gimple_assign_single_p (def_stmt)
3164 && !TREE_THIS_VOLATILE (gimple_assign_lhs (def_stmt))
3165 && CHAR_BIT == 8
3166 && BITS_PER_UNIT == 8
3167 && BYTES_BIG_ENDIAN == WORDS_BIG_ENDIAN
3168 /* native_encode and native_decode operate on arrays of bytes
3169 and so fundamentally need a compile-time size and offset. */
3170 && maxsize.is_constant (&maxsizei)
3171 && offset.is_constant (&offseti)
3172 && (is_gimple_min_invariant (gimple_assign_rhs1 (def_stmt))
3173 || (TREE_CODE (gimple_assign_rhs1 (def_stmt)) == SSA_NAME
3174 && is_gimple_min_invariant (SSA_VAL (gimple_assign_rhs1 (def_stmt))))))
3175 {
3176 tree lhs = gimple_assign_lhs (def_stmt);
3177 tree base2;
3178 poly_int64 offset2, size2, maxsize2;
3179 HOST_WIDE_INT offset2i, size2i;
3180 bool reverse;
3181 gcc_assert (lhs_ref_ok);
3182 base2 = ao_ref_base (&lhs_ref);
3183 offset2 = lhs_ref.offset;
3184 size2 = lhs_ref.size;
3185 maxsize2 = lhs_ref.max_size;
3186 reverse = reverse_storage_order_for_component_p (lhs);
3187 if (base2
3188 && !reverse
3189 && !storage_order_barrier_p (lhs)
3190 && known_eq (maxsize2, size2)
3191 && adjust_offsets_for_equal_base_address (base, &offset,
3192 base2, &offset2)
3193 && offset.is_constant (&offseti)
3194 && offset2.is_constant (&offset2i)
3195 && size2.is_constant (&size2i))
3196 {
3197 if (data->partial_defs.is_empty ()
3198 && known_subrange_p (offseti, maxsizei, offset2, size2))
3199 {
3200 /* We support up to 512-bit values (for V8DFmode). */
3201 unsigned char buffer[65];
3202 int len;
3203
3204 tree rhs = gimple_assign_rhs1 (def_stmt);
3205 if (TREE_CODE (rhs) == SSA_NAME)
3206 rhs = SSA_VAL (rhs);
3207 len = native_encode_expr (rhs,
3208 buffer, sizeof (buffer) - 1,
3209 (offseti - offset2i) / BITS_PER_UNIT);
3210 if (len > 0 && len * BITS_PER_UNIT >= maxsizei)
3211 {
3212 tree type = vr->type;
3213 unsigned char *buf = buffer;
3214 unsigned int amnt = 0;
3215 /* Make sure to interpret in a type that has a range
3216 covering the whole access size. */
3217 if (INTEGRAL_TYPE_P (vr->type)
3218 && maxsizei != TYPE_PRECISION (vr->type))
3219 type = build_nonstandard_integer_type (maxsizei,
3220 TYPE_UNSIGNED (type));
3221 if (BYTES_BIG_ENDIAN)
3222 {
3223 /* For big-endian native_encode_expr stored the rhs
3224 such that the LSB of it is the LSB of buffer[len - 1].
3225 That bit is stored into memory at position
3226 offset2 + size2 - 1, i.e. in byte
3227 base + (offset2 + size2 - 1) / BITS_PER_UNIT.
3228 E.g. for offset2 1 and size2 14, rhs -1 and memory
3229 previously cleared that is:
3230 0 1
3231 01111111|11111110
3232 Now, if we want to extract offset 2 and size 12 from
3233 it using native_interpret_expr (which actually works
3234 for integral bitfield types in terms of byte size of
3235 the mode), the native_encode_expr stored the value
3236 into buffer as
3237 XX111111|11111111
3238 and returned len 2 (the X bits are outside of
3239 precision).
3240 Let sz be maxsize / BITS_PER_UNIT if not extracting
3241 a bitfield, and GET_MODE_SIZE otherwise.
3242 We need to align the LSB of the value we want to
3243 extract as the LSB of buf[sz - 1].
3244 The LSB from memory we need to read is at position
3245 offset + maxsize - 1. */
3246 HOST_WIDE_INT sz = maxsizei / BITS_PER_UNIT;
3247 if (INTEGRAL_TYPE_P (type))
3248 {
3249 if (TYPE_MODE (type) != BLKmode)
3250 sz = GET_MODE_SIZE (SCALAR_INT_TYPE_MODE (type));
3251 else
3252 sz = TREE_INT_CST_LOW (TYPE_SIZE_UNIT (type));
3253 }
3254 amnt = ((unsigned HOST_WIDE_INT) offset2i + size2i
3255 - offseti - maxsizei) % BITS_PER_UNIT;
3256 if (amnt)
3257 shift_bytes_in_array_right (buffer, len, amnt);
3258 amnt = ((unsigned HOST_WIDE_INT) offset2i + size2i
3259 - offseti - maxsizei - amnt) / BITS_PER_UNIT;
3260 if ((unsigned HOST_WIDE_INT) sz + amnt > (unsigned) len)
3261 len = 0;
3262 else
3263 {
3264 buf = buffer + len - sz - amnt;
3265 len -= (buf - buffer);
3266 }
3267 }
3268 else
3269 {
3270 amnt = ((unsigned HOST_WIDE_INT) offset2i
3271 - offseti) % BITS_PER_UNIT;
3272 if (amnt)
3273 {
3274 buffer[len] = 0;
3275 shift_bytes_in_array_left (buffer, len + 1, amnt);
3276 buf = buffer + 1;
3277 }
3278 }
3279 tree val = native_interpret_expr (type, buf, len);
3280 /* If we chop off bits because the types precision doesn't
3281 match the memory access size this is ok when optimizing
3282 reads but not when called from the DSE code during
3283 elimination. */
3284 if (val
3285 && type != vr->type)
3286 {
3287 if (! int_fits_type_p (val, vr->type))
3288 val = NULL_TREE;
3289 else
3290 val = fold_convert (vr->type, val);
3291 }
3292
3293 if (val)
3294 return data->finish (ao_ref_alias_set (&lhs_ref),
3295 ao_ref_base_alias_set (&lhs_ref), val);
3296 }
3297 }
3298 else if (ranges_known_overlap_p (offseti, maxsizei, offset2i,
3299 size2i))
3300 {
3301 pd_data pd;
3302 tree rhs = gimple_assign_rhs1 (def_stmt);
3303 if (TREE_CODE (rhs) == SSA_NAME)
3304 rhs = SSA_VAL (rhs);
3305 pd.rhs = rhs;
3306 pd.rhs_off = 0;
3307 pd.offset = offset2i;
3308 pd.size = size2i;
3309 return data->push_partial_def (pd, ao_ref_alias_set (&lhs_ref),
3310 ao_ref_base_alias_set (&lhs_ref),
3311 offseti, maxsizei);
3312 }
3313 }
3314 }
3315
3316 /* 4) Assignment from an SSA name which definition we may be able
3317 to access pieces from or we can combine to a larger entity. */
3318 else if (known_eq (ref->size, maxsize)
3319 && is_gimple_reg_type (vr->type)
3320 && !reverse_storage_order_for_component_p (vr->operands)
3321 && !contains_storage_order_barrier_p (vr->operands)
3322 && gimple_assign_single_p (def_stmt)
3323 && !TREE_THIS_VOLATILE (gimple_assign_lhs (def_stmt))
3324 && TREE_CODE (gimple_assign_rhs1 (def_stmt)) == SSA_NAME)
3325 {
3326 tree lhs = gimple_assign_lhs (def_stmt);
3327 tree base2;
3328 poly_int64 offset2, size2, maxsize2;
3329 HOST_WIDE_INT offset2i, size2i, offseti;
3330 bool reverse;
3331 gcc_assert (lhs_ref_ok);
3332 base2 = ao_ref_base (&lhs_ref);
3333 offset2 = lhs_ref.offset;
3334 size2 = lhs_ref.size;
3335 maxsize2 = lhs_ref.max_size;
3336 reverse = reverse_storage_order_for_component_p (lhs);
3337 tree def_rhs = gimple_assign_rhs1 (def_stmt);
3338 if (!reverse
3339 && !storage_order_barrier_p (lhs)
3340 && known_size_p (maxsize2)
3341 && known_eq (maxsize2, size2)
3342 && adjust_offsets_for_equal_base_address (base, &offset,
3343 base2, &offset2))
3344 {
3345 if (data->partial_defs.is_empty ()
3346 && known_subrange_p (offset, maxsize, offset2, size2)
3347 /* ??? We can't handle bitfield precision extracts without
3348 either using an alternate type for the BIT_FIELD_REF and
3349 then doing a conversion or possibly adjusting the offset
3350 according to endianness. */
3351 && (! INTEGRAL_TYPE_P (vr->type)
3352 || known_eq (ref->size, TYPE_PRECISION (vr->type)))
3353 && multiple_p (ref->size, BITS_PER_UNIT))
3354 {
3355 tree val = NULL_TREE;
3356 if (! INTEGRAL_TYPE_P (TREE_TYPE (def_rhs))
3357 || type_has_mode_precision_p (TREE_TYPE (def_rhs)))
3358 {
3359 gimple_match_op op (gimple_match_cond::UNCOND,
3360 BIT_FIELD_REF, vr->type,
3361 SSA_VAL (def_rhs),
3362 bitsize_int (ref->size),
3363 bitsize_int (offset - offset2));
3364 val = vn_nary_build_or_lookup (&op);
3365 }
3366 else if (known_eq (ref->size, size2))
3367 {
3368 gimple_match_op op (gimple_match_cond::UNCOND,
3369 VIEW_CONVERT_EXPR, vr->type,
3370 SSA_VAL (def_rhs));
3371 val = vn_nary_build_or_lookup (&op);
3372 }
3373 if (val
3374 && (TREE_CODE (val) != SSA_NAME
3375 || ! SSA_NAME_OCCURS_IN_ABNORMAL_PHI (val)))
3376 return data->finish (ao_ref_alias_set (&lhs_ref),
3377 ao_ref_base_alias_set (&lhs_ref), val);
3378 }
3379 else if (maxsize.is_constant (&maxsizei)
3380 && offset.is_constant (&offseti)
3381 && offset2.is_constant (&offset2i)
3382 && size2.is_constant (&size2i)
3383 && ranges_known_overlap_p (offset, maxsize, offset2, size2))
3384 {
3385 pd_data pd;
3386 pd.rhs = SSA_VAL (def_rhs);
3387 pd.rhs_off = 0;
3388 pd.offset = offset2i;
3389 pd.size = size2i;
3390 return data->push_partial_def (pd, ao_ref_alias_set (&lhs_ref),
3391 ao_ref_base_alias_set (&lhs_ref),
3392 offseti, maxsizei);
3393 }
3394 }
3395 }
3396
3397 /* 4b) Assignment done via one of the vectorizer internal store
3398 functions where we may be able to access pieces from or we can
3399 combine to a larger entity. */
3400 else if (known_eq (ref->size, maxsize)
3401 && is_gimple_reg_type (vr->type)
3402 && !reverse_storage_order_for_component_p (vr->operands)
3403 && !contains_storage_order_barrier_p (vr->operands)
3404 && is_gimple_call (def_stmt)
3405 && gimple_call_internal_p (def_stmt)
3406 && internal_store_fn_p (gimple_call_internal_fn (def_stmt)))
3407 {
3408 gcall *call = as_a <gcall *> (def_stmt);
3409 internal_fn fn = gimple_call_internal_fn (call);
3410
3411 tree mask = NULL_TREE, len = NULL_TREE, bias = NULL_TREE;
3412 switch (fn)
3413 {
3414 case IFN_MASK_STORE:
3415 mask = gimple_call_arg (call, internal_fn_mask_index (fn));
3416 mask = vn_valueize (mask);
3417 if (TREE_CODE (mask) != VECTOR_CST)
3418 return (void *)-1;
3419 break;
3420 case IFN_LEN_STORE:
3421 {
3422 int len_index = internal_fn_len_index (fn);
3423 len = gimple_call_arg (call, len_index);
3424 bias = gimple_call_arg (call, len_index + 1);
3425 if (!tree_fits_uhwi_p (len) || !tree_fits_shwi_p (bias))
3426 return (void *) -1;
3427 break;
3428 }
3429 default:
3430 return (void *)-1;
3431 }
3432 tree def_rhs = gimple_call_arg (call,
3433 internal_fn_stored_value_index (fn));
3434 def_rhs = vn_valueize (def_rhs);
3435 if (TREE_CODE (def_rhs) != VECTOR_CST)
3436 return (void *)-1;
3437
3438 ao_ref_init_from_ptr_and_size (&lhs_ref,
3439 vn_valueize (gimple_call_arg (call, 0)),
3440 TYPE_SIZE_UNIT (TREE_TYPE (def_rhs)));
3441 tree base2;
3442 poly_int64 offset2, size2, maxsize2;
3443 HOST_WIDE_INT offset2i, size2i, offseti;
3444 base2 = ao_ref_base (&lhs_ref);
3445 offset2 = lhs_ref.offset;
3446 size2 = lhs_ref.size;
3447 maxsize2 = lhs_ref.max_size;
3448 if (known_size_p (maxsize2)
3449 && known_eq (maxsize2, size2)
3450 && adjust_offsets_for_equal_base_address (base, &offset,
3451 base2, &offset2)
3452 && maxsize.is_constant (&maxsizei)
3453 && offset.is_constant (&offseti)
3454 && offset2.is_constant (&offset2i)
3455 && size2.is_constant (&size2i))
3456 {
3457 if (!ranges_maybe_overlap_p (offset, maxsize, offset2, size2))
3458 /* Poor-mans disambiguation. */
3459 return NULL;
3460 else if (ranges_known_overlap_p (offset, maxsize, offset2, size2))
3461 {
3462 pd_data pd;
3463 pd.rhs = def_rhs;
3464 tree aa = gimple_call_arg (call, 1);
3465 alias_set_type set = get_deref_alias_set (TREE_TYPE (aa));
3466 tree vectype = TREE_TYPE (def_rhs);
3467 unsigned HOST_WIDE_INT elsz
3468 = tree_to_uhwi (TYPE_SIZE (TREE_TYPE (vectype)));
3469 if (mask)
3470 {
3471 HOST_WIDE_INT start = 0, length = 0;
3472 unsigned mask_idx = 0;
3473 do
3474 {
3475 if (integer_zerop (VECTOR_CST_ELT (mask, mask_idx)))
3476 {
3477 if (length != 0)
3478 {
3479 pd.rhs_off = start;
3480 pd.offset = offset2i + start;
3481 pd.size = length;
3482 if (ranges_known_overlap_p
3483 (offset, maxsize, pd.offset, pd.size))
3484 {
3485 void *res = data->push_partial_def
3486 (pd, set, set, offseti, maxsizei);
3487 if (res != NULL)
3488 return res;
3489 }
3490 }
3491 start = (mask_idx + 1) * elsz;
3492 length = 0;
3493 }
3494 else
3495 length += elsz;
3496 mask_idx++;
3497 }
3498 while (known_lt (mask_idx, TYPE_VECTOR_SUBPARTS (vectype)));
3499 if (length != 0)
3500 {
3501 pd.rhs_off = start;
3502 pd.offset = offset2i + start;
3503 pd.size = length;
3504 if (ranges_known_overlap_p (offset, maxsize,
3505 pd.offset, pd.size))
3506 return data->push_partial_def (pd, set, set,
3507 offseti, maxsizei);
3508 }
3509 }
3510 else if (fn == IFN_LEN_STORE)
3511 {
3512 pd.offset = offset2i;
3513 pd.size = (tree_to_uhwi (len)
3514 + -tree_to_shwi (bias)) * BITS_PER_UNIT;
3515 if (BYTES_BIG_ENDIAN)
3516 pd.rhs_off = pd.size - tree_to_uhwi (TYPE_SIZE (vectype));
3517 else
3518 pd.rhs_off = 0;
3519 if (ranges_known_overlap_p (offset, maxsize,
3520 pd.offset, pd.size))
3521 return data->push_partial_def (pd, set, set,
3522 offseti, maxsizei);
3523 }
3524 else
3525 gcc_unreachable ();
3526 return NULL;
3527 }
3528 }
3529 }
3530
3531 /* 5) For aggregate copies translate the reference through them if
3532 the copy kills ref. */
3533 else if (data->vn_walk_kind == VN_WALKREWRITE
3534 && gimple_assign_single_p (def_stmt)
3535 && !gimple_has_volatile_ops (def_stmt)
3536 && (DECL_P (gimple_assign_rhs1 (def_stmt))
3537 || TREE_CODE (gimple_assign_rhs1 (def_stmt)) == MEM_REF
3538 || handled_component_p (gimple_assign_rhs1 (def_stmt))))
3539 {
3540 tree base2;
3541 int i, j, k;
3542 auto_vec<vn_reference_op_s> rhs;
3543 vn_reference_op_t vro;
3544 ao_ref r;
3545
3546 gcc_assert (lhs_ref_ok);
3547
3548 /* See if the assignment kills REF. */
3549 base2 = ao_ref_base (&lhs_ref);
3550 if (!lhs_ref.max_size_known_p ()
3551 || (base != base2
3552 && (TREE_CODE (base) != MEM_REF
3553 || TREE_CODE (base2) != MEM_REF
3554 || TREE_OPERAND (base, 0) != TREE_OPERAND (base2, 0)
3555 || !tree_int_cst_equal (TREE_OPERAND (base, 1),
3556 TREE_OPERAND (base2, 1))))
3557 || !stmt_kills_ref_p (def_stmt, ref))
3558 return (void *)-1;
3559
3560 /* Find the common base of ref and the lhs. lhs_ops already
3561 contains valueized operands for the lhs. */
3562 i = vr->operands.length () - 1;
3563 j = lhs_ops.length () - 1;
3564 while (j >= 0 && i >= 0
3565 && vn_reference_op_eq (&vr->operands[i], &lhs_ops[j]))
3566 {
3567 i--;
3568 j--;
3569 }
3570
3571 /* ??? The innermost op should always be a MEM_REF and we already
3572 checked that the assignment to the lhs kills vr. Thus for
3573 aggregate copies using char[] types the vn_reference_op_eq
3574 may fail when comparing types for compatibility. But we really
3575 don't care here - further lookups with the rewritten operands
3576 will simply fail if we messed up types too badly. */
3577 poly_int64 extra_off = 0;
3578 if (j == 0 && i >= 0
3579 && lhs_ops[0].opcode == MEM_REF
3580 && maybe_ne (lhs_ops[0].off, -1))
3581 {
3582 if (known_eq (lhs_ops[0].off, vr->operands[i].off))
3583 i--, j--;
3584 else if (vr->operands[i].opcode == MEM_REF
3585 && maybe_ne (vr->operands[i].off, -1))
3586 {
3587 extra_off = vr->operands[i].off - lhs_ops[0].off;
3588 i--, j--;
3589 }
3590 }
3591
3592 /* i now points to the first additional op.
3593 ??? LHS may not be completely contained in VR, one or more
3594 VIEW_CONVERT_EXPRs could be in its way. We could at least
3595 try handling outermost VIEW_CONVERT_EXPRs. */
3596 if (j != -1)
3597 return (void *)-1;
3598
3599 /* Punt if the additional ops contain a storage order barrier. */
3600 for (k = i; k >= 0; k--)
3601 {
3602 vro = &vr->operands[k];
3603 if (vro->opcode == VIEW_CONVERT_EXPR && vro->reverse)
3604 return (void *)-1;
3605 }
3606
3607 /* Now re-write REF to be based on the rhs of the assignment. */
3608 tree rhs1 = gimple_assign_rhs1 (def_stmt);
3609 copy_reference_ops_from_ref (rhs1, &rhs);
3610
3611 /* Apply an extra offset to the inner MEM_REF of the RHS. */
3612 bool force_no_tbaa = false;
3613 if (maybe_ne (extra_off, 0))
3614 {
3615 if (rhs.length () < 2)
3616 return (void *)-1;
3617 int ix = rhs.length () - 2;
3618 if (rhs[ix].opcode != MEM_REF
3619 || known_eq (rhs[ix].off, -1))
3620 return (void *)-1;
3621 rhs[ix].off += extra_off;
3622 rhs[ix].op0 = int_const_binop (PLUS_EXPR, rhs[ix].op0,
3623 build_int_cst (TREE_TYPE (rhs[ix].op0),
3624 extra_off));
3625 /* When we have offsetted the RHS, reading only parts of it,
3626 we can no longer use the original TBAA type, force alias-set
3627 zero. */
3628 force_no_tbaa = true;
3629 }
3630
3631 /* Save the operands since we need to use the original ones for
3632 the hash entry we use. */
3633 if (!data->saved_operands.exists ())
3634 data->saved_operands = vr->operands.copy ();
3635
3636 /* We need to pre-pend vr->operands[0..i] to rhs. */
3637 vec<vn_reference_op_s> old = vr->operands;
3638 if (i + 1 + rhs.length () > vr->operands.length ())
3639 vr->operands.safe_grow (i + 1 + rhs.length (), true);
3640 else
3641 vr->operands.truncate (i + 1 + rhs.length ());
3642 FOR_EACH_VEC_ELT (rhs, j, vro)
3643 vr->operands[i + 1 + j] = *vro;
3644 valueize_refs (&vr->operands);
3645 if (old == shared_lookup_references)
3646 shared_lookup_references = vr->operands;
3647 vr->hashcode = vn_reference_compute_hash (vr);
3648
3649 /* Try folding the new reference to a constant. */
3650 tree val = fully_constant_vn_reference_p (vr);
3651 if (val)
3652 {
3653 if (data->partial_defs.is_empty ())
3654 return data->finish (ao_ref_alias_set (&lhs_ref),
3655 ao_ref_base_alias_set (&lhs_ref), val);
3656 /* This is the only interesting case for partial-def handling
3657 coming from targets that like to gimplify init-ctors as
3658 aggregate copies from constant data like aarch64 for
3659 PR83518. */
3660 if (maxsize.is_constant (&maxsizei) && known_eq (ref->size, maxsize))
3661 {
3662 pd_data pd;
3663 pd.rhs = val;
3664 pd.rhs_off = 0;
3665 pd.offset = 0;
3666 pd.size = maxsizei;
3667 return data->push_partial_def (pd, ao_ref_alias_set (&lhs_ref),
3668 ao_ref_base_alias_set (&lhs_ref),
3669 0, maxsizei);
3670 }
3671 }
3672
3673 /* Continuing with partial defs isn't easily possible here, we
3674 have to find a full def from further lookups from here. Probably
3675 not worth the special-casing everywhere. */
3676 if (!data->partial_defs.is_empty ())
3677 return (void *)-1;
3678
3679 /* Adjust *ref from the new operands. */
3680 ao_ref rhs1_ref;
3681 ao_ref_init (&rhs1_ref, rhs1);
3682 if (!ao_ref_init_from_vn_reference (&r,
3683 force_no_tbaa ? 0
3684 : ao_ref_alias_set (&rhs1_ref),
3685 force_no_tbaa ? 0
3686 : ao_ref_base_alias_set (&rhs1_ref),
3687 vr->type, vr->operands))
3688 return (void *)-1;
3689 /* This can happen with bitfields. */
3690 if (maybe_ne (ref->size, r.size))
3691 {
3692 /* If the access lacks some subsetting simply apply that by
3693 shortening it. That in the end can only be successful
3694 if we can pun the lookup result which in turn requires
3695 exact offsets. */
3696 if (known_eq (r.size, r.max_size)
3697 && known_lt (ref->size, r.size))
3698 r.size = r.max_size = ref->size;
3699 else
3700 return (void *)-1;
3701 }
3702 *ref = r;
3703 vr->offset = r.offset;
3704 vr->max_size = r.max_size;
3705
3706 /* Do not update last seen VUSE after translating. */
3707 data->last_vuse_ptr = NULL;
3708 /* Invalidate the original access path since it now contains
3709 the wrong base. */
3710 data->orig_ref.ref = NULL_TREE;
3711 /* Use the alias-set of this LHS for recording an eventual result. */
3712 if (data->first_set == -2)
3713 {
3714 data->first_set = ao_ref_alias_set (&lhs_ref);
3715 data->first_base_set = ao_ref_base_alias_set (&lhs_ref);
3716 }
3717
3718 /* Keep looking for the adjusted *REF / VR pair. */
3719 return NULL;
3720 }
3721
3722 /* 6) For memcpy copies translate the reference through them if the copy
3723 kills ref. But we cannot (easily) do this translation if the memcpy is
3724 a storage order barrier, i.e. is equivalent to a VIEW_CONVERT_EXPR that
3725 can modify the storage order of objects (see storage_order_barrier_p). */
3726 else if (data->vn_walk_kind == VN_WALKREWRITE
3727 && is_gimple_reg_type (vr->type)
3728 /* ??? Handle BCOPY as well. */
3729 && (gimple_call_builtin_p (def_stmt, BUILT_IN_MEMCPY)
3730 || gimple_call_builtin_p (def_stmt, BUILT_IN_MEMCPY_CHK)
3731 || gimple_call_builtin_p (def_stmt, BUILT_IN_MEMPCPY)
3732 || gimple_call_builtin_p (def_stmt, BUILT_IN_MEMPCPY_CHK)
3733 || gimple_call_builtin_p (def_stmt, BUILT_IN_MEMMOVE)
3734 || gimple_call_builtin_p (def_stmt, BUILT_IN_MEMMOVE_CHK))
3735 && (TREE_CODE (gimple_call_arg (def_stmt, 0)) == ADDR_EXPR
3736 || TREE_CODE (gimple_call_arg (def_stmt, 0)) == SSA_NAME)
3737 && (TREE_CODE (gimple_call_arg (def_stmt, 1)) == ADDR_EXPR
3738 || TREE_CODE (gimple_call_arg (def_stmt, 1)) == SSA_NAME)
3739 && (poly_int_tree_p (gimple_call_arg (def_stmt, 2), &copy_size)
3740 || (TREE_CODE (gimple_call_arg (def_stmt, 2)) == SSA_NAME
3741 && poly_int_tree_p (SSA_VAL (gimple_call_arg (def_stmt, 2)),
3742 &copy_size)))
3743 /* Handling this is more complicated, give up for now. */
3744 && data->partial_defs.is_empty ())
3745 {
3746 tree lhs, rhs;
3747 ao_ref r;
3748 poly_int64 rhs_offset, lhs_offset;
3749 vn_reference_op_s op;
3750 poly_uint64 mem_offset;
3751 poly_int64 at, byte_maxsize;
3752
3753 /* Only handle non-variable, addressable refs. */
3754 if (maybe_ne (ref->size, maxsize)
3755 || !multiple_p (offset, BITS_PER_UNIT, &at)
3756 || !multiple_p (maxsize, BITS_PER_UNIT, &byte_maxsize))
3757 return (void *)-1;
3758
3759 /* Extract a pointer base and an offset for the destination. */
3760 lhs = gimple_call_arg (def_stmt, 0);
3761 lhs_offset = 0;
3762 if (TREE_CODE (lhs) == SSA_NAME)
3763 {
3764 lhs = vn_valueize (lhs);
3765 if (TREE_CODE (lhs) == SSA_NAME)
3766 {
3767 gimple *def_stmt = SSA_NAME_DEF_STMT (lhs);
3768 if (gimple_assign_single_p (def_stmt)
3769 && gimple_assign_rhs_code (def_stmt) == ADDR_EXPR)
3770 lhs = gimple_assign_rhs1 (def_stmt);
3771 }
3772 }
3773 if (TREE_CODE (lhs) == ADDR_EXPR)
3774 {
3775 if (AGGREGATE_TYPE_P (TREE_TYPE (TREE_TYPE (lhs)))
3776 && TYPE_REVERSE_STORAGE_ORDER (TREE_TYPE (TREE_TYPE (lhs))))
3777 return (void *)-1;
3778 tree tem = get_addr_base_and_unit_offset (TREE_OPERAND (lhs, 0),
3779 &lhs_offset);
3780 if (!tem)
3781 return (void *)-1;
3782 if (TREE_CODE (tem) == MEM_REF
3783 && poly_int_tree_p (TREE_OPERAND (tem, 1), &mem_offset))
3784 {
3785 lhs = TREE_OPERAND (tem, 0);
3786 if (TREE_CODE (lhs) == SSA_NAME)
3787 lhs = vn_valueize (lhs);
3788 lhs_offset += mem_offset;
3789 }
3790 else if (DECL_P (tem))
3791 lhs = build_fold_addr_expr (tem);
3792 else
3793 return (void *)-1;
3794 }
3795 if (TREE_CODE (lhs) != SSA_NAME
3796 && TREE_CODE (lhs) != ADDR_EXPR)
3797 return (void *)-1;
3798
3799 /* Extract a pointer base and an offset for the source. */
3800 rhs = gimple_call_arg (def_stmt, 1);
3801 rhs_offset = 0;
3802 if (TREE_CODE (rhs) == SSA_NAME)
3803 rhs = vn_valueize (rhs);
3804 if (TREE_CODE (rhs) == ADDR_EXPR)
3805 {
3806 if (AGGREGATE_TYPE_P (TREE_TYPE (TREE_TYPE (rhs)))
3807 && TYPE_REVERSE_STORAGE_ORDER (TREE_TYPE (TREE_TYPE (rhs))))
3808 return (void *)-1;
3809 tree tem = get_addr_base_and_unit_offset (TREE_OPERAND (rhs, 0),
3810 &rhs_offset);
3811 if (!tem)
3812 return (void *)-1;
3813 if (TREE_CODE (tem) == MEM_REF
3814 && poly_int_tree_p (TREE_OPERAND (tem, 1), &mem_offset))
3815 {
3816 rhs = TREE_OPERAND (tem, 0);
3817 rhs_offset += mem_offset;
3818 }
3819 else if (DECL_P (tem)
3820 || TREE_CODE (tem) == STRING_CST)
3821 rhs = build_fold_addr_expr (tem);
3822 else
3823 return (void *)-1;
3824 }
3825 if (TREE_CODE (rhs) == SSA_NAME)
3826 rhs = SSA_VAL (rhs);
3827 else if (TREE_CODE (rhs) != ADDR_EXPR)
3828 return (void *)-1;
3829
3830 /* The bases of the destination and the references have to agree. */
3831 if (TREE_CODE (base) == MEM_REF)
3832 {
3833 if (TREE_OPERAND (base, 0) != lhs
3834 || !poly_int_tree_p (TREE_OPERAND (base, 1), &mem_offset))
3835 return (void *) -1;
3836 at += mem_offset;
3837 }
3838 else if (!DECL_P (base)
3839 || TREE_CODE (lhs) != ADDR_EXPR
3840 || TREE_OPERAND (lhs, 0) != base)
3841 return (void *)-1;
3842
3843 /* If the access is completely outside of the memcpy destination
3844 area there is no aliasing. */
3845 if (!ranges_maybe_overlap_p (lhs_offset, copy_size, at, byte_maxsize))
3846 return NULL;
3847 /* And the access has to be contained within the memcpy destination. */
3848 if (!known_subrange_p (at, byte_maxsize, lhs_offset, copy_size))
3849 return (void *)-1;
3850
3851 /* Save the operands since we need to use the original ones for
3852 the hash entry we use. */
3853 if (!data->saved_operands.exists ())
3854 data->saved_operands = vr->operands.copy ();
3855
3856 /* Make room for 2 operands in the new reference. */
3857 if (vr->operands.length () < 2)
3858 {
3859 vec<vn_reference_op_s> old = vr->operands;
3860 vr->operands.safe_grow_cleared (2, true);
3861 if (old == shared_lookup_references)
3862 shared_lookup_references = vr->operands;
3863 }
3864 else
3865 vr->operands.truncate (2);
3866
3867 /* The looked-through reference is a simple MEM_REF. */
3868 memset (&op, 0, sizeof (op));
3869 op.type = vr->type;
3870 op.opcode = MEM_REF;
3871 op.op0 = build_int_cst (ptr_type_node, at - lhs_offset + rhs_offset);
3872 op.off = at - lhs_offset + rhs_offset;
3873 vr->operands[0] = op;
3874 op.type = TREE_TYPE (rhs);
3875 op.opcode = TREE_CODE (rhs);
3876 op.op0 = rhs;
3877 op.off = -1;
3878 vr->operands[1] = op;
3879 vr->hashcode = vn_reference_compute_hash (vr);
3880
3881 /* Try folding the new reference to a constant. */
3882 tree val = fully_constant_vn_reference_p (vr);
3883 if (val)
3884 return data->finish (0, 0, val);
3885
3886 /* Adjust *ref from the new operands. */
3887 if (!ao_ref_init_from_vn_reference (&r, 0, 0, vr->type, vr->operands))
3888 return (void *)-1;
3889 /* This can happen with bitfields. */
3890 if (maybe_ne (ref->size, r.size))
3891 return (void *)-1;
3892 *ref = r;
3893 vr->offset = r.offset;
3894 vr->max_size = r.max_size;
3895
3896 /* Do not update last seen VUSE after translating. */
3897 data->last_vuse_ptr = NULL;
3898 /* Invalidate the original access path since it now contains
3899 the wrong base. */
3900 data->orig_ref.ref = NULL_TREE;
3901 /* Use the alias-set of this stmt for recording an eventual result. */
3902 if (data->first_set == -2)
3903 {
3904 data->first_set = 0;
3905 data->first_base_set = 0;
3906 }
3907
3908 /* Keep looking for the adjusted *REF / VR pair. */
3909 return NULL;
3910 }
3911
3912 /* Bail out and stop walking. */
3913 return (void *)-1;
3914 }
3915
3916 /* Return true if E is a backedge with respect to our CFG walk order. */
3917
3918 static bool
3919 vn_is_backedge (edge e, void *)
3920 {
3921 /* During PRE elimination we no longer have access to this info. */
3922 return (!vn_bb_to_rpo
3923 || vn_bb_to_rpo[e->dest->index] <= vn_bb_to_rpo[e->src->index]);
3924 }
3925
3926 /* Return a reference op vector from OP that can be used for
3927 vn_reference_lookup_pieces. The caller is responsible for releasing
3928 the vector. */
3929
3930 vec<vn_reference_op_s>
3931 vn_reference_operands_for_lookup (tree op)
3932 {
3933 bool valueized;
3934 return valueize_shared_reference_ops_from_ref (op, &valueized).copy ();
3935 }
3936
3937 /* Lookup a reference operation by it's parts, in the current hash table.
3938 Returns the resulting value number if it exists in the hash table,
3939 NULL_TREE otherwise. VNRESULT will be filled in with the actual
3940 vn_reference_t stored in the hashtable if something is found. */
3941
3942 tree
3943 vn_reference_lookup_pieces (tree vuse, alias_set_type set,
3944 alias_set_type base_set, tree type,
3945 vec<vn_reference_op_s> operands,
3946 vn_reference_t *vnresult, vn_lookup_kind kind)
3947 {
3948 struct vn_reference_s vr1;
3949 vn_reference_t tmp;
3950 tree cst;
3951
3952 if (!vnresult)
3953 vnresult = &tmp;
3954 *vnresult = NULL;
3955
3956 vr1.vuse = vuse_ssa_val (vuse);
3957 shared_lookup_references.truncate (0);
3958 shared_lookup_references.safe_grow (operands.length (), true);
3959 memcpy (shared_lookup_references.address (),
3960 operands.address (),
3961 sizeof (vn_reference_op_s)
3962 * operands.length ());
3963 bool valueized_p;
3964 valueize_refs_1 (&shared_lookup_references, &valueized_p);
3965 vr1.operands = shared_lookup_references;
3966 vr1.type = type;
3967 vr1.set = set;
3968 vr1.base_set = base_set;
3969 /* We can pretend there's no extra info fed in since the ao_refs offset
3970 and max_size are computed only from the VN reference ops. */
3971 vr1.offset = 0;
3972 vr1.max_size = -1;
3973 vr1.hashcode = vn_reference_compute_hash (&vr1);
3974 if ((cst = fully_constant_vn_reference_p (&vr1)))
3975 return cst;
3976
3977 vn_reference_lookup_1 (&vr1, vnresult);
3978 if (!*vnresult
3979 && kind != VN_NOWALK
3980 && vr1.vuse)
3981 {
3982 ao_ref r;
3983 unsigned limit = param_sccvn_max_alias_queries_per_access;
3984 vn_walk_cb_data data (&vr1, NULL_TREE, NULL, kind, true, NULL_TREE,
3985 false);
3986 vec<vn_reference_op_s> ops_for_ref;
3987 if (!valueized_p)
3988 ops_for_ref = vr1.operands;
3989 else
3990 {
3991 /* For ao_ref_from_mem we have to ensure only available SSA names
3992 end up in base and the only convenient way to make this work
3993 for PRE is to re-valueize with that in mind. */
3994 ops_for_ref.create (operands.length ());
3995 ops_for_ref.quick_grow (operands.length ());
3996 memcpy (ops_for_ref.address (),
3997 operands.address (),
3998 sizeof (vn_reference_op_s)
3999 * operands.length ());
4000 valueize_refs_1 (&ops_for_ref, &valueized_p, true);
4001 }
4002 if (ao_ref_init_from_vn_reference (&r, set, base_set, type,
4003 ops_for_ref))
4004 *vnresult
4005 = ((vn_reference_t)
4006 walk_non_aliased_vuses (&r, vr1.vuse, true, vn_reference_lookup_2,
4007 vn_reference_lookup_3, vn_is_backedge,
4008 vuse_valueize, limit, &data));
4009 if (ops_for_ref != shared_lookup_references)
4010 ops_for_ref.release ();
4011 gcc_checking_assert (vr1.operands == shared_lookup_references);
4012 if (*vnresult
4013 && data.same_val
4014 && (!(*vnresult)->result
4015 || !operand_equal_p ((*vnresult)->result, data.same_val)))
4016 {
4017 *vnresult = NULL;
4018 return NULL_TREE;
4019 }
4020 }
4021
4022 if (*vnresult)
4023 return (*vnresult)->result;
4024
4025 return NULL_TREE;
4026 }
4027
4028 /* Lookup OP in the current hash table, and return the resulting value
4029 number if it exists in the hash table. Return NULL_TREE if it does
4030 not exist in the hash table or if the result field of the structure
4031 was NULL.. VNRESULT will be filled in with the vn_reference_t
4032 stored in the hashtable if one exists. When TBAA_P is false assume
4033 we are looking up a store and treat it as having alias-set zero.
4034 *LAST_VUSE_PTR will be updated with the VUSE the value lookup succeeded.
4035 MASK is either NULL_TREE, or can be an INTEGER_CST if the result of the
4036 load is bitwise anded with MASK and so we are only interested in a subset
4037 of the bits and can ignore if the other bits are uninitialized or
4038 not initialized with constants. When doing redundant store removal
4039 the caller has to set REDUNDANT_STORE_REMOVAL_P. */
4040
4041 tree
4042 vn_reference_lookup (tree op, tree vuse, vn_lookup_kind kind,
4043 vn_reference_t *vnresult, bool tbaa_p,
4044 tree *last_vuse_ptr, tree mask,
4045 bool redundant_store_removal_p)
4046 {
4047 vec<vn_reference_op_s> operands;
4048 struct vn_reference_s vr1;
4049 bool valueized_anything;
4050
4051 if (vnresult)
4052 *vnresult = NULL;
4053
4054 vr1.vuse = vuse_ssa_val (vuse);
4055 vr1.operands = operands
4056 = valueize_shared_reference_ops_from_ref (op, &valueized_anything);
4057
4058 /* Handle &MEM[ptr + 5].b[1].c as POINTER_PLUS_EXPR. Avoid doing
4059 this before the pass folding __builtin_object_size had a chance to run. */
4060 if ((cfun->curr_properties & PROP_objsz)
4061 && operands[0].opcode == ADDR_EXPR
4062 && operands.last ().opcode == SSA_NAME)
4063 {
4064 poly_int64 off = 0;
4065 vn_reference_op_t vro;
4066 unsigned i;
4067 for (i = 1; operands.iterate (i, &vro); ++i)
4068 {
4069 if (vro->opcode == SSA_NAME)
4070 break;
4071 else if (known_eq (vro->off, -1))
4072 break;
4073 off += vro->off;
4074 }
4075 if (i == operands.length () - 1
4076 /* Make sure we the offset we accumulated in a 64bit int
4077 fits the address computation carried out in target
4078 offset precision. */
4079 && (off.coeffs[0]
4080 == sext_hwi (off.coeffs[0], TYPE_PRECISION (sizetype))))
4081 {
4082 gcc_assert (operands[i-1].opcode == MEM_REF);
4083 tree ops[2];
4084 ops[0] = operands[i].op0;
4085 ops[1] = wide_int_to_tree (sizetype, off);
4086 tree res = vn_nary_op_lookup_pieces (2, POINTER_PLUS_EXPR,
4087 TREE_TYPE (op), ops, NULL);
4088 if (res)
4089 return res;
4090 return NULL_TREE;
4091 }
4092 }
4093
4094 vr1.type = TREE_TYPE (op);
4095 ao_ref op_ref;
4096 ao_ref_init (&op_ref, op);
4097 vr1.set = ao_ref_alias_set (&op_ref);
4098 vr1.base_set = ao_ref_base_alias_set (&op_ref);
4099 vr1.offset = 0;
4100 vr1.max_size = -1;
4101 vr1.hashcode = vn_reference_compute_hash (&vr1);
4102 if (mask == NULL_TREE)
4103 if (tree cst = fully_constant_vn_reference_p (&vr1))
4104 return cst;
4105
4106 if (kind != VN_NOWALK && vr1.vuse)
4107 {
4108 vn_reference_t wvnresult;
4109 ao_ref r;
4110 unsigned limit = param_sccvn_max_alias_queries_per_access;
4111 auto_vec<vn_reference_op_s> ops_for_ref;
4112 if (valueized_anything)
4113 {
4114 copy_reference_ops_from_ref (op, &ops_for_ref);
4115 bool tem;
4116 valueize_refs_1 (&ops_for_ref, &tem, true);
4117 }
4118 /* Make sure to use a valueized reference if we valueized anything.
4119 Otherwise preserve the full reference for advanced TBAA. */
4120 if (!valueized_anything
4121 || !ao_ref_init_from_vn_reference (&r, vr1.set, vr1.base_set,
4122 vr1.type, ops_for_ref))
4123 {
4124 ao_ref_init (&r, op);
4125 /* Record the extra info we're getting from the full ref. */
4126 ao_ref_base (&r);
4127 vr1.offset = r.offset;
4128 vr1.max_size = r.max_size;
4129 }
4130 vn_walk_cb_data data (&vr1, r.ref ? NULL_TREE : op,
4131 last_vuse_ptr, kind, tbaa_p, mask,
4132 redundant_store_removal_p);
4133
4134 wvnresult
4135 = ((vn_reference_t)
4136 walk_non_aliased_vuses (&r, vr1.vuse, tbaa_p, vn_reference_lookup_2,
4137 vn_reference_lookup_3, vn_is_backedge,
4138 vuse_valueize, limit, &data));
4139 gcc_checking_assert (vr1.operands == shared_lookup_references);
4140 if (wvnresult)
4141 {
4142 gcc_assert (mask == NULL_TREE);
4143 if (data.same_val
4144 && (!wvnresult->result
4145 || !operand_equal_p (wvnresult->result, data.same_val)))
4146 return NULL_TREE;
4147 if (vnresult)
4148 *vnresult = wvnresult;
4149 return wvnresult->result;
4150 }
4151 else if (mask)
4152 return data.masked_result;
4153
4154 return NULL_TREE;
4155 }
4156
4157 if (last_vuse_ptr)
4158 *last_vuse_ptr = vr1.vuse;
4159 if (mask)
4160 return NULL_TREE;
4161 return vn_reference_lookup_1 (&vr1, vnresult);
4162 }
4163
4164 /* Lookup CALL in the current hash table and return the entry in
4165 *VNRESULT if found. Populates *VR for the hashtable lookup. */
4166
4167 void
4168 vn_reference_lookup_call (gcall *call, vn_reference_t *vnresult,
4169 vn_reference_t vr)
4170 {
4171 if (vnresult)
4172 *vnresult = NULL;
4173
4174 tree vuse = gimple_vuse (call);
4175
4176 vr->vuse = vuse ? SSA_VAL (vuse) : NULL_TREE;
4177 vr->operands = valueize_shared_reference_ops_from_call (call);
4178 tree lhs = gimple_call_lhs (call);
4179 /* For non-SSA return values the referece ops contain the LHS. */
4180 vr->type = ((lhs && TREE_CODE (lhs) == SSA_NAME)
4181 ? TREE_TYPE (lhs) : NULL_TREE);
4182 vr->punned = false;
4183 vr->set = 0;
4184 vr->base_set = 0;
4185 vr->offset = 0;
4186 vr->max_size = -1;
4187 vr->hashcode = vn_reference_compute_hash (vr);
4188 vn_reference_lookup_1 (vr, vnresult);
4189 }
4190
4191 /* Insert OP into the current hash table with a value number of RESULT. */
4192
4193 static void
4194 vn_reference_insert (tree op, tree result, tree vuse, tree vdef)
4195 {
4196 vn_reference_s **slot;
4197 vn_reference_t vr1;
4198 bool tem;
4199
4200 vec<vn_reference_op_s> operands
4201 = valueize_shared_reference_ops_from_ref (op, &tem);
4202 /* Handle &MEM[ptr + 5].b[1].c as POINTER_PLUS_EXPR. Avoid doing this
4203 before the pass folding __builtin_object_size had a chance to run. */
4204 if ((cfun->curr_properties & PROP_objsz)
4205 && operands[0].opcode == ADDR_EXPR
4206 && operands.last ().opcode == SSA_NAME)
4207 {
4208 poly_int64 off = 0;
4209 vn_reference_op_t vro;
4210 unsigned i;
4211 for (i = 1; operands.iterate (i, &vro); ++i)
4212 {
4213 if (vro->opcode == SSA_NAME)
4214 break;
4215 else if (known_eq (vro->off, -1))
4216 break;
4217 off += vro->off;
4218 }
4219 if (i == operands.length () - 1
4220 /* Make sure we the offset we accumulated in a 64bit int
4221 fits the address computation carried out in target
4222 offset precision. */
4223 && (off.coeffs[0]
4224 == sext_hwi (off.coeffs[0], TYPE_PRECISION (sizetype))))
4225 {
4226 gcc_assert (operands[i-1].opcode == MEM_REF);
4227 tree ops[2];
4228 ops[0] = operands[i].op0;
4229 ops[1] = wide_int_to_tree (sizetype, off);
4230 vn_nary_op_insert_pieces (2, POINTER_PLUS_EXPR,
4231 TREE_TYPE (op), ops, result,
4232 VN_INFO (result)->value_id);
4233 return;
4234 }
4235 }
4236
4237 vr1 = XOBNEW (&vn_tables_obstack, vn_reference_s);
4238 if (TREE_CODE (result) == SSA_NAME)
4239 vr1->value_id = VN_INFO (result)->value_id;
4240 else
4241 vr1->value_id = get_or_alloc_constant_value_id (result);
4242 vr1->vuse = vuse_ssa_val (vuse);
4243 vr1->operands = operands.copy ();
4244 vr1->type = TREE_TYPE (op);
4245 vr1->punned = false;
4246 ao_ref op_ref;
4247 ao_ref_init (&op_ref, op);
4248 vr1->set = ao_ref_alias_set (&op_ref);
4249 vr1->base_set = ao_ref_base_alias_set (&op_ref);
4250 /* Specifically use an unknown extent here, we're not doing any lookup
4251 and assume the caller didn't either (or it went VARYING). */
4252 vr1->offset = 0;
4253 vr1->max_size = -1;
4254 vr1->hashcode = vn_reference_compute_hash (vr1);
4255 vr1->result = TREE_CODE (result) == SSA_NAME ? SSA_VAL (result) : result;
4256 vr1->result_vdef = vdef;
4257
4258 slot = valid_info->references->find_slot_with_hash (vr1, vr1->hashcode,
4259 INSERT);
4260
4261 /* Because IL walking on reference lookup can end up visiting
4262 a def that is only to be visited later in iteration order
4263 when we are about to make an irreducible region reducible
4264 the def can be effectively processed and its ref being inserted
4265 by vn_reference_lookup_3 already. So we cannot assert (!*slot)
4266 but save a lookup if we deal with already inserted refs here. */
4267 if (*slot)
4268 {
4269 /* We cannot assert that we have the same value either because
4270 when disentangling an irreducible region we may end up visiting
4271 a use before the corresponding def. That's a missed optimization
4272 only though. See gcc.dg/tree-ssa/pr87126.c for example. */
4273 if (dump_file && (dump_flags & TDF_DETAILS)
4274 && !operand_equal_p ((*slot)->result, vr1->result, 0))
4275 {
4276 fprintf (dump_file, "Keeping old value ");
4277 print_generic_expr (dump_file, (*slot)->result);
4278 fprintf (dump_file, " because of collision\n");
4279 }
4280 free_reference (vr1);
4281 obstack_free (&vn_tables_obstack, vr1);
4282 return;
4283 }
4284
4285 *slot = vr1;
4286 vr1->next = last_inserted_ref;
4287 last_inserted_ref = vr1;
4288 }
4289
4290 /* Insert a reference by it's pieces into the current hash table with
4291 a value number of RESULT. Return the resulting reference
4292 structure we created. */
4293
4294 vn_reference_t
4295 vn_reference_insert_pieces (tree vuse, alias_set_type set,
4296 alias_set_type base_set,
4297 poly_int64 offset, poly_int64 max_size, tree type,
4298 vec<vn_reference_op_s> operands,
4299 tree result, unsigned int value_id)
4300
4301 {
4302 vn_reference_s **slot;
4303 vn_reference_t vr1;
4304
4305 vr1 = XOBNEW (&vn_tables_obstack, vn_reference_s);
4306 vr1->value_id = value_id;
4307 vr1->vuse = vuse_ssa_val (vuse);
4308 vr1->operands = operands;
4309 valueize_refs (&vr1->operands);
4310 vr1->type = type;
4311 vr1->punned = false;
4312 vr1->set = set;
4313 vr1->base_set = base_set;
4314 vr1->offset = offset;
4315 vr1->max_size = max_size;
4316 vr1->hashcode = vn_reference_compute_hash (vr1);
4317 if (result && TREE_CODE (result) == SSA_NAME)
4318 result = SSA_VAL (result);
4319 vr1->result = result;
4320 vr1->result_vdef = NULL_TREE;
4321
4322 slot = valid_info->references->find_slot_with_hash (vr1, vr1->hashcode,
4323 INSERT);
4324
4325 /* At this point we should have all the things inserted that we have
4326 seen before, and we should never try inserting something that
4327 already exists. */
4328 gcc_assert (!*slot);
4329
4330 *slot = vr1;
4331 vr1->next = last_inserted_ref;
4332 last_inserted_ref = vr1;
4333 return vr1;
4334 }
4335
4336 /* Compute and return the hash value for nary operation VBO1. */
4337
4338 hashval_t
4339 vn_nary_op_compute_hash (const vn_nary_op_t vno1)
4340 {
4341 inchash::hash hstate;
4342 unsigned i;
4343
4344 if (((vno1->length == 2
4345 && commutative_tree_code (vno1->opcode))
4346 || (vno1->length == 3
4347 && commutative_ternary_tree_code (vno1->opcode)))
4348 && tree_swap_operands_p (vno1->op[0], vno1->op[1]))
4349 std::swap (vno1->op[0], vno1->op[1]);
4350 else if (TREE_CODE_CLASS (vno1->opcode) == tcc_comparison
4351 && tree_swap_operands_p (vno1->op[0], vno1->op[1]))
4352 {
4353 std::swap (vno1->op[0], vno1->op[1]);
4354 vno1->opcode = swap_tree_comparison (vno1->opcode);
4355 }
4356
4357 hstate.add_int (vno1->opcode);
4358 for (i = 0; i < vno1->length; ++i)
4359 inchash::add_expr (vno1->op[i], hstate);
4360
4361 return hstate.end ();
4362 }
4363
4364 /* Compare nary operations VNO1 and VNO2 and return true if they are
4365 equivalent. */
4366
4367 bool
4368 vn_nary_op_eq (const_vn_nary_op_t const vno1, const_vn_nary_op_t const vno2)
4369 {
4370 unsigned i;
4371
4372 if (vno1->hashcode != vno2->hashcode)
4373 return false;
4374
4375 if (vno1->length != vno2->length)
4376 return false;
4377
4378 if (vno1->opcode != vno2->opcode
4379 || !types_compatible_p (vno1->type, vno2->type))
4380 return false;
4381
4382 for (i = 0; i < vno1->length; ++i)
4383 if (!expressions_equal_p (vno1->op[i], vno2->op[i]))
4384 return false;
4385
4386 /* BIT_INSERT_EXPR has an implict operand as the type precision
4387 of op1. Need to check to make sure they are the same. */
4388 if (vno1->opcode == BIT_INSERT_EXPR
4389 && TREE_CODE (vno1->op[1]) == INTEGER_CST
4390 && TYPE_PRECISION (TREE_TYPE (vno1->op[1]))
4391 != TYPE_PRECISION (TREE_TYPE (vno2->op[1])))
4392 return false;
4393
4394 return true;
4395 }
4396
4397 /* Initialize VNO from the pieces provided. */
4398
4399 static void
4400 init_vn_nary_op_from_pieces (vn_nary_op_t vno, unsigned int length,
4401 enum tree_code code, tree type, tree *ops)
4402 {
4403 vno->opcode = code;
4404 vno->length = length;
4405 vno->type = type;
4406 memcpy (&vno->op[0], ops, sizeof (tree) * length);
4407 }
4408
4409 /* Return the number of operands for a vn_nary ops structure from STMT. */
4410
4411 unsigned int
4412 vn_nary_length_from_stmt (gimple *stmt)
4413 {
4414 switch (gimple_assign_rhs_code (stmt))
4415 {
4416 case REALPART_EXPR:
4417 case IMAGPART_EXPR:
4418 case VIEW_CONVERT_EXPR:
4419 return 1;
4420
4421 case BIT_FIELD_REF:
4422 return 3;
4423
4424 case CONSTRUCTOR:
4425 return CONSTRUCTOR_NELTS (gimple_assign_rhs1 (stmt));
4426
4427 default:
4428 return gimple_num_ops (stmt) - 1;
4429 }
4430 }
4431
4432 /* Initialize VNO from STMT. */
4433
4434 void
4435 init_vn_nary_op_from_stmt (vn_nary_op_t vno, gassign *stmt)
4436 {
4437 unsigned i;
4438
4439 vno->opcode = gimple_assign_rhs_code (stmt);
4440 vno->type = TREE_TYPE (gimple_assign_lhs (stmt));
4441 switch (vno->opcode)
4442 {
4443 case REALPART_EXPR:
4444 case IMAGPART_EXPR:
4445 case VIEW_CONVERT_EXPR:
4446 vno->length = 1;
4447 vno->op[0] = TREE_OPERAND (gimple_assign_rhs1 (stmt), 0);
4448 break;
4449
4450 case BIT_FIELD_REF:
4451 vno->length = 3;
4452 vno->op[0] = TREE_OPERAND (gimple_assign_rhs1 (stmt), 0);
4453 vno->op[1] = TREE_OPERAND (gimple_assign_rhs1 (stmt), 1);
4454 vno->op[2] = TREE_OPERAND (gimple_assign_rhs1 (stmt), 2);
4455 break;
4456
4457 case CONSTRUCTOR:
4458 vno->length = CONSTRUCTOR_NELTS (gimple_assign_rhs1 (stmt));
4459 for (i = 0; i < vno->length; ++i)
4460 vno->op[i] = CONSTRUCTOR_ELT (gimple_assign_rhs1 (stmt), i)->value;
4461 break;
4462
4463 default:
4464 gcc_checking_assert (!gimple_assign_single_p (stmt));
4465 vno->length = gimple_num_ops (stmt) - 1;
4466 for (i = 0; i < vno->length; ++i)
4467 vno->op[i] = gimple_op (stmt, i + 1);
4468 }
4469 }
4470
4471 /* Compute the hashcode for VNO and look for it in the hash table;
4472 return the resulting value number if it exists in the hash table.
4473 Return NULL_TREE if it does not exist in the hash table or if the
4474 result field of the operation is NULL. VNRESULT will contain the
4475 vn_nary_op_t from the hashtable if it exists. */
4476
4477 static tree
4478 vn_nary_op_lookup_1 (vn_nary_op_t vno, vn_nary_op_t *vnresult)
4479 {
4480 vn_nary_op_s **slot;
4481
4482 if (vnresult)
4483 *vnresult = NULL;
4484
4485 for (unsigned i = 0; i < vno->length; ++i)
4486 if (TREE_CODE (vno->op[i]) == SSA_NAME)
4487 vno->op[i] = SSA_VAL (vno->op[i]);
4488
4489 vno->hashcode = vn_nary_op_compute_hash (vno);
4490 slot = valid_info->nary->find_slot_with_hash (vno, vno->hashcode, NO_INSERT);
4491 if (!slot)
4492 return NULL_TREE;
4493 if (vnresult)
4494 *vnresult = *slot;
4495 return (*slot)->predicated_values ? NULL_TREE : (*slot)->u.result;
4496 }
4497
4498 /* Lookup a n-ary operation by its pieces and return the resulting value
4499 number if it exists in the hash table. Return NULL_TREE if it does
4500 not exist in the hash table or if the result field of the operation
4501 is NULL. VNRESULT will contain the vn_nary_op_t from the hashtable
4502 if it exists. */
4503
4504 tree
4505 vn_nary_op_lookup_pieces (unsigned int length, enum tree_code code,
4506 tree type, tree *ops, vn_nary_op_t *vnresult)
4507 {
4508 vn_nary_op_t vno1 = XALLOCAVAR (struct vn_nary_op_s,
4509 sizeof_vn_nary_op (length));
4510 init_vn_nary_op_from_pieces (vno1, length, code, type, ops);
4511 return vn_nary_op_lookup_1 (vno1, vnresult);
4512 }
4513
4514 /* Lookup the rhs of STMT in the current hash table, and return the resulting
4515 value number if it exists in the hash table. Return NULL_TREE if
4516 it does not exist in the hash table. VNRESULT will contain the
4517 vn_nary_op_t from the hashtable if it exists. */
4518
4519 tree
4520 vn_nary_op_lookup_stmt (gimple *stmt, vn_nary_op_t *vnresult)
4521 {
4522 vn_nary_op_t vno1
4523 = XALLOCAVAR (struct vn_nary_op_s,
4524 sizeof_vn_nary_op (vn_nary_length_from_stmt (stmt)));
4525 init_vn_nary_op_from_stmt (vno1, as_a <gassign *> (stmt));
4526 return vn_nary_op_lookup_1 (vno1, vnresult);
4527 }
4528
4529 /* Allocate a vn_nary_op_t with LENGTH operands on STACK. */
4530
4531 vn_nary_op_t
4532 alloc_vn_nary_op_noinit (unsigned int length, struct obstack *stack)
4533 {
4534 return (vn_nary_op_t) obstack_alloc (stack, sizeof_vn_nary_op (length));
4535 }
4536
4537 /* Allocate and initialize a vn_nary_op_t on CURRENT_INFO's
4538 obstack. */
4539
4540 static vn_nary_op_t
4541 alloc_vn_nary_op (unsigned int length, tree result, unsigned int value_id)
4542 {
4543 vn_nary_op_t vno1 = alloc_vn_nary_op_noinit (length, &vn_tables_obstack);
4544
4545 vno1->value_id = value_id;
4546 vno1->length = length;
4547 vno1->predicated_values = 0;
4548 vno1->u.result = result;
4549
4550 return vno1;
4551 }
4552
4553 /* Insert VNO into TABLE. */
4554
4555 static vn_nary_op_t
4556 vn_nary_op_insert_into (vn_nary_op_t vno, vn_nary_op_table_type *table)
4557 {
4558 vn_nary_op_s **slot;
4559
4560 gcc_assert (! vno->predicated_values
4561 || (! vno->u.values->next
4562 && vno->u.values->n == 1));
4563
4564 for (unsigned i = 0; i < vno->length; ++i)
4565 if (TREE_CODE (vno->op[i]) == SSA_NAME)
4566 vno->op[i] = SSA_VAL (vno->op[i]);
4567
4568 vno->hashcode = vn_nary_op_compute_hash (vno);
4569 slot = table->find_slot_with_hash (vno, vno->hashcode, INSERT);
4570 vno->unwind_to = *slot;
4571 if (*slot)
4572 {
4573 /* Prefer non-predicated values.
4574 ??? Only if those are constant, otherwise, with constant predicated
4575 value, turn them into predicated values with entry-block validity
4576 (??? but we always find the first valid result currently). */
4577 if ((*slot)->predicated_values
4578 && ! vno->predicated_values)
4579 {
4580 /* ??? We cannot remove *slot from the unwind stack list.
4581 For the moment we deal with this by skipping not found
4582 entries but this isn't ideal ... */
4583 *slot = vno;
4584 /* ??? Maintain a stack of states we can unwind in
4585 vn_nary_op_s? But how far do we unwind? In reality
4586 we need to push change records somewhere... Or not
4587 unwind vn_nary_op_s and linking them but instead
4588 unwind the results "list", linking that, which also
4589 doesn't move on hashtable resize. */
4590 /* We can also have a ->unwind_to recording *slot there.
4591 That way we can make u.values a fixed size array with
4592 recording the number of entries but of course we then
4593 have always N copies for each unwind_to-state. Or we
4594 make sure to only ever append and each unwinding will
4595 pop off one entry (but how to deal with predicated
4596 replaced with non-predicated here?) */
4597 vno->next = last_inserted_nary;
4598 last_inserted_nary = vno;
4599 return vno;
4600 }
4601 else if (vno->predicated_values
4602 && ! (*slot)->predicated_values)
4603 return *slot;
4604 else if (vno->predicated_values
4605 && (*slot)->predicated_values)
4606 {
4607 /* ??? Factor this all into a insert_single_predicated_value
4608 routine. */
4609 gcc_assert (!vno->u.values->next && vno->u.values->n == 1);
4610 basic_block vno_bb
4611 = BASIC_BLOCK_FOR_FN (cfun, vno->u.values->valid_dominated_by_p[0]);
4612 vn_pval *nval = vno->u.values;
4613 vn_pval **next = &vno->u.values;
4614 bool found = false;
4615 for (vn_pval *val = (*slot)->u.values; val; val = val->next)
4616 {
4617 if (expressions_equal_p (val->result, nval->result))
4618 {
4619 found = true;
4620 for (unsigned i = 0; i < val->n; ++i)
4621 {
4622 basic_block val_bb
4623 = BASIC_BLOCK_FOR_FN (cfun,
4624 val->valid_dominated_by_p[i]);
4625 if (dominated_by_p (CDI_DOMINATORS, vno_bb, val_bb))
4626 /* Value registered with more generic predicate. */
4627 return *slot;
4628 else if (flag_checking)
4629 /* Shouldn't happen, we insert in RPO order. */
4630 gcc_assert (!dominated_by_p (CDI_DOMINATORS,
4631 val_bb, vno_bb));
4632 }
4633 /* Append value. */
4634 *next = (vn_pval *) obstack_alloc (&vn_tables_obstack,
4635 sizeof (vn_pval)
4636 + val->n * sizeof (int));
4637 (*next)->next = NULL;
4638 (*next)->result = val->result;
4639 (*next)->n = val->n + 1;
4640 memcpy ((*next)->valid_dominated_by_p,
4641 val->valid_dominated_by_p,
4642 val->n * sizeof (int));
4643 (*next)->valid_dominated_by_p[val->n] = vno_bb->index;
4644 next = &(*next)->next;
4645 if (dump_file && (dump_flags & TDF_DETAILS))
4646 fprintf (dump_file, "Appending predicate to value.\n");
4647 continue;
4648 }
4649 /* Copy other predicated values. */
4650 *next = (vn_pval *) obstack_alloc (&vn_tables_obstack,
4651 sizeof (vn_pval)
4652 + (val->n-1) * sizeof (int));
4653 memcpy (*next, val, sizeof (vn_pval) + (val->n-1) * sizeof (int));
4654 (*next)->next = NULL;
4655 next = &(*next)->next;
4656 }
4657 if (!found)
4658 *next = nval;
4659
4660 *slot = vno;
4661 vno->next = last_inserted_nary;
4662 last_inserted_nary = vno;
4663 return vno;
4664 }
4665
4666 /* While we do not want to insert things twice it's awkward to
4667 avoid it in the case where visit_nary_op pattern-matches stuff
4668 and ends up simplifying the replacement to itself. We then
4669 get two inserts, one from visit_nary_op and one from
4670 vn_nary_build_or_lookup.
4671 So allow inserts with the same value number. */
4672 if ((*slot)->u.result == vno->u.result)
4673 return *slot;
4674 }
4675
4676 /* ??? There's also optimistic vs. previous commited state merging
4677 that is problematic for the case of unwinding. */
4678
4679 /* ??? We should return NULL if we do not use 'vno' and have the
4680 caller release it. */
4681 gcc_assert (!*slot);
4682
4683 *slot = vno;
4684 vno->next = last_inserted_nary;
4685 last_inserted_nary = vno;
4686 return vno;
4687 }
4688
4689 /* Insert a n-ary operation into the current hash table using it's
4690 pieces. Return the vn_nary_op_t structure we created and put in
4691 the hashtable. */
4692
4693 vn_nary_op_t
4694 vn_nary_op_insert_pieces (unsigned int length, enum tree_code code,
4695 tree type, tree *ops,
4696 tree result, unsigned int value_id)
4697 {
4698 vn_nary_op_t vno1 = alloc_vn_nary_op (length, result, value_id);
4699 init_vn_nary_op_from_pieces (vno1, length, code, type, ops);
4700 return vn_nary_op_insert_into (vno1, valid_info->nary);
4701 }
4702
4703 /* Return whether we can track a predicate valid when PRED_E is executed. */
4704
4705 static bool
4706 can_track_predicate_on_edge (edge pred_e)
4707 {
4708 /* ??? As we are currently recording the destination basic-block index in
4709 vn_pval.valid_dominated_by_p and using dominance for the
4710 validity check we cannot track predicates on all edges. */
4711 if (single_pred_p (pred_e->dest))
4712 return true;
4713 /* Never record for backedges. */
4714 if (pred_e->flags & EDGE_DFS_BACK)
4715 return false;
4716 /* When there's more than one predecessor we cannot track
4717 predicate validity based on the destination block. The
4718 exception is when all other incoming edges sources are
4719 dominated by the destination block. */
4720 edge_iterator ei;
4721 edge e;
4722 FOR_EACH_EDGE (e, ei, pred_e->dest->preds)
4723 if (e != pred_e && ! dominated_by_p (CDI_DOMINATORS, e->src, e->dest))
4724 return false;
4725 return true;
4726 }
4727
4728 static vn_nary_op_t
4729 vn_nary_op_insert_pieces_predicated (unsigned int length, enum tree_code code,
4730 tree type, tree *ops,
4731 tree result, unsigned int value_id,
4732 edge pred_e)
4733 {
4734 gcc_assert (can_track_predicate_on_edge (pred_e));
4735
4736 if (dump_file && (dump_flags & TDF_DETAILS)
4737 /* ??? Fix dumping, but currently we only get comparisons. */
4738 && TREE_CODE_CLASS (code) == tcc_comparison)
4739 {
4740 fprintf (dump_file, "Recording on edge %d->%d ", pred_e->src->index,
4741 pred_e->dest->index);
4742 print_generic_expr (dump_file, ops[0], TDF_SLIM);
4743 fprintf (dump_file, " %s ", get_tree_code_name (code));
4744 print_generic_expr (dump_file, ops[1], TDF_SLIM);
4745 fprintf (dump_file, " == %s\n",
4746 integer_zerop (result) ? "false" : "true");
4747 }
4748 vn_nary_op_t vno1 = alloc_vn_nary_op (length, NULL_TREE, value_id);
4749 init_vn_nary_op_from_pieces (vno1, length, code, type, ops);
4750 vno1->predicated_values = 1;
4751 vno1->u.values = (vn_pval *) obstack_alloc (&vn_tables_obstack,
4752 sizeof (vn_pval));
4753 vno1->u.values->next = NULL;
4754 vno1->u.values->result = result;
4755 vno1->u.values->n = 1;
4756 vno1->u.values->valid_dominated_by_p[0] = pred_e->dest->index;
4757 return vn_nary_op_insert_into (vno1, valid_info->nary);
4758 }
4759
4760 static bool
4761 dominated_by_p_w_unex (basic_block bb1, basic_block bb2, bool);
4762
4763 static tree
4764 vn_nary_op_get_predicated_value (vn_nary_op_t vno, basic_block bb,
4765 edge e = NULL)
4766 {
4767 if (! vno->predicated_values)
4768 return vno->u.result;
4769 for (vn_pval *val = vno->u.values; val; val = val->next)
4770 for (unsigned i = 0; i < val->n; ++i)
4771 {
4772 basic_block cand
4773 = BASIC_BLOCK_FOR_FN (cfun, val->valid_dominated_by_p[i]);
4774 /* Do not handle backedge executability optimistically since
4775 when figuring out whether to iterate we do not consider
4776 changed predication.
4777 When asking for predicated values on an edge avoid looking
4778 at edge executability for edges forward in our iteration
4779 as well. */
4780 if (e && (e->flags & EDGE_DFS_BACK))
4781 {
4782 if (dominated_by_p (CDI_DOMINATORS, bb, cand))
4783 return val->result;
4784 }
4785 else if (dominated_by_p_w_unex (bb, cand, false))
4786 return val->result;
4787 }
4788 return NULL_TREE;
4789 }
4790
4791 static tree
4792 vn_nary_op_get_predicated_value (vn_nary_op_t vno, edge e)
4793 {
4794 return vn_nary_op_get_predicated_value (vno, e->src, e);
4795 }
4796
4797 /* Insert the rhs of STMT into the current hash table with a value number of
4798 RESULT. */
4799
4800 static vn_nary_op_t
4801 vn_nary_op_insert_stmt (gimple *stmt, tree result)
4802 {
4803 vn_nary_op_t vno1
4804 = alloc_vn_nary_op (vn_nary_length_from_stmt (stmt),
4805 result, VN_INFO (result)->value_id);
4806 init_vn_nary_op_from_stmt (vno1, as_a <gassign *> (stmt));
4807 return vn_nary_op_insert_into (vno1, valid_info->nary);
4808 }
4809
4810 /* Compute a hashcode for PHI operation VP1 and return it. */
4811
4812 static inline hashval_t
4813 vn_phi_compute_hash (vn_phi_t vp1)
4814 {
4815 inchash::hash hstate;
4816 tree phi1op;
4817 tree type;
4818 edge e;
4819 edge_iterator ei;
4820
4821 hstate.add_int (EDGE_COUNT (vp1->block->preds));
4822 switch (EDGE_COUNT (vp1->block->preds))
4823 {
4824 case 1:
4825 break;
4826 case 2:
4827 /* When this is a PHI node subject to CSE for different blocks
4828 avoid hashing the block index. */
4829 if (vp1->cclhs)
4830 break;
4831 /* Fallthru. */
4832 default:
4833 hstate.add_int (vp1->block->index);
4834 }
4835
4836 /* If all PHI arguments are constants we need to distinguish
4837 the PHI node via its type. */
4838 type = vp1->type;
4839 hstate.merge_hash (vn_hash_type (type));
4840
4841 FOR_EACH_EDGE (e, ei, vp1->block->preds)
4842 {
4843 /* Don't hash backedge values they need to be handled as VN_TOP
4844 for optimistic value-numbering. */
4845 if (e->flags & EDGE_DFS_BACK)
4846 continue;
4847
4848 phi1op = vp1->phiargs[e->dest_idx];
4849 if (phi1op == VN_TOP)
4850 continue;
4851 inchash::add_expr (phi1op, hstate);
4852 }
4853
4854 return hstate.end ();
4855 }
4856
4857
4858 /* Return true if COND1 and COND2 represent the same condition, set
4859 *INVERTED_P if one needs to be inverted to make it the same as
4860 the other. */
4861
4862 static bool
4863 cond_stmts_equal_p (gcond *cond1, tree lhs1, tree rhs1,
4864 gcond *cond2, tree lhs2, tree rhs2, bool *inverted_p)
4865 {
4866 enum tree_code code1 = gimple_cond_code (cond1);
4867 enum tree_code code2 = gimple_cond_code (cond2);
4868
4869 *inverted_p = false;
4870 if (code1 == code2)
4871 ;
4872 else if (code1 == swap_tree_comparison (code2))
4873 std::swap (lhs2, rhs2);
4874 else if (code1 == invert_tree_comparison (code2, HONOR_NANS (lhs2)))
4875 *inverted_p = true;
4876 else if (code1 == invert_tree_comparison
4877 (swap_tree_comparison (code2), HONOR_NANS (lhs2)))
4878 {
4879 std::swap (lhs2, rhs2);
4880 *inverted_p = true;
4881 }
4882 else
4883 return false;
4884
4885 return ((expressions_equal_p (lhs1, lhs2)
4886 && expressions_equal_p (rhs1, rhs2))
4887 || (commutative_tree_code (code1)
4888 && expressions_equal_p (lhs1, rhs2)
4889 && expressions_equal_p (rhs1, lhs2)));
4890 }
4891
4892 /* Compare two phi entries for equality, ignoring VN_TOP arguments. */
4893
4894 static int
4895 vn_phi_eq (const_vn_phi_t const vp1, const_vn_phi_t const vp2)
4896 {
4897 if (vp1->hashcode != vp2->hashcode)
4898 return false;
4899
4900 if (vp1->block != vp2->block)
4901 {
4902 if (EDGE_COUNT (vp1->block->preds) != EDGE_COUNT (vp2->block->preds))
4903 return false;
4904
4905 switch (EDGE_COUNT (vp1->block->preds))
4906 {
4907 case 1:
4908 /* Single-arg PHIs are just copies. */
4909 break;
4910
4911 case 2:
4912 {
4913 /* Make sure both PHIs are classified as CSEable. */
4914 if (! vp1->cclhs || ! vp2->cclhs)
4915 return false;
4916
4917 /* Rule out backedges into the PHI. */
4918 gcc_checking_assert
4919 (vp1->block->loop_father->header != vp1->block
4920 && vp2->block->loop_father->header != vp2->block);
4921
4922 /* If the PHI nodes do not have compatible types
4923 they are not the same. */
4924 if (!types_compatible_p (vp1->type, vp2->type))
4925 return false;
4926
4927 /* If the immediate dominator end in switch stmts multiple
4928 values may end up in the same PHI arg via intermediate
4929 CFG merges. */
4930 basic_block idom1
4931 = get_immediate_dominator (CDI_DOMINATORS, vp1->block);
4932 basic_block idom2
4933 = get_immediate_dominator (CDI_DOMINATORS, vp2->block);
4934 gcc_checking_assert (EDGE_COUNT (idom1->succs) == 2
4935 && EDGE_COUNT (idom2->succs) == 2);
4936
4937 /* Verify the controlling stmt is the same. */
4938 gcond *last1 = as_a <gcond *> (*gsi_last_bb (idom1));
4939 gcond *last2 = as_a <gcond *> (*gsi_last_bb (idom2));
4940 bool inverted_p;
4941 if (! cond_stmts_equal_p (last1, vp1->cclhs, vp1->ccrhs,
4942 last2, vp2->cclhs, vp2->ccrhs,
4943 &inverted_p))
4944 return false;
4945
4946 /* Get at true/false controlled edges into the PHI. */
4947 edge te1, te2, fe1, fe2;
4948 if (! extract_true_false_controlled_edges (idom1, vp1->block,
4949 &te1, &fe1)
4950 || ! extract_true_false_controlled_edges (idom2, vp2->block,
4951 &te2, &fe2))
4952 return false;
4953
4954 /* Swap edges if the second condition is the inverted of the
4955 first. */
4956 if (inverted_p)
4957 std::swap (te2, fe2);
4958
4959 /* Since we do not know which edge will be executed we have
4960 to be careful when matching VN_TOP. Be conservative and
4961 only match VN_TOP == VN_TOP for now, we could allow
4962 VN_TOP on the not prevailing PHI though. See for example
4963 PR102920. */
4964 if (! expressions_equal_p (vp1->phiargs[te1->dest_idx],
4965 vp2->phiargs[te2->dest_idx], false)
4966 || ! expressions_equal_p (vp1->phiargs[fe1->dest_idx],
4967 vp2->phiargs[fe2->dest_idx], false))
4968 return false;
4969
4970 return true;
4971 }
4972
4973 default:
4974 return false;
4975 }
4976 }
4977
4978 /* If the PHI nodes do not have compatible types
4979 they are not the same. */
4980 if (!types_compatible_p (vp1->type, vp2->type))
4981 return false;
4982
4983 /* Any phi in the same block will have it's arguments in the
4984 same edge order, because of how we store phi nodes. */
4985 unsigned nargs = EDGE_COUNT (vp1->block->preds);
4986 for (unsigned i = 0; i < nargs; ++i)
4987 {
4988 tree phi1op = vp1->phiargs[i];
4989 tree phi2op = vp2->phiargs[i];
4990 if (phi1op == phi2op)
4991 continue;
4992 if (!expressions_equal_p (phi1op, phi2op, false))
4993 return false;
4994 }
4995
4996 return true;
4997 }
4998
4999 /* Lookup PHI in the current hash table, and return the resulting
5000 value number if it exists in the hash table. Return NULL_TREE if
5001 it does not exist in the hash table. */
5002
5003 static tree
5004 vn_phi_lookup (gimple *phi, bool backedges_varying_p)
5005 {
5006 vn_phi_s **slot;
5007 struct vn_phi_s *vp1;
5008 edge e;
5009 edge_iterator ei;
5010
5011 vp1 = XALLOCAVAR (struct vn_phi_s,
5012 sizeof (struct vn_phi_s)
5013 + (gimple_phi_num_args (phi) - 1) * sizeof (tree));
5014
5015 /* Canonicalize the SSA_NAME's to their value number. */
5016 FOR_EACH_EDGE (e, ei, gimple_bb (phi)->preds)
5017 {
5018 tree def = PHI_ARG_DEF_FROM_EDGE (phi, e);
5019 if (TREE_CODE (def) == SSA_NAME
5020 && (!backedges_varying_p || !(e->flags & EDGE_DFS_BACK)))
5021 {
5022 if (!virtual_operand_p (def)
5023 && ssa_undefined_value_p (def, false))
5024 def = VN_TOP;
5025 else
5026 def = SSA_VAL (def);
5027 }
5028 vp1->phiargs[e->dest_idx] = def;
5029 }
5030 vp1->type = TREE_TYPE (gimple_phi_result (phi));
5031 vp1->block = gimple_bb (phi);
5032 /* Extract values of the controlling condition. */
5033 vp1->cclhs = NULL_TREE;
5034 vp1->ccrhs = NULL_TREE;
5035 if (EDGE_COUNT (vp1->block->preds) == 2
5036 && vp1->block->loop_father->header != vp1->block)
5037 {
5038 basic_block idom1 = get_immediate_dominator (CDI_DOMINATORS, vp1->block);
5039 if (EDGE_COUNT (idom1->succs) == 2)
5040 if (gcond *last1 = safe_dyn_cast <gcond *> (*gsi_last_bb (idom1)))
5041 {
5042 /* ??? We want to use SSA_VAL here. But possibly not
5043 allow VN_TOP. */
5044 vp1->cclhs = vn_valueize (gimple_cond_lhs (last1));
5045 vp1->ccrhs = vn_valueize (gimple_cond_rhs (last1));
5046 }
5047 }
5048 vp1->hashcode = vn_phi_compute_hash (vp1);
5049 slot = valid_info->phis->find_slot_with_hash (vp1, vp1->hashcode, NO_INSERT);
5050 if (!slot)
5051 return NULL_TREE;
5052 return (*slot)->result;
5053 }
5054
5055 /* Insert PHI into the current hash table with a value number of
5056 RESULT. */
5057
5058 static vn_phi_t
5059 vn_phi_insert (gimple *phi, tree result, bool backedges_varying_p)
5060 {
5061 vn_phi_s **slot;
5062 vn_phi_t vp1 = (vn_phi_t) obstack_alloc (&vn_tables_obstack,
5063 sizeof (vn_phi_s)
5064 + ((gimple_phi_num_args (phi) - 1)
5065 * sizeof (tree)));
5066 edge e;
5067 edge_iterator ei;
5068
5069 /* Canonicalize the SSA_NAME's to their value number. */
5070 FOR_EACH_EDGE (e, ei, gimple_bb (phi)->preds)
5071 {
5072 tree def = PHI_ARG_DEF_FROM_EDGE (phi, e);
5073 if (TREE_CODE (def) == SSA_NAME
5074 && (!backedges_varying_p || !(e->flags & EDGE_DFS_BACK)))
5075 {
5076 if (!virtual_operand_p (def)
5077 && ssa_undefined_value_p (def, false))
5078 def = VN_TOP;
5079 else
5080 def = SSA_VAL (def);
5081 }
5082 vp1->phiargs[e->dest_idx] = def;
5083 }
5084 vp1->value_id = VN_INFO (result)->value_id;
5085 vp1->type = TREE_TYPE (gimple_phi_result (phi));
5086 vp1->block = gimple_bb (phi);
5087 /* Extract values of the controlling condition. */
5088 vp1->cclhs = NULL_TREE;
5089 vp1->ccrhs = NULL_TREE;
5090 if (EDGE_COUNT (vp1->block->preds) == 2
5091 && vp1->block->loop_father->header != vp1->block)
5092 {
5093 basic_block idom1 = get_immediate_dominator (CDI_DOMINATORS, vp1->block);
5094 if (EDGE_COUNT (idom1->succs) == 2)
5095 if (gcond *last1 = safe_dyn_cast <gcond *> (*gsi_last_bb (idom1)))
5096 {
5097 /* ??? We want to use SSA_VAL here. But possibly not
5098 allow VN_TOP. */
5099 vp1->cclhs = vn_valueize (gimple_cond_lhs (last1));
5100 vp1->ccrhs = vn_valueize (gimple_cond_rhs (last1));
5101 }
5102 }
5103 vp1->result = result;
5104 vp1->hashcode = vn_phi_compute_hash (vp1);
5105
5106 slot = valid_info->phis->find_slot_with_hash (vp1, vp1->hashcode, INSERT);
5107 gcc_assert (!*slot);
5108
5109 *slot = vp1;
5110 vp1->next = last_inserted_phi;
5111 last_inserted_phi = vp1;
5112 return vp1;
5113 }
5114
5115
5116 /* Return true if BB1 is dominated by BB2 taking into account edges
5117 that are not executable. When ALLOW_BACK is false consider not
5118 executable backedges as executable. */
5119
5120 static bool
5121 dominated_by_p_w_unex (basic_block bb1, basic_block bb2, bool allow_back)
5122 {
5123 edge_iterator ei;
5124 edge e;
5125
5126 if (dominated_by_p (CDI_DOMINATORS, bb1, bb2))
5127 return true;
5128
5129 /* Before iterating we'd like to know if there exists a
5130 (executable) path from bb2 to bb1 at all, if not we can
5131 directly return false. For now simply iterate once. */
5132
5133 /* Iterate to the single executable bb1 predecessor. */
5134 if (EDGE_COUNT (bb1->preds) > 1)
5135 {
5136 edge prede = NULL;
5137 FOR_EACH_EDGE (e, ei, bb1->preds)
5138 if ((e->flags & EDGE_EXECUTABLE)
5139 || (!allow_back && (e->flags & EDGE_DFS_BACK)))
5140 {
5141 if (prede)
5142 {
5143 prede = NULL;
5144 break;
5145 }
5146 prede = e;
5147 }
5148 if (prede)
5149 {
5150 bb1 = prede->src;
5151
5152 /* Re-do the dominance check with changed bb1. */
5153 if (dominated_by_p (CDI_DOMINATORS, bb1, bb2))
5154 return true;
5155 }
5156 }
5157
5158 /* Iterate to the single executable bb2 successor. */
5159 if (EDGE_COUNT (bb2->succs) > 1)
5160 {
5161 edge succe = NULL;
5162 FOR_EACH_EDGE (e, ei, bb2->succs)
5163 if ((e->flags & EDGE_EXECUTABLE)
5164 || (!allow_back && (e->flags & EDGE_DFS_BACK)))
5165 {
5166 if (succe)
5167 {
5168 succe = NULL;
5169 break;
5170 }
5171 succe = e;
5172 }
5173 if (succe)
5174 {
5175 /* Verify the reached block is only reached through succe.
5176 If there is only one edge we can spare us the dominator
5177 check and iterate directly. */
5178 if (EDGE_COUNT (succe->dest->preds) > 1)
5179 {
5180 FOR_EACH_EDGE (e, ei, succe->dest->preds)
5181 if (e != succe
5182 && ((e->flags & EDGE_EXECUTABLE)
5183 || (!allow_back && (e->flags & EDGE_DFS_BACK))))
5184 {
5185 succe = NULL;
5186 break;
5187 }
5188 }
5189 if (succe)
5190 {
5191 bb2 = succe->dest;
5192
5193 /* Re-do the dominance check with changed bb2. */
5194 if (dominated_by_p (CDI_DOMINATORS, bb1, bb2))
5195 return true;
5196 }
5197 }
5198 }
5199 /* Iterate to the single successor of bb2 with only a single executable
5200 incoming edge. */
5201 else if (EDGE_COUNT (bb2->succs) == 1
5202 && EDGE_COUNT (single_succ (bb2)->preds) > 1
5203 /* Limit the number of edges we check, we should bring in
5204 context from the iteration and compute the single
5205 executable incoming edge when visiting a block. */
5206 && EDGE_COUNT (single_succ (bb2)->preds) < 8)
5207 {
5208 edge prede = NULL;
5209 FOR_EACH_EDGE (e, ei, single_succ (bb2)->preds)
5210 if ((e->flags & EDGE_EXECUTABLE)
5211 || (!allow_back && (e->flags & EDGE_DFS_BACK)))
5212 {
5213 if (prede)
5214 {
5215 prede = NULL;
5216 break;
5217 }
5218 prede = e;
5219 }
5220 /* We might actually get to a query with BB2 not visited yet when
5221 we're querying for a predicated value. */
5222 if (prede && prede->src == bb2)
5223 {
5224 bb2 = prede->dest;
5225
5226 /* Re-do the dominance check with changed bb2. */
5227 if (dominated_by_p (CDI_DOMINATORS, bb1, bb2))
5228 return true;
5229 }
5230 }
5231
5232 /* We could now iterate updating bb1 / bb2. */
5233 return false;
5234 }
5235
5236 /* Set the value number of FROM to TO, return true if it has changed
5237 as a result. */
5238
5239 static inline bool
5240 set_ssa_val_to (tree from, tree to)
5241 {
5242 vn_ssa_aux_t from_info = VN_INFO (from);
5243 tree currval = from_info->valnum; // SSA_VAL (from)
5244 poly_int64 toff, coff;
5245 bool curr_undefined = false;
5246 bool curr_invariant = false;
5247
5248 /* The only thing we allow as value numbers are ssa_names
5249 and invariants. So assert that here. We don't allow VN_TOP
5250 as visiting a stmt should produce a value-number other than
5251 that.
5252 ??? Still VN_TOP can happen for unreachable code, so force
5253 it to varying in that case. Not all code is prepared to
5254 get VN_TOP on valueization. */
5255 if (to == VN_TOP)
5256 {
5257 /* ??? When iterating and visiting PHI <undef, backedge-value>
5258 for the first time we rightfully get VN_TOP and we need to
5259 preserve that to optimize for example gcc.dg/tree-ssa/ssa-sccvn-2.c.
5260 With SCCVN we were simply lucky we iterated the other PHI
5261 cycles first and thus visited the backedge-value DEF. */
5262 if (currval == VN_TOP)
5263 goto set_and_exit;
5264 if (dump_file && (dump_flags & TDF_DETAILS))
5265 fprintf (dump_file, "Forcing value number to varying on "
5266 "receiving VN_TOP\n");
5267 to = from;
5268 }
5269
5270 gcc_checking_assert (to != NULL_TREE
5271 && ((TREE_CODE (to) == SSA_NAME
5272 && (to == from || SSA_VAL (to) == to))
5273 || is_gimple_min_invariant (to)));
5274
5275 if (from != to)
5276 {
5277 if (currval == from)
5278 {
5279 if (dump_file && (dump_flags & TDF_DETAILS))
5280 {
5281 fprintf (dump_file, "Not changing value number of ");
5282 print_generic_expr (dump_file, from);
5283 fprintf (dump_file, " from VARYING to ");
5284 print_generic_expr (dump_file, to);
5285 fprintf (dump_file, "\n");
5286 }
5287 return false;
5288 }
5289 curr_invariant = is_gimple_min_invariant (currval);
5290 curr_undefined = (TREE_CODE (currval) == SSA_NAME
5291 && !virtual_operand_p (currval)
5292 && ssa_undefined_value_p (currval, false));
5293 if (currval != VN_TOP
5294 && !curr_invariant
5295 && !curr_undefined
5296 && is_gimple_min_invariant (to))
5297 {
5298 if (dump_file && (dump_flags & TDF_DETAILS))
5299 {
5300 fprintf (dump_file, "Forcing VARYING instead of changing "
5301 "value number of ");
5302 print_generic_expr (dump_file, from);
5303 fprintf (dump_file, " from ");
5304 print_generic_expr (dump_file, currval);
5305 fprintf (dump_file, " (non-constant) to ");
5306 print_generic_expr (dump_file, to);
5307 fprintf (dump_file, " (constant)\n");
5308 }
5309 to = from;
5310 }
5311 else if (currval != VN_TOP
5312 && !curr_undefined
5313 && TREE_CODE (to) == SSA_NAME
5314 && !virtual_operand_p (to)
5315 && ssa_undefined_value_p (to, false))
5316 {
5317 if (dump_file && (dump_flags & TDF_DETAILS))
5318 {
5319 fprintf (dump_file, "Forcing VARYING instead of changing "
5320 "value number of ");
5321 print_generic_expr (dump_file, from);
5322 fprintf (dump_file, " from ");
5323 print_generic_expr (dump_file, currval);
5324 fprintf (dump_file, " (non-undefined) to ");
5325 print_generic_expr (dump_file, to);
5326 fprintf (dump_file, " (undefined)\n");
5327 }
5328 to = from;
5329 }
5330 else if (TREE_CODE (to) == SSA_NAME
5331 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (to))
5332 to = from;
5333 }
5334
5335 set_and_exit:
5336 if (dump_file && (dump_flags & TDF_DETAILS))
5337 {
5338 fprintf (dump_file, "Setting value number of ");
5339 print_generic_expr (dump_file, from);
5340 fprintf (dump_file, " to ");
5341 print_generic_expr (dump_file, to);
5342 }
5343
5344 if (currval != to
5345 && !operand_equal_p (currval, to, 0)
5346 /* Different undefined SSA names are not actually different. See
5347 PR82320 for a testcase were we'd otherwise not terminate iteration. */
5348 && !(curr_undefined
5349 && TREE_CODE (to) == SSA_NAME
5350 && !virtual_operand_p (to)
5351 && ssa_undefined_value_p (to, false))
5352 /* ??? For addresses involving volatile objects or types operand_equal_p
5353 does not reliably detect ADDR_EXPRs as equal. We know we are only
5354 getting invariant gimple addresses here, so can use
5355 get_addr_base_and_unit_offset to do this comparison. */
5356 && !(TREE_CODE (currval) == ADDR_EXPR
5357 && TREE_CODE (to) == ADDR_EXPR
5358 && (get_addr_base_and_unit_offset (TREE_OPERAND (currval, 0), &coff)
5359 == get_addr_base_and_unit_offset (TREE_OPERAND (to, 0), &toff))
5360 && known_eq (coff, toff)))
5361 {
5362 if (to != from
5363 && currval != VN_TOP
5364 && !curr_undefined
5365 /* We do not want to allow lattice transitions from one value
5366 to another since that may lead to not terminating iteration
5367 (see PR95049). Since there's no convenient way to check
5368 for the allowed transition of VAL -> PHI (loop entry value,
5369 same on two PHIs, to same PHI result) we restrict the check
5370 to invariants. */
5371 && curr_invariant
5372 && is_gimple_min_invariant (to))
5373 {
5374 if (dump_file && (dump_flags & TDF_DETAILS))
5375 fprintf (dump_file, " forced VARYING");
5376 to = from;
5377 }
5378 if (dump_file && (dump_flags & TDF_DETAILS))
5379 fprintf (dump_file, " (changed)\n");
5380 from_info->valnum = to;
5381 return true;
5382 }
5383 if (dump_file && (dump_flags & TDF_DETAILS))
5384 fprintf (dump_file, "\n");
5385 return false;
5386 }
5387
5388 /* Set all definitions in STMT to value number to themselves.
5389 Return true if a value number changed. */
5390
5391 static bool
5392 defs_to_varying (gimple *stmt)
5393 {
5394 bool changed = false;
5395 ssa_op_iter iter;
5396 def_operand_p defp;
5397
5398 FOR_EACH_SSA_DEF_OPERAND (defp, stmt, iter, SSA_OP_ALL_DEFS)
5399 {
5400 tree def = DEF_FROM_PTR (defp);
5401 changed |= set_ssa_val_to (def, def);
5402 }
5403 return changed;
5404 }
5405
5406 /* Visit a copy between LHS and RHS, return true if the value number
5407 changed. */
5408
5409 static bool
5410 visit_copy (tree lhs, tree rhs)
5411 {
5412 /* Valueize. */
5413 rhs = SSA_VAL (rhs);
5414
5415 return set_ssa_val_to (lhs, rhs);
5416 }
5417
5418 /* Lookup a value for OP in type WIDE_TYPE where the value in type of OP
5419 is the same. */
5420
5421 static tree
5422 valueized_wider_op (tree wide_type, tree op, bool allow_truncate)
5423 {
5424 if (TREE_CODE (op) == SSA_NAME)
5425 op = vn_valueize (op);
5426
5427 /* Either we have the op widened available. */
5428 tree ops[3] = {};
5429 ops[0] = op;
5430 tree tem = vn_nary_op_lookup_pieces (1, NOP_EXPR,
5431 wide_type, ops, NULL);
5432 if (tem)
5433 return tem;
5434
5435 /* Or the op is truncated from some existing value. */
5436 if (allow_truncate && TREE_CODE (op) == SSA_NAME)
5437 {
5438 gimple *def = SSA_NAME_DEF_STMT (op);
5439 if (is_gimple_assign (def)
5440 && CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def)))
5441 {
5442 tem = gimple_assign_rhs1 (def);
5443 if (useless_type_conversion_p (wide_type, TREE_TYPE (tem)))
5444 {
5445 if (TREE_CODE (tem) == SSA_NAME)
5446 tem = vn_valueize (tem);
5447 return tem;
5448 }
5449 }
5450 }
5451
5452 /* For constants simply extend it. */
5453 if (TREE_CODE (op) == INTEGER_CST)
5454 return wide_int_to_tree (wide_type, wi::to_widest (op));
5455
5456 return NULL_TREE;
5457 }
5458
5459 /* Visit a nary operator RHS, value number it, and return true if the
5460 value number of LHS has changed as a result. */
5461
5462 static bool
5463 visit_nary_op (tree lhs, gassign *stmt)
5464 {
5465 vn_nary_op_t vnresult;
5466 tree result = vn_nary_op_lookup_stmt (stmt, &vnresult);
5467 if (! result && vnresult)
5468 result = vn_nary_op_get_predicated_value (vnresult, gimple_bb (stmt));
5469 if (result)
5470 return set_ssa_val_to (lhs, result);
5471
5472 /* Do some special pattern matching for redundancies of operations
5473 in different types. */
5474 enum tree_code code = gimple_assign_rhs_code (stmt);
5475 tree type = TREE_TYPE (lhs);
5476 tree rhs1 = gimple_assign_rhs1 (stmt);
5477 switch (code)
5478 {
5479 CASE_CONVERT:
5480 /* Match arithmetic done in a different type where we can easily
5481 substitute the result from some earlier sign-changed or widened
5482 operation. */
5483 if (INTEGRAL_TYPE_P (type)
5484 && TREE_CODE (rhs1) == SSA_NAME
5485 /* We only handle sign-changes, zero-extension -> & mask or
5486 sign-extension if we know the inner operation doesn't
5487 overflow. */
5488 && (((TYPE_UNSIGNED (TREE_TYPE (rhs1))
5489 || (INTEGRAL_TYPE_P (TREE_TYPE (rhs1))
5490 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (rhs1))))
5491 && TYPE_PRECISION (type) > TYPE_PRECISION (TREE_TYPE (rhs1)))
5492 || TYPE_PRECISION (type) == TYPE_PRECISION (TREE_TYPE (rhs1))))
5493 {
5494 gassign *def = dyn_cast <gassign *> (SSA_NAME_DEF_STMT (rhs1));
5495 if (def
5496 && (gimple_assign_rhs_code (def) == PLUS_EXPR
5497 || gimple_assign_rhs_code (def) == MINUS_EXPR
5498 || gimple_assign_rhs_code (def) == MULT_EXPR))
5499 {
5500 tree ops[3] = {};
5501 /* When requiring a sign-extension we cannot model a
5502 previous truncation with a single op so don't bother. */
5503 bool allow_truncate = TYPE_UNSIGNED (TREE_TYPE (rhs1));
5504 /* Either we have the op widened available. */
5505 ops[0] = valueized_wider_op (type, gimple_assign_rhs1 (def),
5506 allow_truncate);
5507 if (ops[0])
5508 ops[1] = valueized_wider_op (type, gimple_assign_rhs2 (def),
5509 allow_truncate);
5510 if (ops[0] && ops[1])
5511 {
5512 ops[0] = vn_nary_op_lookup_pieces
5513 (2, gimple_assign_rhs_code (def), type, ops, NULL);
5514 /* We have wider operation available. */
5515 if (ops[0]
5516 /* If the leader is a wrapping operation we can
5517 insert it for code hoisting w/o introducing
5518 undefined overflow. If it is not it has to
5519 be available. See PR86554. */
5520 && (TYPE_OVERFLOW_WRAPS (TREE_TYPE (ops[0]))
5521 || (rpo_avail && vn_context_bb
5522 && rpo_avail->eliminate_avail (vn_context_bb,
5523 ops[0]))))
5524 {
5525 unsigned lhs_prec = TYPE_PRECISION (type);
5526 unsigned rhs_prec = TYPE_PRECISION (TREE_TYPE (rhs1));
5527 if (lhs_prec == rhs_prec
5528 || (INTEGRAL_TYPE_P (TREE_TYPE (rhs1))
5529 && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (rhs1))))
5530 {
5531 gimple_match_op match_op (gimple_match_cond::UNCOND,
5532 NOP_EXPR, type, ops[0]);
5533 result = vn_nary_build_or_lookup (&match_op);
5534 if (result)
5535 {
5536 bool changed = set_ssa_val_to (lhs, result);
5537 vn_nary_op_insert_stmt (stmt, result);
5538 return changed;
5539 }
5540 }
5541 else
5542 {
5543 tree mask = wide_int_to_tree
5544 (type, wi::mask (rhs_prec, false, lhs_prec));
5545 gimple_match_op match_op (gimple_match_cond::UNCOND,
5546 BIT_AND_EXPR,
5547 TREE_TYPE (lhs),
5548 ops[0], mask);
5549 result = vn_nary_build_or_lookup (&match_op);
5550 if (result)
5551 {
5552 bool changed = set_ssa_val_to (lhs, result);
5553 vn_nary_op_insert_stmt (stmt, result);
5554 return changed;
5555 }
5556 }
5557 }
5558 }
5559 }
5560 }
5561 break;
5562 case BIT_AND_EXPR:
5563 if (INTEGRAL_TYPE_P (type)
5564 && TREE_CODE (rhs1) == SSA_NAME
5565 && TREE_CODE (gimple_assign_rhs2 (stmt)) == INTEGER_CST
5566 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (rhs1)
5567 && default_vn_walk_kind != VN_NOWALK
5568 && CHAR_BIT == 8
5569 && BITS_PER_UNIT == 8
5570 && BYTES_BIG_ENDIAN == WORDS_BIG_ENDIAN
5571 && TYPE_PRECISION (type) <= vn_walk_cb_data::bufsize * BITS_PER_UNIT
5572 && !integer_all_onesp (gimple_assign_rhs2 (stmt))
5573 && !integer_zerop (gimple_assign_rhs2 (stmt)))
5574 {
5575 gassign *ass = dyn_cast <gassign *> (SSA_NAME_DEF_STMT (rhs1));
5576 if (ass
5577 && !gimple_has_volatile_ops (ass)
5578 && vn_get_stmt_kind (ass) == VN_REFERENCE)
5579 {
5580 tree last_vuse = gimple_vuse (ass);
5581 tree op = gimple_assign_rhs1 (ass);
5582 tree result = vn_reference_lookup (op, gimple_vuse (ass),
5583 default_vn_walk_kind,
5584 NULL, true, &last_vuse,
5585 gimple_assign_rhs2 (stmt));
5586 if (result
5587 && useless_type_conversion_p (TREE_TYPE (result),
5588 TREE_TYPE (op)))
5589 return set_ssa_val_to (lhs, result);
5590 }
5591 }
5592 break;
5593 case TRUNC_DIV_EXPR:
5594 if (TYPE_UNSIGNED (type))
5595 break;
5596 /* Fallthru. */
5597 case RDIV_EXPR:
5598 case MULT_EXPR:
5599 /* Match up ([-]a){/,*}([-])b with v=a{/,*}b, replacing it with -v. */
5600 if (! HONOR_SIGN_DEPENDENT_ROUNDING (type))
5601 {
5602 tree rhs[2];
5603 rhs[0] = rhs1;
5604 rhs[1] = gimple_assign_rhs2 (stmt);
5605 for (unsigned i = 0; i <= 1; ++i)
5606 {
5607 unsigned j = i == 0 ? 1 : 0;
5608 tree ops[2];
5609 gimple_match_op match_op (gimple_match_cond::UNCOND,
5610 NEGATE_EXPR, type, rhs[i]);
5611 ops[i] = vn_nary_build_or_lookup_1 (&match_op, false, true);
5612 ops[j] = rhs[j];
5613 if (ops[i]
5614 && (ops[0] = vn_nary_op_lookup_pieces (2, code,
5615 type, ops, NULL)))
5616 {
5617 gimple_match_op match_op (gimple_match_cond::UNCOND,
5618 NEGATE_EXPR, type, ops[0]);
5619 result = vn_nary_build_or_lookup_1 (&match_op, true, false);
5620 if (result)
5621 {
5622 bool changed = set_ssa_val_to (lhs, result);
5623 vn_nary_op_insert_stmt (stmt, result);
5624 return changed;
5625 }
5626 }
5627 }
5628 }
5629 break;
5630 case LSHIFT_EXPR:
5631 /* For X << C, use the value number of X * (1 << C). */
5632 if (INTEGRAL_TYPE_P (type)
5633 && TYPE_OVERFLOW_WRAPS (type)
5634 && !TYPE_SATURATING (type))
5635 {
5636 tree rhs2 = gimple_assign_rhs2 (stmt);
5637 if (TREE_CODE (rhs2) == INTEGER_CST
5638 && tree_fits_uhwi_p (rhs2)
5639 && tree_to_uhwi (rhs2) < TYPE_PRECISION (type))
5640 {
5641 wide_int w = wi::set_bit_in_zero (tree_to_uhwi (rhs2),
5642 TYPE_PRECISION (type));
5643 gimple_match_op match_op (gimple_match_cond::UNCOND,
5644 MULT_EXPR, type, rhs1,
5645 wide_int_to_tree (type, w));
5646 result = vn_nary_build_or_lookup (&match_op);
5647 if (result)
5648 {
5649 bool changed = set_ssa_val_to (lhs, result);
5650 if (TREE_CODE (result) == SSA_NAME)
5651 vn_nary_op_insert_stmt (stmt, result);
5652 return changed;
5653 }
5654 }
5655 }
5656 break;
5657 default:
5658 break;
5659 }
5660
5661 bool changed = set_ssa_val_to (lhs, lhs);
5662 vn_nary_op_insert_stmt (stmt, lhs);
5663 return changed;
5664 }
5665
5666 /* Visit a call STMT storing into LHS. Return true if the value number
5667 of the LHS has changed as a result. */
5668
5669 static bool
5670 visit_reference_op_call (tree lhs, gcall *stmt)
5671 {
5672 bool changed = false;
5673 struct vn_reference_s vr1;
5674 vn_reference_t vnresult = NULL;
5675 tree vdef = gimple_vdef (stmt);
5676 modref_summary *summary;
5677
5678 /* Non-ssa lhs is handled in copy_reference_ops_from_call. */
5679 if (lhs && TREE_CODE (lhs) != SSA_NAME)
5680 lhs = NULL_TREE;
5681
5682 vn_reference_lookup_call (stmt, &vnresult, &vr1);
5683
5684 /* If the lookup did not succeed for pure functions try to use
5685 modref info to find a candidate to CSE to. */
5686 const unsigned accesses_limit = 8;
5687 if (!vnresult
5688 && !vdef
5689 && lhs
5690 && gimple_vuse (stmt)
5691 && (((summary = get_modref_function_summary (stmt, NULL))
5692 && !summary->global_memory_read
5693 && summary->load_accesses < accesses_limit)
5694 || gimple_call_flags (stmt) & ECF_CONST))
5695 {
5696 /* First search if we can do someting useful and build a
5697 vector of all loads we have to check. */
5698 bool unknown_memory_access = false;
5699 auto_vec<ao_ref, accesses_limit> accesses;
5700 unsigned load_accesses = summary ? summary->load_accesses : 0;
5701 if (!unknown_memory_access)
5702 /* Add loads done as part of setting up the call arguments.
5703 That's also necessary for CONST functions which will
5704 not have a modref summary. */
5705 for (unsigned i = 0; i < gimple_call_num_args (stmt); ++i)
5706 {
5707 tree arg = gimple_call_arg (stmt, i);
5708 if (TREE_CODE (arg) != SSA_NAME
5709 && !is_gimple_min_invariant (arg))
5710 {
5711 if (accesses.length () >= accesses_limit - load_accesses)
5712 {
5713 unknown_memory_access = true;
5714 break;
5715 }
5716 accesses.quick_grow (accesses.length () + 1);
5717 ao_ref_init (&accesses.last (), arg);
5718 }
5719 }
5720 if (summary && !unknown_memory_access)
5721 {
5722 /* Add loads as analyzed by IPA modref. */
5723 for (auto base_node : summary->loads->bases)
5724 if (unknown_memory_access)
5725 break;
5726 else for (auto ref_node : base_node->refs)
5727 if (unknown_memory_access)
5728 break;
5729 else for (auto access_node : ref_node->accesses)
5730 {
5731 accesses.quick_grow (accesses.length () + 1);
5732 ao_ref *r = &accesses.last ();
5733 if (!access_node.get_ao_ref (stmt, r))
5734 {
5735 /* Initialize a ref based on the argument and
5736 unknown offset if possible. */
5737 tree arg = access_node.get_call_arg (stmt);
5738 if (arg && TREE_CODE (arg) == SSA_NAME)
5739 arg = SSA_VAL (arg);
5740 if (arg
5741 && TREE_CODE (arg) == ADDR_EXPR
5742 && (arg = get_base_address (arg))
5743 && DECL_P (arg))
5744 {
5745 ao_ref_init (r, arg);
5746 r->ref = NULL_TREE;
5747 r->base = arg;
5748 }
5749 else
5750 {
5751 unknown_memory_access = true;
5752 break;
5753 }
5754 }
5755 r->base_alias_set = base_node->base;
5756 r->ref_alias_set = ref_node->ref;
5757 }
5758 }
5759
5760 /* Walk the VUSE->VDEF chain optimistically trying to find an entry
5761 for the call in the hashtable. */
5762 unsigned limit = (unknown_memory_access
5763 ? 0
5764 : (param_sccvn_max_alias_queries_per_access
5765 / (accesses.length () + 1)));
5766 tree saved_vuse = vr1.vuse;
5767 hashval_t saved_hashcode = vr1.hashcode;
5768 while (limit > 0 && !vnresult && !SSA_NAME_IS_DEFAULT_DEF (vr1.vuse))
5769 {
5770 vr1.hashcode = vr1.hashcode - SSA_NAME_VERSION (vr1.vuse);
5771 gimple *def = SSA_NAME_DEF_STMT (vr1.vuse);
5772 /* ??? We could use fancy stuff like in walk_non_aliased_vuses, but
5773 do not bother for now. */
5774 if (is_a <gphi *> (def))
5775 break;
5776 vr1.vuse = vuse_ssa_val (gimple_vuse (def));
5777 vr1.hashcode = vr1.hashcode + SSA_NAME_VERSION (vr1.vuse);
5778 vn_reference_lookup_1 (&vr1, &vnresult);
5779 limit--;
5780 }
5781
5782 /* If we found a candidate to CSE to verify it is valid. */
5783 if (vnresult && !accesses.is_empty ())
5784 {
5785 tree vuse = vuse_ssa_val (gimple_vuse (stmt));
5786 while (vnresult && vuse != vr1.vuse)
5787 {
5788 gimple *def = SSA_NAME_DEF_STMT (vuse);
5789 for (auto &ref : accesses)
5790 {
5791 /* ??? stmt_may_clobber_ref_p_1 does per stmt constant
5792 analysis overhead that we might be able to cache. */
5793 if (stmt_may_clobber_ref_p_1 (def, &ref, true))
5794 {
5795 vnresult = NULL;
5796 break;
5797 }
5798 }
5799 vuse = vuse_ssa_val (gimple_vuse (def));
5800 }
5801 }
5802 vr1.vuse = saved_vuse;
5803 vr1.hashcode = saved_hashcode;
5804 }
5805
5806 if (vnresult)
5807 {
5808 if (vdef)
5809 {
5810 if (vnresult->result_vdef)
5811 changed |= set_ssa_val_to (vdef, vnresult->result_vdef);
5812 else if (!lhs && gimple_call_lhs (stmt))
5813 /* If stmt has non-SSA_NAME lhs, value number the vdef to itself,
5814 as the call still acts as a lhs store. */
5815 changed |= set_ssa_val_to (vdef, vdef);
5816 else
5817 /* If the call was discovered to be pure or const reflect
5818 that as far as possible. */
5819 changed |= set_ssa_val_to (vdef,
5820 vuse_ssa_val (gimple_vuse (stmt)));
5821 }
5822
5823 if (!vnresult->result && lhs)
5824 vnresult->result = lhs;
5825
5826 if (vnresult->result && lhs)
5827 changed |= set_ssa_val_to (lhs, vnresult->result);
5828 }
5829 else
5830 {
5831 vn_reference_t vr2;
5832 vn_reference_s **slot;
5833 tree vdef_val = vdef;
5834 if (vdef)
5835 {
5836 /* If we value numbered an indirect functions function to
5837 one not clobbering memory value number its VDEF to its
5838 VUSE. */
5839 tree fn = gimple_call_fn (stmt);
5840 if (fn && TREE_CODE (fn) == SSA_NAME)
5841 {
5842 fn = SSA_VAL (fn);
5843 if (TREE_CODE (fn) == ADDR_EXPR
5844 && TREE_CODE (TREE_OPERAND (fn, 0)) == FUNCTION_DECL
5845 && (flags_from_decl_or_type (TREE_OPERAND (fn, 0))
5846 & (ECF_CONST | ECF_PURE))
5847 /* If stmt has non-SSA_NAME lhs, value number the
5848 vdef to itself, as the call still acts as a lhs
5849 store. */
5850 && (lhs || gimple_call_lhs (stmt) == NULL_TREE))
5851 vdef_val = vuse_ssa_val (gimple_vuse (stmt));
5852 }
5853 changed |= set_ssa_val_to (vdef, vdef_val);
5854 }
5855 if (lhs)
5856 changed |= set_ssa_val_to (lhs, lhs);
5857 vr2 = XOBNEW (&vn_tables_obstack, vn_reference_s);
5858 vr2->vuse = vr1.vuse;
5859 /* As we are not walking the virtual operand chain we know the
5860 shared_lookup_references are still original so we can re-use
5861 them here. */
5862 vr2->operands = vr1.operands.copy ();
5863 vr2->type = vr1.type;
5864 vr2->punned = vr1.punned;
5865 vr2->set = vr1.set;
5866 vr2->offset = vr1.offset;
5867 vr2->max_size = vr1.max_size;
5868 vr2->base_set = vr1.base_set;
5869 vr2->hashcode = vr1.hashcode;
5870 vr2->result = lhs;
5871 vr2->result_vdef = vdef_val;
5872 vr2->value_id = 0;
5873 slot = valid_info->references->find_slot_with_hash (vr2, vr2->hashcode,
5874 INSERT);
5875 gcc_assert (!*slot);
5876 *slot = vr2;
5877 vr2->next = last_inserted_ref;
5878 last_inserted_ref = vr2;
5879 }
5880
5881 return changed;
5882 }
5883
5884 /* Visit a load from a reference operator RHS, part of STMT, value number it,
5885 and return true if the value number of the LHS has changed as a result. */
5886
5887 static bool
5888 visit_reference_op_load (tree lhs, tree op, gimple *stmt)
5889 {
5890 bool changed = false;
5891 tree result;
5892 vn_reference_t res;
5893
5894 tree vuse = gimple_vuse (stmt);
5895 tree last_vuse = vuse;
5896 result = vn_reference_lookup (op, vuse, default_vn_walk_kind, &res, true, &last_vuse);
5897
5898 /* We handle type-punning through unions by value-numbering based
5899 on offset and size of the access. Be prepared to handle a
5900 type-mismatch here via creating a VIEW_CONVERT_EXPR. */
5901 if (result
5902 && !useless_type_conversion_p (TREE_TYPE (result), TREE_TYPE (op)))
5903 {
5904 if (CONSTANT_CLASS_P (result))
5905 result = const_unop (VIEW_CONVERT_EXPR, TREE_TYPE (op), result);
5906 else
5907 {
5908 /* We will be setting the value number of lhs to the value number
5909 of VIEW_CONVERT_EXPR <TREE_TYPE (result)> (result).
5910 So first simplify and lookup this expression to see if it
5911 is already available. */
5912 gimple_match_op res_op (gimple_match_cond::UNCOND,
5913 VIEW_CONVERT_EXPR, TREE_TYPE (op), result);
5914 result = vn_nary_build_or_lookup (&res_op);
5915 if (result
5916 && TREE_CODE (result) == SSA_NAME
5917 && VN_INFO (result)->needs_insertion)
5918 /* Track whether this is the canonical expression for different
5919 typed loads. We use that as a stopgap measure for code
5920 hoisting when dealing with floating point loads. */
5921 res->punned = true;
5922 }
5923
5924 /* When building the conversion fails avoid inserting the reference
5925 again. */
5926 if (!result)
5927 return set_ssa_val_to (lhs, lhs);
5928 }
5929
5930 if (result)
5931 changed = set_ssa_val_to (lhs, result);
5932 else
5933 {
5934 changed = set_ssa_val_to (lhs, lhs);
5935 vn_reference_insert (op, lhs, last_vuse, NULL_TREE);
5936 if (vuse && SSA_VAL (last_vuse) != SSA_VAL (vuse))
5937 {
5938 if (dump_file && (dump_flags & TDF_DETAILS))
5939 {
5940 fprintf (dump_file, "Using extra use virtual operand ");
5941 print_generic_expr (dump_file, last_vuse);
5942 fprintf (dump_file, "\n");
5943 }
5944 vn_reference_insert (op, lhs, vuse, NULL_TREE);
5945 }
5946 }
5947
5948 return changed;
5949 }
5950
5951
5952 /* Visit a store to a reference operator LHS, part of STMT, value number it,
5953 and return true if the value number of the LHS has changed as a result. */
5954
5955 static bool
5956 visit_reference_op_store (tree lhs, tree op, gimple *stmt)
5957 {
5958 bool changed = false;
5959 vn_reference_t vnresult = NULL;
5960 tree assign;
5961 bool resultsame = false;
5962 tree vuse = gimple_vuse (stmt);
5963 tree vdef = gimple_vdef (stmt);
5964
5965 if (TREE_CODE (op) == SSA_NAME)
5966 op = SSA_VAL (op);
5967
5968 /* First we want to lookup using the *vuses* from the store and see
5969 if there the last store to this location with the same address
5970 had the same value.
5971
5972 The vuses represent the memory state before the store. If the
5973 memory state, address, and value of the store is the same as the
5974 last store to this location, then this store will produce the
5975 same memory state as that store.
5976
5977 In this case the vdef versions for this store are value numbered to those
5978 vuse versions, since they represent the same memory state after
5979 this store.
5980
5981 Otherwise, the vdefs for the store are used when inserting into
5982 the table, since the store generates a new memory state. */
5983
5984 vn_reference_lookup (lhs, vuse, VN_NOWALK, &vnresult, false);
5985 if (vnresult
5986 && vnresult->result)
5987 {
5988 tree result = vnresult->result;
5989 gcc_checking_assert (TREE_CODE (result) != SSA_NAME
5990 || result == SSA_VAL (result));
5991 resultsame = expressions_equal_p (result, op);
5992 if (resultsame)
5993 {
5994 /* If the TBAA state isn't compatible for downstream reads
5995 we cannot value-number the VDEFs the same. */
5996 ao_ref lhs_ref;
5997 ao_ref_init (&lhs_ref, lhs);
5998 alias_set_type set = ao_ref_alias_set (&lhs_ref);
5999 alias_set_type base_set = ao_ref_base_alias_set (&lhs_ref);
6000 if ((vnresult->set != set
6001 && ! alias_set_subset_of (set, vnresult->set))
6002 || (vnresult->base_set != base_set
6003 && ! alias_set_subset_of (base_set, vnresult->base_set)))
6004 resultsame = false;
6005 }
6006 }
6007
6008 if (!resultsame)
6009 {
6010 if (dump_file && (dump_flags & TDF_DETAILS))
6011 {
6012 fprintf (dump_file, "No store match\n");
6013 fprintf (dump_file, "Value numbering store ");
6014 print_generic_expr (dump_file, lhs);
6015 fprintf (dump_file, " to ");
6016 print_generic_expr (dump_file, op);
6017 fprintf (dump_file, "\n");
6018 }
6019 /* Have to set value numbers before insert, since insert is
6020 going to valueize the references in-place. */
6021 if (vdef)
6022 changed |= set_ssa_val_to (vdef, vdef);
6023
6024 /* Do not insert structure copies into the tables. */
6025 if (is_gimple_min_invariant (op)
6026 || is_gimple_reg (op))
6027 vn_reference_insert (lhs, op, vdef, NULL);
6028
6029 /* Only perform the following when being called from PRE
6030 which embeds tail merging. */
6031 if (default_vn_walk_kind == VN_WALK)
6032 {
6033 assign = build2 (MODIFY_EXPR, TREE_TYPE (lhs), lhs, op);
6034 vn_reference_lookup (assign, vuse, VN_NOWALK, &vnresult, false);
6035 if (!vnresult)
6036 vn_reference_insert (assign, lhs, vuse, vdef);
6037 }
6038 }
6039 else
6040 {
6041 /* We had a match, so value number the vdef to have the value
6042 number of the vuse it came from. */
6043
6044 if (dump_file && (dump_flags & TDF_DETAILS))
6045 fprintf (dump_file, "Store matched earlier value, "
6046 "value numbering store vdefs to matching vuses.\n");
6047
6048 changed |= set_ssa_val_to (vdef, SSA_VAL (vuse));
6049 }
6050
6051 return changed;
6052 }
6053
6054 /* Visit and value number PHI, return true if the value number
6055 changed. When BACKEDGES_VARYING_P is true then assume all
6056 backedge values are varying. When INSERTED is not NULL then
6057 this is just a ahead query for a possible iteration, set INSERTED
6058 to true if we'd insert into the hashtable. */
6059
6060 static bool
6061 visit_phi (gimple *phi, bool *inserted, bool backedges_varying_p)
6062 {
6063 tree result, sameval = VN_TOP, seen_undef = NULL_TREE;
6064 bool seen_undef_visited = false;
6065 tree backedge_val = NULL_TREE;
6066 bool seen_non_backedge = false;
6067 tree sameval_base = NULL_TREE;
6068 poly_int64 soff, doff;
6069 unsigned n_executable = 0;
6070 edge sameval_e = NULL;
6071
6072 /* TODO: We could check for this in initialization, and replace this
6073 with a gcc_assert. */
6074 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (PHI_RESULT (phi)))
6075 return set_ssa_val_to (PHI_RESULT (phi), PHI_RESULT (phi));
6076
6077 /* We track whether a PHI was CSEd to avoid excessive iterations
6078 that would be necessary only because the PHI changed arguments
6079 but not value. */
6080 if (!inserted)
6081 gimple_set_plf (phi, GF_PLF_1, false);
6082
6083 basic_block bb = gimple_bb (phi);
6084
6085 /* For the equivalence handling below make sure to first process an
6086 edge with a non-constant. */
6087 auto_vec<edge, 2> preds;
6088 preds.reserve_exact (EDGE_COUNT (bb->preds));
6089 bool seen_nonconstant = false;
6090 for (unsigned i = 0; i < EDGE_COUNT (bb->preds); ++i)
6091 {
6092 edge e = EDGE_PRED (bb, i);
6093 preds.quick_push (e);
6094 if (!seen_nonconstant)
6095 {
6096 tree def = PHI_ARG_DEF_FROM_EDGE (phi, e);
6097 if (TREE_CODE (def) == SSA_NAME)
6098 {
6099 seen_nonconstant = true;
6100 if (i != 0)
6101 std::swap (preds[0], preds[i]);
6102 }
6103 }
6104 }
6105
6106 /* See if all non-TOP arguments have the same value. TOP is
6107 equivalent to everything, so we can ignore it. */
6108 for (edge e : preds)
6109 if (e->flags & EDGE_EXECUTABLE)
6110 {
6111 tree def = PHI_ARG_DEF_FROM_EDGE (phi, e);
6112
6113 if (def == PHI_RESULT (phi))
6114 continue;
6115 ++n_executable;
6116 bool visited = true;
6117 if (TREE_CODE (def) == SSA_NAME)
6118 {
6119 tree val = SSA_VAL (def, &visited);
6120 if (SSA_NAME_IS_DEFAULT_DEF (def))
6121 visited = true;
6122 if (!backedges_varying_p || !(e->flags & EDGE_DFS_BACK))
6123 def = val;
6124 if (e->flags & EDGE_DFS_BACK)
6125 backedge_val = def;
6126 }
6127 if (!(e->flags & EDGE_DFS_BACK))
6128 seen_non_backedge = true;
6129 if (def == VN_TOP)
6130 ;
6131 /* Ignore undefined defs for sameval but record one. */
6132 else if (TREE_CODE (def) == SSA_NAME
6133 && ! virtual_operand_p (def)
6134 && ssa_undefined_value_p (def, false))
6135 {
6136 if (!seen_undef
6137 /* Avoid having not visited undefined defs if we also have
6138 a visited one. */
6139 || (!seen_undef_visited && visited))
6140 {
6141 seen_undef = def;
6142 seen_undef_visited = visited;
6143 }
6144 }
6145 else if (sameval == VN_TOP)
6146 {
6147 sameval = def;
6148 sameval_e = e;
6149 }
6150 else if (expressions_equal_p (def, sameval))
6151 sameval_e = NULL;
6152 else if (virtual_operand_p (def))
6153 {
6154 sameval = NULL_TREE;
6155 break;
6156 }
6157 else
6158 {
6159 /* We know we're arriving only with invariant addresses here,
6160 try harder comparing them. We can do some caching here
6161 which we cannot do in expressions_equal_p. */
6162 if (TREE_CODE (def) == ADDR_EXPR
6163 && TREE_CODE (sameval) == ADDR_EXPR
6164 && sameval_base != (void *)-1)
6165 {
6166 if (!sameval_base)
6167 sameval_base = get_addr_base_and_unit_offset
6168 (TREE_OPERAND (sameval, 0), &soff);
6169 if (!sameval_base)
6170 sameval_base = (tree)(void *)-1;
6171 else if ((get_addr_base_and_unit_offset
6172 (TREE_OPERAND (def, 0), &doff) == sameval_base)
6173 && known_eq (soff, doff))
6174 continue;
6175 }
6176 /* There's also the possibility to use equivalences. */
6177 if (!FLOAT_TYPE_P (TREE_TYPE (def))
6178 /* But only do this if we didn't force any of sameval or
6179 val to VARYING because of backedge processing rules. */
6180 && (TREE_CODE (sameval) != SSA_NAME
6181 || SSA_VAL (sameval) == sameval)
6182 && (TREE_CODE (def) != SSA_NAME || SSA_VAL (def) == def))
6183 {
6184 vn_nary_op_t vnresult;
6185 tree ops[2];
6186 ops[0] = def;
6187 ops[1] = sameval;
6188 /* Canonicalize the operands order for eq below. */
6189 if (tree_swap_operands_p (ops[0], ops[1]))
6190 std::swap (ops[0], ops[1]);
6191 tree val = vn_nary_op_lookup_pieces (2, EQ_EXPR,
6192 boolean_type_node,
6193 ops, &vnresult);
6194 if (! val && vnresult && vnresult->predicated_values)
6195 {
6196 val = vn_nary_op_get_predicated_value (vnresult, e);
6197 if (val && integer_truep (val)
6198 && !(sameval_e && (sameval_e->flags & EDGE_DFS_BACK)))
6199 {
6200 if (dump_file && (dump_flags & TDF_DETAILS))
6201 {
6202 fprintf (dump_file, "Predication says ");
6203 print_generic_expr (dump_file, def, TDF_NONE);
6204 fprintf (dump_file, " and ");
6205 print_generic_expr (dump_file, sameval, TDF_NONE);
6206 fprintf (dump_file, " are equal on edge %d -> %d\n",
6207 e->src->index, e->dest->index);
6208 }
6209 continue;
6210 }
6211 }
6212 }
6213 sameval = NULL_TREE;
6214 break;
6215 }
6216 }
6217
6218 /* If the value we want to use is flowing over the backedge and we
6219 should take it as VARYING but it has a non-VARYING value drop to
6220 VARYING.
6221 If we value-number a virtual operand never value-number to the
6222 value from the backedge as that confuses the alias-walking code.
6223 See gcc.dg/torture/pr87176.c. If the value is the same on a
6224 non-backedge everything is OK though. */
6225 bool visited_p;
6226 if ((backedge_val
6227 && !seen_non_backedge
6228 && TREE_CODE (backedge_val) == SSA_NAME
6229 && sameval == backedge_val
6230 && (SSA_NAME_IS_VIRTUAL_OPERAND (backedge_val)
6231 || SSA_VAL (backedge_val) != backedge_val))
6232 /* Do not value-number a virtual operand to sth not visited though
6233 given that allows us to escape a region in alias walking. */
6234 || (sameval
6235 && TREE_CODE (sameval) == SSA_NAME
6236 && !SSA_NAME_IS_DEFAULT_DEF (sameval)
6237 && SSA_NAME_IS_VIRTUAL_OPERAND (sameval)
6238 && (SSA_VAL (sameval, &visited_p), !visited_p)))
6239 /* Note this just drops to VARYING without inserting the PHI into
6240 the hashes. */
6241 result = PHI_RESULT (phi);
6242 /* If none of the edges was executable keep the value-number at VN_TOP,
6243 if only a single edge is exectuable use its value. */
6244 else if (n_executable <= 1)
6245 result = seen_undef ? seen_undef : sameval;
6246 /* If we saw only undefined values and VN_TOP use one of the
6247 undefined values. */
6248 else if (sameval == VN_TOP)
6249 result = (seen_undef && seen_undef_visited) ? seen_undef : sameval;
6250 /* First see if it is equivalent to a phi node in this block. We prefer
6251 this as it allows IV elimination - see PRs 66502 and 67167. */
6252 else if ((result = vn_phi_lookup (phi, backedges_varying_p)))
6253 {
6254 if (!inserted
6255 && TREE_CODE (result) == SSA_NAME
6256 && gimple_code (SSA_NAME_DEF_STMT (result)) == GIMPLE_PHI)
6257 {
6258 gimple_set_plf (SSA_NAME_DEF_STMT (result), GF_PLF_1, true);
6259 if (dump_file && (dump_flags & TDF_DETAILS))
6260 {
6261 fprintf (dump_file, "Marking CSEd to PHI node ");
6262 print_gimple_expr (dump_file, SSA_NAME_DEF_STMT (result),
6263 0, TDF_SLIM);
6264 fprintf (dump_file, "\n");
6265 }
6266 }
6267 }
6268 /* If all values are the same use that, unless we've seen undefined
6269 values as well and the value isn't constant.
6270 CCP/copyprop have the same restriction to not remove uninit warnings. */
6271 else if (sameval
6272 && (! seen_undef || is_gimple_min_invariant (sameval)))
6273 result = sameval;
6274 else
6275 {
6276 result = PHI_RESULT (phi);
6277 /* Only insert PHIs that are varying, for constant value numbers
6278 we mess up equivalences otherwise as we are only comparing
6279 the immediate controlling predicates. */
6280 vn_phi_insert (phi, result, backedges_varying_p);
6281 if (inserted)
6282 *inserted = true;
6283 }
6284
6285 return set_ssa_val_to (PHI_RESULT (phi), result);
6286 }
6287
6288 /* Try to simplify RHS using equivalences and constant folding. */
6289
6290 static tree
6291 try_to_simplify (gassign *stmt)
6292 {
6293 enum tree_code code = gimple_assign_rhs_code (stmt);
6294 tree tem;
6295
6296 /* For stores we can end up simplifying a SSA_NAME rhs. Just return
6297 in this case, there is no point in doing extra work. */
6298 if (code == SSA_NAME)
6299 return NULL_TREE;
6300
6301 /* First try constant folding based on our current lattice. */
6302 mprts_hook = vn_lookup_simplify_result;
6303 tem = gimple_fold_stmt_to_constant_1 (stmt, vn_valueize, vn_valueize);
6304 mprts_hook = NULL;
6305 if (tem
6306 && (TREE_CODE (tem) == SSA_NAME
6307 || is_gimple_min_invariant (tem)))
6308 return tem;
6309
6310 return NULL_TREE;
6311 }
6312
6313 /* Visit and value number STMT, return true if the value number
6314 changed. */
6315
6316 static bool
6317 visit_stmt (gimple *stmt, bool backedges_varying_p = false)
6318 {
6319 bool changed = false;
6320
6321 if (dump_file && (dump_flags & TDF_DETAILS))
6322 {
6323 fprintf (dump_file, "Value numbering stmt = ");
6324 print_gimple_stmt (dump_file, stmt, 0);
6325 }
6326
6327 if (gimple_code (stmt) == GIMPLE_PHI)
6328 changed = visit_phi (stmt, NULL, backedges_varying_p);
6329 else if (gimple_has_volatile_ops (stmt))
6330 changed = defs_to_varying (stmt);
6331 else if (gassign *ass = dyn_cast <gassign *> (stmt))
6332 {
6333 enum tree_code code = gimple_assign_rhs_code (ass);
6334 tree lhs = gimple_assign_lhs (ass);
6335 tree rhs1 = gimple_assign_rhs1 (ass);
6336 tree simplified;
6337
6338 /* Shortcut for copies. Simplifying copies is pointless,
6339 since we copy the expression and value they represent. */
6340 if (code == SSA_NAME
6341 && TREE_CODE (lhs) == SSA_NAME)
6342 {
6343 changed = visit_copy (lhs, rhs1);
6344 goto done;
6345 }
6346 simplified = try_to_simplify (ass);
6347 if (simplified)
6348 {
6349 if (dump_file && (dump_flags & TDF_DETAILS))
6350 {
6351 fprintf (dump_file, "RHS ");
6352 print_gimple_expr (dump_file, ass, 0);
6353 fprintf (dump_file, " simplified to ");
6354 print_generic_expr (dump_file, simplified);
6355 fprintf (dump_file, "\n");
6356 }
6357 }
6358 /* Setting value numbers to constants will occasionally
6359 screw up phi congruence because constants are not
6360 uniquely associated with a single ssa name that can be
6361 looked up. */
6362 if (simplified
6363 && is_gimple_min_invariant (simplified)
6364 && TREE_CODE (lhs) == SSA_NAME)
6365 {
6366 changed = set_ssa_val_to (lhs, simplified);
6367 goto done;
6368 }
6369 else if (simplified
6370 && TREE_CODE (simplified) == SSA_NAME
6371 && TREE_CODE (lhs) == SSA_NAME)
6372 {
6373 changed = visit_copy (lhs, simplified);
6374 goto done;
6375 }
6376
6377 if ((TREE_CODE (lhs) == SSA_NAME
6378 /* We can substitute SSA_NAMEs that are live over
6379 abnormal edges with their constant value. */
6380 && !(gimple_assign_copy_p (ass)
6381 && is_gimple_min_invariant (rhs1))
6382 && !(simplified
6383 && is_gimple_min_invariant (simplified))
6384 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
6385 /* Stores or copies from SSA_NAMEs that are live over
6386 abnormal edges are a problem. */
6387 || (code == SSA_NAME
6388 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (rhs1)))
6389 changed = defs_to_varying (ass);
6390 else if (REFERENCE_CLASS_P (lhs)
6391 || DECL_P (lhs))
6392 changed = visit_reference_op_store (lhs, rhs1, ass);
6393 else if (TREE_CODE (lhs) == SSA_NAME)
6394 {
6395 if ((gimple_assign_copy_p (ass)
6396 && is_gimple_min_invariant (rhs1))
6397 || (simplified
6398 && is_gimple_min_invariant (simplified)))
6399 {
6400 if (simplified)
6401 changed = set_ssa_val_to (lhs, simplified);
6402 else
6403 changed = set_ssa_val_to (lhs, rhs1);
6404 }
6405 else
6406 {
6407 /* Visit the original statement. */
6408 switch (vn_get_stmt_kind (ass))
6409 {
6410 case VN_NARY:
6411 changed = visit_nary_op (lhs, ass);
6412 break;
6413 case VN_REFERENCE:
6414 changed = visit_reference_op_load (lhs, rhs1, ass);
6415 break;
6416 default:
6417 changed = defs_to_varying (ass);
6418 break;
6419 }
6420 }
6421 }
6422 else
6423 changed = defs_to_varying (ass);
6424 }
6425 else if (gcall *call_stmt = dyn_cast <gcall *> (stmt))
6426 {
6427 tree lhs = gimple_call_lhs (call_stmt);
6428 if (lhs && TREE_CODE (lhs) == SSA_NAME)
6429 {
6430 /* Try constant folding based on our current lattice. */
6431 tree simplified = gimple_fold_stmt_to_constant_1 (call_stmt,
6432 vn_valueize);
6433 if (simplified)
6434 {
6435 if (dump_file && (dump_flags & TDF_DETAILS))
6436 {
6437 fprintf (dump_file, "call ");
6438 print_gimple_expr (dump_file, call_stmt, 0);
6439 fprintf (dump_file, " simplified to ");
6440 print_generic_expr (dump_file, simplified);
6441 fprintf (dump_file, "\n");
6442 }
6443 }
6444 /* Setting value numbers to constants will occasionally
6445 screw up phi congruence because constants are not
6446 uniquely associated with a single ssa name that can be
6447 looked up. */
6448 if (simplified
6449 && is_gimple_min_invariant (simplified))
6450 {
6451 changed = set_ssa_val_to (lhs, simplified);
6452 if (gimple_vdef (call_stmt))
6453 changed |= set_ssa_val_to (gimple_vdef (call_stmt),
6454 SSA_VAL (gimple_vuse (call_stmt)));
6455 goto done;
6456 }
6457 else if (simplified
6458 && TREE_CODE (simplified) == SSA_NAME)
6459 {
6460 changed = visit_copy (lhs, simplified);
6461 if (gimple_vdef (call_stmt))
6462 changed |= set_ssa_val_to (gimple_vdef (call_stmt),
6463 SSA_VAL (gimple_vuse (call_stmt)));
6464 goto done;
6465 }
6466 else if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs))
6467 {
6468 changed = defs_to_varying (call_stmt);
6469 goto done;
6470 }
6471 }
6472
6473 /* Pick up flags from a devirtualization target. */
6474 tree fn = gimple_call_fn (stmt);
6475 int extra_fnflags = 0;
6476 if (fn && TREE_CODE (fn) == SSA_NAME)
6477 {
6478 fn = SSA_VAL (fn);
6479 if (TREE_CODE (fn) == ADDR_EXPR
6480 && TREE_CODE (TREE_OPERAND (fn, 0)) == FUNCTION_DECL)
6481 extra_fnflags = flags_from_decl_or_type (TREE_OPERAND (fn, 0));
6482 }
6483 if ((/* Calls to the same function with the same vuse
6484 and the same operands do not necessarily return the same
6485 value, unless they're pure or const. */
6486 ((gimple_call_flags (call_stmt) | extra_fnflags)
6487 & (ECF_PURE | ECF_CONST))
6488 /* If calls have a vdef, subsequent calls won't have
6489 the same incoming vuse. So, if 2 calls with vdef have the
6490 same vuse, we know they're not subsequent.
6491 We can value number 2 calls to the same function with the
6492 same vuse and the same operands which are not subsequent
6493 the same, because there is no code in the program that can
6494 compare the 2 values... */
6495 || (gimple_vdef (call_stmt)
6496 /* ... unless the call returns a pointer which does
6497 not alias with anything else. In which case the
6498 information that the values are distinct are encoded
6499 in the IL. */
6500 && !(gimple_call_return_flags (call_stmt) & ERF_NOALIAS)
6501 /* Only perform the following when being called from PRE
6502 which embeds tail merging. */
6503 && default_vn_walk_kind == VN_WALK))
6504 /* Do not process .DEFERRED_INIT since that confuses uninit
6505 analysis. */
6506 && !gimple_call_internal_p (call_stmt, IFN_DEFERRED_INIT))
6507 changed = visit_reference_op_call (lhs, call_stmt);
6508 else
6509 changed = defs_to_varying (call_stmt);
6510 }
6511 else
6512 changed = defs_to_varying (stmt);
6513 done:
6514 return changed;
6515 }
6516
6517
6518 /* Allocate a value number table. */
6519
6520 static void
6521 allocate_vn_table (vn_tables_t table, unsigned size)
6522 {
6523 table->phis = new vn_phi_table_type (size);
6524 table->nary = new vn_nary_op_table_type (size);
6525 table->references = new vn_reference_table_type (size);
6526 }
6527
6528 /* Free a value number table. */
6529
6530 static void
6531 free_vn_table (vn_tables_t table)
6532 {
6533 /* Walk over elements and release vectors. */
6534 vn_reference_iterator_type hir;
6535 vn_reference_t vr;
6536 FOR_EACH_HASH_TABLE_ELEMENT (*table->references, vr, vn_reference_t, hir)
6537 vr->operands.release ();
6538 delete table->phis;
6539 table->phis = NULL;
6540 delete table->nary;
6541 table->nary = NULL;
6542 delete table->references;
6543 table->references = NULL;
6544 }
6545
6546 /* Set *ID according to RESULT. */
6547
6548 static void
6549 set_value_id_for_result (tree result, unsigned int *id)
6550 {
6551 if (result && TREE_CODE (result) == SSA_NAME)
6552 *id = VN_INFO (result)->value_id;
6553 else if (result && is_gimple_min_invariant (result))
6554 *id = get_or_alloc_constant_value_id (result);
6555 else
6556 *id = get_next_value_id ();
6557 }
6558
6559 /* Set the value ids in the valid hash tables. */
6560
6561 static void
6562 set_hashtable_value_ids (void)
6563 {
6564 vn_nary_op_iterator_type hin;
6565 vn_phi_iterator_type hip;
6566 vn_reference_iterator_type hir;
6567 vn_nary_op_t vno;
6568 vn_reference_t vr;
6569 vn_phi_t vp;
6570
6571 /* Now set the value ids of the things we had put in the hash
6572 table. */
6573
6574 FOR_EACH_HASH_TABLE_ELEMENT (*valid_info->nary, vno, vn_nary_op_t, hin)
6575 if (! vno->predicated_values)
6576 set_value_id_for_result (vno->u.result, &vno->value_id);
6577
6578 FOR_EACH_HASH_TABLE_ELEMENT (*valid_info->phis, vp, vn_phi_t, hip)
6579 set_value_id_for_result (vp->result, &vp->value_id);
6580
6581 FOR_EACH_HASH_TABLE_ELEMENT (*valid_info->references, vr, vn_reference_t,
6582 hir)
6583 set_value_id_for_result (vr->result, &vr->value_id);
6584 }
6585
6586 /* Return the maximum value id we have ever seen. */
6587
6588 unsigned int
6589 get_max_value_id (void)
6590 {
6591 return next_value_id;
6592 }
6593
6594 /* Return the maximum constant value id we have ever seen. */
6595
6596 unsigned int
6597 get_max_constant_value_id (void)
6598 {
6599 return -next_constant_value_id;
6600 }
6601
6602 /* Return the next unique value id. */
6603
6604 unsigned int
6605 get_next_value_id (void)
6606 {
6607 gcc_checking_assert ((int)next_value_id > 0);
6608 return next_value_id++;
6609 }
6610
6611 /* Return the next unique value id for constants. */
6612
6613 unsigned int
6614 get_next_constant_value_id (void)
6615 {
6616 gcc_checking_assert (next_constant_value_id < 0);
6617 return next_constant_value_id--;
6618 }
6619
6620
6621 /* Compare two expressions E1 and E2 and return true if they are equal.
6622 If match_vn_top_optimistically is true then VN_TOP is equal to anything,
6623 otherwise VN_TOP only matches VN_TOP. */
6624
6625 bool
6626 expressions_equal_p (tree e1, tree e2, bool match_vn_top_optimistically)
6627 {
6628 /* The obvious case. */
6629 if (e1 == e2)
6630 return true;
6631
6632 /* If either one is VN_TOP consider them equal. */
6633 if (match_vn_top_optimistically
6634 && (e1 == VN_TOP || e2 == VN_TOP))
6635 return true;
6636
6637 /* If only one of them is null, they cannot be equal. While in general
6638 this should not happen for operations like TARGET_MEM_REF some
6639 operands are optional and an identity value we could substitute
6640 has differing semantics. */
6641 if (!e1 || !e2)
6642 return false;
6643
6644 /* SSA_NAME compare pointer equal. */
6645 if (TREE_CODE (e1) == SSA_NAME || TREE_CODE (e2) == SSA_NAME)
6646 return false;
6647
6648 /* Now perform the actual comparison. */
6649 if (TREE_CODE (e1) == TREE_CODE (e2)
6650 && operand_equal_p (e1, e2, OEP_PURE_SAME))
6651 return true;
6652
6653 return false;
6654 }
6655
6656
6657 /* Return true if the nary operation NARY may trap. This is a copy
6658 of stmt_could_throw_1_p adjusted to the SCCVN IL. */
6659
6660 bool
6661 vn_nary_may_trap (vn_nary_op_t nary)
6662 {
6663 tree type;
6664 tree rhs2 = NULL_TREE;
6665 bool honor_nans = false;
6666 bool honor_snans = false;
6667 bool fp_operation = false;
6668 bool honor_trapv = false;
6669 bool handled, ret;
6670 unsigned i;
6671
6672 if (TREE_CODE_CLASS (nary->opcode) == tcc_comparison
6673 || TREE_CODE_CLASS (nary->opcode) == tcc_unary
6674 || TREE_CODE_CLASS (nary->opcode) == tcc_binary)
6675 {
6676 type = nary->type;
6677 fp_operation = FLOAT_TYPE_P (type);
6678 if (fp_operation)
6679 {
6680 honor_nans = flag_trapping_math && !flag_finite_math_only;
6681 honor_snans = flag_signaling_nans != 0;
6682 }
6683 else if (INTEGRAL_TYPE_P (type) && TYPE_OVERFLOW_TRAPS (type))
6684 honor_trapv = true;
6685 }
6686 if (nary->length >= 2)
6687 rhs2 = nary->op[1];
6688 ret = operation_could_trap_helper_p (nary->opcode, fp_operation,
6689 honor_trapv, honor_nans, honor_snans,
6690 rhs2, &handled);
6691 if (handled && ret)
6692 return true;
6693
6694 for (i = 0; i < nary->length; ++i)
6695 if (tree_could_trap_p (nary->op[i]))
6696 return true;
6697
6698 return false;
6699 }
6700
6701 /* Return true if the reference operation REF may trap. */
6702
6703 bool
6704 vn_reference_may_trap (vn_reference_t ref)
6705 {
6706 switch (ref->operands[0].opcode)
6707 {
6708 case MODIFY_EXPR:
6709 case CALL_EXPR:
6710 /* We do not handle calls. */
6711 return true;
6712 case ADDR_EXPR:
6713 /* And toplevel address computations never trap. */
6714 return false;
6715 default:;
6716 }
6717
6718 vn_reference_op_t op;
6719 unsigned i;
6720 FOR_EACH_VEC_ELT (ref->operands, i, op)
6721 {
6722 switch (op->opcode)
6723 {
6724 case WITH_SIZE_EXPR:
6725 case TARGET_MEM_REF:
6726 /* Always variable. */
6727 return true;
6728 case COMPONENT_REF:
6729 if (op->op1 && TREE_CODE (op->op1) == SSA_NAME)
6730 return true;
6731 break;
6732 case ARRAY_RANGE_REF:
6733 if (TREE_CODE (op->op0) == SSA_NAME)
6734 return true;
6735 break;
6736 case ARRAY_REF:
6737 {
6738 if (TREE_CODE (op->op0) != INTEGER_CST)
6739 return true;
6740
6741 /* !in_array_bounds */
6742 tree domain_type = TYPE_DOMAIN (ref->operands[i+1].type);
6743 if (!domain_type)
6744 return true;
6745
6746 tree min = op->op1;
6747 tree max = TYPE_MAX_VALUE (domain_type);
6748 if (!min
6749 || !max
6750 || TREE_CODE (min) != INTEGER_CST
6751 || TREE_CODE (max) != INTEGER_CST)
6752 return true;
6753
6754 if (tree_int_cst_lt (op->op0, min)
6755 || tree_int_cst_lt (max, op->op0))
6756 return true;
6757
6758 break;
6759 }
6760 case MEM_REF:
6761 /* Nothing interesting in itself, the base is separate. */
6762 break;
6763 /* The following are the address bases. */
6764 case SSA_NAME:
6765 return true;
6766 case ADDR_EXPR:
6767 if (op->op0)
6768 return tree_could_trap_p (TREE_OPERAND (op->op0, 0));
6769 return false;
6770 default:;
6771 }
6772 }
6773 return false;
6774 }
6775
6776 eliminate_dom_walker::eliminate_dom_walker (cdi_direction direction,
6777 bitmap inserted_exprs_)
6778 : dom_walker (direction), do_pre (inserted_exprs_ != NULL),
6779 el_todo (0), eliminations (0), insertions (0),
6780 inserted_exprs (inserted_exprs_)
6781 {
6782 need_eh_cleanup = BITMAP_ALLOC (NULL);
6783 need_ab_cleanup = BITMAP_ALLOC (NULL);
6784 }
6785
6786 eliminate_dom_walker::~eliminate_dom_walker ()
6787 {
6788 BITMAP_FREE (need_eh_cleanup);
6789 BITMAP_FREE (need_ab_cleanup);
6790 }
6791
6792 /* Return a leader for OP that is available at the current point of the
6793 eliminate domwalk. */
6794
6795 tree
6796 eliminate_dom_walker::eliminate_avail (basic_block, tree op)
6797 {
6798 tree valnum = VN_INFO (op)->valnum;
6799 if (TREE_CODE (valnum) == SSA_NAME)
6800 {
6801 if (SSA_NAME_IS_DEFAULT_DEF (valnum))
6802 return valnum;
6803 if (avail.length () > SSA_NAME_VERSION (valnum))
6804 {
6805 tree av = avail[SSA_NAME_VERSION (valnum)];
6806 /* When PRE discovers a new redundancy there's no way to unite
6807 the value classes so it instead inserts a copy old-val = new-val.
6808 Look through such copies here, providing one more level of
6809 simplification at elimination time. */
6810 gassign *ass;
6811 if (av && (ass = dyn_cast <gassign *> (SSA_NAME_DEF_STMT (av))))
6812 if (gimple_assign_rhs_class (ass) == GIMPLE_SINGLE_RHS)
6813 {
6814 tree rhs1 = gimple_assign_rhs1 (ass);
6815 if (CONSTANT_CLASS_P (rhs1)
6816 || (TREE_CODE (rhs1) == SSA_NAME
6817 && !SSA_NAME_OCCURS_IN_ABNORMAL_PHI (rhs1)))
6818 av = rhs1;
6819 }
6820 return av;
6821 }
6822 }
6823 else if (is_gimple_min_invariant (valnum))
6824 return valnum;
6825 return NULL_TREE;
6826 }
6827
6828 /* At the current point of the eliminate domwalk make OP available. */
6829
6830 void
6831 eliminate_dom_walker::eliminate_push_avail (basic_block, tree op)
6832 {
6833 tree valnum = VN_INFO (op)->valnum;
6834 if (TREE_CODE (valnum) == SSA_NAME)
6835 {
6836 if (avail.length () <= SSA_NAME_VERSION (valnum))
6837 avail.safe_grow_cleared (SSA_NAME_VERSION (valnum) + 1, true);
6838 tree pushop = op;
6839 if (avail[SSA_NAME_VERSION (valnum)])
6840 pushop = avail[SSA_NAME_VERSION (valnum)];
6841 avail_stack.safe_push (pushop);
6842 avail[SSA_NAME_VERSION (valnum)] = op;
6843 }
6844 }
6845
6846 /* Insert the expression recorded by SCCVN for VAL at *GSI. Returns
6847 the leader for the expression if insertion was successful. */
6848
6849 tree
6850 eliminate_dom_walker::eliminate_insert (basic_block bb,
6851 gimple_stmt_iterator *gsi, tree val)
6852 {
6853 /* We can insert a sequence with a single assignment only. */
6854 gimple_seq stmts = VN_INFO (val)->expr;
6855 if (!gimple_seq_singleton_p (stmts))
6856 return NULL_TREE;
6857 gassign *stmt = dyn_cast <gassign *> (gimple_seq_first_stmt (stmts));
6858 if (!stmt
6859 || (!CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt))
6860 && gimple_assign_rhs_code (stmt) != VIEW_CONVERT_EXPR
6861 && gimple_assign_rhs_code (stmt) != NEGATE_EXPR
6862 && gimple_assign_rhs_code (stmt) != BIT_FIELD_REF
6863 && (gimple_assign_rhs_code (stmt) != BIT_AND_EXPR
6864 || TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)))
6865 return NULL_TREE;
6866
6867 tree op = gimple_assign_rhs1 (stmt);
6868 if (gimple_assign_rhs_code (stmt) == VIEW_CONVERT_EXPR
6869 || gimple_assign_rhs_code (stmt) == BIT_FIELD_REF)
6870 op = TREE_OPERAND (op, 0);
6871 tree leader = TREE_CODE (op) == SSA_NAME ? eliminate_avail (bb, op) : op;
6872 if (!leader)
6873 return NULL_TREE;
6874
6875 tree res;
6876 stmts = NULL;
6877 if (gimple_assign_rhs_code (stmt) == BIT_FIELD_REF)
6878 res = gimple_build (&stmts, BIT_FIELD_REF,
6879 TREE_TYPE (val), leader,
6880 TREE_OPERAND (gimple_assign_rhs1 (stmt), 1),
6881 TREE_OPERAND (gimple_assign_rhs1 (stmt), 2));
6882 else if (gimple_assign_rhs_code (stmt) == BIT_AND_EXPR)
6883 res = gimple_build (&stmts, BIT_AND_EXPR,
6884 TREE_TYPE (val), leader, gimple_assign_rhs2 (stmt));
6885 else
6886 res = gimple_build (&stmts, gimple_assign_rhs_code (stmt),
6887 TREE_TYPE (val), leader);
6888 if (TREE_CODE (res) != SSA_NAME
6889 || SSA_NAME_IS_DEFAULT_DEF (res)
6890 || gimple_bb (SSA_NAME_DEF_STMT (res)))
6891 {
6892 gimple_seq_discard (stmts);
6893
6894 /* During propagation we have to treat SSA info conservatively
6895 and thus we can end up simplifying the inserted expression
6896 at elimination time to sth not defined in stmts. */
6897 /* But then this is a redundancy we failed to detect. Which means
6898 res now has two values. That doesn't play well with how
6899 we track availability here, so give up. */
6900 if (dump_file && (dump_flags & TDF_DETAILS))
6901 {
6902 if (TREE_CODE (res) == SSA_NAME)
6903 res = eliminate_avail (bb, res);
6904 if (res)
6905 {
6906 fprintf (dump_file, "Failed to insert expression for value ");
6907 print_generic_expr (dump_file, val);
6908 fprintf (dump_file, " which is really fully redundant to ");
6909 print_generic_expr (dump_file, res);
6910 fprintf (dump_file, "\n");
6911 }
6912 }
6913
6914 return NULL_TREE;
6915 }
6916 else
6917 {
6918 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
6919 vn_ssa_aux_t vn_info = VN_INFO (res);
6920 vn_info->valnum = val;
6921 vn_info->visited = true;
6922 }
6923
6924 insertions++;
6925 if (dump_file && (dump_flags & TDF_DETAILS))
6926 {
6927 fprintf (dump_file, "Inserted ");
6928 print_gimple_stmt (dump_file, SSA_NAME_DEF_STMT (res), 0);
6929 }
6930
6931 return res;
6932 }
6933
6934 void
6935 eliminate_dom_walker::eliminate_stmt (basic_block b, gimple_stmt_iterator *gsi)
6936 {
6937 tree sprime = NULL_TREE;
6938 gimple *stmt = gsi_stmt (*gsi);
6939 tree lhs = gimple_get_lhs (stmt);
6940 if (lhs && TREE_CODE (lhs) == SSA_NAME
6941 && !gimple_has_volatile_ops (stmt)
6942 /* See PR43491. Do not replace a global register variable when
6943 it is a the RHS of an assignment. Do replace local register
6944 variables since gcc does not guarantee a local variable will
6945 be allocated in register.
6946 ??? The fix isn't effective here. This should instead
6947 be ensured by not value-numbering them the same but treating
6948 them like volatiles? */
6949 && !(gimple_assign_single_p (stmt)
6950 && (TREE_CODE (gimple_assign_rhs1 (stmt)) == VAR_DECL
6951 && DECL_HARD_REGISTER (gimple_assign_rhs1 (stmt))
6952 && is_global_var (gimple_assign_rhs1 (stmt)))))
6953 {
6954 sprime = eliminate_avail (b, lhs);
6955 if (!sprime)
6956 {
6957 /* If there is no existing usable leader but SCCVN thinks
6958 it has an expression it wants to use as replacement,
6959 insert that. */
6960 tree val = VN_INFO (lhs)->valnum;
6961 vn_ssa_aux_t vn_info;
6962 if (val != VN_TOP
6963 && TREE_CODE (val) == SSA_NAME
6964 && (vn_info = VN_INFO (val), true)
6965 && vn_info->needs_insertion
6966 && vn_info->expr != NULL
6967 && (sprime = eliminate_insert (b, gsi, val)) != NULL_TREE)
6968 eliminate_push_avail (b, sprime);
6969 }
6970
6971 /* If this now constitutes a copy duplicate points-to
6972 and range info appropriately. This is especially
6973 important for inserted code. */
6974 if (sprime
6975 && TREE_CODE (sprime) == SSA_NAME)
6976 maybe_duplicate_ssa_info_at_copy (lhs, sprime);
6977
6978 /* Inhibit the use of an inserted PHI on a loop header when
6979 the address of the memory reference is a simple induction
6980 variable. In other cases the vectorizer won't do anything
6981 anyway (either it's loop invariant or a complicated
6982 expression). */
6983 if (sprime
6984 && TREE_CODE (sprime) == SSA_NAME
6985 && do_pre
6986 && (flag_tree_loop_vectorize || flag_tree_parallelize_loops > 1)
6987 && loop_outer (b->loop_father)
6988 && has_zero_uses (sprime)
6989 && bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (sprime))
6990 && gimple_assign_load_p (stmt))
6991 {
6992 gimple *def_stmt = SSA_NAME_DEF_STMT (sprime);
6993 basic_block def_bb = gimple_bb (def_stmt);
6994 if (gimple_code (def_stmt) == GIMPLE_PHI
6995 && def_bb->loop_father->header == def_bb)
6996 {
6997 loop_p loop = def_bb->loop_father;
6998 ssa_op_iter iter;
6999 tree op;
7000 bool found = false;
7001 FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
7002 {
7003 affine_iv iv;
7004 def_bb = gimple_bb (SSA_NAME_DEF_STMT (op));
7005 if (def_bb
7006 && flow_bb_inside_loop_p (loop, def_bb)
7007 && simple_iv (loop, loop, op, &iv, true))
7008 {
7009 found = true;
7010 break;
7011 }
7012 }
7013 if (found)
7014 {
7015 if (dump_file && (dump_flags & TDF_DETAILS))
7016 {
7017 fprintf (dump_file, "Not replacing ");
7018 print_gimple_expr (dump_file, stmt, 0);
7019 fprintf (dump_file, " with ");
7020 print_generic_expr (dump_file, sprime);
7021 fprintf (dump_file, " which would add a loop"
7022 " carried dependence to loop %d\n",
7023 loop->num);
7024 }
7025 /* Don't keep sprime available. */
7026 sprime = NULL_TREE;
7027 }
7028 }
7029 }
7030
7031 if (sprime)
7032 {
7033 /* If we can propagate the value computed for LHS into
7034 all uses don't bother doing anything with this stmt. */
7035 if (may_propagate_copy (lhs, sprime))
7036 {
7037 /* Mark it for removal. */
7038 to_remove.safe_push (stmt);
7039
7040 /* ??? Don't count copy/constant propagations. */
7041 if (gimple_assign_single_p (stmt)
7042 && (TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME
7043 || gimple_assign_rhs1 (stmt) == sprime))
7044 return;
7045
7046 if (dump_file && (dump_flags & TDF_DETAILS))
7047 {
7048 fprintf (dump_file, "Replaced ");
7049 print_gimple_expr (dump_file, stmt, 0);
7050 fprintf (dump_file, " with ");
7051 print_generic_expr (dump_file, sprime);
7052 fprintf (dump_file, " in all uses of ");
7053 print_gimple_stmt (dump_file, stmt, 0);
7054 }
7055
7056 eliminations++;
7057 return;
7058 }
7059
7060 /* If this is an assignment from our leader (which
7061 happens in the case the value-number is a constant)
7062 then there is nothing to do. Likewise if we run into
7063 inserted code that needed a conversion because of
7064 our type-agnostic value-numbering of loads. */
7065 if ((gimple_assign_single_p (stmt)
7066 || (is_gimple_assign (stmt)
7067 && (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (stmt))
7068 || gimple_assign_rhs_code (stmt) == VIEW_CONVERT_EXPR)))
7069 && sprime == gimple_assign_rhs1 (stmt))
7070 return;
7071
7072 /* Else replace its RHS. */
7073 if (dump_file && (dump_flags & TDF_DETAILS))
7074 {
7075 fprintf (dump_file, "Replaced ");
7076 print_gimple_expr (dump_file, stmt, 0);
7077 fprintf (dump_file, " with ");
7078 print_generic_expr (dump_file, sprime);
7079 fprintf (dump_file, " in ");
7080 print_gimple_stmt (dump_file, stmt, 0);
7081 }
7082 eliminations++;
7083
7084 bool can_make_abnormal_goto = (is_gimple_call (stmt)
7085 && stmt_can_make_abnormal_goto (stmt));
7086 gimple *orig_stmt = stmt;
7087 if (!useless_type_conversion_p (TREE_TYPE (lhs),
7088 TREE_TYPE (sprime)))
7089 {
7090 /* We preserve conversions to but not from function or method
7091 types. This asymmetry makes it necessary to re-instantiate
7092 conversions here. */
7093 if (POINTER_TYPE_P (TREE_TYPE (lhs))
7094 && FUNC_OR_METHOD_TYPE_P (TREE_TYPE (TREE_TYPE (lhs))))
7095 sprime = fold_convert (TREE_TYPE (lhs), sprime);
7096 else
7097 gcc_unreachable ();
7098 }
7099 tree vdef = gimple_vdef (stmt);
7100 tree vuse = gimple_vuse (stmt);
7101 propagate_tree_value_into_stmt (gsi, sprime);
7102 stmt = gsi_stmt (*gsi);
7103 update_stmt (stmt);
7104 /* In case the VDEF on the original stmt was released, value-number
7105 it to the VUSE. This is to make vuse_ssa_val able to skip
7106 released virtual operands. */
7107 if (vdef != gimple_vdef (stmt))
7108 {
7109 gcc_assert (SSA_NAME_IN_FREE_LIST (vdef));
7110 VN_INFO (vdef)->valnum = vuse;
7111 }
7112
7113 /* If we removed EH side-effects from the statement, clean
7114 its EH information. */
7115 if (maybe_clean_or_replace_eh_stmt (orig_stmt, stmt))
7116 {
7117 bitmap_set_bit (need_eh_cleanup,
7118 gimple_bb (stmt)->index);
7119 if (dump_file && (dump_flags & TDF_DETAILS))
7120 fprintf (dump_file, " Removed EH side-effects.\n");
7121 }
7122
7123 /* Likewise for AB side-effects. */
7124 if (can_make_abnormal_goto
7125 && !stmt_can_make_abnormal_goto (stmt))
7126 {
7127 bitmap_set_bit (need_ab_cleanup,
7128 gimple_bb (stmt)->index);
7129 if (dump_file && (dump_flags & TDF_DETAILS))
7130 fprintf (dump_file, " Removed AB side-effects.\n");
7131 }
7132
7133 return;
7134 }
7135 }
7136
7137 /* If the statement is a scalar store, see if the expression
7138 has the same value number as its rhs. If so, the store is
7139 dead. */
7140 if (gimple_assign_single_p (stmt)
7141 && !gimple_has_volatile_ops (stmt)
7142 && !is_gimple_reg (gimple_assign_lhs (stmt))
7143 && (TREE_CODE (gimple_assign_lhs (stmt)) != VAR_DECL
7144 || !DECL_HARD_REGISTER (gimple_assign_lhs (stmt)))
7145 && (TREE_CODE (gimple_assign_rhs1 (stmt)) == SSA_NAME
7146 || is_gimple_min_invariant (gimple_assign_rhs1 (stmt))))
7147 {
7148 tree rhs = gimple_assign_rhs1 (stmt);
7149 vn_reference_t vnresult;
7150 /* ??? gcc.dg/torture/pr91445.c shows that we lookup a boolean
7151 typed load of a byte known to be 0x11 as 1 so a store of
7152 a boolean 1 is detected as redundant. Because of this we
7153 have to make sure to lookup with a ref where its size
7154 matches the precision. */
7155 tree lookup_lhs = lhs;
7156 if (INTEGRAL_TYPE_P (TREE_TYPE (lhs))
7157 && (TREE_CODE (lhs) != COMPONENT_REF
7158 || !DECL_BIT_FIELD_TYPE (TREE_OPERAND (lhs, 1)))
7159 && !type_has_mode_precision_p (TREE_TYPE (lhs)))
7160 {
7161 if (TREE_CODE (TREE_TYPE (lhs)) == BITINT_TYPE
7162 && TYPE_PRECISION (TREE_TYPE (lhs)) > MAX_FIXED_MODE_SIZE)
7163 lookup_lhs = NULL_TREE;
7164 else if (TREE_CODE (lhs) == COMPONENT_REF
7165 || TREE_CODE (lhs) == MEM_REF)
7166 {
7167 tree ltype = build_nonstandard_integer_type
7168 (TREE_INT_CST_LOW (TYPE_SIZE (TREE_TYPE (lhs))),
7169 TYPE_UNSIGNED (TREE_TYPE (lhs)));
7170 if (TREE_CODE (lhs) == COMPONENT_REF)
7171 {
7172 tree foff = component_ref_field_offset (lhs);
7173 tree f = TREE_OPERAND (lhs, 1);
7174 if (!poly_int_tree_p (foff))
7175 lookup_lhs = NULL_TREE;
7176 else
7177 lookup_lhs = build3 (BIT_FIELD_REF, ltype,
7178 TREE_OPERAND (lhs, 0),
7179 TYPE_SIZE (TREE_TYPE (lhs)),
7180 bit_from_pos
7181 (foff, DECL_FIELD_BIT_OFFSET (f)));
7182 }
7183 else
7184 lookup_lhs = build2 (MEM_REF, ltype,
7185 TREE_OPERAND (lhs, 0),
7186 TREE_OPERAND (lhs, 1));
7187 }
7188 else
7189 lookup_lhs = NULL_TREE;
7190 }
7191 tree val = NULL_TREE;
7192 if (lookup_lhs)
7193 val = vn_reference_lookup (lookup_lhs, gimple_vuse (stmt),
7194 VN_WALKREWRITE, &vnresult, false,
7195 NULL, NULL_TREE, true);
7196 if (TREE_CODE (rhs) == SSA_NAME)
7197 rhs = VN_INFO (rhs)->valnum;
7198 if (val
7199 && (operand_equal_p (val, rhs, 0)
7200 /* Due to the bitfield lookups above we can get bit
7201 interpretations of the same RHS as values here. Those
7202 are redundant as well. */
7203 || (TREE_CODE (val) == SSA_NAME
7204 && gimple_assign_single_p (SSA_NAME_DEF_STMT (val))
7205 && (val = gimple_assign_rhs1 (SSA_NAME_DEF_STMT (val)))
7206 && TREE_CODE (val) == VIEW_CONVERT_EXPR
7207 && TREE_OPERAND (val, 0) == rhs)))
7208 {
7209 /* We can only remove the later store if the former aliases
7210 at least all accesses the later one does or if the store
7211 was to readonly memory storing the same value. */
7212 ao_ref lhs_ref;
7213 ao_ref_init (&lhs_ref, lhs);
7214 alias_set_type set = ao_ref_alias_set (&lhs_ref);
7215 alias_set_type base_set = ao_ref_base_alias_set (&lhs_ref);
7216 if (! vnresult
7217 || ((vnresult->set == set
7218 || alias_set_subset_of (set, vnresult->set))
7219 && (vnresult->base_set == base_set
7220 || alias_set_subset_of (base_set, vnresult->base_set))))
7221 {
7222 if (dump_file && (dump_flags & TDF_DETAILS))
7223 {
7224 fprintf (dump_file, "Deleted redundant store ");
7225 print_gimple_stmt (dump_file, stmt, 0);
7226 }
7227
7228 /* Queue stmt for removal. */
7229 to_remove.safe_push (stmt);
7230 return;
7231 }
7232 }
7233 }
7234
7235 /* If this is a control statement value numbering left edges
7236 unexecuted on force the condition in a way consistent with
7237 that. */
7238 if (gcond *cond = dyn_cast <gcond *> (stmt))
7239 {
7240 if ((EDGE_SUCC (b, 0)->flags & EDGE_EXECUTABLE)
7241 ^ (EDGE_SUCC (b, 1)->flags & EDGE_EXECUTABLE))
7242 {
7243 if (dump_file && (dump_flags & TDF_DETAILS))
7244 {
7245 fprintf (dump_file, "Removing unexecutable edge from ");
7246 print_gimple_stmt (dump_file, stmt, 0);
7247 }
7248 if (((EDGE_SUCC (b, 0)->flags & EDGE_TRUE_VALUE) != 0)
7249 == ((EDGE_SUCC (b, 0)->flags & EDGE_EXECUTABLE) != 0))
7250 gimple_cond_make_true (cond);
7251 else
7252 gimple_cond_make_false (cond);
7253 update_stmt (cond);
7254 el_todo |= TODO_cleanup_cfg;
7255 return;
7256 }
7257 }
7258
7259 bool can_make_abnormal_goto = stmt_can_make_abnormal_goto (stmt);
7260 bool was_noreturn = (is_gimple_call (stmt)
7261 && gimple_call_noreturn_p (stmt));
7262 tree vdef = gimple_vdef (stmt);
7263 tree vuse = gimple_vuse (stmt);
7264
7265 /* If we didn't replace the whole stmt (or propagate the result
7266 into all uses), replace all uses on this stmt with their
7267 leaders. */
7268 bool modified = false;
7269 use_operand_p use_p;
7270 ssa_op_iter iter;
7271 FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_USE)
7272 {
7273 tree use = USE_FROM_PTR (use_p);
7274 /* ??? The call code above leaves stmt operands un-updated. */
7275 if (TREE_CODE (use) != SSA_NAME)
7276 continue;
7277 tree sprime;
7278 if (SSA_NAME_IS_DEFAULT_DEF (use))
7279 /* ??? For default defs BB shouldn't matter, but we have to
7280 solve the inconsistency between rpo eliminate and
7281 dom eliminate avail valueization first. */
7282 sprime = eliminate_avail (b, use);
7283 else
7284 /* Look for sth available at the definition block of the argument.
7285 This avoids inconsistencies between availability there which
7286 decides if the stmt can be removed and availability at the
7287 use site. The SSA property ensures that things available
7288 at the definition are also available at uses. */
7289 sprime = eliminate_avail (gimple_bb (SSA_NAME_DEF_STMT (use)), use);
7290 if (sprime && sprime != use
7291 && may_propagate_copy (use, sprime, true)
7292 /* We substitute into debug stmts to avoid excessive
7293 debug temporaries created by removed stmts, but we need
7294 to avoid doing so for inserted sprimes as we never want
7295 to create debug temporaries for them. */
7296 && (!inserted_exprs
7297 || TREE_CODE (sprime) != SSA_NAME
7298 || !is_gimple_debug (stmt)
7299 || !bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (sprime))))
7300 {
7301 propagate_value (use_p, sprime);
7302 modified = true;
7303 }
7304 }
7305
7306 /* Fold the stmt if modified, this canonicalizes MEM_REFs we propagated
7307 into which is a requirement for the IPA devirt machinery. */
7308 gimple *old_stmt = stmt;
7309 if (modified)
7310 {
7311 /* If a formerly non-invariant ADDR_EXPR is turned into an
7312 invariant one it was on a separate stmt. */
7313 if (gimple_assign_single_p (stmt)
7314 && TREE_CODE (gimple_assign_rhs1 (stmt)) == ADDR_EXPR)
7315 recompute_tree_invariant_for_addr_expr (gimple_assign_rhs1 (stmt));
7316 gimple_stmt_iterator prev = *gsi;
7317 gsi_prev (&prev);
7318 if (fold_stmt (gsi, follow_all_ssa_edges))
7319 {
7320 /* fold_stmt may have created new stmts inbetween
7321 the previous stmt and the folded stmt. Mark
7322 all defs created there as varying to not confuse
7323 the SCCVN machinery as we're using that even during
7324 elimination. */
7325 if (gsi_end_p (prev))
7326 prev = gsi_start_bb (b);
7327 else
7328 gsi_next (&prev);
7329 if (gsi_stmt (prev) != gsi_stmt (*gsi))
7330 do
7331 {
7332 tree def;
7333 ssa_op_iter dit;
7334 FOR_EACH_SSA_TREE_OPERAND (def, gsi_stmt (prev),
7335 dit, SSA_OP_ALL_DEFS)
7336 /* As existing DEFs may move between stmts
7337 only process new ones. */
7338 if (! has_VN_INFO (def))
7339 {
7340 vn_ssa_aux_t vn_info = VN_INFO (def);
7341 vn_info->valnum = def;
7342 vn_info->visited = true;
7343 }
7344 if (gsi_stmt (prev) == gsi_stmt (*gsi))
7345 break;
7346 gsi_next (&prev);
7347 }
7348 while (1);
7349 }
7350 stmt = gsi_stmt (*gsi);
7351 /* In case we folded the stmt away schedule the NOP for removal. */
7352 if (gimple_nop_p (stmt))
7353 to_remove.safe_push (stmt);
7354 }
7355
7356 /* Visit indirect calls and turn them into direct calls if
7357 possible using the devirtualization machinery. Do this before
7358 checking for required EH/abnormal/noreturn cleanup as devird
7359 may expose more of those. */
7360 if (gcall *call_stmt = dyn_cast <gcall *> (stmt))
7361 {
7362 tree fn = gimple_call_fn (call_stmt);
7363 if (fn
7364 && flag_devirtualize
7365 && virtual_method_call_p (fn))
7366 {
7367 tree otr_type = obj_type_ref_class (fn);
7368 unsigned HOST_WIDE_INT otr_tok
7369 = tree_to_uhwi (OBJ_TYPE_REF_TOKEN (fn));
7370 tree instance;
7371 ipa_polymorphic_call_context context (current_function_decl,
7372 fn, stmt, &instance);
7373 context.get_dynamic_type (instance, OBJ_TYPE_REF_OBJECT (fn),
7374 otr_type, stmt, NULL);
7375 bool final;
7376 vec <cgraph_node *> targets
7377 = possible_polymorphic_call_targets (obj_type_ref_class (fn),
7378 otr_tok, context, &final);
7379 if (dump_file)
7380 dump_possible_polymorphic_call_targets (dump_file,
7381 obj_type_ref_class (fn),
7382 otr_tok, context);
7383 if (final && targets.length () <= 1 && dbg_cnt (devirt))
7384 {
7385 tree fn;
7386 if (targets.length () == 1)
7387 fn = targets[0]->decl;
7388 else
7389 fn = builtin_decl_unreachable ();
7390 if (dump_enabled_p ())
7391 {
7392 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS, stmt,
7393 "converting indirect call to "
7394 "function %s\n",
7395 lang_hooks.decl_printable_name (fn, 2));
7396 }
7397 gimple_call_set_fndecl (call_stmt, fn);
7398 /* If changing the call to __builtin_unreachable
7399 or similar noreturn function, adjust gimple_call_fntype
7400 too. */
7401 if (gimple_call_noreturn_p (call_stmt)
7402 && VOID_TYPE_P (TREE_TYPE (TREE_TYPE (fn)))
7403 && TYPE_ARG_TYPES (TREE_TYPE (fn))
7404 && (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (fn)))
7405 == void_type_node))
7406 gimple_call_set_fntype (call_stmt, TREE_TYPE (fn));
7407 maybe_remove_unused_call_args (cfun, call_stmt);
7408 modified = true;
7409 }
7410 }
7411 }
7412
7413 if (modified)
7414 {
7415 /* When changing a call into a noreturn call, cfg cleanup
7416 is needed to fix up the noreturn call. */
7417 if (!was_noreturn
7418 && is_gimple_call (stmt) && gimple_call_noreturn_p (stmt))
7419 to_fixup.safe_push (stmt);
7420 /* When changing a condition or switch into one we know what
7421 edge will be executed, schedule a cfg cleanup. */
7422 if ((gimple_code (stmt) == GIMPLE_COND
7423 && (gimple_cond_true_p (as_a <gcond *> (stmt))
7424 || gimple_cond_false_p (as_a <gcond *> (stmt))))
7425 || (gimple_code (stmt) == GIMPLE_SWITCH
7426 && TREE_CODE (gimple_switch_index
7427 (as_a <gswitch *> (stmt))) == INTEGER_CST))
7428 el_todo |= TODO_cleanup_cfg;
7429 /* If we removed EH side-effects from the statement, clean
7430 its EH information. */
7431 if (maybe_clean_or_replace_eh_stmt (old_stmt, stmt))
7432 {
7433 bitmap_set_bit (need_eh_cleanup,
7434 gimple_bb (stmt)->index);
7435 if (dump_file && (dump_flags & TDF_DETAILS))
7436 fprintf (dump_file, " Removed EH side-effects.\n");
7437 }
7438 /* Likewise for AB side-effects. */
7439 if (can_make_abnormal_goto
7440 && !stmt_can_make_abnormal_goto (stmt))
7441 {
7442 bitmap_set_bit (need_ab_cleanup,
7443 gimple_bb (stmt)->index);
7444 if (dump_file && (dump_flags & TDF_DETAILS))
7445 fprintf (dump_file, " Removed AB side-effects.\n");
7446 }
7447 update_stmt (stmt);
7448 /* In case the VDEF on the original stmt was released, value-number
7449 it to the VUSE. This is to make vuse_ssa_val able to skip
7450 released virtual operands. */
7451 if (vdef && SSA_NAME_IN_FREE_LIST (vdef))
7452 VN_INFO (vdef)->valnum = vuse;
7453 }
7454
7455 /* Make new values available - for fully redundant LHS we
7456 continue with the next stmt above and skip this.
7457 But avoid picking up dead defs. */
7458 tree def;
7459 FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
7460 if (! has_zero_uses (def)
7461 || (inserted_exprs
7462 && bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (def))))
7463 eliminate_push_avail (b, def);
7464 }
7465
7466 /* Perform elimination for the basic-block B during the domwalk. */
7467
7468 edge
7469 eliminate_dom_walker::before_dom_children (basic_block b)
7470 {
7471 /* Mark new bb. */
7472 avail_stack.safe_push (NULL_TREE);
7473
7474 /* Skip unreachable blocks marked unreachable during the SCCVN domwalk. */
7475 if (!(b->flags & BB_EXECUTABLE))
7476 return NULL;
7477
7478 vn_context_bb = b;
7479
7480 for (gphi_iterator gsi = gsi_start_phis (b); !gsi_end_p (gsi);)
7481 {
7482 gphi *phi = gsi.phi ();
7483 tree res = PHI_RESULT (phi);
7484
7485 if (virtual_operand_p (res))
7486 {
7487 gsi_next (&gsi);
7488 continue;
7489 }
7490
7491 tree sprime = eliminate_avail (b, res);
7492 if (sprime
7493 && sprime != res)
7494 {
7495 if (dump_file && (dump_flags & TDF_DETAILS))
7496 {
7497 fprintf (dump_file, "Replaced redundant PHI node defining ");
7498 print_generic_expr (dump_file, res);
7499 fprintf (dump_file, " with ");
7500 print_generic_expr (dump_file, sprime);
7501 fprintf (dump_file, "\n");
7502 }
7503
7504 /* If we inserted this PHI node ourself, it's not an elimination. */
7505 if (! inserted_exprs
7506 || ! bitmap_bit_p (inserted_exprs, SSA_NAME_VERSION (res)))
7507 eliminations++;
7508
7509 /* If we will propagate into all uses don't bother to do
7510 anything. */
7511 if (may_propagate_copy (res, sprime))
7512 {
7513 /* Mark the PHI for removal. */
7514 to_remove.safe_push (phi);
7515 gsi_next (&gsi);
7516 continue;
7517 }
7518
7519 remove_phi_node (&gsi, false);
7520
7521 if (!useless_type_conversion_p (TREE_TYPE (res), TREE_TYPE (sprime)))
7522 sprime = fold_convert (TREE_TYPE (res), sprime);
7523 gimple *stmt = gimple_build_assign (res, sprime);
7524 gimple_stmt_iterator gsi2 = gsi_after_labels (b);
7525 gsi_insert_before (&gsi2, stmt, GSI_NEW_STMT);
7526 continue;
7527 }
7528
7529 eliminate_push_avail (b, res);
7530 gsi_next (&gsi);
7531 }
7532
7533 for (gimple_stmt_iterator gsi = gsi_start_bb (b);
7534 !gsi_end_p (gsi);
7535 gsi_next (&gsi))
7536 eliminate_stmt (b, &gsi);
7537
7538 /* Replace destination PHI arguments. */
7539 edge_iterator ei;
7540 edge e;
7541 FOR_EACH_EDGE (e, ei, b->succs)
7542 if (e->flags & EDGE_EXECUTABLE)
7543 for (gphi_iterator gsi = gsi_start_phis (e->dest);
7544 !gsi_end_p (gsi);
7545 gsi_next (&gsi))
7546 {
7547 gphi *phi = gsi.phi ();
7548 use_operand_p use_p = PHI_ARG_DEF_PTR_FROM_EDGE (phi, e);
7549 tree arg = USE_FROM_PTR (use_p);
7550 if (TREE_CODE (arg) != SSA_NAME
7551 || virtual_operand_p (arg))
7552 continue;
7553 tree sprime = eliminate_avail (b, arg);
7554 if (sprime && may_propagate_copy (arg, sprime,
7555 !(e->flags & EDGE_ABNORMAL)))
7556 propagate_value (use_p, sprime);
7557 }
7558
7559 vn_context_bb = NULL;
7560
7561 return NULL;
7562 }
7563
7564 /* Make no longer available leaders no longer available. */
7565
7566 void
7567 eliminate_dom_walker::after_dom_children (basic_block)
7568 {
7569 tree entry;
7570 while ((entry = avail_stack.pop ()) != NULL_TREE)
7571 {
7572 tree valnum = VN_INFO (entry)->valnum;
7573 tree old = avail[SSA_NAME_VERSION (valnum)];
7574 if (old == entry)
7575 avail[SSA_NAME_VERSION (valnum)] = NULL_TREE;
7576 else
7577 avail[SSA_NAME_VERSION (valnum)] = entry;
7578 }
7579 }
7580
7581 /* Remove queued stmts and perform delayed cleanups. */
7582
7583 unsigned
7584 eliminate_dom_walker::eliminate_cleanup (bool region_p)
7585 {
7586 statistics_counter_event (cfun, "Eliminated", eliminations);
7587 statistics_counter_event (cfun, "Insertions", insertions);
7588
7589 /* We cannot remove stmts during BB walk, especially not release SSA
7590 names there as this confuses the VN machinery. The stmts ending
7591 up in to_remove are either stores or simple copies.
7592 Remove stmts in reverse order to make debug stmt creation possible. */
7593 while (!to_remove.is_empty ())
7594 {
7595 bool do_release_defs = true;
7596 gimple *stmt = to_remove.pop ();
7597
7598 /* When we are value-numbering a region we do not require exit PHIs to
7599 be present so we have to make sure to deal with uses outside of the
7600 region of stmts that we thought are eliminated.
7601 ??? Note we may be confused by uses in dead regions we didn't run
7602 elimination on. Rather than checking individual uses we accept
7603 dead copies to be generated here (gcc.c-torture/execute/20060905-1.c
7604 contains such example). */
7605 if (region_p)
7606 {
7607 if (gphi *phi = dyn_cast <gphi *> (stmt))
7608 {
7609 tree lhs = gimple_phi_result (phi);
7610 if (!has_zero_uses (lhs))
7611 {
7612 if (dump_file && (dump_flags & TDF_DETAILS))
7613 fprintf (dump_file, "Keeping eliminated stmt live "
7614 "as copy because of out-of-region uses\n");
7615 tree sprime = eliminate_avail (gimple_bb (stmt), lhs);
7616 gimple *copy = gimple_build_assign (lhs, sprime);
7617 gimple_stmt_iterator gsi
7618 = gsi_after_labels (gimple_bb (stmt));
7619 gsi_insert_before (&gsi, copy, GSI_SAME_STMT);
7620 do_release_defs = false;
7621 }
7622 }
7623 else if (tree lhs = gimple_get_lhs (stmt))
7624 if (TREE_CODE (lhs) == SSA_NAME
7625 && !has_zero_uses (lhs))
7626 {
7627 if (dump_file && (dump_flags & TDF_DETAILS))
7628 fprintf (dump_file, "Keeping eliminated stmt live "
7629 "as copy because of out-of-region uses\n");
7630 tree sprime = eliminate_avail (gimple_bb (stmt), lhs);
7631 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
7632 if (is_gimple_assign (stmt))
7633 {
7634 gimple_assign_set_rhs_from_tree (&gsi, sprime);
7635 stmt = gsi_stmt (gsi);
7636 update_stmt (stmt);
7637 if (maybe_clean_or_replace_eh_stmt (stmt, stmt))
7638 bitmap_set_bit (need_eh_cleanup, gimple_bb (stmt)->index);
7639 continue;
7640 }
7641 else
7642 {
7643 gimple *copy = gimple_build_assign (lhs, sprime);
7644 gsi_insert_before (&gsi, copy, GSI_SAME_STMT);
7645 do_release_defs = false;
7646 }
7647 }
7648 }
7649
7650 if (dump_file && (dump_flags & TDF_DETAILS))
7651 {
7652 fprintf (dump_file, "Removing dead stmt ");
7653 print_gimple_stmt (dump_file, stmt, 0, TDF_NONE);
7654 }
7655
7656 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
7657 if (gimple_code (stmt) == GIMPLE_PHI)
7658 remove_phi_node (&gsi, do_release_defs);
7659 else
7660 {
7661 basic_block bb = gimple_bb (stmt);
7662 unlink_stmt_vdef (stmt);
7663 if (gsi_remove (&gsi, true))
7664 bitmap_set_bit (need_eh_cleanup, bb->index);
7665 if (is_gimple_call (stmt) && stmt_can_make_abnormal_goto (stmt))
7666 bitmap_set_bit (need_ab_cleanup, bb->index);
7667 if (do_release_defs)
7668 release_defs (stmt);
7669 }
7670
7671 /* Removing a stmt may expose a forwarder block. */
7672 el_todo |= TODO_cleanup_cfg;
7673 }
7674
7675 /* Fixup stmts that became noreturn calls. This may require splitting
7676 blocks and thus isn't possible during the dominator walk. Do this
7677 in reverse order so we don't inadvertedly remove a stmt we want to
7678 fixup by visiting a dominating now noreturn call first. */
7679 while (!to_fixup.is_empty ())
7680 {
7681 gimple *stmt = to_fixup.pop ();
7682
7683 if (dump_file && (dump_flags & TDF_DETAILS))
7684 {
7685 fprintf (dump_file, "Fixing up noreturn call ");
7686 print_gimple_stmt (dump_file, stmt, 0);
7687 }
7688
7689 if (fixup_noreturn_call (stmt))
7690 el_todo |= TODO_cleanup_cfg;
7691 }
7692
7693 bool do_eh_cleanup = !bitmap_empty_p (need_eh_cleanup);
7694 bool do_ab_cleanup = !bitmap_empty_p (need_ab_cleanup);
7695
7696 if (do_eh_cleanup)
7697 gimple_purge_all_dead_eh_edges (need_eh_cleanup);
7698
7699 if (do_ab_cleanup)
7700 gimple_purge_all_dead_abnormal_call_edges (need_ab_cleanup);
7701
7702 if (do_eh_cleanup || do_ab_cleanup)
7703 el_todo |= TODO_cleanup_cfg;
7704
7705 return el_todo;
7706 }
7707
7708 /* Eliminate fully redundant computations. */
7709
7710 unsigned
7711 eliminate_with_rpo_vn (bitmap inserted_exprs)
7712 {
7713 eliminate_dom_walker walker (CDI_DOMINATORS, inserted_exprs);
7714
7715 eliminate_dom_walker *saved_rpo_avail = rpo_avail;
7716 rpo_avail = &walker;
7717 walker.walk (cfun->cfg->x_entry_block_ptr);
7718 rpo_avail = saved_rpo_avail;
7719
7720 return walker.eliminate_cleanup ();
7721 }
7722
7723 static unsigned
7724 do_rpo_vn_1 (function *fn, edge entry, bitmap exit_bbs,
7725 bool iterate, bool eliminate, bool skip_entry_phis,
7726 vn_lookup_kind kind);
7727
7728 void
7729 run_rpo_vn (vn_lookup_kind kind)
7730 {
7731 do_rpo_vn_1 (cfun, NULL, NULL, true, false, false, kind);
7732
7733 /* ??? Prune requirement of these. */
7734 constant_to_value_id = new hash_table<vn_constant_hasher> (23);
7735
7736 /* Initialize the value ids and prune out remaining VN_TOPs
7737 from dead code. */
7738 tree name;
7739 unsigned i;
7740 FOR_EACH_SSA_NAME (i, name, cfun)
7741 {
7742 vn_ssa_aux_t info = VN_INFO (name);
7743 if (!info->visited
7744 || info->valnum == VN_TOP)
7745 info->valnum = name;
7746 if (info->valnum == name)
7747 info->value_id = get_next_value_id ();
7748 else if (is_gimple_min_invariant (info->valnum))
7749 info->value_id = get_or_alloc_constant_value_id (info->valnum);
7750 }
7751
7752 /* Propagate. */
7753 FOR_EACH_SSA_NAME (i, name, cfun)
7754 {
7755 vn_ssa_aux_t info = VN_INFO (name);
7756 if (TREE_CODE (info->valnum) == SSA_NAME
7757 && info->valnum != name
7758 && info->value_id != VN_INFO (info->valnum)->value_id)
7759 info->value_id = VN_INFO (info->valnum)->value_id;
7760 }
7761
7762 set_hashtable_value_ids ();
7763
7764 if (dump_file && (dump_flags & TDF_DETAILS))
7765 {
7766 fprintf (dump_file, "Value numbers:\n");
7767 FOR_EACH_SSA_NAME (i, name, cfun)
7768 {
7769 if (VN_INFO (name)->visited
7770 && SSA_VAL (name) != name)
7771 {
7772 print_generic_expr (dump_file, name);
7773 fprintf (dump_file, " = ");
7774 print_generic_expr (dump_file, SSA_VAL (name));
7775 fprintf (dump_file, " (%04d)\n", VN_INFO (name)->value_id);
7776 }
7777 }
7778 }
7779 }
7780
7781 /* Free VN associated data structures. */
7782
7783 void
7784 free_rpo_vn (void)
7785 {
7786 free_vn_table (valid_info);
7787 XDELETE (valid_info);
7788 obstack_free (&vn_tables_obstack, NULL);
7789 obstack_free (&vn_tables_insert_obstack, NULL);
7790
7791 vn_ssa_aux_iterator_type it;
7792 vn_ssa_aux_t info;
7793 FOR_EACH_HASH_TABLE_ELEMENT (*vn_ssa_aux_hash, info, vn_ssa_aux_t, it)
7794 if (info->needs_insertion)
7795 release_ssa_name (info->name);
7796 obstack_free (&vn_ssa_aux_obstack, NULL);
7797 delete vn_ssa_aux_hash;
7798
7799 delete constant_to_value_id;
7800 constant_to_value_id = NULL;
7801 }
7802
7803 /* Hook for maybe_push_res_to_seq, lookup the expression in the VN tables. */
7804
7805 static tree
7806 vn_lookup_simplify_result (gimple_match_op *res_op)
7807 {
7808 if (!res_op->code.is_tree_code ())
7809 return NULL_TREE;
7810 tree *ops = res_op->ops;
7811 unsigned int length = res_op->num_ops;
7812 if (res_op->code == CONSTRUCTOR
7813 /* ??? We're arriving here with SCCVNs view, decomposed CONSTRUCTOR
7814 and GIMPLEs / match-and-simplifies, CONSTRUCTOR as GENERIC tree. */
7815 && TREE_CODE (res_op->ops[0]) == CONSTRUCTOR)
7816 {
7817 length = CONSTRUCTOR_NELTS (res_op->ops[0]);
7818 ops = XALLOCAVEC (tree, length);
7819 for (unsigned i = 0; i < length; ++i)
7820 ops[i] = CONSTRUCTOR_ELT (res_op->ops[0], i)->value;
7821 }
7822 vn_nary_op_t vnresult = NULL;
7823 tree res = vn_nary_op_lookup_pieces (length, (tree_code) res_op->code,
7824 res_op->type, ops, &vnresult);
7825 /* If this is used from expression simplification make sure to
7826 return an available expression. */
7827 if (res && TREE_CODE (res) == SSA_NAME && mprts_hook && rpo_avail)
7828 res = rpo_avail->eliminate_avail (vn_context_bb, res);
7829 return res;
7830 }
7831
7832 /* Return a leader for OPs value that is valid at BB. */
7833
7834 tree
7835 rpo_elim::eliminate_avail (basic_block bb, tree op)
7836 {
7837 bool visited;
7838 tree valnum = SSA_VAL (op, &visited);
7839 /* If we didn't visit OP then it must be defined outside of the
7840 region we process and also dominate it. So it is available. */
7841 if (!visited)
7842 return op;
7843 if (TREE_CODE (valnum) == SSA_NAME)
7844 {
7845 if (SSA_NAME_IS_DEFAULT_DEF (valnum))
7846 return valnum;
7847 vn_ssa_aux_t valnum_info = VN_INFO (valnum);
7848 vn_avail *av = valnum_info->avail;
7849 if (!av)
7850 {
7851 /* See above. But when there's availability info prefer
7852 what we recorded there for example to preserve LC SSA. */
7853 if (!valnum_info->visited)
7854 return valnum;
7855 return NULL_TREE;
7856 }
7857 if (av->location == bb->index)
7858 /* On tramp3d 90% of the cases are here. */
7859 return ssa_name (av->leader);
7860 do
7861 {
7862 basic_block abb = BASIC_BLOCK_FOR_FN (cfun, av->location);
7863 /* ??? During elimination we have to use availability at the
7864 definition site of a use we try to replace. This
7865 is required to not run into inconsistencies because
7866 of dominated_by_p_w_unex behavior and removing a definition
7867 while not replacing all uses.
7868 ??? We could try to consistently walk dominators
7869 ignoring non-executable regions. The nearest common
7870 dominator of bb and abb is where we can stop walking. We
7871 may also be able to "pre-compute" (bits of) the next immediate
7872 (non-)dominator during the RPO walk when marking edges as
7873 executable. */
7874 if (dominated_by_p_w_unex (bb, abb, true))
7875 {
7876 tree leader = ssa_name (av->leader);
7877 /* Prevent eliminations that break loop-closed SSA. */
7878 if (loops_state_satisfies_p (LOOP_CLOSED_SSA)
7879 && ! SSA_NAME_IS_DEFAULT_DEF (leader)
7880 && ! flow_bb_inside_loop_p (gimple_bb (SSA_NAME_DEF_STMT
7881 (leader))->loop_father,
7882 bb))
7883 return NULL_TREE;
7884 if (dump_file && (dump_flags & TDF_DETAILS))
7885 {
7886 print_generic_expr (dump_file, leader);
7887 fprintf (dump_file, " is available for ");
7888 print_generic_expr (dump_file, valnum);
7889 fprintf (dump_file, "\n");
7890 }
7891 /* On tramp3d 99% of the _remaining_ cases succeed at
7892 the first enty. */
7893 return leader;
7894 }
7895 /* ??? Can we somehow skip to the immediate dominator
7896 RPO index (bb_to_rpo)? Again, maybe not worth, on
7897 tramp3d the worst number of elements in the vector is 9. */
7898 av = av->next;
7899 }
7900 while (av);
7901 /* While we prefer avail we have to fallback to using the value
7902 directly if defined outside of the region when none of the
7903 available defs suit. */
7904 if (!valnum_info->visited)
7905 return valnum;
7906 }
7907 else if (valnum != VN_TOP)
7908 /* valnum is is_gimple_min_invariant. */
7909 return valnum;
7910 return NULL_TREE;
7911 }
7912
7913 /* Make LEADER a leader for its value at BB. */
7914
7915 void
7916 rpo_elim::eliminate_push_avail (basic_block bb, tree leader)
7917 {
7918 tree valnum = VN_INFO (leader)->valnum;
7919 if (valnum == VN_TOP
7920 || is_gimple_min_invariant (valnum))
7921 return;
7922 if (dump_file && (dump_flags & TDF_DETAILS))
7923 {
7924 fprintf (dump_file, "Making available beyond BB%d ", bb->index);
7925 print_generic_expr (dump_file, leader);
7926 fprintf (dump_file, " for value ");
7927 print_generic_expr (dump_file, valnum);
7928 fprintf (dump_file, "\n");
7929 }
7930 vn_ssa_aux_t value = VN_INFO (valnum);
7931 vn_avail *av;
7932 if (m_avail_freelist)
7933 {
7934 av = m_avail_freelist;
7935 m_avail_freelist = m_avail_freelist->next;
7936 }
7937 else
7938 av = XOBNEW (&vn_ssa_aux_obstack, vn_avail);
7939 av->location = bb->index;
7940 av->leader = SSA_NAME_VERSION (leader);
7941 av->next = value->avail;
7942 av->next_undo = last_pushed_avail;
7943 last_pushed_avail = value;
7944 value->avail = av;
7945 }
7946
7947 /* Valueization hook for RPO VN plus required state. */
7948
7949 tree
7950 rpo_vn_valueize (tree name)
7951 {
7952 if (TREE_CODE (name) == SSA_NAME)
7953 {
7954 vn_ssa_aux_t val = VN_INFO (name);
7955 if (val)
7956 {
7957 tree tem = val->valnum;
7958 if (tem != VN_TOP && tem != name)
7959 {
7960 if (TREE_CODE (tem) != SSA_NAME)
7961 return tem;
7962 /* For all values we only valueize to an available leader
7963 which means we can use SSA name info without restriction. */
7964 tem = rpo_avail->eliminate_avail (vn_context_bb, tem);
7965 if (tem)
7966 return tem;
7967 }
7968 }
7969 }
7970 return name;
7971 }
7972
7973 /* Insert on PRED_E predicates derived from CODE OPS being true besides the
7974 inverted condition. */
7975
7976 static void
7977 insert_related_predicates_on_edge (enum tree_code code, tree *ops, edge pred_e)
7978 {
7979 switch (code)
7980 {
7981 case LT_EXPR:
7982 /* a < b -> a {!,<}= b */
7983 vn_nary_op_insert_pieces_predicated (2, NE_EXPR, boolean_type_node,
7984 ops, boolean_true_node, 0, pred_e);
7985 vn_nary_op_insert_pieces_predicated (2, LE_EXPR, boolean_type_node,
7986 ops, boolean_true_node, 0, pred_e);
7987 /* a < b -> ! a {>,=} b */
7988 vn_nary_op_insert_pieces_predicated (2, GT_EXPR, boolean_type_node,
7989 ops, boolean_false_node, 0, pred_e);
7990 vn_nary_op_insert_pieces_predicated (2, EQ_EXPR, boolean_type_node,
7991 ops, boolean_false_node, 0, pred_e);
7992 break;
7993 case GT_EXPR:
7994 /* a > b -> a {!,>}= b */
7995 vn_nary_op_insert_pieces_predicated (2, NE_EXPR, boolean_type_node,
7996 ops, boolean_true_node, 0, pred_e);
7997 vn_nary_op_insert_pieces_predicated (2, GE_EXPR, boolean_type_node,
7998 ops, boolean_true_node, 0, pred_e);
7999 /* a > b -> ! a {<,=} b */
8000 vn_nary_op_insert_pieces_predicated (2, LT_EXPR, boolean_type_node,
8001 ops, boolean_false_node, 0, pred_e);
8002 vn_nary_op_insert_pieces_predicated (2, EQ_EXPR, boolean_type_node,
8003 ops, boolean_false_node, 0, pred_e);
8004 break;
8005 case EQ_EXPR:
8006 /* a == b -> ! a {<,>} b */
8007 vn_nary_op_insert_pieces_predicated (2, LT_EXPR, boolean_type_node,
8008 ops, boolean_false_node, 0, pred_e);
8009 vn_nary_op_insert_pieces_predicated (2, GT_EXPR, boolean_type_node,
8010 ops, boolean_false_node, 0, pred_e);
8011 break;
8012 case LE_EXPR:
8013 case GE_EXPR:
8014 case NE_EXPR:
8015 /* Nothing besides inverted condition. */
8016 break;
8017 default:;
8018 }
8019 }
8020
8021 /* Insert on the TRUE_E true and FALSE_E false predicates
8022 derived from LHS CODE RHS. */
8023
8024 static void
8025 insert_predicates_for_cond (tree_code code, tree lhs, tree rhs,
8026 edge true_e, edge false_e)
8027 {
8028 /* If both edges are null, then there is nothing to be done. */
8029 if (!true_e && !false_e)
8030 return;
8031
8032 /* Canonicalize the comparison if needed, putting
8033 the constant in the rhs. */
8034 if (tree_swap_operands_p (lhs, rhs))
8035 {
8036 std::swap (lhs, rhs);
8037 code = swap_tree_comparison (code);
8038 }
8039
8040 /* If the lhs is not a ssa name, don't record anything. */
8041 if (TREE_CODE (lhs) != SSA_NAME)
8042 return;
8043
8044 tree_code icode = invert_tree_comparison (code, HONOR_NANS (lhs));
8045 tree ops[2];
8046 ops[0] = lhs;
8047 ops[1] = rhs;
8048 if (true_e)
8049 vn_nary_op_insert_pieces_predicated (2, code, boolean_type_node, ops,
8050 boolean_true_node, 0, true_e);
8051 if (false_e)
8052 vn_nary_op_insert_pieces_predicated (2, code, boolean_type_node, ops,
8053 boolean_false_node, 0, false_e);
8054 if (icode != ERROR_MARK)
8055 {
8056 if (true_e)
8057 vn_nary_op_insert_pieces_predicated (2, icode, boolean_type_node, ops,
8058 boolean_false_node, 0, true_e);
8059 if (false_e)
8060 vn_nary_op_insert_pieces_predicated (2, icode, boolean_type_node, ops,
8061 boolean_true_node, 0, false_e);
8062 }
8063 /* Relax for non-integers, inverted condition handled
8064 above. */
8065 if (INTEGRAL_TYPE_P (TREE_TYPE (lhs)))
8066 {
8067 if (true_e)
8068 insert_related_predicates_on_edge (code, ops, true_e);
8069 if (false_e)
8070 insert_related_predicates_on_edge (icode, ops, false_e);
8071 }
8072 if (integer_zerop (rhs)
8073 && (code == NE_EXPR || code == EQ_EXPR))
8074 {
8075 gimple *def_stmt = SSA_NAME_DEF_STMT (lhs);
8076 /* (A CMP B) != 0 is the same as (A CMP B).
8077 (A CMP B) == 0 is just (A CMP B) with the edges swapped. */
8078 if (is_gimple_assign (def_stmt)
8079 && TREE_CODE_CLASS (gimple_assign_rhs_code (def_stmt)) == tcc_comparison)
8080 {
8081 tree_code nc = gimple_assign_rhs_code (def_stmt);
8082 tree nlhs = vn_valueize (gimple_assign_rhs1 (def_stmt));
8083 tree nrhs = vn_valueize (gimple_assign_rhs2 (def_stmt));
8084 edge nt = true_e;
8085 edge nf = false_e;
8086 if (code == EQ_EXPR)
8087 std::swap (nt, nf);
8088 if (lhs != nlhs)
8089 insert_predicates_for_cond (nc, nlhs, nrhs, nt, nf);
8090 }
8091 /* (a | b) == 0 ->
8092 on true edge assert: a == 0 & b == 0. */
8093 /* (a | b) != 0 ->
8094 on false edge assert: a == 0 & b == 0. */
8095 if (is_gimple_assign (def_stmt)
8096 && gimple_assign_rhs_code (def_stmt) == BIT_IOR_EXPR)
8097 {
8098 edge e = code == EQ_EXPR ? true_e : false_e;
8099 tree nlhs;
8100
8101 nlhs = vn_valueize (gimple_assign_rhs1 (def_stmt));
8102 /* A valueization of the `a` might return the old lhs
8103 which is already handled above. */
8104 if (nlhs != lhs)
8105 insert_predicates_for_cond (EQ_EXPR, nlhs, rhs, e, nullptr);
8106
8107 /* A valueization of the `b` might return the old lhs
8108 which is already handled above. */
8109 nlhs = vn_valueize (gimple_assign_rhs2 (def_stmt));
8110 if (nlhs != lhs)
8111 insert_predicates_for_cond (EQ_EXPR, nlhs, rhs, e, nullptr);
8112 }
8113 }
8114 }
8115
8116 /* Main stmt worker for RPO VN, process BB. */
8117
8118 static unsigned
8119 process_bb (rpo_elim &avail, basic_block bb,
8120 bool bb_visited, bool iterate_phis, bool iterate, bool eliminate,
8121 bool do_region, bitmap exit_bbs, bool skip_phis)
8122 {
8123 unsigned todo = 0;
8124 edge_iterator ei;
8125 edge e;
8126
8127 vn_context_bb = bb;
8128
8129 /* If we are in loop-closed SSA preserve this state. This is
8130 relevant when called on regions from outside of FRE/PRE. */
8131 bool lc_phi_nodes = false;
8132 if (!skip_phis
8133 && loops_state_satisfies_p (LOOP_CLOSED_SSA))
8134 FOR_EACH_EDGE (e, ei, bb->preds)
8135 if (e->src->loop_father != e->dest->loop_father
8136 && flow_loop_nested_p (e->dest->loop_father,
8137 e->src->loop_father))
8138 {
8139 lc_phi_nodes = true;
8140 break;
8141 }
8142
8143 /* When we visit a loop header substitute into loop info. */
8144 if (!iterate && eliminate && bb->loop_father->header == bb)
8145 {
8146 /* Keep fields in sync with substitute_in_loop_info. */
8147 if (bb->loop_father->nb_iterations)
8148 bb->loop_father->nb_iterations
8149 = simplify_replace_tree (bb->loop_father->nb_iterations,
8150 NULL_TREE, NULL_TREE, &vn_valueize_for_srt);
8151 }
8152
8153 /* Value-number all defs in the basic-block. */
8154 if (!skip_phis)
8155 for (gphi_iterator gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
8156 gsi_next (&gsi))
8157 {
8158 gphi *phi = gsi.phi ();
8159 tree res = PHI_RESULT (phi);
8160 vn_ssa_aux_t res_info = VN_INFO (res);
8161 if (!bb_visited)
8162 {
8163 gcc_assert (!res_info->visited);
8164 res_info->valnum = VN_TOP;
8165 res_info->visited = true;
8166 }
8167
8168 /* When not iterating force backedge values to varying. */
8169 visit_stmt (phi, !iterate_phis);
8170 if (virtual_operand_p (res))
8171 continue;
8172
8173 /* Eliminate */
8174 /* The interesting case is gcc.dg/tree-ssa/pr22230.c for correctness
8175 how we handle backedges and availability.
8176 And gcc.dg/tree-ssa/ssa-sccvn-2.c for optimization. */
8177 tree val = res_info->valnum;
8178 if (res != val && !iterate && eliminate)
8179 {
8180 if (tree leader = avail.eliminate_avail (bb, res))
8181 {
8182 if (leader != res
8183 /* Preserve loop-closed SSA form. */
8184 && (! lc_phi_nodes
8185 || is_gimple_min_invariant (leader)))
8186 {
8187 if (dump_file && (dump_flags & TDF_DETAILS))
8188 {
8189 fprintf (dump_file, "Replaced redundant PHI node "
8190 "defining ");
8191 print_generic_expr (dump_file, res);
8192 fprintf (dump_file, " with ");
8193 print_generic_expr (dump_file, leader);
8194 fprintf (dump_file, "\n");
8195 }
8196 avail.eliminations++;
8197
8198 if (may_propagate_copy (res, leader))
8199 {
8200 /* Schedule for removal. */
8201 avail.to_remove.safe_push (phi);
8202 continue;
8203 }
8204 /* ??? Else generate a copy stmt. */
8205 }
8206 }
8207 }
8208 /* Only make defs available that not already are. But make
8209 sure loop-closed SSA PHI node defs are picked up for
8210 downstream uses. */
8211 if (lc_phi_nodes
8212 || res == val
8213 || ! avail.eliminate_avail (bb, res))
8214 avail.eliminate_push_avail (bb, res);
8215 }
8216
8217 /* For empty BBs mark outgoing edges executable. For non-empty BBs
8218 we do this when processing the last stmt as we have to do this
8219 before elimination which otherwise forces GIMPLE_CONDs to
8220 if (1 != 0) style when seeing non-executable edges. */
8221 if (gsi_end_p (gsi_start_bb (bb)))
8222 {
8223 FOR_EACH_EDGE (e, ei, bb->succs)
8224 {
8225 if (!(e->flags & EDGE_EXECUTABLE))
8226 {
8227 if (dump_file && (dump_flags & TDF_DETAILS))
8228 fprintf (dump_file,
8229 "marking outgoing edge %d -> %d executable\n",
8230 e->src->index, e->dest->index);
8231 e->flags |= EDGE_EXECUTABLE;
8232 e->dest->flags |= BB_EXECUTABLE;
8233 }
8234 else if (!(e->dest->flags & BB_EXECUTABLE))
8235 {
8236 if (dump_file && (dump_flags & TDF_DETAILS))
8237 fprintf (dump_file,
8238 "marking destination block %d reachable\n",
8239 e->dest->index);
8240 e->dest->flags |= BB_EXECUTABLE;
8241 }
8242 }
8243 }
8244 for (gimple_stmt_iterator gsi = gsi_start_bb (bb);
8245 !gsi_end_p (gsi); gsi_next (&gsi))
8246 {
8247 ssa_op_iter i;
8248 tree op;
8249 if (!bb_visited)
8250 {
8251 FOR_EACH_SSA_TREE_OPERAND (op, gsi_stmt (gsi), i, SSA_OP_ALL_DEFS)
8252 {
8253 vn_ssa_aux_t op_info = VN_INFO (op);
8254 gcc_assert (!op_info->visited);
8255 op_info->valnum = VN_TOP;
8256 op_info->visited = true;
8257 }
8258
8259 /* We somehow have to deal with uses that are not defined
8260 in the processed region. Forcing unvisited uses to
8261 varying here doesn't play well with def-use following during
8262 expression simplification, so we deal with this by checking
8263 the visited flag in SSA_VAL. */
8264 }
8265
8266 visit_stmt (gsi_stmt (gsi));
8267
8268 gimple *last = gsi_stmt (gsi);
8269 e = NULL;
8270 switch (gimple_code (last))
8271 {
8272 case GIMPLE_SWITCH:
8273 e = find_taken_edge (bb, vn_valueize (gimple_switch_index
8274 (as_a <gswitch *> (last))));
8275 break;
8276 case GIMPLE_COND:
8277 {
8278 tree lhs = vn_valueize (gimple_cond_lhs (last));
8279 tree rhs = vn_valueize (gimple_cond_rhs (last));
8280 tree_code cmpcode = gimple_cond_code (last);
8281 /* Canonicalize the comparison if needed, putting
8282 the constant in the rhs. */
8283 if (tree_swap_operands_p (lhs, rhs))
8284 {
8285 std::swap (lhs, rhs);
8286 cmpcode = swap_tree_comparison (cmpcode);
8287 }
8288 tree val = gimple_simplify (cmpcode,
8289 boolean_type_node, lhs, rhs,
8290 NULL, vn_valueize);
8291 /* If the condition didn't simplfy see if we have recorded
8292 an expression from sofar taken edges. */
8293 if (! val || TREE_CODE (val) != INTEGER_CST)
8294 {
8295 vn_nary_op_t vnresult;
8296 tree ops[2];
8297 ops[0] = lhs;
8298 ops[1] = rhs;
8299 val = vn_nary_op_lookup_pieces (2, cmpcode,
8300 boolean_type_node, ops,
8301 &vnresult);
8302 /* Got back a ssa name, then try looking up `val != 0`
8303 as it might have been recorded that way. */
8304 if (val && TREE_CODE (val) == SSA_NAME)
8305 {
8306 ops[0] = val;
8307 ops[1] = build_zero_cst (TREE_TYPE (val));
8308 val = vn_nary_op_lookup_pieces (2, NE_EXPR,
8309 boolean_type_node, ops,
8310 &vnresult);
8311 }
8312 /* Did we get a predicated value? */
8313 if (! val && vnresult && vnresult->predicated_values)
8314 {
8315 val = vn_nary_op_get_predicated_value (vnresult, bb);
8316 if (val && dump_file && (dump_flags & TDF_DETAILS))
8317 {
8318 fprintf (dump_file, "Got predicated value ");
8319 print_generic_expr (dump_file, val, TDF_NONE);
8320 fprintf (dump_file, " for ");
8321 print_gimple_stmt (dump_file, last, TDF_SLIM);
8322 }
8323 }
8324 }
8325 if (val)
8326 e = find_taken_edge (bb, val);
8327 if (! e)
8328 {
8329 /* If we didn't manage to compute the taken edge then
8330 push predicated expressions for the condition itself
8331 and related conditions to the hashtables. This allows
8332 simplification of redundant conditions which is
8333 important as early cleanup. */
8334 edge true_e, false_e;
8335 extract_true_false_edges_from_block (bb, &true_e, &false_e);
8336 if ((do_region && bitmap_bit_p (exit_bbs, true_e->dest->index))
8337 || !can_track_predicate_on_edge (true_e))
8338 true_e = NULL;
8339 if ((do_region && bitmap_bit_p (exit_bbs, false_e->dest->index))
8340 || !can_track_predicate_on_edge (false_e))
8341 false_e = NULL;
8342 insert_predicates_for_cond (cmpcode, lhs, rhs, true_e, false_e);
8343 }
8344 break;
8345 }
8346 case GIMPLE_GOTO:
8347 e = find_taken_edge (bb, vn_valueize (gimple_goto_dest (last)));
8348 break;
8349 default:
8350 e = NULL;
8351 }
8352 if (e)
8353 {
8354 todo = TODO_cleanup_cfg;
8355 if (!(e->flags & EDGE_EXECUTABLE))
8356 {
8357 if (dump_file && (dump_flags & TDF_DETAILS))
8358 fprintf (dump_file,
8359 "marking known outgoing %sedge %d -> %d executable\n",
8360 e->flags & EDGE_DFS_BACK ? "back-" : "",
8361 e->src->index, e->dest->index);
8362 e->flags |= EDGE_EXECUTABLE;
8363 e->dest->flags |= BB_EXECUTABLE;
8364 }
8365 else if (!(e->dest->flags & BB_EXECUTABLE))
8366 {
8367 if (dump_file && (dump_flags & TDF_DETAILS))
8368 fprintf (dump_file,
8369 "marking destination block %d reachable\n",
8370 e->dest->index);
8371 e->dest->flags |= BB_EXECUTABLE;
8372 }
8373 }
8374 else if (gsi_one_before_end_p (gsi))
8375 {
8376 FOR_EACH_EDGE (e, ei, bb->succs)
8377 {
8378 if (!(e->flags & EDGE_EXECUTABLE))
8379 {
8380 if (dump_file && (dump_flags & TDF_DETAILS))
8381 fprintf (dump_file,
8382 "marking outgoing edge %d -> %d executable\n",
8383 e->src->index, e->dest->index);
8384 e->flags |= EDGE_EXECUTABLE;
8385 e->dest->flags |= BB_EXECUTABLE;
8386 }
8387 else if (!(e->dest->flags & BB_EXECUTABLE))
8388 {
8389 if (dump_file && (dump_flags & TDF_DETAILS))
8390 fprintf (dump_file,
8391 "marking destination block %d reachable\n",
8392 e->dest->index);
8393 e->dest->flags |= BB_EXECUTABLE;
8394 }
8395 }
8396 }
8397
8398 /* Eliminate. That also pushes to avail. */
8399 if (eliminate && ! iterate)
8400 avail.eliminate_stmt (bb, &gsi);
8401 else
8402 /* If not eliminating, make all not already available defs
8403 available. But avoid picking up dead defs. */
8404 FOR_EACH_SSA_TREE_OPERAND (op, gsi_stmt (gsi), i, SSA_OP_DEF)
8405 if (! has_zero_uses (op)
8406 && ! avail.eliminate_avail (bb, op))
8407 avail.eliminate_push_avail (bb, op);
8408 }
8409
8410 /* Eliminate in destination PHI arguments. Always substitute in dest
8411 PHIs, even for non-executable edges. This handles region
8412 exits PHIs. */
8413 if (!iterate && eliminate)
8414 FOR_EACH_EDGE (e, ei, bb->succs)
8415 for (gphi_iterator gsi = gsi_start_phis (e->dest);
8416 !gsi_end_p (gsi); gsi_next (&gsi))
8417 {
8418 gphi *phi = gsi.phi ();
8419 use_operand_p use_p = PHI_ARG_DEF_PTR_FROM_EDGE (phi, e);
8420 tree arg = USE_FROM_PTR (use_p);
8421 if (TREE_CODE (arg) != SSA_NAME
8422 || virtual_operand_p (arg))
8423 continue;
8424 tree sprime;
8425 if (SSA_NAME_IS_DEFAULT_DEF (arg))
8426 {
8427 sprime = SSA_VAL (arg);
8428 gcc_assert (TREE_CODE (sprime) != SSA_NAME
8429 || SSA_NAME_IS_DEFAULT_DEF (sprime));
8430 }
8431 else
8432 /* Look for sth available at the definition block of the argument.
8433 This avoids inconsistencies between availability there which
8434 decides if the stmt can be removed and availability at the
8435 use site. The SSA property ensures that things available
8436 at the definition are also available at uses. */
8437 sprime = avail.eliminate_avail (gimple_bb (SSA_NAME_DEF_STMT (arg)),
8438 arg);
8439 if (sprime
8440 && sprime != arg
8441 && may_propagate_copy (arg, sprime, !(e->flags & EDGE_ABNORMAL)))
8442 propagate_value (use_p, sprime);
8443 }
8444
8445 vn_context_bb = NULL;
8446 return todo;
8447 }
8448
8449 /* Unwind state per basic-block. */
8450
8451 struct unwind_state
8452 {
8453 /* Times this block has been visited. */
8454 unsigned visited;
8455 /* Whether to handle this as iteration point or whether to treat
8456 incoming backedge PHI values as varying. */
8457 bool iterate;
8458 /* Maximum RPO index this block is reachable from. */
8459 int max_rpo;
8460 /* Unwind state. */
8461 void *ob_top;
8462 vn_reference_t ref_top;
8463 vn_phi_t phi_top;
8464 vn_nary_op_t nary_top;
8465 vn_avail *avail_top;
8466 };
8467
8468 /* Unwind the RPO VN state for iteration. */
8469
8470 static void
8471 do_unwind (unwind_state *to, rpo_elim &avail)
8472 {
8473 gcc_assert (to->iterate);
8474 for (; last_inserted_nary != to->nary_top;
8475 last_inserted_nary = last_inserted_nary->next)
8476 {
8477 vn_nary_op_t *slot;
8478 slot = valid_info->nary->find_slot_with_hash
8479 (last_inserted_nary, last_inserted_nary->hashcode, NO_INSERT);
8480 /* Predication causes the need to restore previous state. */
8481 if ((*slot)->unwind_to)
8482 *slot = (*slot)->unwind_to;
8483 else
8484 valid_info->nary->clear_slot (slot);
8485 }
8486 for (; last_inserted_phi != to->phi_top;
8487 last_inserted_phi = last_inserted_phi->next)
8488 {
8489 vn_phi_t *slot;
8490 slot = valid_info->phis->find_slot_with_hash
8491 (last_inserted_phi, last_inserted_phi->hashcode, NO_INSERT);
8492 valid_info->phis->clear_slot (slot);
8493 }
8494 for (; last_inserted_ref != to->ref_top;
8495 last_inserted_ref = last_inserted_ref->next)
8496 {
8497 vn_reference_t *slot;
8498 slot = valid_info->references->find_slot_with_hash
8499 (last_inserted_ref, last_inserted_ref->hashcode, NO_INSERT);
8500 (*slot)->operands.release ();
8501 valid_info->references->clear_slot (slot);
8502 }
8503 obstack_free (&vn_tables_obstack, to->ob_top);
8504
8505 /* Prune [rpo_idx, ] from avail. */
8506 for (; last_pushed_avail && last_pushed_avail->avail != to->avail_top;)
8507 {
8508 vn_ssa_aux_t val = last_pushed_avail;
8509 vn_avail *av = val->avail;
8510 val->avail = av->next;
8511 last_pushed_avail = av->next_undo;
8512 av->next = avail.m_avail_freelist;
8513 avail.m_avail_freelist = av;
8514 }
8515 }
8516
8517 /* Do VN on a SEME region specified by ENTRY and EXIT_BBS in FN.
8518 If ITERATE is true then treat backedges optimistically as not
8519 executed and iterate. If ELIMINATE is true then perform
8520 elimination, otherwise leave that to the caller. If SKIP_ENTRY_PHIS
8521 is true then force PHI nodes in ENTRY->dest to VARYING. */
8522
8523 static unsigned
8524 do_rpo_vn_1 (function *fn, edge entry, bitmap exit_bbs,
8525 bool iterate, bool eliminate, bool skip_entry_phis,
8526 vn_lookup_kind kind)
8527 {
8528 unsigned todo = 0;
8529 default_vn_walk_kind = kind;
8530
8531 /* We currently do not support region-based iteration when
8532 elimination is requested. */
8533 gcc_assert (!entry || !iterate || !eliminate);
8534 /* When iterating we need loop info up-to-date. */
8535 gcc_assert (!iterate || !loops_state_satisfies_p (LOOPS_NEED_FIXUP));
8536
8537 bool do_region = entry != NULL;
8538 if (!do_region)
8539 {
8540 entry = single_succ_edge (ENTRY_BLOCK_PTR_FOR_FN (fn));
8541 exit_bbs = BITMAP_ALLOC (NULL);
8542 bitmap_set_bit (exit_bbs, EXIT_BLOCK);
8543 }
8544
8545 /* Clear EDGE_DFS_BACK on "all" entry edges, RPO order compute will
8546 re-mark those that are contained in the region. */
8547 edge_iterator ei;
8548 edge e;
8549 FOR_EACH_EDGE (e, ei, entry->dest->preds)
8550 e->flags &= ~EDGE_DFS_BACK;
8551
8552 int *rpo = XNEWVEC (int, n_basic_blocks_for_fn (fn) - NUM_FIXED_BLOCKS);
8553 auto_vec<std::pair<int, int> > toplevel_scc_extents;
8554 int n = rev_post_order_and_mark_dfs_back_seme
8555 (fn, entry, exit_bbs, true, rpo, !iterate ? &toplevel_scc_extents : NULL);
8556
8557 if (!do_region)
8558 BITMAP_FREE (exit_bbs);
8559
8560 /* If there are any non-DFS_BACK edges into entry->dest skip
8561 processing PHI nodes for that block. This supports
8562 value-numbering loop bodies w/o the actual loop. */
8563 FOR_EACH_EDGE (e, ei, entry->dest->preds)
8564 if (e != entry
8565 && !(e->flags & EDGE_DFS_BACK))
8566 break;
8567 if (e != NULL && dump_file && (dump_flags & TDF_DETAILS))
8568 fprintf (dump_file, "Region does not contain all edges into "
8569 "the entry block, skipping its PHIs.\n");
8570 skip_entry_phis |= e != NULL;
8571
8572 int *bb_to_rpo = XNEWVEC (int, last_basic_block_for_fn (fn));
8573 for (int i = 0; i < n; ++i)
8574 bb_to_rpo[rpo[i]] = i;
8575 vn_bb_to_rpo = bb_to_rpo;
8576
8577 unwind_state *rpo_state = XNEWVEC (unwind_state, n);
8578
8579 rpo_elim avail (entry->dest);
8580 rpo_avail = &avail;
8581
8582 /* Verify we have no extra entries into the region. */
8583 if (flag_checking && do_region)
8584 {
8585 auto_bb_flag bb_in_region (fn);
8586 for (int i = 0; i < n; ++i)
8587 {
8588 basic_block bb = BASIC_BLOCK_FOR_FN (fn, rpo[i]);
8589 bb->flags |= bb_in_region;
8590 }
8591 /* We can't merge the first two loops because we cannot rely
8592 on EDGE_DFS_BACK for edges not within the region. But if
8593 we decide to always have the bb_in_region flag we can
8594 do the checking during the RPO walk itself (but then it's
8595 also easy to handle MEME conservatively). */
8596 for (int i = 0; i < n; ++i)
8597 {
8598 basic_block bb = BASIC_BLOCK_FOR_FN (fn, rpo[i]);
8599 edge e;
8600 edge_iterator ei;
8601 FOR_EACH_EDGE (e, ei, bb->preds)
8602 gcc_assert (e == entry
8603 || (skip_entry_phis && bb == entry->dest)
8604 || (e->src->flags & bb_in_region));
8605 }
8606 for (int i = 0; i < n; ++i)
8607 {
8608 basic_block bb = BASIC_BLOCK_FOR_FN (fn, rpo[i]);
8609 bb->flags &= ~bb_in_region;
8610 }
8611 }
8612
8613 /* Create the VN state. For the initial size of the various hashtables
8614 use a heuristic based on region size and number of SSA names. */
8615 unsigned region_size = (((unsigned HOST_WIDE_INT)n * num_ssa_names)
8616 / (n_basic_blocks_for_fn (fn) - NUM_FIXED_BLOCKS));
8617 VN_TOP = create_tmp_var_raw (void_type_node, "vn_top");
8618 next_value_id = 1;
8619 next_constant_value_id = -1;
8620
8621 vn_ssa_aux_hash = new hash_table <vn_ssa_aux_hasher> (region_size * 2);
8622 gcc_obstack_init (&vn_ssa_aux_obstack);
8623
8624 gcc_obstack_init (&vn_tables_obstack);
8625 gcc_obstack_init (&vn_tables_insert_obstack);
8626 valid_info = XCNEW (struct vn_tables_s);
8627 allocate_vn_table (valid_info, region_size);
8628 last_inserted_ref = NULL;
8629 last_inserted_phi = NULL;
8630 last_inserted_nary = NULL;
8631 last_pushed_avail = NULL;
8632
8633 vn_valueize = rpo_vn_valueize;
8634
8635 /* Initialize the unwind state and edge/BB executable state. */
8636 unsigned curr_scc = 0;
8637 for (int i = 0; i < n; ++i)
8638 {
8639 basic_block bb = BASIC_BLOCK_FOR_FN (fn, rpo[i]);
8640 rpo_state[i].visited = 0;
8641 rpo_state[i].max_rpo = i;
8642 if (!iterate && curr_scc < toplevel_scc_extents.length ())
8643 {
8644 if (i >= toplevel_scc_extents[curr_scc].first
8645 && i <= toplevel_scc_extents[curr_scc].second)
8646 rpo_state[i].max_rpo = toplevel_scc_extents[curr_scc].second;
8647 if (i == toplevel_scc_extents[curr_scc].second)
8648 curr_scc++;
8649 }
8650 bb->flags &= ~BB_EXECUTABLE;
8651 bool has_backedges = false;
8652 edge e;
8653 edge_iterator ei;
8654 FOR_EACH_EDGE (e, ei, bb->preds)
8655 {
8656 if (e->flags & EDGE_DFS_BACK)
8657 has_backedges = true;
8658 e->flags &= ~EDGE_EXECUTABLE;
8659 if (iterate || e == entry || (skip_entry_phis && bb == entry->dest))
8660 continue;
8661 }
8662 rpo_state[i].iterate = iterate && has_backedges;
8663 }
8664 entry->flags |= EDGE_EXECUTABLE;
8665 entry->dest->flags |= BB_EXECUTABLE;
8666
8667 /* As heuristic to improve compile-time we handle only the N innermost
8668 loops and the outermost one optimistically. */
8669 if (iterate)
8670 {
8671 unsigned max_depth = param_rpo_vn_max_loop_depth;
8672 for (auto loop : loops_list (cfun, LI_ONLY_INNERMOST))
8673 if (loop_depth (loop) > max_depth)
8674 for (unsigned i = 2;
8675 i < loop_depth (loop) - max_depth; ++i)
8676 {
8677 basic_block header = superloop_at_depth (loop, i)->header;
8678 bool non_latch_backedge = false;
8679 edge e;
8680 edge_iterator ei;
8681 FOR_EACH_EDGE (e, ei, header->preds)
8682 if (e->flags & EDGE_DFS_BACK)
8683 {
8684 /* There can be a non-latch backedge into the header
8685 which is part of an outer irreducible region. We
8686 cannot avoid iterating this block then. */
8687 if (!dominated_by_p (CDI_DOMINATORS,
8688 e->src, e->dest))
8689 {
8690 if (dump_file && (dump_flags & TDF_DETAILS))
8691 fprintf (dump_file, "non-latch backedge %d -> %d "
8692 "forces iteration of loop %d\n",
8693 e->src->index, e->dest->index, loop->num);
8694 non_latch_backedge = true;
8695 }
8696 else
8697 e->flags |= EDGE_EXECUTABLE;
8698 }
8699 rpo_state[bb_to_rpo[header->index]].iterate = non_latch_backedge;
8700 }
8701 }
8702
8703 uint64_t nblk = 0;
8704 int idx = 0;
8705 if (iterate)
8706 /* Go and process all blocks, iterating as necessary. */
8707 do
8708 {
8709 basic_block bb = BASIC_BLOCK_FOR_FN (fn, rpo[idx]);
8710
8711 /* If the block has incoming backedges remember unwind state. This
8712 is required even for non-executable blocks since in irreducible
8713 regions we might reach them via the backedge and re-start iterating
8714 from there.
8715 Note we can individually mark blocks with incoming backedges to
8716 not iterate where we then handle PHIs conservatively. We do that
8717 heuristically to reduce compile-time for degenerate cases. */
8718 if (rpo_state[idx].iterate)
8719 {
8720 rpo_state[idx].ob_top = obstack_alloc (&vn_tables_obstack, 0);
8721 rpo_state[idx].ref_top = last_inserted_ref;
8722 rpo_state[idx].phi_top = last_inserted_phi;
8723 rpo_state[idx].nary_top = last_inserted_nary;
8724 rpo_state[idx].avail_top
8725 = last_pushed_avail ? last_pushed_avail->avail : NULL;
8726 }
8727
8728 if (!(bb->flags & BB_EXECUTABLE))
8729 {
8730 if (dump_file && (dump_flags & TDF_DETAILS))
8731 fprintf (dump_file, "Block %d: BB%d found not executable\n",
8732 idx, bb->index);
8733 idx++;
8734 continue;
8735 }
8736
8737 if (dump_file && (dump_flags & TDF_DETAILS))
8738 fprintf (dump_file, "Processing block %d: BB%d\n", idx, bb->index);
8739 nblk++;
8740 todo |= process_bb (avail, bb,
8741 rpo_state[idx].visited != 0,
8742 rpo_state[idx].iterate,
8743 iterate, eliminate, do_region, exit_bbs, false);
8744 rpo_state[idx].visited++;
8745
8746 /* Verify if changed values flow over executable outgoing backedges
8747 and those change destination PHI values (that's the thing we
8748 can easily verify). Reduce over all such edges to the farthest
8749 away PHI. */
8750 int iterate_to = -1;
8751 edge_iterator ei;
8752 edge e;
8753 FOR_EACH_EDGE (e, ei, bb->succs)
8754 if ((e->flags & (EDGE_DFS_BACK|EDGE_EXECUTABLE))
8755 == (EDGE_DFS_BACK|EDGE_EXECUTABLE)
8756 && rpo_state[bb_to_rpo[e->dest->index]].iterate)
8757 {
8758 int destidx = bb_to_rpo[e->dest->index];
8759 if (!rpo_state[destidx].visited)
8760 {
8761 if (dump_file && (dump_flags & TDF_DETAILS))
8762 fprintf (dump_file, "Unvisited destination %d\n",
8763 e->dest->index);
8764 if (iterate_to == -1 || destidx < iterate_to)
8765 iterate_to = destidx;
8766 continue;
8767 }
8768 if (dump_file && (dump_flags & TDF_DETAILS))
8769 fprintf (dump_file, "Looking for changed values of backedge"
8770 " %d->%d destination PHIs\n",
8771 e->src->index, e->dest->index);
8772 vn_context_bb = e->dest;
8773 gphi_iterator gsi;
8774 for (gsi = gsi_start_phis (e->dest);
8775 !gsi_end_p (gsi); gsi_next (&gsi))
8776 {
8777 bool inserted = false;
8778 /* While we'd ideally just iterate on value changes
8779 we CSE PHIs and do that even across basic-block
8780 boundaries. So even hashtable state changes can
8781 be important (which is roughly equivalent to
8782 PHI argument value changes). To not excessively
8783 iterate because of that we track whether a PHI
8784 was CSEd to with GF_PLF_1. */
8785 bool phival_changed;
8786 if ((phival_changed = visit_phi (gsi.phi (),
8787 &inserted, false))
8788 || (inserted && gimple_plf (gsi.phi (), GF_PLF_1)))
8789 {
8790 if (!phival_changed
8791 && dump_file && (dump_flags & TDF_DETAILS))
8792 fprintf (dump_file, "PHI was CSEd and hashtable "
8793 "state (changed)\n");
8794 if (iterate_to == -1 || destidx < iterate_to)
8795 iterate_to = destidx;
8796 break;
8797 }
8798 }
8799 vn_context_bb = NULL;
8800 }
8801 if (iterate_to != -1)
8802 {
8803 do_unwind (&rpo_state[iterate_to], avail);
8804 idx = iterate_to;
8805 if (dump_file && (dump_flags & TDF_DETAILS))
8806 fprintf (dump_file, "Iterating to %d BB%d\n",
8807 iterate_to, rpo[iterate_to]);
8808 continue;
8809 }
8810
8811 idx++;
8812 }
8813 while (idx < n);
8814
8815 else /* !iterate */
8816 {
8817 /* Process all blocks greedily with a worklist that enforces RPO
8818 processing of reachable blocks. */
8819 auto_bitmap worklist;
8820 bitmap_set_bit (worklist, 0);
8821 while (!bitmap_empty_p (worklist))
8822 {
8823 int idx = bitmap_clear_first_set_bit (worklist);
8824 basic_block bb = BASIC_BLOCK_FOR_FN (fn, rpo[idx]);
8825 gcc_assert ((bb->flags & BB_EXECUTABLE)
8826 && !rpo_state[idx].visited);
8827
8828 if (dump_file && (dump_flags & TDF_DETAILS))
8829 fprintf (dump_file, "Processing block %d: BB%d\n", idx, bb->index);
8830
8831 /* When we run into predecessor edges where we cannot trust its
8832 executable state mark them executable so PHI processing will
8833 be conservative.
8834 ??? Do we need to force arguments flowing over that edge
8835 to be varying or will they even always be? */
8836 edge_iterator ei;
8837 edge e;
8838 FOR_EACH_EDGE (e, ei, bb->preds)
8839 if (!(e->flags & EDGE_EXECUTABLE)
8840 && (bb == entry->dest
8841 || (!rpo_state[bb_to_rpo[e->src->index]].visited
8842 && (rpo_state[bb_to_rpo[e->src->index]].max_rpo
8843 >= (int)idx))))
8844 {
8845 if (dump_file && (dump_flags & TDF_DETAILS))
8846 fprintf (dump_file, "Cannot trust state of predecessor "
8847 "edge %d -> %d, marking executable\n",
8848 e->src->index, e->dest->index);
8849 e->flags |= EDGE_EXECUTABLE;
8850 }
8851
8852 nblk++;
8853 todo |= process_bb (avail, bb, false, false, false, eliminate,
8854 do_region, exit_bbs,
8855 skip_entry_phis && bb == entry->dest);
8856 rpo_state[idx].visited++;
8857
8858 FOR_EACH_EDGE (e, ei, bb->succs)
8859 if ((e->flags & EDGE_EXECUTABLE)
8860 && e->dest->index != EXIT_BLOCK
8861 && (!do_region || !bitmap_bit_p (exit_bbs, e->dest->index))
8862 && !rpo_state[bb_to_rpo[e->dest->index]].visited)
8863 bitmap_set_bit (worklist, bb_to_rpo[e->dest->index]);
8864 }
8865 }
8866
8867 /* If statistics or dump file active. */
8868 int nex = 0;
8869 unsigned max_visited = 1;
8870 for (int i = 0; i < n; ++i)
8871 {
8872 basic_block bb = BASIC_BLOCK_FOR_FN (fn, rpo[i]);
8873 if (bb->flags & BB_EXECUTABLE)
8874 nex++;
8875 statistics_histogram_event (cfun, "RPO block visited times",
8876 rpo_state[i].visited);
8877 if (rpo_state[i].visited > max_visited)
8878 max_visited = rpo_state[i].visited;
8879 }
8880 unsigned nvalues = 0, navail = 0;
8881 for (hash_table<vn_ssa_aux_hasher>::iterator i = vn_ssa_aux_hash->begin ();
8882 i != vn_ssa_aux_hash->end (); ++i)
8883 {
8884 nvalues++;
8885 vn_avail *av = (*i)->avail;
8886 while (av)
8887 {
8888 navail++;
8889 av = av->next;
8890 }
8891 }
8892 statistics_counter_event (cfun, "RPO blocks", n);
8893 statistics_counter_event (cfun, "RPO blocks visited", nblk);
8894 statistics_counter_event (cfun, "RPO blocks executable", nex);
8895 statistics_histogram_event (cfun, "RPO iterations", 10*nblk / nex);
8896 statistics_histogram_event (cfun, "RPO num values", nvalues);
8897 statistics_histogram_event (cfun, "RPO num avail", navail);
8898 statistics_histogram_event (cfun, "RPO num lattice",
8899 vn_ssa_aux_hash->elements ());
8900 if (dump_file && (dump_flags & (TDF_DETAILS|TDF_STATS)))
8901 {
8902 fprintf (dump_file, "RPO iteration over %d blocks visited %" PRIu64
8903 " blocks in total discovering %d executable blocks iterating "
8904 "%d.%d times, a block was visited max. %u times\n",
8905 n, nblk, nex,
8906 (int)((10*nblk / nex)/10), (int)((10*nblk / nex)%10),
8907 max_visited);
8908 fprintf (dump_file, "RPO tracked %d values available at %d locations "
8909 "and %" PRIu64 " lattice elements\n",
8910 nvalues, navail, (uint64_t) vn_ssa_aux_hash->elements ());
8911 }
8912
8913 if (eliminate)
8914 {
8915 /* When !iterate we already performed elimination during the RPO
8916 walk. */
8917 if (iterate)
8918 {
8919 /* Elimination for region-based VN needs to be done within the
8920 RPO walk. */
8921 gcc_assert (! do_region);
8922 /* Note we can't use avail.walk here because that gets confused
8923 by the existing availability and it will be less efficient
8924 as well. */
8925 todo |= eliminate_with_rpo_vn (NULL);
8926 }
8927 else
8928 todo |= avail.eliminate_cleanup (do_region);
8929 }
8930
8931 vn_valueize = NULL;
8932 rpo_avail = NULL;
8933 vn_bb_to_rpo = NULL;
8934
8935 XDELETEVEC (bb_to_rpo);
8936 XDELETEVEC (rpo);
8937 XDELETEVEC (rpo_state);
8938
8939 return todo;
8940 }
8941
8942 /* Region-based entry for RPO VN. Performs value-numbering and elimination
8943 on the SEME region specified by ENTRY and EXIT_BBS. If ENTRY is not
8944 the only edge into the region at ENTRY->dest PHI nodes in ENTRY->dest
8945 are not considered.
8946 If ITERATE is true then treat backedges optimistically as not
8947 executed and iterate. If ELIMINATE is true then perform
8948 elimination, otherwise leave that to the caller.
8949 If SKIP_ENTRY_PHIS is true then force PHI nodes in ENTRY->dest to VARYING.
8950 KIND specifies the amount of work done for handling memory operations. */
8951
8952 unsigned
8953 do_rpo_vn (function *fn, edge entry, bitmap exit_bbs,
8954 bool iterate, bool eliminate, bool skip_entry_phis,
8955 vn_lookup_kind kind)
8956 {
8957 auto_timevar tv (TV_TREE_RPO_VN);
8958 unsigned todo = do_rpo_vn_1 (fn, entry, exit_bbs, iterate, eliminate,
8959 skip_entry_phis, kind);
8960 free_rpo_vn ();
8961 return todo;
8962 }
8963
8964
8965 namespace {
8966
8967 const pass_data pass_data_fre =
8968 {
8969 GIMPLE_PASS, /* type */
8970 "fre", /* name */
8971 OPTGROUP_NONE, /* optinfo_flags */
8972 TV_TREE_FRE, /* tv_id */
8973 ( PROP_cfg | PROP_ssa ), /* properties_required */
8974 0, /* properties_provided */
8975 0, /* properties_destroyed */
8976 0, /* todo_flags_start */
8977 0, /* todo_flags_finish */
8978 };
8979
8980 class pass_fre : public gimple_opt_pass
8981 {
8982 public:
8983 pass_fre (gcc::context *ctxt)
8984 : gimple_opt_pass (pass_data_fre, ctxt), may_iterate (true)
8985 {}
8986
8987 /* opt_pass methods: */
8988 opt_pass * clone () final override { return new pass_fre (m_ctxt); }
8989 void set_pass_param (unsigned int n, bool param) final override
8990 {
8991 gcc_assert (n == 0);
8992 may_iterate = param;
8993 }
8994 bool gate (function *) final override
8995 {
8996 return flag_tree_fre != 0 && (may_iterate || optimize > 1);
8997 }
8998 unsigned int execute (function *) final override;
8999
9000 private:
9001 bool may_iterate;
9002 }; // class pass_fre
9003
9004 unsigned int
9005 pass_fre::execute (function *fun)
9006 {
9007 unsigned todo = 0;
9008
9009 /* At -O[1g] use the cheap non-iterating mode. */
9010 bool iterate_p = may_iterate && (optimize > 1);
9011 calculate_dominance_info (CDI_DOMINATORS);
9012 if (iterate_p)
9013 loop_optimizer_init (AVOID_CFG_MODIFICATIONS);
9014
9015 todo = do_rpo_vn_1 (fun, NULL, NULL, iterate_p, true, false, VN_WALKREWRITE);
9016 free_rpo_vn ();
9017
9018 if (iterate_p)
9019 loop_optimizer_finalize ();
9020
9021 if (scev_initialized_p ())
9022 scev_reset_htab ();
9023
9024 /* For late FRE after IVOPTs and unrolling, see if we can
9025 remove some TREE_ADDRESSABLE and rewrite stuff into SSA. */
9026 if (!may_iterate)
9027 todo |= TODO_update_address_taken;
9028
9029 return todo;
9030 }
9031
9032 } // anon namespace
9033
9034 gimple_opt_pass *
9035 make_pass_fre (gcc::context *ctxt)
9036 {
9037 return new pass_fre (ctxt);
9038 }
9039
9040 #undef BB_EXECUTABLE