Debian Codegraph @

gcc/tree-ssa-forwprop.cc

raw
1 /* Forward propagation of expressions for single use variables.
2 Copyright (C) 2004-2025 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
6 GCC is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3, or (at your option)
9 any later version.
10
11 GCC is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
19
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "backend.h"
24 #include "rtl.h"
25 #include "tree.h"
26 #include "gimple.h"
27 #include "cfghooks.h"
28 #include "tree-pass.h"
29 #include "ssa.h"
30 #include "expmed.h"
31 #include "optabs-query.h"
32 #include "gimple-pretty-print.h"
33 #include "fold-const.h"
34 #include "stor-layout.h"
35 #include "gimple-iterator.h"
36 #include "gimple-fold.h"
37 #include "tree-eh.h"
38 #include "gimplify.h"
39 #include "gimplify-me.h"
40 #include "tree-cfg.h"
41 #include "expr.h"
42 #include "tree-dfa.h"
43 #include "tree-ssa-propagate.h"
44 #include "tree-ssa-dom.h"
45 #include "tree-ssa-strlen.h"
46 #include "builtins.h"
47 #include "tree-cfgcleanup.h"
48 #include "cfganal.h"
49 #include "optabs-tree.h"
50 #include "insn-config.h"
51 #include "recog.h"
52 #include "cfgloop.h"
53 #include "tree-vectorizer.h"
54 #include "tree-vector-builder.h"
55 #include "vec-perm-indices.h"
56 #include "internal-fn.h"
57 #include "cgraph.h"
58 #include "tree-ssa.h"
59 #include "gimple-range.h"
60 #include "tree-ssa-dce.h"
61
62 /* This pass propagates the RHS of assignment statements into use
63 sites of the LHS of the assignment. It's basically a specialized
64 form of tree combination. It is hoped all of this can disappear
65 when we have a generalized tree combiner.
66
67 One class of common cases we handle is forward propagating a single use
68 variable into a COND_EXPR.
69
70 bb0:
71 x = a COND b;
72 if (x) goto ... else goto ...
73
74 Will be transformed into:
75
76 bb0:
77 if (a COND b) goto ... else goto ...
78
79 Similarly for the tests (x == 0), (x != 0), (x == 1) and (x != 1).
80
81 Or (assuming c1 and c2 are constants):
82
83 bb0:
84 x = a + c1;
85 if (x EQ/NEQ c2) goto ... else goto ...
86
87 Will be transformed into:
88
89 bb0:
90 if (a EQ/NEQ (c2 - c1)) goto ... else goto ...
91
92 Similarly for x = a - c1.
93
94 Or
95
96 bb0:
97 x = !a
98 if (x) goto ... else goto ...
99
100 Will be transformed into:
101
102 bb0:
103 if (a == 0) goto ... else goto ...
104
105 Similarly for the tests (x == 0), (x != 0), (x == 1) and (x != 1).
106 For these cases, we propagate A into all, possibly more than one,
107 COND_EXPRs that use X.
108
109 Or
110
111 bb0:
112 x = (typecast) a
113 if (x) goto ... else goto ...
114
115 Will be transformed into:
116
117 bb0:
118 if (a != 0) goto ... else goto ...
119
120 (Assuming a is an integral type and x is a boolean or x is an
121 integral and a is a boolean.)
122
123 Similarly for the tests (x == 0), (x != 0), (x == 1) and (x != 1).
124 For these cases, we propagate A into all, possibly more than one,
125 COND_EXPRs that use X.
126
127 In addition to eliminating the variable and the statement which assigns
128 a value to the variable, we may be able to later thread the jump without
129 adding insane complexity in the dominator optimizer.
130
131 Also note these transformations can cascade. We handle this by having
132 a worklist of COND_EXPR statements to examine. As we make a change to
133 a statement, we put it back on the worklist to examine on the next
134 iteration of the main loop.
135
136 A second class of propagation opportunities arises for ADDR_EXPR
137 nodes.
138
139 ptr = &x->y->z;
140 res = *ptr;
141
142 Will get turned into
143
144 res = x->y->z;
145
146 Or
147 ptr = (type1*)&type2var;
148 res = *ptr
149
150 Will get turned into (if type1 and type2 are the same size
151 and neither have volatile on them):
152 res = VIEW_CONVERT_EXPR<type1>(type2var)
153
154 Or
155
156 ptr = &x[0];
157 ptr2 = ptr + <constant>;
158
159 Will get turned into
160
161 ptr2 = &x[constant/elementsize];
162
163 Or
164
165 ptr = &x[0];
166 offset = index * element_size;
167 offset_p = (pointer) offset;
168 ptr2 = ptr + offset_p
169
170 Will get turned into:
171
172 ptr2 = &x[index];
173
174 Or
175 ssa = (int) decl
176 res = ssa & 1
177
178 Provided that decl has known alignment >= 2, will get turned into
179
180 res = 0
181
182 We also propagate casts into SWITCH_EXPR and COND_EXPR conditions to
183 allow us to remove the cast and {NOT_EXPR,NEG_EXPR} into a subsequent
184 {NOT_EXPR,NEG_EXPR}.
185
186 This will (of course) be extended as other needs arise. */
187
188 /* Data structure that contains simplifiable vectorized permute sequences.
189 See recognise_vec_perm_simplify_seq () for a description of the sequence. */
190
191 struct _vec_perm_simplify_seq
192 {
193 /* Defining stmts of vectors in the sequence. */
194 gassign *v_1_stmt;
195 gassign *v_2_stmt;
196 gassign *v_x_stmt;
197 gassign *v_y_stmt;
198 /* Final permute statment. */
199 gassign *stmt;
200 /* New selector indices for stmt. */
201 tree new_sel;
202 /* Elements of each vector and selector. */
203 unsigned int nelts;
204 };
205 typedef struct _vec_perm_simplify_seq *vec_perm_simplify_seq;
206
207 static bool forward_propagate_addr_expr (tree, tree, bool);
208 static void optimize_vector_load (gimple_stmt_iterator *);
209
210 /* Set to true if we delete dead edges during the optimization. */
211 static bool cfg_changed;
212
213 static tree rhs_to_tree (tree type, gimple *stmt);
214
215 static bitmap to_purge;
216
217 /* Const-and-copy lattice. */
218 static vec<tree> lattice;
219
220 /* Set the lattice entry for NAME to VAL. */
221 static void
222 fwprop_set_lattice_val (tree name, tree val)
223 {
224 if (TREE_CODE (name) == SSA_NAME)
225 {
226 if (SSA_NAME_VERSION (name) >= lattice.length ())
227 {
228 lattice.reserve (num_ssa_names - lattice.length ());
229 lattice.quick_grow_cleared (num_ssa_names);
230 }
231 lattice[SSA_NAME_VERSION (name)] = val;
232 /* As this now constitutes a copy duplicate points-to
233 and range info appropriately. */
234 if (TREE_CODE (val) == SSA_NAME)
235 maybe_duplicate_ssa_info_at_copy (name, val);
236 }
237 }
238
239 /* Invalidate the lattice entry for NAME, done when releasing SSA names. */
240 static void
241 fwprop_invalidate_lattice (tree name)
242 {
243 if (name
244 && TREE_CODE (name) == SSA_NAME
245 && SSA_NAME_VERSION (name) < lattice.length ())
246 lattice[SSA_NAME_VERSION (name)] = NULL_TREE;
247 }
248
249 /* Get the statement we can propagate from into NAME skipping
250 trivial copies. Returns the statement which defines the
251 propagation source or NULL_TREE if there is no such one.
252 If SINGLE_USE_ONLY is set considers only sources which have
253 a single use chain up to NAME. If SINGLE_USE_P is non-null,
254 it is set to whether the chain to NAME is a single use chain
255 or not. SINGLE_USE_P is not written to if SINGLE_USE_ONLY is set. */
256
257 static gimple *
258 get_prop_source_stmt (tree name, bool single_use_only, bool *single_use_p)
259 {
260 bool single_use = true;
261
262 do {
263 gimple *def_stmt = SSA_NAME_DEF_STMT (name);
264
265 if (!has_single_use (name))
266 {
267 single_use = false;
268 if (single_use_only)
269 return NULL;
270 }
271
272 /* If name is defined by a PHI node or is the default def, bail out. */
273 if (!is_gimple_assign (def_stmt))
274 return NULL;
275
276 /* If def_stmt is a simple copy, continue looking. */
277 if (gimple_assign_rhs_code (def_stmt) == SSA_NAME)
278 name = gimple_assign_rhs1 (def_stmt);
279 else
280 {
281 if (!single_use_only && single_use_p)
282 *single_use_p = single_use;
283
284 return def_stmt;
285 }
286 } while (1);
287 }
288
289 /* Checks if the destination ssa name in DEF_STMT can be used as
290 propagation source. Returns true if so, otherwise false. */
291
292 static bool
293 can_propagate_from (gimple *def_stmt)
294 {
295 gcc_assert (is_gimple_assign (def_stmt));
296
297 /* If the rhs has side-effects we cannot propagate from it. */
298 if (gimple_has_volatile_ops (def_stmt))
299 return false;
300
301 /* If the rhs is a load we cannot propagate from it. */
302 if (TREE_CODE_CLASS (gimple_assign_rhs_code (def_stmt)) == tcc_reference
303 || TREE_CODE_CLASS (gimple_assign_rhs_code (def_stmt)) == tcc_declaration)
304 return false;
305
306 /* Constants can be always propagated. */
307 if (gimple_assign_single_p (def_stmt)
308 && is_gimple_min_invariant (gimple_assign_rhs1 (def_stmt)))
309 return true;
310
311 /* We cannot propagate ssa names that occur in abnormal phi nodes. */
312 if (stmt_references_abnormal_ssa_name (def_stmt))
313 return false;
314
315 /* If the definition is a conversion of a pointer to a function type,
316 then we cannot apply optimizations as some targets require
317 function pointers to be canonicalized and in this case this
318 optimization could eliminate a necessary canonicalization. */
319 if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
320 {
321 tree rhs = gimple_assign_rhs1 (def_stmt);
322 if (FUNCTION_POINTER_TYPE_P (TREE_TYPE (rhs)))
323 return false;
324 }
325
326 return true;
327 }
328
329 /* Remove a chain of dead statements starting at the definition of
330 NAME. The chain is linked via the first operand of the defining statements.
331 If NAME was replaced in its only use then this function can be used
332 to clean up dead stmts. The function handles already released SSA
333 names gracefully.
334 Returns true if cleanup-cfg has to run. */
335
336 static bool
337 remove_prop_source_from_use (tree name)
338 {
339 gimple_stmt_iterator gsi;
340 gimple *stmt;
341 bool cfg_changed = false;
342
343 do {
344 basic_block bb;
345
346 if (SSA_NAME_IN_FREE_LIST (name)
347 || SSA_NAME_IS_DEFAULT_DEF (name)
348 || !has_zero_uses (name))
349 return cfg_changed;
350
351 stmt = SSA_NAME_DEF_STMT (name);
352 if (gimple_code (stmt) == GIMPLE_PHI
353 || gimple_has_side_effects (stmt))
354 return cfg_changed;
355
356 bb = gimple_bb (stmt);
357 gsi = gsi_for_stmt (stmt);
358 unlink_stmt_vdef (stmt);
359 if (gsi_remove (&gsi, true))
360 bitmap_set_bit (to_purge, bb->index);
361 fwprop_invalidate_lattice (gimple_get_lhs (stmt));
362 release_defs (stmt);
363
364 name = is_gimple_assign (stmt) ? gimple_assign_rhs1 (stmt) : NULL_TREE;
365 } while (name && TREE_CODE (name) == SSA_NAME);
366
367 return cfg_changed;
368 }
369
370 /* Return the rhs of a gassign *STMT in a form of a single tree,
371 converted to type TYPE.
372
373 This should disappear, but is needed so we can combine expressions and use
374 the fold() interfaces. Long term, we need to develop folding and combine
375 routines that deal with gimple exclusively . */
376
377 static tree
378 rhs_to_tree (tree type, gimple *stmt)
379 {
380 location_t loc = gimple_location (stmt);
381 enum tree_code code = gimple_assign_rhs_code (stmt);
382 switch (get_gimple_rhs_class (code))
383 {
384 case GIMPLE_TERNARY_RHS:
385 return fold_build3_loc (loc, code, type, gimple_assign_rhs1 (stmt),
386 gimple_assign_rhs2 (stmt),
387 gimple_assign_rhs3 (stmt));
388 case GIMPLE_BINARY_RHS:
389 return fold_build2_loc (loc, code, type, gimple_assign_rhs1 (stmt),
390 gimple_assign_rhs2 (stmt));
391 case GIMPLE_UNARY_RHS:
392 return build1 (code, type, gimple_assign_rhs1 (stmt));
393 case GIMPLE_SINGLE_RHS:
394 return gimple_assign_rhs1 (stmt);
395 default:
396 gcc_unreachable ();
397 }
398 }
399
400 /* Combine OP0 CODE OP1 in the context of a COND_EXPR. Returns
401 the folded result in a form suitable for COND_EXPR_COND or
402 NULL_TREE, if there is no suitable simplified form. If
403 INVARIANT_ONLY is true only gimple_min_invariant results are
404 considered simplified. */
405
406 static tree
407 combine_cond_expr_cond (gimple *stmt, enum tree_code code, tree type,
408 tree op0, tree op1, bool invariant_only)
409 {
410 tree t;
411
412 gcc_assert (TREE_CODE_CLASS (code) == tcc_comparison);
413
414 fold_defer_overflow_warnings ();
415 t = fold_binary_loc (gimple_location (stmt), code, type, op0, op1);
416 if (!t)
417 {
418 fold_undefer_overflow_warnings (false, NULL, 0);
419 return NULL_TREE;
420 }
421
422 /* Require that we got a boolean type out if we put one in. */
423 gcc_assert (TREE_CODE (TREE_TYPE (t)) == TREE_CODE (type));
424
425 /* Canonicalize the combined condition for use in a COND_EXPR. */
426 t = canonicalize_cond_expr_cond (t);
427
428 /* Bail out if we required an invariant but didn't get one. */
429 if (!t || (invariant_only && !is_gimple_min_invariant (t)))
430 {
431 fold_undefer_overflow_warnings (false, NULL, 0);
432 return NULL_TREE;
433 }
434
435 bool nowarn = warning_suppressed_p (stmt, OPT_Wstrict_overflow);
436 fold_undefer_overflow_warnings (!nowarn, stmt, 0);
437
438 return t;
439 }
440
441 /* Combine the comparison OP0 CODE OP1 at LOC with the defining statements
442 of its operand. Return a new comparison tree or NULL_TREE if there
443 were no simplifying combines. */
444
445 static tree
446 forward_propagate_into_comparison_1 (gimple *stmt,
447 enum tree_code code, tree type,
448 tree op0, tree op1)
449 {
450 tree tmp = NULL_TREE;
451 tree rhs0 = NULL_TREE, rhs1 = NULL_TREE;
452 bool single_use0_p = false, single_use1_p = false;
453
454 /* For comparisons use the first operand, that is likely to
455 simplify comparisons against constants. */
456 if (TREE_CODE (op0) == SSA_NAME)
457 {
458 gimple *def_stmt = get_prop_source_stmt (op0, false, &single_use0_p);
459 if (def_stmt && can_propagate_from (def_stmt))
460 {
461 enum tree_code def_code = gimple_assign_rhs_code (def_stmt);
462 bool invariant_only_p = !single_use0_p;
463
464 rhs0 = rhs_to_tree (TREE_TYPE (op1), def_stmt);
465
466 /* Always combine comparisons or conversions from booleans. */
467 if (TREE_CODE (op1) == INTEGER_CST
468 && ((CONVERT_EXPR_CODE_P (def_code)
469 && TREE_CODE (TREE_TYPE (TREE_OPERAND (rhs0, 0)))
470 == BOOLEAN_TYPE)
471 || TREE_CODE_CLASS (def_code) == tcc_comparison))
472 invariant_only_p = false;
473
474 tmp = combine_cond_expr_cond (stmt, code, type,
475 rhs0, op1, invariant_only_p);
476 if (tmp)
477 return tmp;
478 }
479 }
480
481 /* If that wasn't successful, try the second operand. */
482 if (TREE_CODE (op1) == SSA_NAME)
483 {
484 gimple *def_stmt = get_prop_source_stmt (op1, false, &single_use1_p);
485 if (def_stmt && can_propagate_from (def_stmt))
486 {
487 rhs1 = rhs_to_tree (TREE_TYPE (op0), def_stmt);
488 tmp = combine_cond_expr_cond (stmt, code, type,
489 op0, rhs1, !single_use1_p);
490 if (tmp)
491 return tmp;
492 }
493 }
494
495 /* If that wasn't successful either, try both operands. */
496 if (rhs0 != NULL_TREE
497 && rhs1 != NULL_TREE)
498 tmp = combine_cond_expr_cond (stmt, code, type,
499 rhs0, rhs1,
500 !(single_use0_p && single_use1_p));
501
502 return tmp;
503 }
504
505 /* Propagate from the ssa name definition statements of the assignment
506 from a comparison at *GSI into the conditional if that simplifies it.
507 Returns 1 if the stmt was modified and 2 if the CFG needs cleanup,
508 otherwise returns 0. */
509
510 static int
511 forward_propagate_into_comparison (gimple_stmt_iterator *gsi)
512 {
513 gimple *stmt = gsi_stmt (*gsi);
514 tree tmp;
515 bool cfg_changed = false;
516 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
517 tree rhs1 = gimple_assign_rhs1 (stmt);
518 tree rhs2 = gimple_assign_rhs2 (stmt);
519
520 /* Combine the comparison with defining statements. */
521 tmp = forward_propagate_into_comparison_1 (stmt,
522 gimple_assign_rhs_code (stmt),
523 type, rhs1, rhs2);
524 if (tmp && useless_type_conversion_p (type, TREE_TYPE (tmp)))
525 {
526 gimple_assign_set_rhs_from_tree (gsi, tmp);
527 fold_stmt (gsi);
528 update_stmt (gsi_stmt (*gsi));
529
530 if (TREE_CODE (rhs1) == SSA_NAME)
531 cfg_changed |= remove_prop_source_from_use (rhs1);
532 if (TREE_CODE (rhs2) == SSA_NAME)
533 cfg_changed |= remove_prop_source_from_use (rhs2);
534 return cfg_changed ? 2 : 1;
535 }
536
537 return 0;
538 }
539
540 /* Propagate from the ssa name definition statements of COND_EXPR
541 in GIMPLE_COND statement STMT into the conditional if that simplifies it.
542 Returns zero if no statement was changed, one if there were
543 changes and two if cfg_cleanup needs to run. */
544
545 static int
546 forward_propagate_into_gimple_cond (gcond *stmt)
547 {
548 tree tmp;
549 enum tree_code code = gimple_cond_code (stmt);
550 bool cfg_changed = false;
551 tree rhs1 = gimple_cond_lhs (stmt);
552 tree rhs2 = gimple_cond_rhs (stmt);
553
554 /* We can do tree combining on SSA_NAME and comparison expressions. */
555 if (TREE_CODE_CLASS (gimple_cond_code (stmt)) != tcc_comparison)
556 return 0;
557
558 tmp = forward_propagate_into_comparison_1 (stmt, code,
559 boolean_type_node,
560 rhs1, rhs2);
561 if (tmp
562 && is_gimple_condexpr_for_cond (tmp))
563 {
564 if (dump_file)
565 {
566 fprintf (dump_file, " Replaced '");
567 print_gimple_expr (dump_file, stmt, 0);
568 fprintf (dump_file, "' with '");
569 print_generic_expr (dump_file, tmp);
570 fprintf (dump_file, "'\n");
571 }
572
573 gimple_cond_set_condition_from_tree (stmt, unshare_expr (tmp));
574 update_stmt (stmt);
575
576 if (TREE_CODE (rhs1) == SSA_NAME)
577 cfg_changed |= remove_prop_source_from_use (rhs1);
578 if (TREE_CODE (rhs2) == SSA_NAME)
579 cfg_changed |= remove_prop_source_from_use (rhs2);
580 return (cfg_changed || is_gimple_min_invariant (tmp)) ? 2 : 1;
581 }
582
583 /* Canonicalize _Bool == 0 and _Bool != 1 to _Bool != 0 by swapping edges. */
584 if ((TREE_CODE (TREE_TYPE (rhs1)) == BOOLEAN_TYPE
585 || (INTEGRAL_TYPE_P (TREE_TYPE (rhs1))
586 && TYPE_PRECISION (TREE_TYPE (rhs1)) == 1))
587 && ((code == EQ_EXPR
588 && integer_zerop (rhs2))
589 || (code == NE_EXPR
590 && integer_onep (rhs2))))
591 {
592 basic_block bb = gimple_bb (stmt);
593 gimple_cond_set_code (stmt, NE_EXPR);
594 gimple_cond_set_rhs (stmt, build_zero_cst (TREE_TYPE (rhs1)));
595 EDGE_SUCC (bb, 0)->flags ^= (EDGE_TRUE_VALUE|EDGE_FALSE_VALUE);
596 EDGE_SUCC (bb, 1)->flags ^= (EDGE_TRUE_VALUE|EDGE_FALSE_VALUE);
597 return 1;
598 }
599
600 return 0;
601 }
602
603 /* We've just substituted an ADDR_EXPR into stmt. Update all the
604 relevant data structures to match. */
605
606 static void
607 tidy_after_forward_propagate_addr (gimple *stmt)
608 {
609 /* We may have turned a trapping insn into a non-trapping insn. */
610 if (maybe_clean_or_replace_eh_stmt (stmt, stmt))
611 bitmap_set_bit (to_purge, gimple_bb (stmt)->index);
612
613 if (TREE_CODE (gimple_assign_rhs1 (stmt)) == ADDR_EXPR)
614 recompute_tree_invariant_for_addr_expr (gimple_assign_rhs1 (stmt));
615 }
616
617 /* NAME is a SSA_NAME representing DEF_RHS which is of the form
618 ADDR_EXPR <whatever>.
619
620 Try to forward propagate the ADDR_EXPR into the use USE_STMT.
621 Often this will allow for removal of an ADDR_EXPR and INDIRECT_REF
622 node or for recovery of array indexing from pointer arithmetic.
623
624 Return true if the propagation was successful (the propagation can
625 be not totally successful, yet things may have been changed). */
626
627 static bool
628 forward_propagate_addr_expr_1 (tree name, tree def_rhs,
629 gimple_stmt_iterator *use_stmt_gsi,
630 bool single_use_p)
631 {
632 tree lhs, rhs, rhs2, array_ref;
633 gimple *use_stmt = gsi_stmt (*use_stmt_gsi);
634 enum tree_code rhs_code;
635 bool res = true;
636
637 gcc_assert (TREE_CODE (def_rhs) == ADDR_EXPR);
638
639 lhs = gimple_assign_lhs (use_stmt);
640 rhs_code = gimple_assign_rhs_code (use_stmt);
641 rhs = gimple_assign_rhs1 (use_stmt);
642
643 /* Do not perform copy-propagation but recurse through copy chains. */
644 if (TREE_CODE (lhs) == SSA_NAME
645 && rhs_code == SSA_NAME)
646 return forward_propagate_addr_expr (lhs, def_rhs, single_use_p);
647
648 /* The use statement could be a conversion. Recurse to the uses of the
649 lhs as copyprop does not copy through pointer to integer to pointer
650 conversions and FRE does not catch all cases either.
651 Treat the case of a single-use name and
652 a conversion to def_rhs type separate, though. */
653 if (TREE_CODE (lhs) == SSA_NAME
654 && CONVERT_EXPR_CODE_P (rhs_code))
655 {
656 /* If there is a point in a conversion chain where the types match
657 so we can remove a conversion re-materialize the address here
658 and stop. */
659 if (single_use_p
660 && useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (def_rhs)))
661 {
662 gimple_assign_set_rhs1 (use_stmt, unshare_expr (def_rhs));
663 gimple_assign_set_rhs_code (use_stmt, TREE_CODE (def_rhs));
664 return true;
665 }
666
667 /* Else recurse if the conversion preserves the address value. */
668 if ((INTEGRAL_TYPE_P (TREE_TYPE (lhs))
669 || POINTER_TYPE_P (TREE_TYPE (lhs)))
670 && (TYPE_PRECISION (TREE_TYPE (lhs))
671 >= TYPE_PRECISION (TREE_TYPE (def_rhs))))
672 return forward_propagate_addr_expr (lhs, def_rhs, single_use_p);
673
674 return false;
675 }
676
677 /* If this isn't a conversion chain from this on we only can propagate
678 into compatible pointer contexts. */
679 if (!types_compatible_p (TREE_TYPE (name), TREE_TYPE (def_rhs)))
680 return false;
681
682 /* Propagate through constant pointer adjustments. */
683 if (TREE_CODE (lhs) == SSA_NAME
684 && rhs_code == POINTER_PLUS_EXPR
685 && rhs == name
686 && TREE_CODE (gimple_assign_rhs2 (use_stmt)) == INTEGER_CST)
687 {
688 tree new_def_rhs;
689 /* As we come here with non-invariant addresses in def_rhs we need
690 to make sure we can build a valid constant offsetted address
691 for further propagation. Simply rely on fold building that
692 and check after the fact. */
693 new_def_rhs = fold_build2 (MEM_REF, TREE_TYPE (TREE_TYPE (rhs)),
694 def_rhs,
695 fold_convert (ptr_type_node,
696 gimple_assign_rhs2 (use_stmt)));
697 if (TREE_CODE (new_def_rhs) == MEM_REF
698 && !is_gimple_mem_ref_addr (TREE_OPERAND (new_def_rhs, 0)))
699 return false;
700 new_def_rhs = build1 (ADDR_EXPR, TREE_TYPE (rhs), new_def_rhs);
701
702 /* Recurse. If we could propagate into all uses of lhs do not
703 bother to replace into the current use but just pretend we did. */
704 if (forward_propagate_addr_expr (lhs, new_def_rhs, single_use_p))
705 return true;
706
707 if (useless_type_conversion_p (TREE_TYPE (lhs),
708 TREE_TYPE (new_def_rhs)))
709 gimple_assign_set_rhs_with_ops (use_stmt_gsi, TREE_CODE (new_def_rhs),
710 new_def_rhs);
711 else if (is_gimple_min_invariant (new_def_rhs))
712 gimple_assign_set_rhs_with_ops (use_stmt_gsi, NOP_EXPR, new_def_rhs);
713 else
714 return false;
715 gcc_assert (gsi_stmt (*use_stmt_gsi) == use_stmt);
716 update_stmt (use_stmt);
717 return true;
718 }
719
720 /* Now strip away any outer COMPONENT_REF/ARRAY_REF nodes from the LHS.
721 ADDR_EXPR will not appear on the LHS. */
722 tree *lhsp = gimple_assign_lhs_ptr (use_stmt);
723 while (handled_component_p (*lhsp))
724 lhsp = &TREE_OPERAND (*lhsp, 0);
725 lhs = *lhsp;
726
727 /* Now see if the LHS node is a MEM_REF using NAME. If so,
728 propagate the ADDR_EXPR into the use of NAME and fold the result. */
729 if (TREE_CODE (lhs) == MEM_REF
730 && TREE_OPERAND (lhs, 0) == name)
731 {
732 tree def_rhs_base;
733 poly_int64 def_rhs_offset;
734 /* If the address is invariant we can always fold it. */
735 if ((def_rhs_base = get_addr_base_and_unit_offset (TREE_OPERAND (def_rhs, 0),
736 &def_rhs_offset)))
737 {
738 poly_offset_int off = mem_ref_offset (lhs);
739 tree new_ptr;
740 off += def_rhs_offset;
741 if (TREE_CODE (def_rhs_base) == MEM_REF)
742 {
743 off += mem_ref_offset (def_rhs_base);
744 new_ptr = TREE_OPERAND (def_rhs_base, 0);
745 }
746 else
747 new_ptr = build_fold_addr_expr (def_rhs_base);
748 TREE_OPERAND (lhs, 0) = new_ptr;
749 TREE_OPERAND (lhs, 1)
750 = wide_int_to_tree (TREE_TYPE (TREE_OPERAND (lhs, 1)), off);
751 tidy_after_forward_propagate_addr (use_stmt);
752 /* Continue propagating into the RHS if this was not the only use. */
753 if (single_use_p)
754 return true;
755 }
756 /* If the LHS is a plain dereference and the value type is the same as
757 that of the pointed-to type of the address we can put the
758 dereferenced address on the LHS preserving the original alias-type. */
759 else if (integer_zerop (TREE_OPERAND (lhs, 1))
760 && ((gimple_assign_lhs (use_stmt) == lhs
761 && useless_type_conversion_p
762 (TREE_TYPE (TREE_OPERAND (def_rhs, 0)),
763 TREE_TYPE (gimple_assign_rhs1 (use_stmt))))
764 || types_compatible_p (TREE_TYPE (lhs),
765 TREE_TYPE (TREE_OPERAND (def_rhs, 0))))
766 /* Don't forward anything into clobber stmts if it would result
767 in the lhs no longer being a MEM_REF. */
768 && (!gimple_clobber_p (use_stmt)
769 || TREE_CODE (TREE_OPERAND (def_rhs, 0)) == MEM_REF))
770 {
771 tree *def_rhs_basep = &TREE_OPERAND (def_rhs, 0);
772 tree new_offset, new_base, saved, new_lhs;
773 while (handled_component_p (*def_rhs_basep))
774 def_rhs_basep = &TREE_OPERAND (*def_rhs_basep, 0);
775 saved = *def_rhs_basep;
776 if (TREE_CODE (*def_rhs_basep) == MEM_REF)
777 {
778 new_base = TREE_OPERAND (*def_rhs_basep, 0);
779 new_offset = fold_convert (TREE_TYPE (TREE_OPERAND (lhs, 1)),
780 TREE_OPERAND (*def_rhs_basep, 1));
781 }
782 else
783 {
784 new_base = build_fold_addr_expr (*def_rhs_basep);
785 new_offset = TREE_OPERAND (lhs, 1);
786 }
787 *def_rhs_basep = build2 (MEM_REF, TREE_TYPE (*def_rhs_basep),
788 new_base, new_offset);
789 TREE_THIS_VOLATILE (*def_rhs_basep) = TREE_THIS_VOLATILE (lhs);
790 TREE_SIDE_EFFECTS (*def_rhs_basep) = TREE_SIDE_EFFECTS (lhs);
791 TREE_THIS_NOTRAP (*def_rhs_basep) = TREE_THIS_NOTRAP (lhs);
792 new_lhs = unshare_expr (TREE_OPERAND (def_rhs, 0));
793 *lhsp = new_lhs;
794 TREE_THIS_VOLATILE (new_lhs) = TREE_THIS_VOLATILE (lhs);
795 TREE_SIDE_EFFECTS (new_lhs) = TREE_SIDE_EFFECTS (lhs);
796 *def_rhs_basep = saved;
797 tidy_after_forward_propagate_addr (use_stmt);
798 /* Continue propagating into the RHS if this was not the
799 only use. */
800 if (single_use_p)
801 return true;
802 }
803 else
804 /* We can have a struct assignment dereferencing our name twice.
805 Note that we didn't propagate into the lhs to not falsely
806 claim we did when propagating into the rhs. */
807 res = false;
808 }
809
810 /* Strip away any outer COMPONENT_REF, ARRAY_REF or ADDR_EXPR
811 nodes from the RHS. */
812 tree *rhsp = gimple_assign_rhs1_ptr (use_stmt);
813 if (TREE_CODE (*rhsp) == ADDR_EXPR)
814 rhsp = &TREE_OPERAND (*rhsp, 0);
815 while (handled_component_p (*rhsp))
816 rhsp = &TREE_OPERAND (*rhsp, 0);
817 rhs = *rhsp;
818
819 /* Now see if the RHS node is a MEM_REF using NAME. If so,
820 propagate the ADDR_EXPR into the use of NAME and fold the result. */
821 if (TREE_CODE (rhs) == MEM_REF
822 && TREE_OPERAND (rhs, 0) == name)
823 {
824 tree def_rhs_base;
825 poly_int64 def_rhs_offset;
826 if ((def_rhs_base = get_addr_base_and_unit_offset (TREE_OPERAND (def_rhs, 0),
827 &def_rhs_offset)))
828 {
829 poly_offset_int off = mem_ref_offset (rhs);
830 tree new_ptr;
831 off += def_rhs_offset;
832 if (TREE_CODE (def_rhs_base) == MEM_REF)
833 {
834 off += mem_ref_offset (def_rhs_base);
835 new_ptr = TREE_OPERAND (def_rhs_base, 0);
836 }
837 else
838 new_ptr = build_fold_addr_expr (def_rhs_base);
839 TREE_OPERAND (rhs, 0) = new_ptr;
840 TREE_OPERAND (rhs, 1)
841 = wide_int_to_tree (TREE_TYPE (TREE_OPERAND (rhs, 1)), off);
842 fold_stmt_inplace (use_stmt_gsi);
843 tidy_after_forward_propagate_addr (use_stmt);
844 return res;
845 }
846 /* If the RHS is a plain dereference and the value type is the same as
847 that of the pointed-to type of the address we can put the
848 dereferenced address on the RHS preserving the original alias-type. */
849 else if (integer_zerop (TREE_OPERAND (rhs, 1))
850 && ((gimple_assign_rhs1 (use_stmt) == rhs
851 && useless_type_conversion_p
852 (TREE_TYPE (gimple_assign_lhs (use_stmt)),
853 TREE_TYPE (TREE_OPERAND (def_rhs, 0))))
854 || types_compatible_p (TREE_TYPE (rhs),
855 TREE_TYPE (TREE_OPERAND (def_rhs, 0)))))
856 {
857 tree *def_rhs_basep = &TREE_OPERAND (def_rhs, 0);
858 tree new_offset, new_base, saved, new_rhs;
859 while (handled_component_p (*def_rhs_basep))
860 def_rhs_basep = &TREE_OPERAND (*def_rhs_basep, 0);
861 saved = *def_rhs_basep;
862 if (TREE_CODE (*def_rhs_basep) == MEM_REF)
863 {
864 new_base = TREE_OPERAND (*def_rhs_basep, 0);
865 new_offset = fold_convert (TREE_TYPE (TREE_OPERAND (rhs, 1)),
866 TREE_OPERAND (*def_rhs_basep, 1));
867 }
868 else
869 {
870 new_base = build_fold_addr_expr (*def_rhs_basep);
871 new_offset = TREE_OPERAND (rhs, 1);
872 }
873 *def_rhs_basep = build2 (MEM_REF, TREE_TYPE (*def_rhs_basep),
874 new_base, new_offset);
875 TREE_THIS_VOLATILE (*def_rhs_basep) = TREE_THIS_VOLATILE (rhs);
876 TREE_SIDE_EFFECTS (*def_rhs_basep) = TREE_SIDE_EFFECTS (rhs);
877 TREE_THIS_NOTRAP (*def_rhs_basep) = TREE_THIS_NOTRAP (rhs);
878 new_rhs = unshare_expr (TREE_OPERAND (def_rhs, 0));
879 *rhsp = new_rhs;
880 TREE_THIS_VOLATILE (new_rhs) = TREE_THIS_VOLATILE (rhs);
881 TREE_SIDE_EFFECTS (new_rhs) = TREE_SIDE_EFFECTS (rhs);
882 *def_rhs_basep = saved;
883 fold_stmt_inplace (use_stmt_gsi);
884 tidy_after_forward_propagate_addr (use_stmt);
885 return res;
886 }
887 }
888
889 /* If the use of the ADDR_EXPR is not a POINTER_PLUS_EXPR, there
890 is nothing to do. */
891 if (gimple_assign_rhs_code (use_stmt) != POINTER_PLUS_EXPR
892 || gimple_assign_rhs1 (use_stmt) != name)
893 return false;
894
895 /* The remaining cases are all for turning pointer arithmetic into
896 array indexing. They only apply when we have the address of
897 element zero in an array. If that is not the case then there
898 is nothing to do. */
899 array_ref = TREE_OPERAND (def_rhs, 0);
900 if ((TREE_CODE (array_ref) != ARRAY_REF
901 || TREE_CODE (TREE_TYPE (TREE_OPERAND (array_ref, 0))) != ARRAY_TYPE
902 || TREE_CODE (TREE_OPERAND (array_ref, 1)) != INTEGER_CST)
903 && TREE_CODE (TREE_TYPE (array_ref)) != ARRAY_TYPE)
904 return false;
905
906 rhs2 = gimple_assign_rhs2 (use_stmt);
907 /* Optimize &x[C1] p+ C2 to &x p+ C3 with C3 = C1 * element_size + C2. */
908 if (TREE_CODE (rhs2) == INTEGER_CST)
909 {
910 tree new_rhs = build1_loc (gimple_location (use_stmt),
911 ADDR_EXPR, TREE_TYPE (def_rhs),
912 fold_build2 (MEM_REF,
913 TREE_TYPE (TREE_TYPE (def_rhs)),
914 unshare_expr (def_rhs),
915 fold_convert (ptr_type_node,
916 rhs2)));
917 gimple_assign_set_rhs_from_tree (use_stmt_gsi, new_rhs);
918 use_stmt = gsi_stmt (*use_stmt_gsi);
919 update_stmt (use_stmt);
920 tidy_after_forward_propagate_addr (use_stmt);
921 return true;
922 }
923
924 return false;
925 }
926
927 /* STMT is a statement of the form SSA_NAME = ADDR_EXPR <whatever>.
928
929 Try to forward propagate the ADDR_EXPR into all uses of the SSA_NAME.
930 Often this will allow for removal of an ADDR_EXPR and INDIRECT_REF
931 node or for recovery of array indexing from pointer arithmetic.
932
933 PARENT_SINGLE_USE_P tells if, when in a recursive invocation, NAME was
934 the single use in the previous invocation. Pass true when calling
935 this as toplevel.
936
937 Returns true, if all uses have been propagated into. */
938
939 static bool
940 forward_propagate_addr_expr (tree name, tree rhs, bool parent_single_use_p)
941 {
942 imm_use_iterator iter;
943 gimple *use_stmt;
944 bool all = true;
945 bool single_use_p = parent_single_use_p && has_single_use (name);
946
947 FOR_EACH_IMM_USE_STMT (use_stmt, iter, name)
948 {
949 bool result;
950 tree use_rhs;
951
952 /* If the use is not in a simple assignment statement, then
953 there is nothing we can do. */
954 if (!is_gimple_assign (use_stmt))
955 {
956 if (!is_gimple_debug (use_stmt))
957 all = false;
958 continue;
959 }
960
961 gimple_stmt_iterator gsi = gsi_for_stmt (use_stmt);
962 result = forward_propagate_addr_expr_1 (name, rhs, &gsi,
963 single_use_p);
964 /* If the use has moved to a different statement adjust
965 the update machinery for the old statement too. */
966 if (use_stmt != gsi_stmt (gsi))
967 {
968 update_stmt (use_stmt);
969 use_stmt = gsi_stmt (gsi);
970 }
971 update_stmt (use_stmt);
972 all &= result;
973
974 /* Remove intermediate now unused copy and conversion chains. */
975 use_rhs = gimple_assign_rhs1 (use_stmt);
976 if (result
977 && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
978 && TREE_CODE (use_rhs) == SSA_NAME
979 && has_zero_uses (gimple_assign_lhs (use_stmt)))
980 {
981 gimple_stmt_iterator gsi = gsi_for_stmt (use_stmt);
982 fwprop_invalidate_lattice (gimple_get_lhs (use_stmt));
983 release_defs (use_stmt);
984 gsi_remove (&gsi, true);
985 }
986 }
987
988 return all && has_zero_uses (name);
989 }
990
991
992 /* Helper function for simplify_gimple_switch. Remove case labels that
993 have values outside the range of the new type. */
994
995 static void
996 simplify_gimple_switch_label_vec (gswitch *stmt, tree index_type,
997 vec<std::pair<int, int> > &edges_to_remove)
998 {
999 unsigned int branch_num = gimple_switch_num_labels (stmt);
1000 auto_vec<tree> labels (branch_num);
1001 unsigned int i, len;
1002
1003 /* Collect the existing case labels in a VEC, and preprocess it as if
1004 we are gimplifying a GENERIC SWITCH_EXPR. */
1005 for (i = 1; i < branch_num; i++)
1006 labels.quick_push (gimple_switch_label (stmt, i));
1007 preprocess_case_label_vec_for_gimple (labels, index_type, NULL);
1008
1009 /* If any labels were removed, replace the existing case labels
1010 in the GIMPLE_SWITCH statement with the correct ones.
1011 Note that the type updates were done in-place on the case labels,
1012 so we only have to replace the case labels in the GIMPLE_SWITCH
1013 if the number of labels changed. */
1014 len = labels.length ();
1015 if (len < branch_num - 1)
1016 {
1017 bitmap target_blocks;
1018 edge_iterator ei;
1019 edge e;
1020
1021 /* Corner case: *all* case labels have been removed as being
1022 out-of-range for INDEX_TYPE. Push one label and let the
1023 CFG cleanups deal with this further. */
1024 if (len == 0)
1025 {
1026 tree label, elt;
1027
1028 label = CASE_LABEL (gimple_switch_default_label (stmt));
1029 elt = build_case_label (build_int_cst (index_type, 0), NULL, label);
1030 labels.quick_push (elt);
1031 len = 1;
1032 }
1033
1034 for (i = 0; i < labels.length (); i++)
1035 gimple_switch_set_label (stmt, i + 1, labels[i]);
1036 for (i++ ; i < branch_num; i++)
1037 gimple_switch_set_label (stmt, i, NULL_TREE);
1038 gimple_switch_set_num_labels (stmt, len + 1);
1039
1040 /* Cleanup any edges that are now dead. */
1041 target_blocks = BITMAP_ALLOC (NULL);
1042 for (i = 0; i < gimple_switch_num_labels (stmt); i++)
1043 {
1044 tree elt = gimple_switch_label (stmt, i);
1045 basic_block target = label_to_block (cfun, CASE_LABEL (elt));
1046 bitmap_set_bit (target_blocks, target->index);
1047 }
1048 for (ei = ei_start (gimple_bb (stmt)->succs); (e = ei_safe_edge (ei)); )
1049 {
1050 if (! bitmap_bit_p (target_blocks, e->dest->index))
1051 edges_to_remove.safe_push (std::make_pair (e->src->index,
1052 e->dest->index));
1053 else
1054 ei_next (&ei);
1055 }
1056 BITMAP_FREE (target_blocks);
1057 }
1058 }
1059
1060 /* STMT is a SWITCH_EXPR for which we attempt to find equivalent forms of
1061 the condition which we may be able to optimize better. */
1062
1063 static bool
1064 simplify_gimple_switch (gswitch *stmt,
1065 vec<std::pair<int, int> > &edges_to_remove)
1066 {
1067 /* The optimization that we really care about is removing unnecessary
1068 casts. That will let us do much better in propagating the inferred
1069 constant at the switch target. */
1070 tree cond = gimple_switch_index (stmt);
1071 if (TREE_CODE (cond) == SSA_NAME)
1072 {
1073 gimple *def_stmt = SSA_NAME_DEF_STMT (cond);
1074 if (gimple_assign_cast_p (def_stmt))
1075 {
1076 tree def = gimple_assign_rhs1 (def_stmt);
1077 if (TREE_CODE (def) != SSA_NAME)
1078 return false;
1079
1080 /* If we have an extension or sign-change that preserves the
1081 values we check against then we can copy the source value into
1082 the switch. */
1083 tree ti = TREE_TYPE (def);
1084 if (INTEGRAL_TYPE_P (ti)
1085 && TYPE_PRECISION (ti) <= TYPE_PRECISION (TREE_TYPE (cond)))
1086 {
1087 size_t n = gimple_switch_num_labels (stmt);
1088 tree min = NULL_TREE, max = NULL_TREE;
1089 if (n > 1)
1090 {
1091 min = CASE_LOW (gimple_switch_label (stmt, 1));
1092 if (CASE_HIGH (gimple_switch_label (stmt, n - 1)))
1093 max = CASE_HIGH (gimple_switch_label (stmt, n - 1));
1094 else
1095 max = CASE_LOW (gimple_switch_label (stmt, n - 1));
1096 }
1097 if ((!min || int_fits_type_p (min, ti))
1098 && (!max || int_fits_type_p (max, ti)))
1099 {
1100 gimple_switch_set_index (stmt, def);
1101 simplify_gimple_switch_label_vec (stmt, ti,
1102 edges_to_remove);
1103 update_stmt (stmt);
1104 return true;
1105 }
1106 }
1107 }
1108 }
1109
1110 return false;
1111 }
1112
1113 /* For pointers p2 and p1 return p2 - p1 if the
1114 difference is known and constant, otherwise return NULL. */
1115
1116 static tree
1117 constant_pointer_difference (tree p1, tree p2)
1118 {
1119 int i, j;
1120 #define CPD_ITERATIONS 5
1121 tree exps[2][CPD_ITERATIONS];
1122 tree offs[2][CPD_ITERATIONS];
1123 int cnt[2];
1124
1125 for (i = 0; i < 2; i++)
1126 {
1127 tree p = i ? p1 : p2;
1128 tree off = size_zero_node;
1129 gimple *stmt;
1130 enum tree_code code;
1131
1132 /* For each of p1 and p2 we need to iterate at least
1133 twice, to handle ADDR_EXPR directly in p1/p2,
1134 SSA_NAME with ADDR_EXPR or POINTER_PLUS_EXPR etc.
1135 on definition's stmt RHS. Iterate a few extra times. */
1136 j = 0;
1137 do
1138 {
1139 if (!POINTER_TYPE_P (TREE_TYPE (p)))
1140 break;
1141 if (TREE_CODE (p) == ADDR_EXPR)
1142 {
1143 tree q = TREE_OPERAND (p, 0);
1144 poly_int64 offset;
1145 tree base = get_addr_base_and_unit_offset (q, &offset);
1146 if (base)
1147 {
1148 q = base;
1149 if (maybe_ne (offset, 0))
1150 off = size_binop (PLUS_EXPR, off, size_int (offset));
1151 }
1152 if (TREE_CODE (q) == MEM_REF
1153 && TREE_CODE (TREE_OPERAND (q, 0)) == SSA_NAME)
1154 {
1155 p = TREE_OPERAND (q, 0);
1156 off = size_binop (PLUS_EXPR, off,
1157 wide_int_to_tree (sizetype,
1158 mem_ref_offset (q)));
1159 }
1160 else
1161 {
1162 exps[i][j] = q;
1163 offs[i][j++] = off;
1164 break;
1165 }
1166 }
1167 if (TREE_CODE (p) != SSA_NAME)
1168 break;
1169 exps[i][j] = p;
1170 offs[i][j++] = off;
1171 if (j == CPD_ITERATIONS)
1172 break;
1173 stmt = SSA_NAME_DEF_STMT (p);
1174 if (!is_gimple_assign (stmt) || gimple_assign_lhs (stmt) != p)
1175 break;
1176 code = gimple_assign_rhs_code (stmt);
1177 if (code == POINTER_PLUS_EXPR)
1178 {
1179 if (TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
1180 break;
1181 off = size_binop (PLUS_EXPR, off, gimple_assign_rhs2 (stmt));
1182 p = gimple_assign_rhs1 (stmt);
1183 }
1184 else if (code == ADDR_EXPR || CONVERT_EXPR_CODE_P (code))
1185 p = gimple_assign_rhs1 (stmt);
1186 else
1187 break;
1188 }
1189 while (1);
1190 cnt[i] = j;
1191 }
1192
1193 for (i = 0; i < cnt[0]; i++)
1194 for (j = 0; j < cnt[1]; j++)
1195 if (exps[0][i] == exps[1][j])
1196 return size_binop (MINUS_EXPR, offs[0][i], offs[1][j]);
1197
1198 return NULL_TREE;
1199 }
1200
1201 /* *GSI_P is a GIMPLE_CALL to a builtin function.
1202 Optimize
1203 memcpy (p, "abcd", 4);
1204 memset (p + 4, ' ', 3);
1205 into
1206 memcpy (p, "abcd ", 7);
1207 call if the latter can be stored by pieces during expansion.
1208
1209 Optimize
1210 memchr ("abcd", a, 4) == 0;
1211 or
1212 memchr ("abcd", a, 4) != 0;
1213 to
1214 (a == 'a' || a == 'b' || a == 'c' || a == 'd') == 0
1215 or
1216 (a == 'a' || a == 'b' || a == 'c' || a == 'd') != 0
1217
1218 Also canonicalize __atomic_fetch_op (p, x, y) op x
1219 to __atomic_op_fetch (p, x, y) or
1220 __atomic_op_fetch (p, x, y) iop x
1221 to __atomic_fetch_op (p, x, y) when possible (also __sync). */
1222
1223 static bool
1224 simplify_builtin_call (gimple_stmt_iterator *gsi_p, tree callee2)
1225 {
1226 gimple *stmt1, *stmt2 = gsi_stmt (*gsi_p);
1227 enum built_in_function other_atomic = END_BUILTINS;
1228 enum tree_code atomic_op = ERROR_MARK;
1229 tree vuse = gimple_vuse (stmt2);
1230 if (vuse == NULL)
1231 return false;
1232 stmt1 = SSA_NAME_DEF_STMT (vuse);
1233
1234 tree res;
1235
1236 switch (DECL_FUNCTION_CODE (callee2))
1237 {
1238 case BUILT_IN_MEMCHR:
1239 if (gimple_call_num_args (stmt2) == 3
1240 && (res = gimple_call_lhs (stmt2)) != nullptr
1241 && use_in_zero_equality (res) != nullptr
1242 && CHAR_BIT == 8
1243 && BITS_PER_UNIT == 8)
1244 {
1245 tree ptr = gimple_call_arg (stmt2, 0);
1246 if (TREE_CODE (ptr) != ADDR_EXPR
1247 || TREE_CODE (TREE_OPERAND (ptr, 0)) != STRING_CST)
1248 break;
1249 unsigned HOST_WIDE_INT slen
1250 = TREE_STRING_LENGTH (TREE_OPERAND (ptr, 0));
1251 /* It must be a non-empty string constant. */
1252 if (slen < 2)
1253 break;
1254 /* For -Os, only simplify strings with a single character. */
1255 if (!optimize_bb_for_speed_p (gimple_bb (stmt2))
1256 && slen > 2)
1257 break;
1258 tree size = gimple_call_arg (stmt2, 2);
1259 /* Size must be a constant which is <= UNITS_PER_WORD and
1260 <= the string length. */
1261 if (TREE_CODE (size) != INTEGER_CST)
1262 break;
1263
1264 if (!tree_fits_uhwi_p (size))
1265 break;
1266
1267 unsigned HOST_WIDE_INT sz = tree_to_uhwi (size);
1268 if (sz == 0 || sz > UNITS_PER_WORD || sz >= slen)
1269 break;
1270
1271 tree ch = gimple_call_arg (stmt2, 1);
1272 location_t loc = gimple_location (stmt2);
1273 if (!useless_type_conversion_p (char_type_node,
1274 TREE_TYPE (ch)))
1275 ch = fold_convert_loc (loc, char_type_node, ch);
1276 const char *p = TREE_STRING_POINTER (TREE_OPERAND (ptr, 0));
1277 unsigned int isize = sz;
1278 tree *op = XALLOCAVEC (tree, isize);
1279 for (unsigned int i = 0; i < isize; i++)
1280 {
1281 op[i] = build_int_cst (char_type_node, p[i]);
1282 op[i] = fold_build2_loc (loc, EQ_EXPR, boolean_type_node,
1283 op[i], ch);
1284 }
1285 for (unsigned int i = isize - 1; i >= 1; i--)
1286 op[i - 1] = fold_convert_loc (loc, boolean_type_node,
1287 fold_build2_loc (loc,
1288 BIT_IOR_EXPR,
1289 boolean_type_node,
1290 op[i - 1],
1291 op[i]));
1292 res = fold_convert_loc (loc, TREE_TYPE (res), op[0]);
1293 gimplify_and_update_call_from_tree (gsi_p, res);
1294 return true;
1295 }
1296 break;
1297
1298 case BUILT_IN_MEMSET:
1299 if (gimple_call_num_args (stmt2) != 3
1300 || gimple_call_lhs (stmt2)
1301 || CHAR_BIT != 8
1302 || BITS_PER_UNIT != 8)
1303 break;
1304 else
1305 {
1306 tree callee1;
1307 tree ptr1, src1, str1, off1, len1, lhs1;
1308 tree ptr2 = gimple_call_arg (stmt2, 0);
1309 tree val2 = gimple_call_arg (stmt2, 1);
1310 tree len2 = gimple_call_arg (stmt2, 2);
1311 tree diff, vdef, new_str_cst;
1312 gimple *use_stmt;
1313 unsigned int ptr1_align;
1314 unsigned HOST_WIDE_INT src_len;
1315 char *src_buf;
1316 use_operand_p use_p;
1317
1318 if (!tree_fits_shwi_p (val2)
1319 || !tree_fits_uhwi_p (len2)
1320 || compare_tree_int (len2, 1024) == 1)
1321 break;
1322 if (is_gimple_call (stmt1))
1323 {
1324 /* If first stmt is a call, it needs to be memcpy
1325 or mempcpy, with string literal as second argument and
1326 constant length. */
1327 callee1 = gimple_call_fndecl (stmt1);
1328 if (callee1 == NULL_TREE
1329 || !fndecl_built_in_p (callee1, BUILT_IN_NORMAL)
1330 || gimple_call_num_args (stmt1) != 3)
1331 break;
1332 if (DECL_FUNCTION_CODE (callee1) != BUILT_IN_MEMCPY
1333 && DECL_FUNCTION_CODE (callee1) != BUILT_IN_MEMPCPY)
1334 break;
1335 ptr1 = gimple_call_arg (stmt1, 0);
1336 src1 = gimple_call_arg (stmt1, 1);
1337 len1 = gimple_call_arg (stmt1, 2);
1338 lhs1 = gimple_call_lhs (stmt1);
1339 if (!tree_fits_uhwi_p (len1))
1340 break;
1341 str1 = string_constant (src1, &off1, NULL, NULL);
1342 if (str1 == NULL_TREE)
1343 break;
1344 if (!tree_fits_uhwi_p (off1)
1345 || compare_tree_int (off1, TREE_STRING_LENGTH (str1) - 1) > 0
1346 || compare_tree_int (len1, TREE_STRING_LENGTH (str1)
1347 - tree_to_uhwi (off1)) > 0
1348 || TREE_CODE (TREE_TYPE (str1)) != ARRAY_TYPE
1349 || TYPE_MODE (TREE_TYPE (TREE_TYPE (str1)))
1350 != TYPE_MODE (char_type_node))
1351 break;
1352 }
1353 else if (gimple_assign_single_p (stmt1))
1354 {
1355 /* Otherwise look for length 1 memcpy optimized into
1356 assignment. */
1357 ptr1 = gimple_assign_lhs (stmt1);
1358 src1 = gimple_assign_rhs1 (stmt1);
1359 if (TREE_CODE (ptr1) != MEM_REF
1360 || TYPE_MODE (TREE_TYPE (ptr1)) != TYPE_MODE (char_type_node)
1361 || !tree_fits_shwi_p (src1))
1362 break;
1363 ptr1 = build_fold_addr_expr (ptr1);
1364 STRIP_USELESS_TYPE_CONVERSION (ptr1);
1365 callee1 = NULL_TREE;
1366 len1 = size_one_node;
1367 lhs1 = NULL_TREE;
1368 off1 = size_zero_node;
1369 str1 = NULL_TREE;
1370 }
1371 else
1372 break;
1373
1374 diff = constant_pointer_difference (ptr1, ptr2);
1375 if (diff == NULL && lhs1 != NULL)
1376 {
1377 diff = constant_pointer_difference (lhs1, ptr2);
1378 if (DECL_FUNCTION_CODE (callee1) == BUILT_IN_MEMPCPY
1379 && diff != NULL)
1380 diff = size_binop (PLUS_EXPR, diff,
1381 fold_convert (sizetype, len1));
1382 }
1383 /* If the difference between the second and first destination pointer
1384 is not constant, or is bigger than memcpy length, bail out. */
1385 if (diff == NULL
1386 || !tree_fits_uhwi_p (diff)
1387 || tree_int_cst_lt (len1, diff)
1388 || compare_tree_int (diff, 1024) == 1)
1389 break;
1390
1391 /* Use maximum of difference plus memset length and memcpy length
1392 as the new memcpy length, if it is too big, bail out. */
1393 src_len = tree_to_uhwi (diff);
1394 src_len += tree_to_uhwi (len2);
1395 if (src_len < tree_to_uhwi (len1))
1396 src_len = tree_to_uhwi (len1);
1397 if (src_len > 1024)
1398 break;
1399
1400 /* If mempcpy value is used elsewhere, bail out, as mempcpy
1401 with bigger length will return different result. */
1402 if (lhs1 != NULL_TREE
1403 && DECL_FUNCTION_CODE (callee1) == BUILT_IN_MEMPCPY
1404 && (TREE_CODE (lhs1) != SSA_NAME
1405 || !single_imm_use (lhs1, &use_p, &use_stmt)
1406 || use_stmt != stmt2))
1407 break;
1408
1409 /* If anything reads memory in between memcpy and memset
1410 call, the modified memcpy call might change it. */
1411 vdef = gimple_vdef (stmt1);
1412 if (vdef != NULL
1413 && (!single_imm_use (vdef, &use_p, &use_stmt)
1414 || use_stmt != stmt2))
1415 break;
1416
1417 ptr1_align = get_pointer_alignment (ptr1);
1418 /* Construct the new source string literal. */
1419 src_buf = XALLOCAVEC (char, src_len + 1);
1420 if (callee1)
1421 memcpy (src_buf,
1422 TREE_STRING_POINTER (str1) + tree_to_uhwi (off1),
1423 tree_to_uhwi (len1));
1424 else
1425 src_buf[0] = tree_to_shwi (src1);
1426 memset (src_buf + tree_to_uhwi (diff),
1427 tree_to_shwi (val2), tree_to_uhwi (len2));
1428 src_buf[src_len] = '\0';
1429 /* Neither builtin_strncpy_read_str nor builtin_memcpy_read_str
1430 handle embedded '\0's. */
1431 if (strlen (src_buf) != src_len)
1432 break;
1433 rtl_profile_for_bb (gimple_bb (stmt2));
1434 /* If the new memcpy wouldn't be emitted by storing the literal
1435 by pieces, this optimization might enlarge .rodata too much,
1436 as commonly used string literals couldn't be shared any
1437 longer. */
1438 if (!can_store_by_pieces (src_len,
1439 builtin_strncpy_read_str,
1440 src_buf, ptr1_align, false))
1441 break;
1442
1443 new_str_cst = build_string_literal (src_len, src_buf);
1444 if (callee1)
1445 {
1446 /* If STMT1 is a mem{,p}cpy call, adjust it and remove
1447 memset call. */
1448 if (lhs1 && DECL_FUNCTION_CODE (callee1) == BUILT_IN_MEMPCPY)
1449 gimple_call_set_lhs (stmt1, NULL_TREE);
1450 gimple_call_set_arg (stmt1, 1, new_str_cst);
1451 gimple_call_set_arg (stmt1, 2,
1452 build_int_cst (TREE_TYPE (len1), src_len));
1453 update_stmt (stmt1);
1454 unlink_stmt_vdef (stmt2);
1455 gsi_replace (gsi_p, gimple_build_nop (), false);
1456 fwprop_invalidate_lattice (gimple_get_lhs (stmt2));
1457 release_defs (stmt2);
1458 if (lhs1 && DECL_FUNCTION_CODE (callee1) == BUILT_IN_MEMPCPY)
1459 {
1460 fwprop_invalidate_lattice (lhs1);
1461 release_ssa_name (lhs1);
1462 }
1463 return true;
1464 }
1465 else
1466 {
1467 /* Otherwise, if STMT1 is length 1 memcpy optimized into
1468 assignment, remove STMT1 and change memset call into
1469 memcpy call. */
1470 gimple_stmt_iterator gsi = gsi_for_stmt (stmt1);
1471
1472 if (!is_gimple_val (ptr1))
1473 ptr1 = force_gimple_operand_gsi (gsi_p, ptr1, true, NULL_TREE,
1474 true, GSI_SAME_STMT);
1475 tree fndecl = builtin_decl_explicit (BUILT_IN_MEMCPY);
1476 gimple_call_set_fndecl (stmt2, fndecl);
1477 gimple_call_set_fntype (as_a <gcall *> (stmt2),
1478 TREE_TYPE (fndecl));
1479 gimple_call_set_arg (stmt2, 0, ptr1);
1480 gimple_call_set_arg (stmt2, 1, new_str_cst);
1481 gimple_call_set_arg (stmt2, 2,
1482 build_int_cst (TREE_TYPE (len2), src_len));
1483 unlink_stmt_vdef (stmt1);
1484 gsi_remove (&gsi, true);
1485 fwprop_invalidate_lattice (gimple_get_lhs (stmt1));
1486 release_defs (stmt1);
1487 update_stmt (stmt2);
1488 return false;
1489 }
1490 }
1491 break;
1492
1493 #define CASE_ATOMIC(NAME, OTHER, OP) \
1494 case BUILT_IN_##NAME##_1: \
1495 case BUILT_IN_##NAME##_2: \
1496 case BUILT_IN_##NAME##_4: \
1497 case BUILT_IN_##NAME##_8: \
1498 case BUILT_IN_##NAME##_16: \
1499 atomic_op = OP; \
1500 other_atomic \
1501 = (enum built_in_function) (BUILT_IN_##OTHER##_1 \
1502 + (DECL_FUNCTION_CODE (callee2) \
1503 - BUILT_IN_##NAME##_1)); \
1504 goto handle_atomic_fetch_op;
1505
1506 CASE_ATOMIC (ATOMIC_FETCH_ADD, ATOMIC_ADD_FETCH, PLUS_EXPR)
1507 CASE_ATOMIC (ATOMIC_FETCH_SUB, ATOMIC_SUB_FETCH, MINUS_EXPR)
1508 CASE_ATOMIC (ATOMIC_FETCH_AND, ATOMIC_AND_FETCH, BIT_AND_EXPR)
1509 CASE_ATOMIC (ATOMIC_FETCH_XOR, ATOMIC_XOR_FETCH, BIT_XOR_EXPR)
1510 CASE_ATOMIC (ATOMIC_FETCH_OR, ATOMIC_OR_FETCH, BIT_IOR_EXPR)
1511
1512 CASE_ATOMIC (SYNC_FETCH_AND_ADD, SYNC_ADD_AND_FETCH, PLUS_EXPR)
1513 CASE_ATOMIC (SYNC_FETCH_AND_SUB, SYNC_SUB_AND_FETCH, MINUS_EXPR)
1514 CASE_ATOMIC (SYNC_FETCH_AND_AND, SYNC_AND_AND_FETCH, BIT_AND_EXPR)
1515 CASE_ATOMIC (SYNC_FETCH_AND_XOR, SYNC_XOR_AND_FETCH, BIT_XOR_EXPR)
1516 CASE_ATOMIC (SYNC_FETCH_AND_OR, SYNC_OR_AND_FETCH, BIT_IOR_EXPR)
1517
1518 CASE_ATOMIC (ATOMIC_ADD_FETCH, ATOMIC_FETCH_ADD, MINUS_EXPR)
1519 CASE_ATOMIC (ATOMIC_SUB_FETCH, ATOMIC_FETCH_SUB, PLUS_EXPR)
1520 CASE_ATOMIC (ATOMIC_XOR_FETCH, ATOMIC_FETCH_XOR, BIT_XOR_EXPR)
1521
1522 CASE_ATOMIC (SYNC_ADD_AND_FETCH, SYNC_FETCH_AND_ADD, MINUS_EXPR)
1523 CASE_ATOMIC (SYNC_SUB_AND_FETCH, SYNC_FETCH_AND_SUB, PLUS_EXPR)
1524 CASE_ATOMIC (SYNC_XOR_AND_FETCH, SYNC_FETCH_AND_XOR, BIT_XOR_EXPR)
1525
1526 #undef CASE_ATOMIC
1527
1528 handle_atomic_fetch_op:
1529 if (gimple_call_num_args (stmt2) >= 2 && gimple_call_lhs (stmt2))
1530 {
1531 tree lhs2 = gimple_call_lhs (stmt2), lhsc = lhs2;
1532 tree arg = gimple_call_arg (stmt2, 1);
1533 gimple *use_stmt, *cast_stmt = NULL;
1534 use_operand_p use_p;
1535 tree ndecl = builtin_decl_explicit (other_atomic);
1536
1537 if (ndecl == NULL_TREE || !single_imm_use (lhs2, &use_p, &use_stmt))
1538 break;
1539
1540 if (gimple_assign_cast_p (use_stmt))
1541 {
1542 cast_stmt = use_stmt;
1543 lhsc = gimple_assign_lhs (cast_stmt);
1544 if (lhsc == NULL_TREE
1545 || !INTEGRAL_TYPE_P (TREE_TYPE (lhsc))
1546 || (TYPE_PRECISION (TREE_TYPE (lhsc))
1547 != TYPE_PRECISION (TREE_TYPE (lhs2)))
1548 || !single_imm_use (lhsc, &use_p, &use_stmt))
1549 {
1550 use_stmt = cast_stmt;
1551 cast_stmt = NULL;
1552 lhsc = lhs2;
1553 }
1554 }
1555
1556 bool ok = false;
1557 tree oarg = NULL_TREE;
1558 enum tree_code ccode = ERROR_MARK;
1559 tree crhs1 = NULL_TREE, crhs2 = NULL_TREE;
1560 if (is_gimple_assign (use_stmt)
1561 && gimple_assign_rhs_code (use_stmt) == atomic_op)
1562 {
1563 if (gimple_assign_rhs1 (use_stmt) == lhsc)
1564 oarg = gimple_assign_rhs2 (use_stmt);
1565 else if (atomic_op != MINUS_EXPR)
1566 oarg = gimple_assign_rhs1 (use_stmt);
1567 }
1568 else if (atomic_op == MINUS_EXPR
1569 && is_gimple_assign (use_stmt)
1570 && gimple_assign_rhs_code (use_stmt) == PLUS_EXPR
1571 && TREE_CODE (arg) == INTEGER_CST
1572 && (TREE_CODE (gimple_assign_rhs2 (use_stmt))
1573 == INTEGER_CST))
1574 {
1575 tree a = fold_convert (TREE_TYPE (lhs2), arg);
1576 tree o = fold_convert (TREE_TYPE (lhs2),
1577 gimple_assign_rhs2 (use_stmt));
1578 if (wi::to_wide (a) == wi::neg (wi::to_wide (o)))
1579 ok = true;
1580 }
1581 else if (atomic_op == BIT_AND_EXPR || atomic_op == BIT_IOR_EXPR)
1582 ;
1583 else if (gimple_code (use_stmt) == GIMPLE_COND)
1584 {
1585 ccode = gimple_cond_code (use_stmt);
1586 crhs1 = gimple_cond_lhs (use_stmt);
1587 crhs2 = gimple_cond_rhs (use_stmt);
1588 }
1589 else if (is_gimple_assign (use_stmt))
1590 {
1591 if (gimple_assign_rhs_class (use_stmt) == GIMPLE_BINARY_RHS)
1592 {
1593 ccode = gimple_assign_rhs_code (use_stmt);
1594 crhs1 = gimple_assign_rhs1 (use_stmt);
1595 crhs2 = gimple_assign_rhs2 (use_stmt);
1596 }
1597 else if (gimple_assign_rhs_code (use_stmt) == COND_EXPR)
1598 {
1599 tree cond = gimple_assign_rhs1 (use_stmt);
1600 if (COMPARISON_CLASS_P (cond))
1601 {
1602 ccode = TREE_CODE (cond);
1603 crhs1 = TREE_OPERAND (cond, 0);
1604 crhs2 = TREE_OPERAND (cond, 1);
1605 }
1606 }
1607 }
1608 if (ccode == EQ_EXPR || ccode == NE_EXPR)
1609 {
1610 /* Deal with x - y == 0 or x ^ y == 0
1611 being optimized into x == y and x + cst == 0
1612 into x == -cst. */
1613 tree o = NULL_TREE;
1614 if (crhs1 == lhsc)
1615 o = crhs2;
1616 else if (crhs2 == lhsc)
1617 o = crhs1;
1618 if (o && atomic_op != PLUS_EXPR)
1619 oarg = o;
1620 else if (o
1621 && TREE_CODE (o) == INTEGER_CST
1622 && TREE_CODE (arg) == INTEGER_CST)
1623 {
1624 tree a = fold_convert (TREE_TYPE (lhs2), arg);
1625 o = fold_convert (TREE_TYPE (lhs2), o);
1626 if (wi::to_wide (a) == wi::neg (wi::to_wide (o)))
1627 ok = true;
1628 }
1629 }
1630 if (oarg && !ok)
1631 {
1632 if (operand_equal_p (arg, oarg, 0))
1633 ok = true;
1634 else if (TREE_CODE (arg) == SSA_NAME
1635 && TREE_CODE (oarg) == SSA_NAME)
1636 {
1637 tree oarg2 = oarg;
1638 if (gimple_assign_cast_p (SSA_NAME_DEF_STMT (oarg)))
1639 {
1640 gimple *g = SSA_NAME_DEF_STMT (oarg);
1641 oarg2 = gimple_assign_rhs1 (g);
1642 if (TREE_CODE (oarg2) != SSA_NAME
1643 || !INTEGRAL_TYPE_P (TREE_TYPE (oarg2))
1644 || (TYPE_PRECISION (TREE_TYPE (oarg2))
1645 != TYPE_PRECISION (TREE_TYPE (oarg))))
1646 oarg2 = oarg;
1647 }
1648 if (gimple_assign_cast_p (SSA_NAME_DEF_STMT (arg)))
1649 {
1650 gimple *g = SSA_NAME_DEF_STMT (arg);
1651 tree rhs1 = gimple_assign_rhs1 (g);
1652 /* Handle e.g.
1653 x.0_1 = (long unsigned int) x_4(D);
1654 _2 = __atomic_fetch_add_8 (&vlong, x.0_1, 0);
1655 _3 = (long int) _2;
1656 _7 = x_4(D) + _3; */
1657 if (rhs1 == oarg || rhs1 == oarg2)
1658 ok = true;
1659 /* Handle e.g.
1660 x.18_1 = (short unsigned int) x_5(D);
1661 _2 = (int) x.18_1;
1662 _3 = __atomic_fetch_xor_2 (&vshort, _2, 0);
1663 _4 = (short int) _3;
1664 _8 = x_5(D) ^ _4;
1665 This happens only for char/short. */
1666 else if (TREE_CODE (rhs1) == SSA_NAME
1667 && INTEGRAL_TYPE_P (TREE_TYPE (rhs1))
1668 && (TYPE_PRECISION (TREE_TYPE (rhs1))
1669 == TYPE_PRECISION (TREE_TYPE (lhs2))))
1670 {
1671 g = SSA_NAME_DEF_STMT (rhs1);
1672 if (gimple_assign_cast_p (g)
1673 && (gimple_assign_rhs1 (g) == oarg
1674 || gimple_assign_rhs1 (g) == oarg2))
1675 ok = true;
1676 }
1677 }
1678 if (!ok && arg == oarg2)
1679 /* Handle e.g.
1680 _1 = __sync_fetch_and_add_4 (&v, x_5(D));
1681 _2 = (int) _1;
1682 x.0_3 = (int) x_5(D);
1683 _7 = _2 + x.0_3; */
1684 ok = true;
1685 }
1686 }
1687
1688 if (ok)
1689 {
1690 tree new_lhs = make_ssa_name (TREE_TYPE (lhs2));
1691 gimple_call_set_lhs (stmt2, new_lhs);
1692 gimple_call_set_fndecl (stmt2, ndecl);
1693 gimple_stmt_iterator gsi = gsi_for_stmt (use_stmt);
1694 if (ccode == ERROR_MARK)
1695 gimple_assign_set_rhs_with_ops (&gsi, cast_stmt
1696 ? NOP_EXPR : SSA_NAME,
1697 new_lhs);
1698 else
1699 {
1700 crhs1 = new_lhs;
1701 crhs2 = build_zero_cst (TREE_TYPE (lhs2));
1702 if (gimple_code (use_stmt) == GIMPLE_COND)
1703 {
1704 gcond *cond_stmt = as_a <gcond *> (use_stmt);
1705 gimple_cond_set_lhs (cond_stmt, crhs1);
1706 gimple_cond_set_rhs (cond_stmt, crhs2);
1707 }
1708 else if (gimple_assign_rhs_class (use_stmt)
1709 == GIMPLE_BINARY_RHS)
1710 {
1711 gimple_assign_set_rhs1 (use_stmt, crhs1);
1712 gimple_assign_set_rhs2 (use_stmt, crhs2);
1713 }
1714 else
1715 {
1716 gcc_checking_assert (gimple_assign_rhs_code (use_stmt)
1717 == COND_EXPR);
1718 tree cond = build2 (ccode, boolean_type_node,
1719 crhs1, crhs2);
1720 gimple_assign_set_rhs1 (use_stmt, cond);
1721 }
1722 }
1723 update_stmt (use_stmt);
1724 if (atomic_op != BIT_AND_EXPR
1725 && atomic_op != BIT_IOR_EXPR
1726 && !stmt_ends_bb_p (stmt2))
1727 {
1728 /* For the benefit of debug stmts, emit stmt(s) to set
1729 lhs2 to the value it had from the new builtin.
1730 E.g. if it was previously:
1731 lhs2 = __atomic_fetch_add_8 (ptr, arg, 0);
1732 emit:
1733 new_lhs = __atomic_add_fetch_8 (ptr, arg, 0);
1734 lhs2 = new_lhs - arg;
1735 We also keep cast_stmt if any in the IL for
1736 the same reasons.
1737 These stmts will be DCEd later and proper debug info
1738 will be emitted.
1739 This is only possible for reversible operations
1740 (+/-/^) and without -fnon-call-exceptions. */
1741 gsi = gsi_for_stmt (stmt2);
1742 tree type = TREE_TYPE (lhs2);
1743 if (TREE_CODE (arg) == INTEGER_CST)
1744 arg = fold_convert (type, arg);
1745 else if (!useless_type_conversion_p (type, TREE_TYPE (arg)))
1746 {
1747 tree narg = make_ssa_name (type);
1748 gimple *g = gimple_build_assign (narg, NOP_EXPR, arg);
1749 gsi_insert_after (&gsi, g, GSI_NEW_STMT);
1750 arg = narg;
1751 }
1752 enum tree_code rcode;
1753 switch (atomic_op)
1754 {
1755 case PLUS_EXPR: rcode = MINUS_EXPR; break;
1756 case MINUS_EXPR: rcode = PLUS_EXPR; break;
1757 case BIT_XOR_EXPR: rcode = atomic_op; break;
1758 default: gcc_unreachable ();
1759 }
1760 gimple *g = gimple_build_assign (lhs2, rcode, new_lhs, arg);
1761 gsi_insert_after (&gsi, g, GSI_NEW_STMT);
1762 update_stmt (stmt2);
1763 }
1764 else
1765 {
1766 /* For e.g.
1767 lhs2 = __atomic_fetch_or_8 (ptr, arg, 0);
1768 after we change it to
1769 new_lhs = __atomic_or_fetch_8 (ptr, arg, 0);
1770 there is no way to find out the lhs2 value (i.e.
1771 what the atomic memory contained before the operation),
1772 values of some bits are lost. We have checked earlier
1773 that we don't have any non-debug users except for what
1774 we are already changing, so we need to reset the
1775 debug stmts and remove the cast_stmt if any. */
1776 imm_use_iterator iter;
1777 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs2)
1778 if (use_stmt != cast_stmt)
1779 {
1780 gcc_assert (is_gimple_debug (use_stmt));
1781 gimple_debug_bind_reset_value (use_stmt);
1782 update_stmt (use_stmt);
1783 }
1784 if (cast_stmt)
1785 {
1786 gsi = gsi_for_stmt (cast_stmt);
1787 gsi_remove (&gsi, true);
1788 }
1789 update_stmt (stmt2);
1790 release_ssa_name (lhs2);
1791 }
1792 }
1793 }
1794 break;
1795
1796 default:
1797 break;
1798 }
1799 return false;
1800 }
1801
1802 /* Given a ssa_name in NAME see if it was defined by an assignment and
1803 set CODE to be the code and ARG1 to the first operand on the rhs and ARG2
1804 to the second operand on the rhs. */
1805
1806 static inline void
1807 defcodefor_name (tree name, enum tree_code *code, tree *arg1, tree *arg2)
1808 {
1809 gimple *def;
1810 enum tree_code code1;
1811 tree arg11;
1812 tree arg21;
1813 tree arg31;
1814 enum gimple_rhs_class grhs_class;
1815
1816 code1 = TREE_CODE (name);
1817 arg11 = name;
1818 arg21 = NULL_TREE;
1819 arg31 = NULL_TREE;
1820 grhs_class = get_gimple_rhs_class (code1);
1821
1822 if (code1 == SSA_NAME)
1823 {
1824 def = SSA_NAME_DEF_STMT (name);
1825
1826 if (def && is_gimple_assign (def)
1827 && can_propagate_from (def))
1828 {
1829 code1 = gimple_assign_rhs_code (def);
1830 arg11 = gimple_assign_rhs1 (def);
1831 arg21 = gimple_assign_rhs2 (def);
1832 arg31 = gimple_assign_rhs3 (def);
1833 }
1834 }
1835 else if (grhs_class != GIMPLE_SINGLE_RHS)
1836 code1 = ERROR_MARK;
1837
1838 *code = code1;
1839 *arg1 = arg11;
1840 if (arg2)
1841 *arg2 = arg21;
1842 if (arg31)
1843 *code = ERROR_MARK;
1844 }
1845
1846
1847 /* Recognize rotation patterns. Return true if a transformation
1848 applied, otherwise return false.
1849
1850 We are looking for X with unsigned type T with bitsize B, OP being
1851 +, | or ^, some type T2 wider than T. For:
1852 (X << CNT1) OP (X >> CNT2) iff CNT1 + CNT2 == B
1853 ((T) ((T2) X << CNT1)) OP ((T) ((T2) X >> CNT2)) iff CNT1 + CNT2 == B
1854
1855 transform these into:
1856 X r<< CNT1
1857
1858 Or for:
1859 (X << Y) OP (X >> (B - Y))
1860 (X << (int) Y) OP (X >> (int) (B - Y))
1861 ((T) ((T2) X << Y)) OP ((T) ((T2) X >> (B - Y)))
1862 ((T) ((T2) X << (int) Y)) OP ((T) ((T2) X >> (int) (B - Y)))
1863 (X << Y) | (X >> ((-Y) & (B - 1)))
1864 (X << (int) Y) | (X >> (int) ((-Y) & (B - 1)))
1865 ((T) ((T2) X << Y)) | ((T) ((T2) X >> ((-Y) & (B - 1))))
1866 ((T) ((T2) X << (int) Y)) | ((T) ((T2) X >> (int) ((-Y) & (B - 1))))
1867
1868 transform these into (last 2 only if ranger can prove Y < B
1869 or Y = N * B):
1870 X r<< Y
1871 or
1872 X r<< (& & (B - 1))
1873 The latter for the forms with T2 wider than T if ranger can't prove Y < B.
1874
1875 Or for:
1876 (X << (Y & (B - 1))) | (X >> ((-Y) & (B - 1)))
1877 (X << (int) (Y & (B - 1))) | (X >> (int) ((-Y) & (B - 1)))
1878 ((T) ((T2) X << (Y & (B - 1)))) | ((T) ((T2) X >> ((-Y) & (B - 1))))
1879 ((T) ((T2) X << (int) (Y & (B - 1)))) \
1880 | ((T) ((T2) X >> (int) ((-Y) & (B - 1))))
1881
1882 transform these into:
1883 X r<< (Y & (B - 1))
1884
1885 Note, in the patterns with T2 type, the type of OP operands
1886 might be even a signed type, but should have precision B.
1887 Expressions with & (B - 1) should be recognized only if B is
1888 a power of 2. */
1889
1890 static bool
1891 simplify_rotate (gimple_stmt_iterator *gsi)
1892 {
1893 gimple *stmt = gsi_stmt (*gsi);
1894 tree arg[2], rtype, rotcnt = NULL_TREE;
1895 tree def_arg1[2], def_arg2[2];
1896 enum tree_code def_code[2];
1897 tree lhs;
1898 int i;
1899 bool swapped_p = false;
1900 gimple *g;
1901 gimple *def_arg_stmt[2] = { NULL, NULL };
1902 int wider_prec = 0;
1903 bool add_masking = false;
1904
1905 arg[0] = gimple_assign_rhs1 (stmt);
1906 arg[1] = gimple_assign_rhs2 (stmt);
1907 rtype = TREE_TYPE (arg[0]);
1908
1909 /* Only create rotates in complete modes. Other cases are not
1910 expanded properly. */
1911 if (!INTEGRAL_TYPE_P (rtype)
1912 || !type_has_mode_precision_p (rtype))
1913 return false;
1914
1915 for (i = 0; i < 2; i++)
1916 {
1917 defcodefor_name (arg[i], &def_code[i], &def_arg1[i], &def_arg2[i]);
1918 if (TREE_CODE (arg[i]) == SSA_NAME)
1919 def_arg_stmt[i] = SSA_NAME_DEF_STMT (arg[i]);
1920 }
1921
1922 /* Look through narrowing (or same precision) conversions. */
1923 if (CONVERT_EXPR_CODE_P (def_code[0])
1924 && CONVERT_EXPR_CODE_P (def_code[1])
1925 && INTEGRAL_TYPE_P (TREE_TYPE (def_arg1[0]))
1926 && INTEGRAL_TYPE_P (TREE_TYPE (def_arg1[1]))
1927 && TYPE_PRECISION (TREE_TYPE (def_arg1[0]))
1928 == TYPE_PRECISION (TREE_TYPE (def_arg1[1]))
1929 && TYPE_PRECISION (TREE_TYPE (def_arg1[0])) >= TYPE_PRECISION (rtype)
1930 && has_single_use (arg[0])
1931 && has_single_use (arg[1]))
1932 {
1933 wider_prec = TYPE_PRECISION (TREE_TYPE (def_arg1[0]));
1934 for (i = 0; i < 2; i++)
1935 {
1936 arg[i] = def_arg1[i];
1937 defcodefor_name (arg[i], &def_code[i], &def_arg1[i], &def_arg2[i]);
1938 if (TREE_CODE (arg[i]) == SSA_NAME)
1939 def_arg_stmt[i] = SSA_NAME_DEF_STMT (arg[i]);
1940 }
1941 }
1942 else
1943 {
1944 /* Handle signed rotate; the RSHIFT_EXPR has to be done
1945 in unsigned type but LSHIFT_EXPR could be signed. */
1946 i = (def_code[0] == LSHIFT_EXPR || def_code[0] == RSHIFT_EXPR);
1947 if (CONVERT_EXPR_CODE_P (def_code[i])
1948 && (def_code[1 - i] == LSHIFT_EXPR || def_code[1 - i] == RSHIFT_EXPR)
1949 && INTEGRAL_TYPE_P (TREE_TYPE (def_arg1[i]))
1950 && TYPE_PRECISION (rtype) == TYPE_PRECISION (TREE_TYPE (def_arg1[i]))
1951 && has_single_use (arg[i]))
1952 {
1953 arg[i] = def_arg1[i];
1954 defcodefor_name (arg[i], &def_code[i], &def_arg1[i], &def_arg2[i]);
1955 if (TREE_CODE (arg[i]) == SSA_NAME)
1956 def_arg_stmt[i] = SSA_NAME_DEF_STMT (arg[i]);
1957 }
1958 }
1959
1960 /* One operand has to be LSHIFT_EXPR and one RSHIFT_EXPR. */
1961 for (i = 0; i < 2; i++)
1962 if (def_code[i] != LSHIFT_EXPR && def_code[i] != RSHIFT_EXPR)
1963 return false;
1964 else if (!has_single_use (arg[i]))
1965 return false;
1966 if (def_code[0] == def_code[1])
1967 return false;
1968
1969 /* If we've looked through narrowing conversions before, look through
1970 widening conversions from unsigned type with the same precision
1971 as rtype here. */
1972 if (TYPE_PRECISION (TREE_TYPE (def_arg1[0])) != TYPE_PRECISION (rtype))
1973 for (i = 0; i < 2; i++)
1974 {
1975 tree tem;
1976 enum tree_code code;
1977 defcodefor_name (def_arg1[i], &code, &tem, NULL);
1978 if (!CONVERT_EXPR_CODE_P (code)
1979 || !INTEGRAL_TYPE_P (TREE_TYPE (tem))
1980 || TYPE_PRECISION (TREE_TYPE (tem)) != TYPE_PRECISION (rtype))
1981 return false;
1982 def_arg1[i] = tem;
1983 }
1984 /* Both shifts have to use the same first operand. */
1985 if (!operand_equal_for_phi_arg_p (def_arg1[0], def_arg1[1])
1986 || !types_compatible_p (TREE_TYPE (def_arg1[0]),
1987 TREE_TYPE (def_arg1[1])))
1988 {
1989 if ((TYPE_PRECISION (TREE_TYPE (def_arg1[0]))
1990 != TYPE_PRECISION (TREE_TYPE (def_arg1[1])))
1991 || (TYPE_UNSIGNED (TREE_TYPE (def_arg1[0]))
1992 == TYPE_UNSIGNED (TREE_TYPE (def_arg1[1]))))
1993 return false;
1994
1995 /* Handle signed rotate; the RSHIFT_EXPR has to be done
1996 in unsigned type but LSHIFT_EXPR could be signed. */
1997 i = def_code[0] != RSHIFT_EXPR;
1998 if (!TYPE_UNSIGNED (TREE_TYPE (def_arg1[i])))
1999 return false;
2000
2001 tree tem;
2002 enum tree_code code;
2003 defcodefor_name (def_arg1[i], &code, &tem, NULL);
2004 if (!CONVERT_EXPR_CODE_P (code)
2005 || !INTEGRAL_TYPE_P (TREE_TYPE (tem))
2006 || TYPE_PRECISION (TREE_TYPE (tem)) != TYPE_PRECISION (rtype))
2007 return false;
2008 def_arg1[i] = tem;
2009 if (!operand_equal_for_phi_arg_p (def_arg1[0], def_arg1[1])
2010 || !types_compatible_p (TREE_TYPE (def_arg1[0]),
2011 TREE_TYPE (def_arg1[1])))
2012 return false;
2013 }
2014 else if (!TYPE_UNSIGNED (TREE_TYPE (def_arg1[0])))
2015 return false;
2016
2017 /* CNT1 + CNT2 == B case above. */
2018 if (tree_fits_uhwi_p (def_arg2[0])
2019 && tree_fits_uhwi_p (def_arg2[1])
2020 && tree_to_uhwi (def_arg2[0])
2021 + tree_to_uhwi (def_arg2[1]) == TYPE_PRECISION (rtype))
2022 rotcnt = def_arg2[0];
2023 else if (TREE_CODE (def_arg2[0]) != SSA_NAME
2024 || TREE_CODE (def_arg2[1]) != SSA_NAME)
2025 return false;
2026 else
2027 {
2028 tree cdef_arg1[2], cdef_arg2[2], def_arg2_alt[2];
2029 enum tree_code cdef_code[2];
2030 gimple *def_arg_alt_stmt[2] = { NULL, NULL };
2031 int check_range = 0;
2032 gimple *check_range_stmt = NULL;
2033 /* Look through conversion of the shift count argument.
2034 The C/C++ FE cast any shift count argument to integer_type_node.
2035 The only problem might be if the shift count type maximum value
2036 is equal or smaller than number of bits in rtype. */
2037 for (i = 0; i < 2; i++)
2038 {
2039 def_arg2_alt[i] = def_arg2[i];
2040 defcodefor_name (def_arg2[i], &cdef_code[i],
2041 &cdef_arg1[i], &cdef_arg2[i]);
2042 if (CONVERT_EXPR_CODE_P (cdef_code[i])
2043 && INTEGRAL_TYPE_P (TREE_TYPE (cdef_arg1[i]))
2044 && TYPE_PRECISION (TREE_TYPE (cdef_arg1[i]))
2045 > floor_log2 (TYPE_PRECISION (rtype))
2046 && type_has_mode_precision_p (TREE_TYPE (cdef_arg1[i])))
2047 {
2048 def_arg2_alt[i] = cdef_arg1[i];
2049 if (TREE_CODE (def_arg2[i]) == SSA_NAME)
2050 def_arg_alt_stmt[i] = SSA_NAME_DEF_STMT (def_arg2[i]);
2051 defcodefor_name (def_arg2_alt[i], &cdef_code[i],
2052 &cdef_arg1[i], &cdef_arg2[i]);
2053 }
2054 else
2055 def_arg_alt_stmt[i] = def_arg_stmt[i];
2056 }
2057 for (i = 0; i < 2; i++)
2058 /* Check for one shift count being Y and the other B - Y,
2059 with optional casts. */
2060 if (cdef_code[i] == MINUS_EXPR
2061 && tree_fits_shwi_p (cdef_arg1[i])
2062 && tree_to_shwi (cdef_arg1[i]) == TYPE_PRECISION (rtype)
2063 && TREE_CODE (cdef_arg2[i]) == SSA_NAME)
2064 {
2065 tree tem;
2066 enum tree_code code;
2067
2068 if (cdef_arg2[i] == def_arg2[1 - i]
2069 || cdef_arg2[i] == def_arg2_alt[1 - i])
2070 {
2071 rotcnt = cdef_arg2[i];
2072 check_range = -1;
2073 if (cdef_arg2[i] == def_arg2[1 - i])
2074 check_range_stmt = def_arg_stmt[1 - i];
2075 else
2076 check_range_stmt = def_arg_alt_stmt[1 - i];
2077 break;
2078 }
2079 defcodefor_name (cdef_arg2[i], &code, &tem, NULL);
2080 if (CONVERT_EXPR_CODE_P (code)
2081 && INTEGRAL_TYPE_P (TREE_TYPE (tem))
2082 && TYPE_PRECISION (TREE_TYPE (tem))
2083 > floor_log2 (TYPE_PRECISION (rtype))
2084 && type_has_mode_precision_p (TREE_TYPE (tem))
2085 && (tem == def_arg2[1 - i]
2086 || tem == def_arg2_alt[1 - i]))
2087 {
2088 rotcnt = tem;
2089 check_range = -1;
2090 if (tem == def_arg2[1 - i])
2091 check_range_stmt = def_arg_stmt[1 - i];
2092 else
2093 check_range_stmt = def_arg_alt_stmt[1 - i];
2094 break;
2095 }
2096 }
2097 /* The above sequence isn't safe for Y being 0,
2098 because then one of the shifts triggers undefined behavior.
2099 This alternative is safe even for rotation count of 0.
2100 One shift count is Y and the other (-Y) & (B - 1).
2101 Or one shift count is Y & (B - 1) and the other (-Y) & (B - 1). */
2102 else if (cdef_code[i] == BIT_AND_EXPR
2103 && pow2p_hwi (TYPE_PRECISION (rtype))
2104 && tree_fits_shwi_p (cdef_arg2[i])
2105 && tree_to_shwi (cdef_arg2[i])
2106 == TYPE_PRECISION (rtype) - 1
2107 && TREE_CODE (cdef_arg1[i]) == SSA_NAME
2108 && gimple_assign_rhs_code (stmt) == BIT_IOR_EXPR)
2109 {
2110 tree tem;
2111 enum tree_code code;
2112
2113 defcodefor_name (cdef_arg1[i], &code, &tem, NULL);
2114 if (CONVERT_EXPR_CODE_P (code)
2115 && INTEGRAL_TYPE_P (TREE_TYPE (tem))
2116 && TYPE_PRECISION (TREE_TYPE (tem))
2117 > floor_log2 (TYPE_PRECISION (rtype))
2118 && type_has_mode_precision_p (TREE_TYPE (tem)))
2119 defcodefor_name (tem, &code, &tem, NULL);
2120
2121 if (code == NEGATE_EXPR)
2122 {
2123 if (tem == def_arg2[1 - i] || tem == def_arg2_alt[1 - i])
2124 {
2125 rotcnt = tem;
2126 check_range = 1;
2127 if (tem == def_arg2[1 - i])
2128 check_range_stmt = def_arg_stmt[1 - i];
2129 else
2130 check_range_stmt = def_arg_alt_stmt[1 - i];
2131 break;
2132 }
2133 tree tem2;
2134 defcodefor_name (tem, &code, &tem2, NULL);
2135 if (CONVERT_EXPR_CODE_P (code)
2136 && INTEGRAL_TYPE_P (TREE_TYPE (tem2))
2137 && TYPE_PRECISION (TREE_TYPE (tem2))
2138 > floor_log2 (TYPE_PRECISION (rtype))
2139 && type_has_mode_precision_p (TREE_TYPE (tem2)))
2140 {
2141 if (tem2 == def_arg2[1 - i]
2142 || tem2 == def_arg2_alt[1 - i])
2143 {
2144 rotcnt = tem2;
2145 check_range = 1;
2146 if (tem2 == def_arg2[1 - i])
2147 check_range_stmt = def_arg_stmt[1 - i];
2148 else
2149 check_range_stmt = def_arg_alt_stmt[1 - i];
2150 break;
2151 }
2152 }
2153 else
2154 tem2 = NULL_TREE;
2155
2156 if (cdef_code[1 - i] == BIT_AND_EXPR
2157 && tree_fits_shwi_p (cdef_arg2[1 - i])
2158 && tree_to_shwi (cdef_arg2[1 - i])
2159 == TYPE_PRECISION (rtype) - 1
2160 && TREE_CODE (cdef_arg1[1 - i]) == SSA_NAME)
2161 {
2162 if (tem == cdef_arg1[1 - i]
2163 || tem2 == cdef_arg1[1 - i])
2164 {
2165 rotcnt = def_arg2[1 - i];
2166 break;
2167 }
2168 tree tem3;
2169 defcodefor_name (cdef_arg1[1 - i], &code, &tem3, NULL);
2170 if (CONVERT_EXPR_CODE_P (code)
2171 && INTEGRAL_TYPE_P (TREE_TYPE (tem3))
2172 && TYPE_PRECISION (TREE_TYPE (tem3))
2173 > floor_log2 (TYPE_PRECISION (rtype))
2174 && type_has_mode_precision_p (TREE_TYPE (tem3)))
2175 {
2176 if (tem == tem3 || tem2 == tem3)
2177 {
2178 rotcnt = def_arg2[1 - i];
2179 break;
2180 }
2181 }
2182 }
2183 }
2184 }
2185 if (check_range && wider_prec > TYPE_PRECISION (rtype))
2186 {
2187 if (TREE_CODE (rotcnt) != SSA_NAME)
2188 return false;
2189 int_range_max r;
2190 range_query *q = get_range_query (cfun);
2191 if (q == get_global_range_query ())
2192 q = enable_ranger (cfun);
2193 if (!q->range_of_expr (r, rotcnt, check_range_stmt))
2194 {
2195 if (check_range > 0)
2196 return false;
2197 r.set_varying (TREE_TYPE (rotcnt));
2198 }
2199 int prec = TYPE_PRECISION (TREE_TYPE (rotcnt));
2200 signop sign = TYPE_SIGN (TREE_TYPE (rotcnt));
2201 wide_int min = wide_int::from (TYPE_PRECISION (rtype), prec, sign);
2202 wide_int max = wide_int::from (wider_prec - 1, prec, sign);
2203 if (check_range < 0)
2204 max = min;
2205 int_range<1> r2 (TREE_TYPE (rotcnt), min, max);
2206 r.intersect (r2);
2207 if (!r.undefined_p ())
2208 {
2209 if (check_range > 0)
2210 {
2211 int_range_max r3;
2212 for (int i = TYPE_PRECISION (rtype) + 1; i < wider_prec;
2213 i += TYPE_PRECISION (rtype))
2214 {
2215 int j = i + TYPE_PRECISION (rtype) - 2;
2216 min = wide_int::from (i, prec, sign);
2217 max = wide_int::from (MIN (j, wider_prec - 1),
2218 prec, sign);
2219 int_range<1> r4 (TREE_TYPE (rotcnt), min, max);
2220 r3.union_ (r4);
2221 }
2222 r.intersect (r3);
2223 if (!r.undefined_p ())
2224 return false;
2225 }
2226 add_masking = true;
2227 }
2228 }
2229 if (rotcnt == NULL_TREE)
2230 return false;
2231 swapped_p = i != 1;
2232 }
2233
2234 if (!useless_type_conversion_p (TREE_TYPE (def_arg2[0]),
2235 TREE_TYPE (rotcnt)))
2236 {
2237 g = gimple_build_assign (make_ssa_name (TREE_TYPE (def_arg2[0])),
2238 NOP_EXPR, rotcnt);
2239 gsi_insert_before (gsi, g, GSI_SAME_STMT);
2240 rotcnt = gimple_assign_lhs (g);
2241 }
2242 if (add_masking)
2243 {
2244 g = gimple_build_assign (make_ssa_name (TREE_TYPE (rotcnt)),
2245 BIT_AND_EXPR, rotcnt,
2246 build_int_cst (TREE_TYPE (rotcnt),
2247 TYPE_PRECISION (rtype) - 1));
2248 gsi_insert_before (gsi, g, GSI_SAME_STMT);
2249 rotcnt = gimple_assign_lhs (g);
2250 }
2251 lhs = gimple_assign_lhs (stmt);
2252 if (!useless_type_conversion_p (rtype, TREE_TYPE (def_arg1[0])))
2253 lhs = make_ssa_name (TREE_TYPE (def_arg1[0]));
2254 g = gimple_build_assign (lhs,
2255 ((def_code[0] == LSHIFT_EXPR) ^ swapped_p)
2256 ? LROTATE_EXPR : RROTATE_EXPR, def_arg1[0], rotcnt);
2257 if (!useless_type_conversion_p (rtype, TREE_TYPE (def_arg1[0])))
2258 {
2259 gsi_insert_before (gsi, g, GSI_SAME_STMT);
2260 g = gimple_build_assign (gimple_assign_lhs (stmt), NOP_EXPR, lhs);
2261 }
2262 gsi_replace (gsi, g, false);
2263 return true;
2264 }
2265
2266
2267 /* Check whether an array contains a valid ctz table. */
2268 static bool
2269 check_ctz_array (tree ctor, unsigned HOST_WIDE_INT mulc,
2270 HOST_WIDE_INT &zero_val, unsigned shift, unsigned bits)
2271 {
2272 tree elt, idx;
2273 unsigned HOST_WIDE_INT i, mask, raw_idx = 0;
2274 unsigned matched = 0;
2275
2276 mask = ((HOST_WIDE_INT_1U << (bits - shift)) - 1) << shift;
2277
2278 zero_val = 0;
2279
2280 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (ctor), i, idx, elt)
2281 {
2282 if (!tree_fits_shwi_p (idx))
2283 return false;
2284 if (!tree_fits_shwi_p (elt) && TREE_CODE (elt) != RAW_DATA_CST)
2285 return false;
2286
2287 unsigned HOST_WIDE_INT index = tree_to_shwi (idx);
2288 HOST_WIDE_INT val;
2289
2290 if (TREE_CODE (elt) == INTEGER_CST)
2291 val = tree_to_shwi (elt);
2292 else
2293 {
2294 if (raw_idx == (unsigned) RAW_DATA_LENGTH (elt))
2295 {
2296 raw_idx = 0;
2297 continue;
2298 }
2299 if (TYPE_UNSIGNED (TREE_TYPE (elt)))
2300 val = RAW_DATA_UCHAR_ELT (elt, raw_idx);
2301 else
2302 val = RAW_DATA_SCHAR_ELT (elt, raw_idx);
2303 index += raw_idx;
2304 raw_idx++;
2305 i--;
2306 }
2307
2308 if (index > bits * 2)
2309 return false;
2310
2311 if (index == 0)
2312 {
2313 zero_val = val;
2314 matched++;
2315 }
2316
2317 if (val >= 0 && val < bits && (((mulc << val) & mask) >> shift) == index)
2318 matched++;
2319
2320 if (matched > bits)
2321 return true;
2322 }
2323
2324 return false;
2325 }
2326
2327 /* Check whether a string contains a valid ctz table. */
2328 static bool
2329 check_ctz_string (tree string, unsigned HOST_WIDE_INT mulc,
2330 HOST_WIDE_INT &zero_val, unsigned shift, unsigned bits)
2331 {
2332 unsigned HOST_WIDE_INT len = TREE_STRING_LENGTH (string);
2333 unsigned HOST_WIDE_INT mask;
2334 unsigned matched = 0;
2335 const unsigned char *p = (const unsigned char *) TREE_STRING_POINTER (string);
2336
2337 if (len < bits || len > bits * 2)
2338 return false;
2339
2340 mask = ((HOST_WIDE_INT_1U << (bits - shift)) - 1) << shift;
2341
2342 zero_val = p[0];
2343
2344 for (unsigned i = 0; i < len; i++)
2345 if (p[i] < bits && (((mulc << p[i]) & mask) >> shift) == i)
2346 matched++;
2347
2348 return matched == bits;
2349 }
2350
2351 /* Recognize count trailing zeroes idiom.
2352 The canonical form is array[((x & -x) * C) >> SHIFT] where C is a magic
2353 constant which when multiplied by a power of 2 creates a unique value
2354 in the top 5 or 6 bits. This is then indexed into a table which maps it
2355 to the number of trailing zeroes. Array[0] is returned so the caller can
2356 emit an appropriate sequence depending on whether ctz (0) is defined on
2357 the target. */
2358 static bool
2359 optimize_count_trailing_zeroes (tree array_ref, tree x, tree mulc,
2360 tree tshift, HOST_WIDE_INT &zero_val)
2361 {
2362 tree type = TREE_TYPE (array_ref);
2363 tree array = TREE_OPERAND (array_ref, 0);
2364
2365 gcc_assert (TREE_CODE (mulc) == INTEGER_CST);
2366 gcc_assert (TREE_CODE (tshift) == INTEGER_CST);
2367
2368 tree input_type = TREE_TYPE (x);
2369 unsigned input_bits = tree_to_shwi (TYPE_SIZE (input_type));
2370
2371 /* Check the array element type is not wider than 32 bits and the input is
2372 an unsigned 32-bit or 64-bit type. */
2373 if (TYPE_PRECISION (type) > 32 || !TYPE_UNSIGNED (input_type))
2374 return false;
2375 if (input_bits != 32 && input_bits != 64)
2376 return false;
2377
2378 if (!direct_internal_fn_supported_p (IFN_CTZ, input_type, OPTIMIZE_FOR_BOTH))
2379 return false;
2380
2381 /* Check the lower bound of the array is zero. */
2382 tree low = array_ref_low_bound (array_ref);
2383 if (!low || !integer_zerop (low))
2384 return false;
2385
2386 unsigned shiftval = tree_to_shwi (tshift);
2387
2388 /* Check the shift extracts the top 5..7 bits. */
2389 if (shiftval < input_bits - 7 || shiftval > input_bits - 5)
2390 return false;
2391
2392 tree ctor = ctor_for_folding (array);
2393 if (!ctor)
2394 return false;
2395
2396 unsigned HOST_WIDE_INT val = tree_to_uhwi (mulc);
2397
2398 if (TREE_CODE (ctor) == CONSTRUCTOR)
2399 return check_ctz_array (ctor, val, zero_val, shiftval, input_bits);
2400
2401 if (TREE_CODE (ctor) == STRING_CST
2402 && TYPE_PRECISION (type) == CHAR_TYPE_SIZE)
2403 return check_ctz_string (ctor, val, zero_val, shiftval, input_bits);
2404
2405 return false;
2406 }
2407
2408 /* Match.pd function to match the ctz expression. */
2409 extern bool gimple_ctz_table_index (tree, tree *, tree (*)(tree));
2410
2411 static bool
2412 simplify_count_trailing_zeroes (gimple_stmt_iterator *gsi)
2413 {
2414 gimple *stmt = gsi_stmt (*gsi);
2415 tree array_ref = gimple_assign_rhs1 (stmt);
2416 tree res_ops[3];
2417 HOST_WIDE_INT zero_val;
2418
2419 gcc_checking_assert (TREE_CODE (array_ref) == ARRAY_REF);
2420
2421 if (!gimple_ctz_table_index (TREE_OPERAND (array_ref, 1), &res_ops[0], NULL))
2422 return false;
2423
2424 if (optimize_count_trailing_zeroes (array_ref, res_ops[0],
2425 res_ops[1], res_ops[2], zero_val))
2426 {
2427 tree type = TREE_TYPE (res_ops[0]);
2428 HOST_WIDE_INT ctz_val = 0;
2429 HOST_WIDE_INT type_size = tree_to_shwi (TYPE_SIZE (type));
2430 bool zero_ok
2431 = CTZ_DEFINED_VALUE_AT_ZERO (SCALAR_INT_TYPE_MODE (type), ctz_val) == 2;
2432 int nargs = 2;
2433
2434 /* If the input value can't be zero, don't special case ctz (0). */
2435 if (tree_expr_nonzero_p (res_ops[0]))
2436 {
2437 zero_ok = true;
2438 zero_val = 0;
2439 ctz_val = 0;
2440 nargs = 1;
2441 }
2442
2443 /* Skip if there is no value defined at zero, or if we can't easily
2444 return the correct value for zero. */
2445 if (!zero_ok)
2446 return false;
2447 if (zero_val != ctz_val && !(zero_val == 0 && ctz_val == type_size))
2448 return false;
2449
2450 gimple_seq seq = NULL;
2451 gimple *g;
2452 gcall *call
2453 = gimple_build_call_internal (IFN_CTZ, nargs, res_ops[0],
2454 nargs == 1 ? NULL_TREE
2455 : build_int_cst (integer_type_node,
2456 ctz_val));
2457 gimple_set_location (call, gimple_location (stmt));
2458 gimple_set_lhs (call, make_ssa_name (integer_type_node));
2459 gimple_seq_add_stmt (&seq, call);
2460
2461 tree prev_lhs = gimple_call_lhs (call);
2462
2463 /* Emit ctz (x) & 31 if ctz (0) is 32 but we need to return 0. */
2464 if (zero_val == 0 && ctz_val == type_size)
2465 {
2466 g = gimple_build_assign (make_ssa_name (integer_type_node),
2467 BIT_AND_EXPR, prev_lhs,
2468 build_int_cst (integer_type_node,
2469 type_size - 1));
2470 gimple_set_location (g, gimple_location (stmt));
2471 gimple_seq_add_stmt (&seq, g);
2472 prev_lhs = gimple_assign_lhs (g);
2473 }
2474
2475 g = gimple_build_assign (gimple_assign_lhs (stmt), NOP_EXPR, prev_lhs);
2476 gimple_seq_add_stmt (&seq, g);
2477 gsi_replace_with_seq (gsi, seq, true);
2478 return true;
2479 }
2480
2481 return false;
2482 }
2483
2484
2485 /* Determine whether applying the 2 permutations (mask1 then mask2)
2486 gives back one of the input. */
2487
2488 static int
2489 is_combined_permutation_identity (tree mask1, tree mask2)
2490 {
2491 tree mask;
2492 unsigned HOST_WIDE_INT nelts, i, j;
2493 bool maybe_identity1 = true;
2494 bool maybe_identity2 = true;
2495
2496 gcc_checking_assert (TREE_CODE (mask1) == VECTOR_CST
2497 && TREE_CODE (mask2) == VECTOR_CST);
2498
2499 /* For VLA masks, check for the following pattern:
2500 v1 = VEC_PERM_EXPR (v0, ..., mask1)
2501 v2 = VEC_PERM_EXPR (v1, ..., mask2)
2502 -->
2503 v2 = v0
2504 if mask1 == mask2 == {nelts - 1, nelts - 2, ...}. */
2505
2506 if (operand_equal_p (mask1, mask2, 0)
2507 && !VECTOR_CST_NELTS (mask1).is_constant ())
2508 {
2509 vec_perm_builder builder;
2510 if (tree_to_vec_perm_builder (&builder, mask1))
2511 {
2512 poly_uint64 nelts = TYPE_VECTOR_SUBPARTS (TREE_TYPE (mask1));
2513 vec_perm_indices sel (builder, 1, nelts);
2514 if (sel.series_p (0, 1, nelts - 1, -1))
2515 return 1;
2516 }
2517 }
2518
2519 mask = fold_ternary (VEC_PERM_EXPR, TREE_TYPE (mask1), mask1, mask1, mask2);
2520 if (mask == NULL_TREE || TREE_CODE (mask) != VECTOR_CST)
2521 return 0;
2522
2523 if (!VECTOR_CST_NELTS (mask).is_constant (&nelts))
2524 return 0;
2525 for (i = 0; i < nelts; i++)
2526 {
2527 tree val = VECTOR_CST_ELT (mask, i);
2528 gcc_assert (TREE_CODE (val) == INTEGER_CST);
2529 j = TREE_INT_CST_LOW (val) & (2 * nelts - 1);
2530 if (j == i)
2531 maybe_identity2 = false;
2532 else if (j == i + nelts)
2533 maybe_identity1 = false;
2534 else
2535 return 0;
2536 }
2537 return maybe_identity1 ? 1 : maybe_identity2 ? 2 : 0;
2538 }
2539
2540 /* Combine a shuffle with its arguments. Returns 1 if there were any
2541 changes made, 2 if cfg-cleanup needs to run. Else it returns 0. */
2542
2543 static int
2544 simplify_permutation (gimple_stmt_iterator *gsi)
2545 {
2546 gimple *stmt = gsi_stmt (*gsi);
2547 gimple *def_stmt = NULL;
2548 tree op0, op1, op2, op3, arg0, arg1;
2549 enum tree_code code, code2 = ERROR_MARK;
2550 bool single_use_op0 = false;
2551
2552 gcc_checking_assert (gimple_assign_rhs_code (stmt) == VEC_PERM_EXPR);
2553
2554 op0 = gimple_assign_rhs1 (stmt);
2555 op1 = gimple_assign_rhs2 (stmt);
2556 op2 = gimple_assign_rhs3 (stmt);
2557
2558 if (TREE_CODE (op2) != VECTOR_CST)
2559 return 0;
2560
2561 if (TREE_CODE (op0) == VECTOR_CST)
2562 {
2563 code = VECTOR_CST;
2564 arg0 = op0;
2565 }
2566 else if (TREE_CODE (op0) == SSA_NAME)
2567 {
2568 def_stmt = get_prop_source_stmt (op0, false, &single_use_op0);
2569 if (!def_stmt)
2570 return 0;
2571 code = gimple_assign_rhs_code (def_stmt);
2572 if (code == VIEW_CONVERT_EXPR)
2573 {
2574 tree rhs = gimple_assign_rhs1 (def_stmt);
2575 tree name = TREE_OPERAND (rhs, 0);
2576 if (TREE_CODE (name) != SSA_NAME)
2577 return 0;
2578 if (!has_single_use (name))
2579 single_use_op0 = false;
2580 /* Here we update the def_stmt through this VIEW_CONVERT_EXPR,
2581 but still keep the code to indicate it comes from
2582 VIEW_CONVERT_EXPR. */
2583 def_stmt = SSA_NAME_DEF_STMT (name);
2584 if (!def_stmt || !is_gimple_assign (def_stmt))
2585 return 0;
2586 if (gimple_assign_rhs_code (def_stmt) != CONSTRUCTOR)
2587 return 0;
2588 }
2589 if (!can_propagate_from (def_stmt))
2590 return 0;
2591 arg0 = gimple_assign_rhs1 (def_stmt);
2592 }
2593 else
2594 return 0;
2595
2596 /* Two consecutive shuffles. */
2597 if (code == VEC_PERM_EXPR)
2598 {
2599 tree orig;
2600 int ident;
2601
2602 if (op0 != op1)
2603 return 0;
2604 op3 = gimple_assign_rhs3 (def_stmt);
2605 if (TREE_CODE (op3) != VECTOR_CST)
2606 return 0;
2607 ident = is_combined_permutation_identity (op3, op2);
2608 if (!ident)
2609 return 0;
2610 orig = (ident == 1) ? gimple_assign_rhs1 (def_stmt)
2611 : gimple_assign_rhs2 (def_stmt);
2612 gimple_assign_set_rhs1 (stmt, unshare_expr (orig));
2613 gimple_assign_set_rhs_code (stmt, TREE_CODE (orig));
2614 gimple_set_num_ops (stmt, 2);
2615 update_stmt (stmt);
2616 return remove_prop_source_from_use (op0) ? 2 : 1;
2617 }
2618 else if (code == CONSTRUCTOR
2619 || code == VECTOR_CST
2620 || code == VIEW_CONVERT_EXPR)
2621 {
2622 if (op0 != op1)
2623 {
2624 if (TREE_CODE (op0) == SSA_NAME && !single_use_op0)
2625 return 0;
2626
2627 if (TREE_CODE (op1) == VECTOR_CST)
2628 arg1 = op1;
2629 else if (TREE_CODE (op1) == SSA_NAME)
2630 {
2631 gimple *def_stmt2 = get_prop_source_stmt (op1, true, NULL);
2632 if (!def_stmt2)
2633 return 0;
2634 code2 = gimple_assign_rhs_code (def_stmt2);
2635 if (code2 == VIEW_CONVERT_EXPR)
2636 {
2637 tree rhs = gimple_assign_rhs1 (def_stmt2);
2638 tree name = TREE_OPERAND (rhs, 0);
2639 if (TREE_CODE (name) != SSA_NAME)
2640 return 0;
2641 if (!has_single_use (name))
2642 return 0;
2643 def_stmt2 = SSA_NAME_DEF_STMT (name);
2644 if (!def_stmt2 || !is_gimple_assign (def_stmt2))
2645 return 0;
2646 if (gimple_assign_rhs_code (def_stmt2) != CONSTRUCTOR)
2647 return 0;
2648 }
2649 else if (code2 != CONSTRUCTOR && code2 != VECTOR_CST)
2650 return 0;
2651 if (!can_propagate_from (def_stmt2))
2652 return 0;
2653 arg1 = gimple_assign_rhs1 (def_stmt2);
2654 }
2655 else
2656 return 0;
2657 }
2658 else
2659 {
2660 /* Already used twice in this statement. */
2661 if (TREE_CODE (op0) == SSA_NAME && num_imm_uses (op0) > 2)
2662 return 0;
2663 arg1 = arg0;
2664 }
2665
2666 /* If there are any VIEW_CONVERT_EXPRs found when finding permutation
2667 operands source, check whether it's valid to transform and prepare
2668 the required new operands. */
2669 if (code == VIEW_CONVERT_EXPR || code2 == VIEW_CONVERT_EXPR)
2670 {
2671 /* Figure out the target vector type to which operands should be
2672 converted. If both are CONSTRUCTOR, the types should be the
2673 same, otherwise, use the one of CONSTRUCTOR. */
2674 tree tgt_type = NULL_TREE;
2675 if (code == VIEW_CONVERT_EXPR)
2676 {
2677 gcc_assert (gimple_assign_rhs_code (def_stmt) == CONSTRUCTOR);
2678 code = CONSTRUCTOR;
2679 tgt_type = TREE_TYPE (arg0);
2680 }
2681 if (code2 == VIEW_CONVERT_EXPR)
2682 {
2683 tree arg1_type = TREE_TYPE (arg1);
2684 if (tgt_type == NULL_TREE)
2685 tgt_type = arg1_type;
2686 else if (tgt_type != arg1_type)
2687 return 0;
2688 }
2689
2690 if (!VECTOR_TYPE_P (tgt_type))
2691 return 0;
2692 tree op2_type = TREE_TYPE (op2);
2693
2694 /* Figure out the shrunk factor. */
2695 poly_uint64 tgt_units = TYPE_VECTOR_SUBPARTS (tgt_type);
2696 poly_uint64 op2_units = TYPE_VECTOR_SUBPARTS (op2_type);
2697 if (maybe_gt (tgt_units, op2_units))
2698 return 0;
2699 unsigned int factor;
2700 if (!constant_multiple_p (op2_units, tgt_units, &factor))
2701 return 0;
2702
2703 /* Build the new permutation control vector as target vector. */
2704 vec_perm_builder builder;
2705 if (!tree_to_vec_perm_builder (&builder, op2))
2706 return 0;
2707 vec_perm_indices indices (builder, 2, op2_units);
2708 vec_perm_indices new_indices;
2709 if (new_indices.new_shrunk_vector (indices, factor))
2710 {
2711 tree mask_type = tgt_type;
2712 if (!VECTOR_INTEGER_TYPE_P (mask_type))
2713 {
2714 tree elem_type = TREE_TYPE (mask_type);
2715 unsigned elem_size = TREE_INT_CST_LOW (TYPE_SIZE (elem_type));
2716 tree int_type = build_nonstandard_integer_type (elem_size, 0);
2717 mask_type = build_vector_type (int_type, tgt_units);
2718 }
2719 op2 = vec_perm_indices_to_tree (mask_type, new_indices);
2720 }
2721 else
2722 return 0;
2723
2724 /* Convert the VECTOR_CST to the appropriate vector type. */
2725 if (tgt_type != TREE_TYPE (arg0))
2726 arg0 = fold_build1 (VIEW_CONVERT_EXPR, tgt_type, arg0);
2727 else if (tgt_type != TREE_TYPE (arg1))
2728 arg1 = fold_build1 (VIEW_CONVERT_EXPR, tgt_type, arg1);
2729 }
2730
2731 /* VIEW_CONVERT_EXPR should be updated to CONSTRUCTOR before. */
2732 gcc_assert (code == CONSTRUCTOR || code == VECTOR_CST);
2733
2734 /* Shuffle of a constructor. */
2735 bool ret = false;
2736 tree res_type
2737 = build_vector_type (TREE_TYPE (TREE_TYPE (arg0)),
2738 TYPE_VECTOR_SUBPARTS (TREE_TYPE (op2)));
2739 tree opt = fold_ternary (VEC_PERM_EXPR, res_type, arg0, arg1, op2);
2740 if (!opt
2741 || (TREE_CODE (opt) != CONSTRUCTOR && TREE_CODE (opt) != VECTOR_CST))
2742 return 0;
2743 /* Found VIEW_CONVERT_EXPR before, need one explicit conversion. */
2744 if (res_type != TREE_TYPE (op0))
2745 {
2746 tree name = make_ssa_name (TREE_TYPE (opt));
2747 gimple *ass_stmt = gimple_build_assign (name, opt);
2748 gsi_insert_before (gsi, ass_stmt, GSI_SAME_STMT);
2749 opt = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (op0), name);
2750 }
2751 gimple_assign_set_rhs_from_tree (gsi, opt);
2752 update_stmt (gsi_stmt (*gsi));
2753 if (TREE_CODE (op0) == SSA_NAME)
2754 ret = remove_prop_source_from_use (op0);
2755 if (op0 != op1 && TREE_CODE (op1) == SSA_NAME)
2756 ret |= remove_prop_source_from_use (op1);
2757 return ret ? 2 : 1;
2758 }
2759
2760 return 0;
2761 }
2762
2763 /* Get the BIT_FIELD_REF definition of VAL, if any, looking through
2764 conversions with code CONV_CODE or update it if still ERROR_MARK.
2765 Return NULL_TREE if no such matching def was found. */
2766
2767 static tree
2768 get_bit_field_ref_def (tree val, enum tree_code &conv_code)
2769 {
2770 if (TREE_CODE (val) != SSA_NAME)
2771 return NULL_TREE ;
2772 gimple *def_stmt = get_prop_source_stmt (val, false, NULL);
2773 if (!def_stmt)
2774 return NULL_TREE;
2775 enum tree_code code = gimple_assign_rhs_code (def_stmt);
2776 if (code == FLOAT_EXPR
2777 || code == FIX_TRUNC_EXPR
2778 || CONVERT_EXPR_CODE_P (code))
2779 {
2780 tree op1 = gimple_assign_rhs1 (def_stmt);
2781 if (conv_code == ERROR_MARK)
2782 conv_code = code;
2783 else if (conv_code != code)
2784 return NULL_TREE;
2785 if (TREE_CODE (op1) != SSA_NAME)
2786 return NULL_TREE;
2787 def_stmt = SSA_NAME_DEF_STMT (op1);
2788 if (! is_gimple_assign (def_stmt))
2789 return NULL_TREE;
2790 code = gimple_assign_rhs_code (def_stmt);
2791 }
2792 if (code != BIT_FIELD_REF)
2793 return NULL_TREE;
2794 return gimple_assign_rhs1 (def_stmt);
2795 }
2796
2797 /* Recognize a VEC_PERM_EXPR. Returns true if there were any changes. */
2798
2799 static bool
2800 simplify_vector_constructor (gimple_stmt_iterator *gsi)
2801 {
2802 gimple *stmt = gsi_stmt (*gsi);
2803 tree op, orig[2], type, elem_type;
2804 unsigned elem_size, i;
2805 unsigned HOST_WIDE_INT nelts;
2806 unsigned HOST_WIDE_INT refnelts;
2807 enum tree_code conv_code;
2808 constructor_elt *elt;
2809
2810 op = gimple_assign_rhs1 (stmt);
2811 type = TREE_TYPE (op);
2812 gcc_checking_assert (TREE_CODE (op) == CONSTRUCTOR
2813 && TREE_CODE (type) == VECTOR_TYPE);
2814
2815 if (!TYPE_VECTOR_SUBPARTS (type).is_constant (&nelts))
2816 return false;
2817 elem_type = TREE_TYPE (type);
2818 elem_size = TREE_INT_CST_LOW (TYPE_SIZE (elem_type));
2819
2820 orig[0] = NULL;
2821 orig[1] = NULL;
2822 conv_code = ERROR_MARK;
2823 bool maybe_ident = true;
2824 bool maybe_blend[2] = { true, true };
2825 tree one_constant = NULL_TREE;
2826 tree one_nonconstant = NULL_TREE;
2827 auto_vec<tree> constants;
2828 constants.safe_grow_cleared (nelts, true);
2829 auto_vec<std::pair<unsigned, unsigned>, 64> elts;
2830 FOR_EACH_VEC_SAFE_ELT (CONSTRUCTOR_ELTS (op), i, elt)
2831 {
2832 tree ref, op1;
2833 unsigned int elem;
2834
2835 if (i >= nelts)
2836 return false;
2837
2838 /* Look for elements extracted and possibly converted from
2839 another vector. */
2840 op1 = get_bit_field_ref_def (elt->value, conv_code);
2841 if (op1
2842 && TREE_CODE ((ref = TREE_OPERAND (op1, 0))) == SSA_NAME
2843 && VECTOR_TYPE_P (TREE_TYPE (ref))
2844 && useless_type_conversion_p (TREE_TYPE (op1),
2845 TREE_TYPE (TREE_TYPE (ref)))
2846 && constant_multiple_p (bit_field_offset (op1),
2847 bit_field_size (op1), &elem)
2848 && TYPE_VECTOR_SUBPARTS (TREE_TYPE (ref)).is_constant (&refnelts))
2849 {
2850 unsigned int j;
2851 for (j = 0; j < 2; ++j)
2852 {
2853 if (!orig[j])
2854 {
2855 if (j == 0
2856 || useless_type_conversion_p (TREE_TYPE (orig[0]),
2857 TREE_TYPE (ref)))
2858 break;
2859 }
2860 else if (ref == orig[j])
2861 break;
2862 }
2863 /* Found a suitable vector element. */
2864 if (j < 2)
2865 {
2866 orig[j] = ref;
2867 if (elem != i || j != 0)
2868 maybe_ident = false;
2869 if (elem != i)
2870 maybe_blend[j] = false;
2871 elts.safe_push (std::make_pair (j, elem));
2872 continue;
2873 }
2874 /* Else fallthru. */
2875 }
2876 /* Handle elements not extracted from a vector.
2877 1. constants by permuting with constant vector
2878 2. a unique non-constant element by permuting with a splat vector */
2879 if (orig[1]
2880 && orig[1] != error_mark_node)
2881 return false;
2882 orig[1] = error_mark_node;
2883 if (CONSTANT_CLASS_P (elt->value))
2884 {
2885 if (one_nonconstant)
2886 return false;
2887 if (!one_constant)
2888 one_constant = elt->value;
2889 constants[i] = elt->value;
2890 }
2891 else
2892 {
2893 if (one_constant)
2894 return false;
2895 if (!one_nonconstant)
2896 one_nonconstant = elt->value;
2897 else if (!operand_equal_p (one_nonconstant, elt->value, 0))
2898 return false;
2899 }
2900 elts.safe_push (std::make_pair (1, i));
2901 maybe_ident = false;
2902 }
2903 if (i < nelts)
2904 return false;
2905
2906 if (! orig[0]
2907 || ! VECTOR_TYPE_P (TREE_TYPE (orig[0])))
2908 return false;
2909 refnelts = TYPE_VECTOR_SUBPARTS (TREE_TYPE (orig[0])).to_constant ();
2910 /* We currently do not handle larger destination vectors. */
2911 if (refnelts < nelts)
2912 return false;
2913
2914 if (maybe_ident)
2915 {
2916 tree conv_src_type
2917 = (nelts != refnelts
2918 ? (conv_code != ERROR_MARK
2919 ? build_vector_type (TREE_TYPE (TREE_TYPE (orig[0])), nelts)
2920 : type)
2921 : TREE_TYPE (orig[0]));
2922 if (conv_code != ERROR_MARK
2923 && !supportable_convert_operation (conv_code, type, conv_src_type,
2924 &conv_code))
2925 {
2926 /* Only few targets implement direct conversion patterns so try
2927 some simple special cases via VEC_[UN]PACK[_FLOAT]_LO_EXPR. */
2928 optab optab;
2929 insn_code icode;
2930 tree halfvectype, dblvectype;
2931 enum tree_code unpack_op;
2932
2933 if (!BYTES_BIG_ENDIAN)
2934 unpack_op = (FLOAT_TYPE_P (TREE_TYPE (type))
2935 ? VEC_UNPACK_FLOAT_LO_EXPR
2936 : VEC_UNPACK_LO_EXPR);
2937 else
2938 unpack_op = (FLOAT_TYPE_P (TREE_TYPE (type))
2939 ? VEC_UNPACK_FLOAT_HI_EXPR
2940 : VEC_UNPACK_HI_EXPR);
2941
2942 /* Conversions between DFP and FP have no special tree code
2943 but we cannot handle those since all relevant vector conversion
2944 optabs only have a single mode. */
2945 if (CONVERT_EXPR_CODE_P (conv_code)
2946 && FLOAT_TYPE_P (TREE_TYPE (type))
2947 && (DECIMAL_FLOAT_TYPE_P (TREE_TYPE (type))
2948 != DECIMAL_FLOAT_TYPE_P (TREE_TYPE (conv_src_type))))
2949 return false;
2950
2951 if (CONVERT_EXPR_CODE_P (conv_code)
2952 && (2 * TYPE_PRECISION (TREE_TYPE (TREE_TYPE (orig[0])))
2953 == TYPE_PRECISION (TREE_TYPE (type)))
2954 && mode_for_vector (as_a <scalar_mode>
2955 (TYPE_MODE (TREE_TYPE (TREE_TYPE (orig[0])))),
2956 nelts * 2).exists ()
2957 && (dblvectype
2958 = build_vector_type (TREE_TYPE (TREE_TYPE (orig[0])),
2959 nelts * 2))
2960 /* Only use it for vector modes or for vector booleans
2961 represented as scalar bitmasks. See PR95528. */
2962 && (VECTOR_MODE_P (TYPE_MODE (dblvectype))
2963 || VECTOR_BOOLEAN_TYPE_P (dblvectype))
2964 && (optab = optab_for_tree_code (unpack_op,
2965 dblvectype,
2966 optab_default))
2967 && ((icode = optab_handler (optab, TYPE_MODE (dblvectype)))
2968 != CODE_FOR_nothing)
2969 && (insn_data[icode].operand[0].mode == TYPE_MODE (type)))
2970 {
2971 gimple_seq stmts = NULL;
2972 tree dbl;
2973 if (refnelts == nelts)
2974 {
2975 /* ??? Paradoxical subregs don't exist, so insert into
2976 the lower half of a wider zero vector. */
2977 dbl = gimple_build (&stmts, BIT_INSERT_EXPR, dblvectype,
2978 build_zero_cst (dblvectype), orig[0],
2979 bitsize_zero_node);
2980 }
2981 else if (refnelts == 2 * nelts)
2982 dbl = orig[0];
2983 else
2984 dbl = gimple_build (&stmts, BIT_FIELD_REF, dblvectype,
2985 orig[0], TYPE_SIZE (dblvectype),
2986 bitsize_zero_node);
2987 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
2988 gimple_assign_set_rhs_with_ops (gsi, unpack_op, dbl);
2989 }
2990 else if (CONVERT_EXPR_CODE_P (conv_code)
2991 && (TYPE_PRECISION (TREE_TYPE (TREE_TYPE (orig[0])))
2992 == 2 * TYPE_PRECISION (TREE_TYPE (type)))
2993 && mode_for_vector (as_a <scalar_mode>
2994 (TYPE_MODE
2995 (TREE_TYPE (TREE_TYPE (orig[0])))),
2996 nelts / 2).exists ()
2997 && (halfvectype
2998 = build_vector_type (TREE_TYPE (TREE_TYPE (orig[0])),
2999 nelts / 2))
3000 /* Only use it for vector modes or for vector booleans
3001 represented as scalar bitmasks. See PR95528. */
3002 && (VECTOR_MODE_P (TYPE_MODE (halfvectype))
3003 || VECTOR_BOOLEAN_TYPE_P (halfvectype))
3004 && (optab = optab_for_tree_code (VEC_PACK_TRUNC_EXPR,
3005 halfvectype,
3006 optab_default))
3007 && ((icode = optab_handler (optab, TYPE_MODE (halfvectype)))
3008 != CODE_FOR_nothing)
3009 && (insn_data[icode].operand[0].mode == TYPE_MODE (type)))
3010 {
3011 gimple_seq stmts = NULL;
3012 tree low = gimple_build (&stmts, BIT_FIELD_REF, halfvectype,
3013 orig[0], TYPE_SIZE (halfvectype),
3014 bitsize_zero_node);
3015 tree hig = gimple_build (&stmts, BIT_FIELD_REF, halfvectype,
3016 orig[0], TYPE_SIZE (halfvectype),
3017 TYPE_SIZE (halfvectype));
3018 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
3019 gimple_assign_set_rhs_with_ops (gsi, VEC_PACK_TRUNC_EXPR,
3020 low, hig);
3021 }
3022 else
3023 return false;
3024 update_stmt (gsi_stmt (*gsi));
3025 return true;
3026 }
3027 if (nelts != refnelts)
3028 {
3029 gassign *lowpart
3030 = gimple_build_assign (make_ssa_name (conv_src_type),
3031 build3 (BIT_FIELD_REF, conv_src_type,
3032 orig[0], TYPE_SIZE (conv_src_type),
3033 bitsize_zero_node));
3034 gsi_insert_before (gsi, lowpart, GSI_SAME_STMT);
3035 orig[0] = gimple_assign_lhs (lowpart);
3036 }
3037 if (conv_code == ERROR_MARK)
3038 {
3039 tree src_type = TREE_TYPE (orig[0]);
3040 if (!useless_type_conversion_p (type, src_type))
3041 {
3042 gcc_assert (known_eq (TYPE_VECTOR_SUBPARTS (type),
3043 TYPE_VECTOR_SUBPARTS (src_type))
3044 && useless_type_conversion_p (TREE_TYPE (type),
3045 TREE_TYPE (src_type)));
3046 tree rhs = build1 (VIEW_CONVERT_EXPR, type, orig[0]);
3047 orig[0] = make_ssa_name (type);
3048 gassign *assign = gimple_build_assign (orig[0], rhs);
3049 gsi_insert_before (gsi, assign, GSI_SAME_STMT);
3050 }
3051 gimple_assign_set_rhs_from_tree (gsi, orig[0]);
3052 }
3053 else
3054 gimple_assign_set_rhs_with_ops (gsi, conv_code, orig[0],
3055 NULL_TREE, NULL_TREE);
3056 }
3057 else
3058 {
3059 /* If we combine a vector with a non-vector avoid cases where
3060 we'll obviously end up with more GIMPLE stmts which is when
3061 we'll later not fold this to a single insert into the vector
3062 and we had a single extract originally. See PR92819. */
3063 if (nelts == 2
3064 && refnelts > 2
3065 && orig[1] == error_mark_node
3066 && !maybe_blend[0])
3067 return false;
3068 tree mask_type, perm_type, conv_src_type;
3069 perm_type = TREE_TYPE (orig[0]);
3070 conv_src_type = (nelts == refnelts
3071 ? perm_type
3072 : build_vector_type (TREE_TYPE (perm_type), nelts));
3073 if (conv_code != ERROR_MARK
3074 && !supportable_convert_operation (conv_code, type, conv_src_type,
3075 &conv_code))
3076 return false;
3077
3078 /* Now that we know the number of elements of the source build the
3079 permute vector.
3080 ??? When the second vector has constant values we can shuffle
3081 it and its source indexes to make the permutation supported.
3082 For now it mimics a blend. */
3083 vec_perm_builder sel (refnelts, refnelts, 1);
3084 bool all_same_p = true;
3085 for (i = 0; i < elts.length (); ++i)
3086 {
3087 sel.quick_push (elts[i].second + elts[i].first * refnelts);
3088 all_same_p &= known_eq (sel[i], sel[0]);
3089 }
3090 /* And fill the tail with "something". It's really don't care,
3091 and ideally we'd allow VEC_PERM to have a smaller destination
3092 vector. As a heuristic:
3093
3094 (a) if what we have so far duplicates a single element, make the
3095 tail do the same
3096
3097 (b) otherwise preserve a uniform orig[0]. This facilitates
3098 later pattern-matching of VEC_PERM_EXPR to a BIT_INSERT_EXPR. */
3099 for (; i < refnelts; ++i)
3100 sel.quick_push (all_same_p
3101 ? sel[0]
3102 : (elts[0].second == 0 && elts[0].first == 0
3103 ? 0 : refnelts) + i);
3104 vec_perm_indices indices (sel, orig[1] ? 2 : 1, refnelts);
3105 machine_mode vmode = TYPE_MODE (perm_type);
3106 if (!can_vec_perm_const_p (vmode, vmode, indices))
3107 return false;
3108 mask_type
3109 = build_vector_type (build_nonstandard_integer_type (elem_size, 1),
3110 refnelts);
3111 if (GET_MODE_CLASS (TYPE_MODE (mask_type)) != MODE_VECTOR_INT
3112 || maybe_ne (GET_MODE_SIZE (TYPE_MODE (mask_type)),
3113 GET_MODE_SIZE (TYPE_MODE (perm_type))))
3114 return false;
3115 tree op2 = vec_perm_indices_to_tree (mask_type, indices);
3116 bool converted_orig1 = false;
3117 gimple_seq stmts = NULL;
3118 if (!orig[1])
3119 orig[1] = orig[0];
3120 else if (orig[1] == error_mark_node
3121 && one_nonconstant)
3122 {
3123 /* ??? We can see if we can safely convert to the original
3124 element type. */
3125 converted_orig1 = conv_code != ERROR_MARK;
3126 orig[1] = gimple_build_vector_from_val (&stmts, UNKNOWN_LOCATION,
3127 converted_orig1
3128 ? type : perm_type,
3129 one_nonconstant);
3130 }
3131 else if (orig[1] == error_mark_node)
3132 {
3133 /* ??? See if we can convert the vector to the original type. */
3134 converted_orig1 = conv_code != ERROR_MARK;
3135 unsigned n = converted_orig1 ? nelts : refnelts;
3136 tree_vector_builder vec (converted_orig1
3137 ? type : perm_type, n, 1);
3138 for (unsigned i = 0; i < n; ++i)
3139 if (i < nelts && constants[i])
3140 vec.quick_push (constants[i]);
3141 else
3142 /* ??? Push a don't-care value. */
3143 vec.quick_push (one_constant);
3144 orig[1] = vec.build ();
3145 }
3146 tree blend_op2 = NULL_TREE;
3147 if (converted_orig1)
3148 {
3149 /* Make sure we can do a blend in the target type. */
3150 vec_perm_builder sel (nelts, nelts, 1);
3151 for (i = 0; i < elts.length (); ++i)
3152 sel.quick_push (elts[i].first
3153 ? elts[i].second + nelts : i);
3154 vec_perm_indices indices (sel, 2, nelts);
3155 machine_mode vmode = TYPE_MODE (type);
3156 if (!can_vec_perm_const_p (vmode, vmode, indices))
3157 return false;
3158 mask_type
3159 = build_vector_type (build_nonstandard_integer_type (elem_size, 1),
3160 nelts);
3161 if (GET_MODE_CLASS (TYPE_MODE (mask_type)) != MODE_VECTOR_INT
3162 || maybe_ne (GET_MODE_SIZE (TYPE_MODE (mask_type)),
3163 GET_MODE_SIZE (TYPE_MODE (type))))
3164 return false;
3165 blend_op2 = vec_perm_indices_to_tree (mask_type, indices);
3166 }
3167 tree orig1_for_perm
3168 = converted_orig1 ? build_zero_cst (perm_type) : orig[1];
3169 tree res = gimple_build (&stmts, VEC_PERM_EXPR, perm_type,
3170 orig[0], orig1_for_perm, op2);
3171 if (nelts != refnelts)
3172 res = gimple_build (&stmts, BIT_FIELD_REF,
3173 conv_code != ERROR_MARK ? conv_src_type : type,
3174 res, TYPE_SIZE (type), bitsize_zero_node);
3175 if (conv_code != ERROR_MARK)
3176 res = gimple_build (&stmts, conv_code, type, res);
3177 else if (!useless_type_conversion_p (type, TREE_TYPE (res)))
3178 {
3179 gcc_assert (known_eq (TYPE_VECTOR_SUBPARTS (type),
3180 TYPE_VECTOR_SUBPARTS (perm_type))
3181 && useless_type_conversion_p (TREE_TYPE (type),
3182 TREE_TYPE (perm_type)));
3183 res = gimple_build (&stmts, VIEW_CONVERT_EXPR, type, res);
3184 }
3185 /* Blend in the actual constant. */
3186 if (converted_orig1)
3187 res = gimple_build (&stmts, VEC_PERM_EXPR, type,
3188 res, orig[1], blend_op2);
3189 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
3190 gimple_assign_set_rhs_with_ops (gsi, SSA_NAME, res);
3191 }
3192 update_stmt (gsi_stmt (*gsi));
3193 return true;
3194 }
3195
3196 /* Prepare a TARGET_MEM_REF ref so that it can be subsetted as
3197 lvalue. This splits out an address computation stmt before *GSI
3198 and returns a MEM_REF wrapping the address. */
3199
3200 static tree
3201 prepare_target_mem_ref_lvalue (tree ref, gimple_stmt_iterator *gsi)
3202 {
3203 if (TREE_CODE (TREE_OPERAND (ref, 0)) == ADDR_EXPR)
3204 mark_addressable (TREE_OPERAND (TREE_OPERAND (ref, 0), 0));
3205 tree ptrtype = build_pointer_type (TREE_TYPE (ref));
3206 tree tem = make_ssa_name (ptrtype);
3207 gimple *new_stmt
3208 = gimple_build_assign (tem, build1 (ADDR_EXPR, TREE_TYPE (tem),
3209 unshare_expr (ref)));
3210 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
3211 ref = build2_loc (EXPR_LOCATION (ref),
3212 MEM_REF, TREE_TYPE (ref), tem,
3213 build_int_cst (TREE_TYPE (TREE_OPERAND (ref, 1)), 0));
3214 return ref;
3215 }
3216
3217 /* Rewrite the vector load at *GSI to component-wise loads if the load
3218 is only used in BIT_FIELD_REF extractions with eventual intermediate
3219 widening. */
3220
3221 static void
3222 optimize_vector_load (gimple_stmt_iterator *gsi)
3223 {
3224 gimple *stmt = gsi_stmt (*gsi);
3225 tree lhs = gimple_assign_lhs (stmt);
3226 tree rhs = gimple_assign_rhs1 (stmt);
3227
3228 /* Gather BIT_FIELD_REFs to rewrite, looking through
3229 VEC_UNPACK_{LO,HI}_EXPR. */
3230 use_operand_p use_p;
3231 imm_use_iterator iter;
3232 bool rewrite = true;
3233 auto_vec<gimple *, 8> bf_stmts;
3234 auto_vec<tree, 8> worklist;
3235 worklist.quick_push (lhs);
3236 do
3237 {
3238 tree def = worklist.pop ();
3239 unsigned HOST_WIDE_INT def_eltsize
3240 = TREE_INT_CST_LOW (TYPE_SIZE (TREE_TYPE (TREE_TYPE (def))));
3241 FOR_EACH_IMM_USE_FAST (use_p, iter, def)
3242 {
3243 gimple *use_stmt = USE_STMT (use_p);
3244 if (is_gimple_debug (use_stmt))
3245 continue;
3246 if (!is_gimple_assign (use_stmt))
3247 {
3248 rewrite = false;
3249 break;
3250 }
3251 enum tree_code use_code = gimple_assign_rhs_code (use_stmt);
3252 tree use_rhs = gimple_assign_rhs1 (use_stmt);
3253 if (use_code == BIT_FIELD_REF
3254 && TREE_OPERAND (use_rhs, 0) == def
3255 /* If its on the VEC_UNPACK_{HI,LO}_EXPR
3256 def need to verify it is element aligned. */
3257 && (def == lhs
3258 || (known_eq (bit_field_size (use_rhs), def_eltsize)
3259 && constant_multiple_p (bit_field_offset (use_rhs),
3260 def_eltsize)
3261 /* We can simulate the VEC_UNPACK_{HI,LO}_EXPR
3262 via a NOP_EXPR only for integral types.
3263 ??? Support VEC_UNPACK_FLOAT_{HI,LO}_EXPR. */
3264 && INTEGRAL_TYPE_P (TREE_TYPE (use_rhs)))))
3265 {
3266 bf_stmts.safe_push (use_stmt);
3267 continue;
3268 }
3269 /* Walk through one level of VEC_UNPACK_{LO,HI}_EXPR. */
3270 if (def == lhs
3271 && (use_code == VEC_UNPACK_HI_EXPR
3272 || use_code == VEC_UNPACK_LO_EXPR)
3273 && use_rhs == lhs)
3274 {
3275 worklist.safe_push (gimple_assign_lhs (use_stmt));
3276 continue;
3277 }
3278 rewrite = false;
3279 break;
3280 }
3281 if (!rewrite)
3282 break;
3283 }
3284 while (!worklist.is_empty ());
3285
3286 if (!rewrite)
3287 {
3288 gsi_next (gsi);
3289 return;
3290 }
3291 /* We now have all ultimate uses of the load to rewrite in bf_stmts. */
3292
3293 /* Prepare the original ref to be wrapped in adjusted BIT_FIELD_REFs.
3294 For TARGET_MEM_REFs we have to separate the LEA from the reference. */
3295 tree load_rhs = rhs;
3296 if (TREE_CODE (load_rhs) == TARGET_MEM_REF)
3297 load_rhs = prepare_target_mem_ref_lvalue (load_rhs, gsi);
3298
3299 /* Rewrite the BIT_FIELD_REFs to be actual loads, re-emitting them at
3300 the place of the original load. */
3301 for (gimple *use_stmt : bf_stmts)
3302 {
3303 tree bfr = gimple_assign_rhs1 (use_stmt);
3304 tree new_rhs = unshare_expr (load_rhs);
3305 if (TREE_OPERAND (bfr, 0) != lhs)
3306 {
3307 /* When the BIT_FIELD_REF is on the promoted vector we have to
3308 adjust it and emit a conversion afterwards. */
3309 gimple *def_stmt
3310 = SSA_NAME_DEF_STMT (TREE_OPERAND (bfr, 0));
3311 enum tree_code def_code
3312 = gimple_assign_rhs_code (def_stmt);
3313
3314 /* The adjusted BIT_FIELD_REF is of the promotion source
3315 vector size and at half of the offset... */
3316 new_rhs = fold_build3 (BIT_FIELD_REF,
3317 TREE_TYPE (TREE_TYPE (lhs)),
3318 new_rhs,
3319 TYPE_SIZE (TREE_TYPE (TREE_TYPE (lhs))),
3320 size_binop (EXACT_DIV_EXPR,
3321 TREE_OPERAND (bfr, 2),
3322 bitsize_int (2)));
3323 /* ... and offsetted by half of the vector if VEC_UNPACK_HI_EXPR. */
3324 if (def_code == (!BYTES_BIG_ENDIAN
3325 ? VEC_UNPACK_HI_EXPR : VEC_UNPACK_LO_EXPR))
3326 TREE_OPERAND (new_rhs, 2)
3327 = size_binop (PLUS_EXPR, TREE_OPERAND (new_rhs, 2),
3328 size_binop (EXACT_DIV_EXPR,
3329 TYPE_SIZE (TREE_TYPE (lhs)),
3330 bitsize_int (2)));
3331 tree tem = make_ssa_name (TREE_TYPE (TREE_TYPE (lhs)));
3332 gimple *new_stmt = gimple_build_assign (tem, new_rhs);
3333 location_t loc = gimple_location (use_stmt);
3334 gimple_set_location (new_stmt, loc);
3335 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
3336 /* Perform scalar promotion. */
3337 new_stmt = gimple_build_assign (gimple_assign_lhs (use_stmt),
3338 NOP_EXPR, tem);
3339 gimple_set_location (new_stmt, loc);
3340 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
3341 }
3342 else
3343 {
3344 /* When the BIT_FIELD_REF is on the original load result
3345 we can just wrap that. */
3346 tree new_rhs = fold_build3 (BIT_FIELD_REF, TREE_TYPE (bfr),
3347 unshare_expr (load_rhs),
3348 TREE_OPERAND (bfr, 1),
3349 TREE_OPERAND (bfr, 2));
3350 gimple *new_stmt = gimple_build_assign (gimple_assign_lhs (use_stmt),
3351 new_rhs);
3352 location_t loc = gimple_location (use_stmt);
3353 gimple_set_location (new_stmt, loc);
3354 gsi_insert_before (gsi, new_stmt, GSI_SAME_STMT);
3355 }
3356 gimple_stmt_iterator gsi2 = gsi_for_stmt (use_stmt);
3357 unlink_stmt_vdef (use_stmt);
3358 gsi_remove (&gsi2, true);
3359 }
3360
3361 /* Finally get rid of the intermediate stmts. */
3362 gimple *use_stmt;
3363 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
3364 {
3365 if (is_gimple_debug (use_stmt))
3366 {
3367 if (gimple_debug_bind_p (use_stmt))
3368 {
3369 gimple_debug_bind_reset_value (use_stmt);
3370 update_stmt (use_stmt);
3371 }
3372 continue;
3373 }
3374 gimple_stmt_iterator gsi2 = gsi_for_stmt (use_stmt);
3375 unlink_stmt_vdef (use_stmt);
3376 release_defs (use_stmt);
3377 gsi_remove (&gsi2, true);
3378 }
3379 /* And the original load. */
3380 release_defs (stmt);
3381 gsi_remove (gsi, true);
3382 }
3383
3384
3385 /* Primitive "lattice" function for gimple_simplify. */
3386
3387 static tree
3388 fwprop_ssa_val (tree name)
3389 {
3390 /* First valueize NAME. */
3391 if (TREE_CODE (name) == SSA_NAME
3392 && SSA_NAME_VERSION (name) < lattice.length ())
3393 {
3394 tree val = lattice[SSA_NAME_VERSION (name)];
3395 if (val)
3396 name = val;
3397 }
3398 /* We continue matching along SSA use-def edges for SSA names
3399 that are not single-use. Currently there are no patterns
3400 that would cause any issues with that. */
3401 return name;
3402 }
3403
3404 /* Search for opportunities to free half of the lanes in the following pattern:
3405
3406 v_in = {e0, e1, e2, e3}
3407 v_1 = VEC_PERM <v_in, v_in, {0, 2, 0, 2}>
3408 // v_1 = {e0, e2, e0, e2}
3409 v_2 = VEC_PERM <v_in, v_in, {1, 3, 1, 3}>
3410 // v_2 = {e1, e3, e1, e3}
3411
3412 v_x = v_1 + v_2
3413 // v_x = {e0+e1, e2+e3, e0+e1, e2+e3}
3414 v_y = v_1 - v_2
3415 // v_y = {e0-e1, e2-e3, e0-e1, e2-e3}
3416
3417 v_out = VEC_PERM <v_x, v_y, {0, 1, 6, 7}>
3418 // v_out = {e0+e1, e2+e3, e0-e1, e2-e3}
3419
3420 The last statement could be simplified to:
3421 v_out' = VEC_PERM <v_x, v_y, {0, 1, 4, 5}>
3422 // v_out' = {e0+e1, e2+e3, e0-e1, e2-e3}
3423
3424 Characteristic properties:
3425 - v_1 and v_2 are created from the same input vector v_in and introduce the
3426 lane duplication (in the selection operand) that we can eliminate.
3427 - v_x and v_y are results from lane-preserving operations that use v_1 and
3428 v_2 as inputs.
3429 - v_out is created by selecting from duplicated lanes. */
3430
3431 static bool
3432 recognise_vec_perm_simplify_seq (gassign *stmt, vec_perm_simplify_seq *seq)
3433 {
3434 unsigned HOST_WIDE_INT nelts;
3435
3436 gcc_checking_assert (stmt);
3437 gcc_checking_assert (gimple_assign_rhs_code (stmt) == VEC_PERM_EXPR);
3438 basic_block bb = gimple_bb (stmt);
3439
3440 /* Decompose the final vec permute statement. */
3441 tree v_x = gimple_assign_rhs1 (stmt);
3442 tree v_y = gimple_assign_rhs2 (stmt);
3443 tree sel = gimple_assign_rhs3 (stmt);
3444
3445 if (TREE_CODE (sel) != VECTOR_CST
3446 || !VECTOR_CST_NELTS (sel).is_constant (&nelts)
3447 || TREE_CODE (v_x) != SSA_NAME
3448 || TREE_CODE (v_y) != SSA_NAME
3449 || !has_single_use (v_x)
3450 || !has_single_use (v_y))
3451 return false;
3452
3453 /* Don't analyse sequences with many lanes. */
3454 if (nelts > 4)
3455 return false;
3456
3457 /* Lookup the definition of v_x and v_y. */
3458 gassign *v_x_stmt = dyn_cast<gassign *> (SSA_NAME_DEF_STMT (v_x));
3459 gassign *v_y_stmt = dyn_cast<gassign *> (SSA_NAME_DEF_STMT (v_y));
3460 if (!v_x_stmt || gimple_bb (v_x_stmt) != bb
3461 || !v_y_stmt || gimple_bb (v_y_stmt) != bb)
3462 return false;
3463
3464 /* Check the operations that define v_x and v_y. */
3465 if (TREE_CODE_CLASS (gimple_assign_rhs_code (v_x_stmt)) != tcc_binary
3466 || TREE_CODE_CLASS (gimple_assign_rhs_code (v_y_stmt)) != tcc_binary)
3467 return false;
3468
3469 tree v_x_1 = gimple_assign_rhs1 (v_x_stmt);
3470 tree v_x_2 = gimple_assign_rhs2 (v_x_stmt);
3471 tree v_y_1 = gimple_assign_rhs1 (v_y_stmt);
3472 tree v_y_2 = gimple_assign_rhs2 (v_y_stmt);
3473
3474 if (v_x_stmt == v_y_stmt
3475 || TREE_CODE (v_x_1) != SSA_NAME
3476 || TREE_CODE (v_x_2) != SSA_NAME
3477 || num_imm_uses (v_x_1) != 2
3478 || num_imm_uses (v_x_2) != 2)
3479 return false;
3480
3481 if (v_x_1 != v_y_1 || v_x_2 != v_y_2)
3482 {
3483 /* Allow operands of commutative operators to swap. */
3484 if (commutative_tree_code (gimple_assign_rhs_code (v_x_stmt)))
3485 {
3486 /* Keep v_x_1 the first operand for non-commutative operators. */
3487 std::swap (v_x_1, v_x_2);
3488 if (v_x_1 != v_y_1 || v_x_2 != v_y_2)
3489 return false;
3490 }
3491 else if (commutative_tree_code (gimple_assign_rhs_code (v_y_stmt)))
3492 {
3493 if (v_x_1 != v_y_2 || v_x_2 != v_y_1)
3494 return false;
3495 }
3496 else
3497 return false;
3498 }
3499 gassign *v_1_stmt = dyn_cast<gassign *> (SSA_NAME_DEF_STMT (v_x_1));
3500 gassign *v_2_stmt = dyn_cast<gassign *> (SSA_NAME_DEF_STMT (v_x_2));
3501 if (!v_1_stmt || gimple_bb (v_1_stmt) != bb
3502 || !v_2_stmt || gimple_bb (v_2_stmt) != bb)
3503 return false;
3504
3505 if (gimple_assign_rhs_code (v_1_stmt) != VEC_PERM_EXPR
3506 || gimple_assign_rhs_code (v_2_stmt) != VEC_PERM_EXPR)
3507 return false;
3508
3509 /* Decompose initial VEC_PERM_EXPRs. */
3510 tree v_in = gimple_assign_rhs1 (v_1_stmt);
3511 tree v_1_sel = gimple_assign_rhs3 (v_1_stmt);
3512 tree v_2_sel = gimple_assign_rhs3 (v_2_stmt);
3513 if (v_in != gimple_assign_rhs2 (v_1_stmt)
3514 || v_in != gimple_assign_rhs1 (v_2_stmt)
3515 || v_in != gimple_assign_rhs2 (v_2_stmt))
3516 return false;
3517
3518 unsigned HOST_WIDE_INT v_1_nelts, v_2_nelts;
3519 if (TREE_CODE (v_1_sel) != VECTOR_CST
3520 || !VECTOR_CST_NELTS (v_1_sel).is_constant (&v_1_nelts)
3521 || TREE_CODE (v_2_sel) != VECTOR_CST
3522 || !VECTOR_CST_NELTS (v_2_sel).is_constant (&v_2_nelts))
3523 return false;
3524
3525 if (nelts != v_1_nelts || nelts != v_2_nelts)
3526 return false;
3527
3528 /* Create the new selector. */
3529 vec_perm_builder new_sel_perm (nelts, nelts, 1);
3530 auto_vec<bool> lanes (nelts);
3531 lanes.quick_grow_cleared (nelts);
3532 for (unsigned int i = 0; i < nelts; i++)
3533 {
3534 /* Extract the i-th value from the selector. */
3535 unsigned int sel_cst = TREE_INT_CST_LOW (VECTOR_CST_ELT (sel, i));
3536 unsigned int lane = sel_cst % nelts;
3537 unsigned int offs = sel_cst / nelts;
3538
3539 /* Check what's in the lane. */
3540 unsigned int e_1 = TREE_INT_CST_LOW (VECTOR_CST_ELT (v_1_sel, lane));
3541 unsigned int e_2 = TREE_INT_CST_LOW (VECTOR_CST_ELT (v_2_sel, lane));
3542
3543 /* Reuse previous lane (if any). */
3544 unsigned int l = 0;
3545 for (; l < lane; l++)
3546 {
3547 if ((TREE_INT_CST_LOW (VECTOR_CST_ELT (v_1_sel, l)) == e_1)
3548 && (TREE_INT_CST_LOW (VECTOR_CST_ELT (v_2_sel, l)) == e_2))
3549 break;
3550 }
3551
3552 /* Add to narrowed selector. */
3553 new_sel_perm.quick_push (l + offs * nelts);
3554
3555 /* Mark lane as used. */
3556 lanes[l] = true;
3557 }
3558
3559 /* Count how many lanes are need. */
3560 unsigned int cnt = 0;
3561 for (unsigned int i = 0; i < nelts; i++)
3562 cnt += lanes[i];
3563
3564 /* If more than (nelts/2) lanes are needed, skip the sequence. */
3565 if (cnt > nelts / 2)
3566 return false;
3567
3568 /* Check if the resulting permutation is cheap. */
3569 vec_perm_indices new_indices (new_sel_perm, 2, nelts);
3570 tree vectype = TREE_TYPE (gimple_assign_lhs (stmt));
3571 machine_mode vmode = TYPE_MODE (vectype);
3572 if (!can_vec_perm_const_p (vmode, vmode, new_indices, false))
3573 return false;
3574
3575 *seq = XNEW (struct _vec_perm_simplify_seq);
3576 (*seq)->stmt = stmt;
3577 (*seq)->v_1_stmt = v_1_stmt;
3578 (*seq)->v_2_stmt = v_2_stmt;
3579 (*seq)->v_x_stmt = v_x_stmt;
3580 (*seq)->v_y_stmt = v_y_stmt;
3581 (*seq)->nelts = nelts;
3582 (*seq)->new_sel = vect_gen_perm_mask_checked (vectype, new_indices);
3583
3584 if (dump_file)
3585 {
3586 fprintf (dump_file, "Found vec perm simplify sequence ending with:\n\t");
3587 print_gimple_stmt (dump_file, stmt, 0);
3588
3589 if (dump_flags & TDF_DETAILS)
3590 {
3591 fprintf (dump_file, "\tNarrowed vec_perm selector: ");
3592 print_generic_expr (dump_file, (*seq)->new_sel);
3593 fprintf (dump_file, "\n");
3594 }
3595 }
3596
3597 return true;
3598 }
3599
3600 /* Reduce the lane consumption of a simplifiable vec perm sequence. */
3601
3602 static void
3603 narrow_vec_perm_simplify_seq (const vec_perm_simplify_seq &seq)
3604 {
3605 gassign *stmt = seq->stmt;
3606 if (dump_file && (dump_flags & TDF_DETAILS))
3607 {
3608 fprintf (dump_file, "Updating VEC_PERM statment:\n");
3609 fprintf (dump_file, "Old stmt: ");
3610 print_gimple_stmt (dump_file, stmt, 0);
3611 }
3612
3613 /* Update the last VEC_PERM statement. */
3614 gimple_assign_set_rhs3 (stmt, seq->new_sel);
3615 update_stmt (stmt);
3616
3617 if (dump_file && (dump_flags & TDF_DETAILS))
3618 {
3619 fprintf (dump_file, "New stmt: ");
3620 print_gimple_stmt (dump_file, stmt, 0);
3621 }
3622 }
3623
3624 /* Test if we can blend two simplifiable vec permute sequences.
3625 NEED_SWAP will be set, if sequences must be swapped for blending. */
3626
3627 static bool
3628 can_blend_vec_perm_simplify_seqs_p (vec_perm_simplify_seq seq1,
3629 vec_perm_simplify_seq seq2,
3630 bool *need_swap)
3631 {
3632 unsigned int nelts = seq1->nelts;
3633 basic_block bb = gimple_bb (seq1->stmt);
3634
3635 gcc_assert (gimple_bb (seq2->stmt) == bb);
3636
3637 /* BBs and number of elements must be equal. */
3638 if (gimple_bb (seq2->stmt) != bb || seq2->nelts != nelts)
3639 return false;
3640
3641 /* We need vectors of the same type. */
3642 if (TREE_TYPE (gimple_assign_lhs (seq1->stmt))
3643 != TREE_TYPE (gimple_assign_lhs (seq2->stmt)))
3644 return false;
3645
3646 /* We require isomorphic operators. */
3647 if (((gimple_assign_rhs_code (seq1->v_x_stmt)
3648 != gimple_assign_rhs_code (seq2->v_x_stmt))
3649 || (gimple_assign_rhs_code (seq1->v_y_stmt)
3650 != gimple_assign_rhs_code (seq2->v_y_stmt))))
3651 return false;
3652
3653 /* We cannot have any dependencies between the sequences.
3654
3655 For merging, we will reuse seq1->v_1_stmt and seq1->v_2_stmt.
3656 seq1's v_in is defined before these statements, but we need
3657 to check if seq2's v_in is defined before them as well.
3658
3659 Further, we will reuse seq2->stmt. We need to ensure that
3660 seq1->v_x_stmt and seq1->v_y_stmt are before it.
3661
3662 Note, that we don't need to check the BBs here, because all
3663 statements of both sequences have to be in the same BB. */
3664
3665 tree seq2_v_in = gimple_assign_rhs1 (seq2->v_1_stmt);
3666 if (TREE_CODE (seq2_v_in) != SSA_NAME)
3667 return false;
3668
3669 gassign *seq2_v_in_stmt = dyn_cast<gassign *> (SSA_NAME_DEF_STMT (seq2_v_in));
3670 if (!seq2_v_in_stmt || gimple_bb (seq2_v_in_stmt) != bb
3671 || (gimple_uid (seq2_v_in_stmt) > gimple_uid (seq1->v_1_stmt))
3672 || (gimple_uid (seq1->v_x_stmt) > gimple_uid (seq2->stmt))
3673 || (gimple_uid (seq1->v_y_stmt) > gimple_uid (seq2->stmt)))
3674 {
3675 tree seq1_v_in = gimple_assign_rhs1 (seq1->v_1_stmt);
3676 if (TREE_CODE (seq1_v_in) != SSA_NAME)
3677 return false;
3678
3679 gassign *seq1_v_in_stmt
3680 = dyn_cast<gassign *> (SSA_NAME_DEF_STMT (seq1_v_in));
3681 /* Let's try to see if we succeed when swapping the sequences. */
3682 if (!seq1_v_in_stmt || gimple_bb (seq1_v_in_stmt)
3683 || (gimple_uid (seq1_v_in_stmt) > gimple_uid (seq2->v_1_stmt))
3684 || (gimple_uid (seq2->v_x_stmt) > gimple_uid (seq1->stmt))
3685 || (gimple_uid (seq2->v_y_stmt) > gimple_uid (seq1->stmt)))
3686 return false;
3687 *need_swap = true;
3688 }
3689 else
3690 *need_swap = false;
3691
3692 if (dump_file && (dump_flags & TDF_DETAILS))
3693 fprintf (dump_file, "Found vec perm simplify sequence pair.\n");
3694
3695 return true;
3696 }
3697
3698 /* Calculate the permutations for blending the two given vec permute
3699 sequences. This may fail if the resulting permutation is not
3700 supported. */
3701
3702 static bool
3703 calc_perm_vec_perm_simplify_seqs (vec_perm_simplify_seq seq1,
3704 vec_perm_simplify_seq seq2,
3705 vec_perm_indices *seq2_stmt_indices,
3706 vec_perm_indices *seq1_v_1_stmt_indices,
3707 vec_perm_indices *seq1_v_2_stmt_indices)
3708 {
3709 unsigned int i;
3710 unsigned int nelts = seq1->nelts;
3711 auto_vec<unsigned int> lane_assignment;
3712 lane_assignment.create (nelts);
3713
3714 /* Mark all lanes as free. */
3715 lane_assignment.quick_grow_cleared (nelts);
3716
3717 /* Allocate lanes for seq1. */
3718 for (i = 0; i < nelts; i++)
3719 {
3720 unsigned int l = TREE_INT_CST_LOW (VECTOR_CST_ELT (seq1->new_sel, i));
3721 l %= nelts;
3722 lane_assignment[l] = 1;
3723 }
3724
3725 /* Allocate lanes for seq2 and calculate selector for seq2->stmt. */
3726 vec_perm_builder seq2_stmt_sel_perm (nelts, nelts, 1);
3727 for (i = 0; i < nelts; i++)
3728 {
3729 unsigned int sel = TREE_INT_CST_LOW (VECTOR_CST_ELT (seq2->new_sel, i));
3730 unsigned int lane = sel % nelts;
3731 unsigned int offs = sel / nelts;
3732 unsigned int new_sel;
3733
3734 /* Check if we already allocated the lane for seq2. */
3735 unsigned int j = 0;
3736 for (; j < i; j++)
3737 {
3738 unsigned int sel_old;
3739 sel_old = TREE_INT_CST_LOW (VECTOR_CST_ELT (seq2->new_sel, j));
3740 unsigned int lane_old = sel_old % nelts;
3741 if (lane == lane_old)
3742 {
3743 new_sel = seq2_stmt_sel_perm[j].to_constant ();
3744 new_sel = (new_sel % nelts) + offs * nelts;
3745 break;
3746 }
3747 }
3748
3749 /* If the lane is not allocated, we need to do that now. */
3750 if (j == i)
3751 {
3752 unsigned int l_orig = lane;
3753 while (lane_assignment[lane] != 0)
3754 {
3755 lane = (lane + 1) % nelts;
3756
3757 /* This should not happen if both sequences utilize no more than
3758 half of the lanes. Test anyway to guarantee termination. */
3759 if (lane == l_orig)
3760 return false;
3761 }
3762
3763 /* Allocate lane. */
3764 lane_assignment[lane] = 2 + l_orig;
3765 new_sel = lane + offs * nelts;
3766 }
3767
3768 seq2_stmt_sel_perm.quick_push (new_sel);
3769 }
3770
3771 /* Check if the resulting permutation is cheap. */
3772 seq2_stmt_indices->new_vector (seq2_stmt_sel_perm, 2, nelts);
3773 tree vectype = TREE_TYPE (gimple_assign_lhs (seq2->stmt));
3774 machine_mode vmode = TYPE_MODE (vectype);
3775 if (!can_vec_perm_const_p (vmode, vmode, *seq2_stmt_indices, false))
3776 return false;
3777
3778 /* Calculate selectors for seq1->v_1_stmt and seq1->v_2_stmt. */
3779 vec_perm_builder seq1_v_1_stmt_sel_perm (nelts, nelts, 1);
3780 vec_perm_builder seq1_v_2_stmt_sel_perm (nelts, nelts, 1);
3781 for (i = 0; i < nelts; i++)
3782 {
3783 bool use_seq1 = lane_assignment[i] < 2;
3784 unsigned int l1, l2;
3785
3786 if (use_seq1)
3787 {
3788 /* Just reuse the selector indices. */
3789 tree s1 = gimple_assign_rhs3 (seq1->v_1_stmt);
3790 tree s2 = gimple_assign_rhs3 (seq1->v_2_stmt);
3791 l1 = TREE_INT_CST_LOW (VECTOR_CST_ELT (s1, i));
3792 l2 = TREE_INT_CST_LOW (VECTOR_CST_ELT (s2, i));
3793 }
3794 else
3795 {
3796 /* We moved the lanes for seq2, so we need to adjust for that. */
3797 tree s1 = gimple_assign_rhs3 (seq2->v_1_stmt);
3798 tree s2 = gimple_assign_rhs3 (seq2->v_2_stmt);
3799 l1 = TREE_INT_CST_LOW (VECTOR_CST_ELT (s1, lane_assignment[i] - 2));
3800 l2 = TREE_INT_CST_LOW (VECTOR_CST_ELT (s2, lane_assignment[i] - 2));
3801 }
3802
3803 l1 %= nelts;
3804 l2 %= nelts;
3805 seq1_v_1_stmt_sel_perm.quick_push (l1 + (use_seq1 ? 0 : nelts));
3806 seq1_v_2_stmt_sel_perm.quick_push (l2 + (use_seq1 ? 0 : nelts));
3807 }
3808
3809 seq1_v_1_stmt_indices->new_vector (seq1_v_1_stmt_sel_perm, 2, nelts);
3810 vectype = TREE_TYPE (gimple_assign_lhs (seq1->v_1_stmt));
3811 vmode = TYPE_MODE (vectype);
3812 if (!can_vec_perm_const_p (vmode, vmode, *seq1_v_1_stmt_indices, false))
3813 return false;
3814
3815 seq1_v_2_stmt_indices->new_vector (seq1_v_2_stmt_sel_perm, 2, nelts);
3816 vectype = TREE_TYPE (gimple_assign_lhs (seq1->v_2_stmt));
3817 vmode = TYPE_MODE (vectype);
3818 if (!can_vec_perm_const_p (vmode, vmode, *seq1_v_2_stmt_indices, false))
3819 return false;
3820
3821 return true;
3822 }
3823
3824 /* Blend the two given simplifiable vec permute sequences using the
3825 given permutations. */
3826
3827 static void
3828 blend_vec_perm_simplify_seqs (vec_perm_simplify_seq seq1,
3829 vec_perm_simplify_seq seq2,
3830 const vec_perm_indices &seq2_stmt_indices,
3831 const vec_perm_indices &seq1_v_1_stmt_indices,
3832 const vec_perm_indices &seq1_v_2_stmt_indices)
3833 {
3834 /* We don't need to adjust seq1->stmt because its lanes consumption
3835 was already narrowed before entering this function. */
3836
3837 /* Adjust seq2->stmt: copy RHS1/RHS2 from seq1->stmt and set new sel. */
3838 if (dump_file && (dump_flags & TDF_DETAILS))
3839 {
3840 fprintf (dump_file, "Updating VEC_PERM statment:\n");
3841 fprintf (dump_file, "Old stmt: ");
3842 print_gimple_stmt (dump_file, seq2->stmt, 0);
3843 }
3844
3845 gimple_assign_set_rhs1 (seq2->stmt, gimple_assign_rhs1 (seq1->stmt));
3846 gimple_assign_set_rhs2 (seq2->stmt, gimple_assign_rhs2 (seq1->stmt));
3847 tree vectype = TREE_TYPE (gimple_assign_lhs (seq2->stmt));
3848 tree sel = vect_gen_perm_mask_checked (vectype, seq2_stmt_indices);
3849 gimple_assign_set_rhs3 (seq2->stmt, sel);
3850 update_stmt (seq2->stmt);
3851
3852 if (dump_file && (dump_flags & TDF_DETAILS))
3853 {
3854 fprintf (dump_file, "New stmt: ");
3855 print_gimple_stmt (dump_file, seq2->stmt, 0);
3856 }
3857
3858 /* Adjust seq1->v_1_stmt: copy RHS2 from seq2->v_1_stmt and set new sel. */
3859 if (dump_file && (dump_flags & TDF_DETAILS))
3860 {
3861 fprintf (dump_file, "Updating VEC_PERM statment:\n");
3862 fprintf (dump_file, "Old stmt: ");
3863 print_gimple_stmt (dump_file, seq1->v_1_stmt, 0);
3864 }
3865
3866 gimple_assign_set_rhs2 (seq1->v_1_stmt, gimple_assign_rhs1 (seq2->v_1_stmt));
3867 vectype = TREE_TYPE (gimple_assign_lhs (seq1->v_1_stmt));
3868 sel = vect_gen_perm_mask_checked (vectype, seq1_v_1_stmt_indices);
3869 gimple_assign_set_rhs3 (seq1->v_1_stmt, sel);
3870 update_stmt (seq1->v_1_stmt);
3871
3872 if (dump_file && (dump_flags & TDF_DETAILS))
3873 {
3874 fprintf (dump_file, "New stmt: ");
3875 print_gimple_stmt (dump_file, seq1->v_1_stmt, 0);
3876 }
3877
3878 /* Adjust seq1->v_2_stmt: copy RHS2 from seq2->v_2_stmt and set new sel. */
3879 if (dump_file && (dump_flags & TDF_DETAILS))
3880 {
3881 fprintf (dump_file, "Updating VEC_PERM statment:\n");
3882 fprintf (dump_file, "Old stmt: ");
3883 print_gimple_stmt (dump_file, seq1->v_2_stmt, 0);
3884 }
3885
3886 gimple_assign_set_rhs2 (seq1->v_2_stmt, gimple_assign_rhs1 (seq2->v_2_stmt));
3887 vectype = TREE_TYPE (gimple_assign_lhs (seq1->v_2_stmt));
3888 sel = vect_gen_perm_mask_checked (vectype, seq1_v_2_stmt_indices);
3889 gimple_assign_set_rhs3 (seq1->v_2_stmt, sel);
3890 update_stmt (seq1->v_2_stmt);
3891
3892 if (dump_file && (dump_flags & TDF_DETAILS))
3893 {
3894 fprintf (dump_file, "New stmt: ");
3895 print_gimple_stmt (dump_file, seq1->v_2_stmt, 0);
3896 }
3897
3898 /* At this point, we have four unmodified seq2 stmts, which will be
3899 eliminated by DCE. */
3900
3901 if (dump_file)
3902 fprintf (dump_file, "Vec perm simplify sequences have been blended.\n\n");
3903 }
3904
3905 /* Try to blend narrowed vec_perm_simplify_seqs pairwise.
3906 The provided list will be empty after this call. */
3907
3908 static void
3909 process_vec_perm_simplify_seq_list (vec<vec_perm_simplify_seq> *l)
3910 {
3911 unsigned int i, j;
3912 vec_perm_simplify_seq seq1, seq2;
3913
3914 if (l->is_empty ())
3915 return;
3916
3917 if (dump_file && (dump_flags & TDF_DETAILS))
3918 fprintf (dump_file, "\nProcessing %u vec perm simplify sequences.\n",
3919 l->length ());
3920
3921 FOR_EACH_VEC_ELT (*l, i, seq1)
3922 {
3923 if (i + 1 < l->length ())
3924 {
3925 FOR_EACH_VEC_ELT_FROM (*l, j, seq2, i + 1)
3926 {
3927 bool swap = false;
3928 if (can_blend_vec_perm_simplify_seqs_p (seq1, seq2, &swap))
3929 {
3930 vec_perm_indices seq2_stmt_indices;
3931 vec_perm_indices seq1_v_1_stmt_indices;
3932 vec_perm_indices seq1_v_2_stmt_indices;
3933 if (calc_perm_vec_perm_simplify_seqs (swap ? seq2 : seq1,
3934 swap ? seq1 : seq2,
3935 &seq2_stmt_indices,
3936 &seq1_v_1_stmt_indices,
3937 &seq1_v_2_stmt_indices))
3938 {
3939 /* Narrow lane usage. */
3940 narrow_vec_perm_simplify_seq (seq1);
3941 narrow_vec_perm_simplify_seq (seq2);
3942
3943 /* Blend sequences. */
3944 blend_vec_perm_simplify_seqs (swap ? seq2 : seq1,
3945 swap ? seq1 : seq2,
3946 seq2_stmt_indices,
3947 seq1_v_1_stmt_indices,
3948 seq1_v_2_stmt_indices);
3949
3950 /* We can use unordered_remove as we break the loop. */
3951 l->unordered_remove (j);
3952 XDELETE (seq2);
3953 break;
3954 }
3955 }
3956 }
3957 }
3958
3959 /* We don't need to call l->remove for seq1. */
3960 XDELETE (seq1);
3961 }
3962
3963 l->truncate (0);
3964 }
3965
3966 static void
3967 append_vec_perm_simplify_seq_list (vec<vec_perm_simplify_seq> *l,
3968 const vec_perm_simplify_seq &seq)
3969 {
3970 /* If no space on list left, then process the list. */
3971 if (!l->space (1))
3972 process_vec_perm_simplify_seq_list (l);
3973
3974 l->quick_push (seq);
3975 }
3976
3977 /* Main entry point for the forward propagation and statement combine
3978 optimizer. */
3979
3980 namespace {
3981
3982 const pass_data pass_data_forwprop =
3983 {
3984 GIMPLE_PASS, /* type */
3985 "forwprop", /* name */
3986 OPTGROUP_NONE, /* optinfo_flags */
3987 TV_TREE_FORWPROP, /* tv_id */
3988 ( PROP_cfg | PROP_ssa ), /* properties_required */
3989 0, /* properties_provided */
3990 0, /* properties_destroyed */
3991 0, /* todo_flags_start */
3992 TODO_update_ssa, /* todo_flags_finish */
3993 };
3994
3995 class pass_forwprop : public gimple_opt_pass
3996 {
3997 public:
3998 pass_forwprop (gcc::context *ctxt)
3999 : gimple_opt_pass (pass_data_forwprop, ctxt), last_p (false)
4000 {}
4001
4002 /* opt_pass methods: */
4003 opt_pass * clone () final override { return new pass_forwprop (m_ctxt); }
4004 void set_pass_param (unsigned int n, bool param) final override
4005 {
4006 gcc_assert (n == 0);
4007 last_p = param;
4008 }
4009 bool gate (function *) final override { return flag_tree_forwprop; }
4010 unsigned int execute (function *) final override;
4011
4012 private:
4013 /* Determines whether the pass instance should set PROP_last_full_fold. */
4014 bool last_p;
4015 }; // class pass_forwprop
4016
4017 unsigned int
4018 pass_forwprop::execute (function *fun)
4019 {
4020 unsigned int todoflags = 0;
4021
4022 cfg_changed = false;
4023 if (last_p)
4024 fun->curr_properties |= PROP_last_full_fold;
4025
4026 calculate_dominance_info (CDI_DOMINATORS);
4027
4028 /* Combine stmts with the stmts defining their operands. Do that
4029 in an order that guarantees visiting SSA defs before SSA uses. */
4030 lattice.create (num_ssa_names);
4031 lattice.quick_grow_cleared (num_ssa_names);
4032 int *postorder = XNEWVEC (int, n_basic_blocks_for_fn (fun));
4033 int postorder_num = pre_and_rev_post_order_compute_fn (fun, NULL,
4034 postorder, false);
4035 int *bb_to_rpo = XNEWVEC (int, last_basic_block_for_fn (fun));
4036 for (int i = 0; i < postorder_num; ++i)
4037 {
4038 bb_to_rpo[postorder[i]] = i;
4039 edge_iterator ei;
4040 edge e;
4041 FOR_EACH_EDGE (e, ei, BASIC_BLOCK_FOR_FN (fun, postorder[i])->succs)
4042 e->flags &= ~EDGE_EXECUTABLE;
4043 }
4044 single_succ_edge (BASIC_BLOCK_FOR_FN (fun, ENTRY_BLOCK))->flags
4045 |= EDGE_EXECUTABLE;
4046 auto_vec<gimple *, 4> to_fixup;
4047 auto_vec<gimple *, 32> to_remove;
4048 auto_vec<unsigned, 32> to_remove_defs;
4049 auto_vec<std::pair<int, int>, 10> edges_to_remove;
4050 auto_bitmap simple_dce_worklist;
4051 auto_bitmap need_ab_cleanup;
4052 to_purge = BITMAP_ALLOC (NULL);
4053 auto_vec<vec_perm_simplify_seq, 8> vec_perm_simplify_seq_list;
4054 for (int i = 0; i < postorder_num; ++i)
4055 {
4056 gimple_stmt_iterator gsi;
4057 basic_block bb = BASIC_BLOCK_FOR_FN (fun, postorder[i]);
4058 edge_iterator ei;
4059 edge e;
4060
4061 /* Skip processing not executable blocks. We could improve
4062 single_use tracking by at least unlinking uses from unreachable
4063 blocks but since blocks with uses are not processed in a
4064 meaningful order this is probably not worth it. */
4065 bool any = false;
4066 FOR_EACH_EDGE (e, ei, bb->preds)
4067 {
4068 if ((e->flags & EDGE_EXECUTABLE)
4069 /* We can handle backedges in natural loops correctly but
4070 for irreducible regions we have to take all backedges
4071 conservatively when we did not visit the source yet. */
4072 || (bb_to_rpo[e->src->index] > i
4073 && !dominated_by_p (CDI_DOMINATORS, e->src, e->dest)))
4074 {
4075 any = true;
4076 break;
4077 }
4078 }
4079 if (!any)
4080 continue;
4081
4082 /* Record degenerate PHIs in the lattice. */
4083 for (gphi_iterator si = gsi_start_phis (bb); !gsi_end_p (si);
4084 gsi_next (&si))
4085 {
4086 gphi *phi = si.phi ();
4087 tree res = gimple_phi_result (phi);
4088 if (virtual_operand_p (res))
4089 continue;
4090
4091 tree first = NULL_TREE;
4092 bool all_same = true;
4093 edge_iterator ei;
4094 edge e;
4095 FOR_EACH_EDGE (e, ei, bb->preds)
4096 {
4097 /* Ignore not executable forward edges. */
4098 if (!(e->flags & EDGE_EXECUTABLE))
4099 {
4100 if (bb_to_rpo[e->src->index] < i)
4101 continue;
4102 /* Avoid equivalences from backedges - while we might
4103 be able to make irreducible regions reducible and
4104 thus turning a back into a forward edge we do not
4105 want to deal with the intermediate SSA issues that
4106 exposes. */
4107 all_same = false;
4108 }
4109 tree use = PHI_ARG_DEF_FROM_EDGE (phi, e);
4110 if (use == res)
4111 /* The PHI result can also appear on a backedge, if so
4112 we can ignore this case for the purpose of determining
4113 the singular value. */
4114 ;
4115 else if (! first)
4116 first = use;
4117 else if (! operand_equal_p (first, use, 0))
4118 {
4119 all_same = false;
4120 break;
4121 }
4122 }
4123 if (all_same)
4124 {
4125 if (may_propagate_copy (res, first))
4126 to_remove_defs.safe_push (SSA_NAME_VERSION (res));
4127 fwprop_set_lattice_val (res, first);
4128 }
4129 }
4130
4131 /* Apply forward propagation to all stmts in the basic-block.
4132 Note we update GSI within the loop as necessary. */
4133 unsigned int uid = 1;
4134 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); )
4135 {
4136 gimple *stmt = gsi_stmt (gsi);
4137 tree lhs, rhs;
4138 enum tree_code code;
4139
4140 gimple_set_uid (stmt, uid++);
4141
4142 if (!is_gimple_assign (stmt))
4143 {
4144 process_vec_perm_simplify_seq_list (&vec_perm_simplify_seq_list);
4145 gsi_next (&gsi);
4146 continue;
4147 }
4148
4149 lhs = gimple_assign_lhs (stmt);
4150 rhs = gimple_assign_rhs1 (stmt);
4151 code = gimple_assign_rhs_code (stmt);
4152
4153 if (TREE_CODE (lhs) != SSA_NAME
4154 || has_zero_uses (lhs))
4155 {
4156 process_vec_perm_simplify_seq_list (&vec_perm_simplify_seq_list);
4157 gsi_next (&gsi);
4158 continue;
4159 }
4160
4161 /* If this statement sets an SSA_NAME to an address,
4162 try to propagate the address into the uses of the SSA_NAME. */
4163 if ((code == ADDR_EXPR
4164 /* Handle pointer conversions on invariant addresses
4165 as well, as this is valid gimple. */
4166 || (CONVERT_EXPR_CODE_P (code)
4167 && TREE_CODE (rhs) == ADDR_EXPR
4168 && POINTER_TYPE_P (TREE_TYPE (lhs))))
4169 && TREE_CODE (TREE_OPERAND (rhs, 0)) != TARGET_MEM_REF)
4170 {
4171 tree base = get_base_address (TREE_OPERAND (rhs, 0));
4172 if ((!base
4173 || !DECL_P (base)
4174 || decl_address_invariant_p (base))
4175 && !stmt_references_abnormal_ssa_name (stmt)
4176 && forward_propagate_addr_expr (lhs, rhs, true))
4177 {
4178 fwprop_invalidate_lattice (gimple_get_lhs (stmt));
4179 release_defs (stmt);
4180 gsi_remove (&gsi, true);
4181 }
4182 else
4183 gsi_next (&gsi);
4184 }
4185 else if (code == POINTER_PLUS_EXPR)
4186 {
4187 tree off = gimple_assign_rhs2 (stmt);
4188 if (TREE_CODE (off) == INTEGER_CST
4189 && can_propagate_from (stmt)
4190 && !simple_iv_increment_p (stmt)
4191 /* ??? Better adjust the interface to that function
4192 instead of building new trees here. */
4193 && forward_propagate_addr_expr
4194 (lhs,
4195 build1_loc (gimple_location (stmt),
4196 ADDR_EXPR, TREE_TYPE (rhs),
4197 fold_build2 (MEM_REF,
4198 TREE_TYPE (TREE_TYPE (rhs)),
4199 rhs,
4200 fold_convert (ptr_type_node,
4201 off))), true))
4202 {
4203 fwprop_invalidate_lattice (gimple_get_lhs (stmt));
4204 release_defs (stmt);
4205 gsi_remove (&gsi, true);
4206 }
4207 else if (is_gimple_min_invariant (rhs))
4208 {
4209 /* Make sure to fold &a[0] + off_1 here. */
4210 fold_stmt_inplace (&gsi);
4211 update_stmt (stmt);
4212 if (gimple_assign_rhs_code (stmt) == POINTER_PLUS_EXPR)
4213 gsi_next (&gsi);
4214 }
4215 else
4216 gsi_next (&gsi);
4217 }
4218 else if (TREE_CODE (TREE_TYPE (lhs)) == COMPLEX_TYPE
4219 && gimple_assign_load_p (stmt)
4220 && !gimple_has_volatile_ops (stmt)
4221 && TREE_CODE (rhs) != TARGET_MEM_REF
4222 && TREE_CODE (rhs) != BIT_FIELD_REF
4223 && !stmt_can_throw_internal (fun, stmt))
4224 {
4225 /* Rewrite loads used only in real/imagpart extractions to
4226 component-wise loads. */
4227 use_operand_p use_p;
4228 imm_use_iterator iter;
4229 bool rewrite = true;
4230 FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
4231 {
4232 gimple *use_stmt = USE_STMT (use_p);
4233 if (is_gimple_debug (use_stmt))
4234 continue;
4235 if (!is_gimple_assign (use_stmt)
4236 || (gimple_assign_rhs_code (use_stmt) != REALPART_EXPR
4237 && gimple_assign_rhs_code (use_stmt) != IMAGPART_EXPR)
4238 || TREE_OPERAND (gimple_assign_rhs1 (use_stmt), 0) != lhs)
4239 {
4240 rewrite = false;
4241 break;
4242 }
4243 }
4244 if (rewrite)
4245 {
4246 gimple *use_stmt;
4247 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
4248 {
4249 if (is_gimple_debug (use_stmt))
4250 {
4251 if (gimple_debug_bind_p (use_stmt))
4252 {
4253 gimple_debug_bind_reset_value (use_stmt);
4254 update_stmt (use_stmt);
4255 }
4256 continue;
4257 }
4258
4259 tree new_rhs = build1 (gimple_assign_rhs_code (use_stmt),
4260 TREE_TYPE (TREE_TYPE (rhs)),
4261 unshare_expr (rhs));
4262 gimple *new_stmt
4263 = gimple_build_assign (gimple_assign_lhs (use_stmt),
4264 new_rhs);
4265
4266 location_t loc = gimple_location (use_stmt);
4267 gimple_set_location (new_stmt, loc);
4268 gimple_stmt_iterator gsi2 = gsi_for_stmt (use_stmt);
4269 unlink_stmt_vdef (use_stmt);
4270 gsi_remove (&gsi2, true);
4271
4272 gsi_insert_before (&gsi, new_stmt, GSI_SAME_STMT);
4273 }
4274
4275 release_defs (stmt);
4276 gsi_remove (&gsi, true);
4277 }
4278 else
4279 gsi_next (&gsi);
4280 }
4281 else if (TREE_CODE (TREE_TYPE (lhs)) == VECTOR_TYPE
4282 && (TYPE_MODE (TREE_TYPE (lhs)) == BLKmode
4283 /* After vector lowering rewrite all loads, but
4284 initially do not since this conflicts with
4285 vector CONSTRUCTOR to shuffle optimization. */
4286 || (fun->curr_properties & PROP_gimple_lvec))
4287 && gimple_assign_load_p (stmt)
4288 && !gimple_has_volatile_ops (stmt)
4289 && !stmt_can_throw_internal (fun, stmt)
4290 && (!VAR_P (rhs) || !DECL_HARD_REGISTER (rhs)))
4291 optimize_vector_load (&gsi);
4292
4293 else if (code == COMPLEX_EXPR)
4294 {
4295 /* Rewrite stores of a single-use complex build expression
4296 to component-wise stores. */
4297 use_operand_p use_p;
4298 gimple *use_stmt, *def1, *def2;
4299 tree rhs2;
4300 if (single_imm_use (lhs, &use_p, &use_stmt)
4301 && gimple_store_p (use_stmt)
4302 && !gimple_has_volatile_ops (use_stmt)
4303 && is_gimple_assign (use_stmt)
4304 && (TREE_CODE (TREE_TYPE (gimple_assign_lhs (use_stmt)))
4305 == COMPLEX_TYPE)
4306 && (TREE_CODE (gimple_assign_lhs (use_stmt))
4307 != TARGET_MEM_REF))
4308 {
4309 tree use_lhs = gimple_assign_lhs (use_stmt);
4310 if (auto_var_p (use_lhs))
4311 DECL_NOT_GIMPLE_REG_P (use_lhs) = 1;
4312 tree new_lhs = build1 (REALPART_EXPR,
4313 TREE_TYPE (TREE_TYPE (use_lhs)),
4314 unshare_expr (use_lhs));
4315 gimple *new_stmt = gimple_build_assign (new_lhs, rhs);
4316 location_t loc = gimple_location (use_stmt);
4317 gimple_set_location (new_stmt, loc);
4318 gimple_set_vuse (new_stmt, gimple_vuse (use_stmt));
4319 gimple_set_vdef (new_stmt, make_ssa_name (gimple_vop (fun)));
4320 SSA_NAME_DEF_STMT (gimple_vdef (new_stmt)) = new_stmt;
4321 gimple_set_vuse (use_stmt, gimple_vdef (new_stmt));
4322 gimple_stmt_iterator gsi2 = gsi_for_stmt (use_stmt);
4323 gsi_insert_before (&gsi2, new_stmt, GSI_SAME_STMT);
4324
4325 new_lhs = build1 (IMAGPART_EXPR,
4326 TREE_TYPE (TREE_TYPE (use_lhs)),
4327 unshare_expr (use_lhs));
4328 gimple_assign_set_lhs (use_stmt, new_lhs);
4329 gimple_assign_set_rhs1 (use_stmt, gimple_assign_rhs2 (stmt));
4330 update_stmt (use_stmt);
4331
4332 release_defs (stmt);
4333 gsi_remove (&gsi, true);
4334 }
4335 /* Rewrite a component-wise load of a complex to a complex
4336 load if the components are not used separately. */
4337 else if (TREE_CODE (rhs) == SSA_NAME
4338 && has_single_use (rhs)
4339 && ((rhs2 = gimple_assign_rhs2 (stmt)), true)
4340 && TREE_CODE (rhs2) == SSA_NAME
4341 && has_single_use (rhs2)
4342 && (def1 = SSA_NAME_DEF_STMT (rhs),
4343 gimple_assign_load_p (def1))
4344 && (def2 = SSA_NAME_DEF_STMT (rhs2),
4345 gimple_assign_load_p (def2))
4346 && (gimple_vuse (def1) == gimple_vuse (def2))
4347 && !gimple_has_volatile_ops (def1)
4348 && !gimple_has_volatile_ops (def2)
4349 && !stmt_can_throw_internal (fun, def1)
4350 && !stmt_can_throw_internal (fun, def2)
4351 && gimple_assign_rhs_code (def1) == REALPART_EXPR
4352 && gimple_assign_rhs_code (def2) == IMAGPART_EXPR
4353 && operand_equal_p (TREE_OPERAND (gimple_assign_rhs1
4354 (def1), 0),
4355 TREE_OPERAND (gimple_assign_rhs1
4356 (def2), 0)))
4357 {
4358 tree cl = TREE_OPERAND (gimple_assign_rhs1 (def1), 0);
4359 gimple_assign_set_rhs_from_tree (&gsi, unshare_expr (cl));
4360 gcc_assert (gsi_stmt (gsi) == stmt);
4361 gimple_set_vuse (stmt, gimple_vuse (def1));
4362 gimple_set_modified (stmt, true);
4363 gimple_stmt_iterator gsi2 = gsi_for_stmt (def1);
4364 gsi_remove (&gsi, false);
4365 gsi_insert_after (&gsi2, stmt, GSI_SAME_STMT);
4366 }
4367 else
4368 gsi_next (&gsi);
4369 }
4370 else if (code == CONSTRUCTOR
4371 && VECTOR_TYPE_P (TREE_TYPE (rhs))
4372 && TYPE_MODE (TREE_TYPE (rhs)) == BLKmode
4373 && CONSTRUCTOR_NELTS (rhs) > 0
4374 && (!VECTOR_TYPE_P (TREE_TYPE (CONSTRUCTOR_ELT (rhs, 0)->value))
4375 || (TYPE_MODE (TREE_TYPE (CONSTRUCTOR_ELT (rhs, 0)->value))
4376 != BLKmode)))
4377 {
4378 /* Rewrite stores of a single-use vector constructors
4379 to component-wise stores if the mode isn't supported. */
4380 use_operand_p use_p;
4381 gimple *use_stmt;
4382 if (single_imm_use (lhs, &use_p, &use_stmt)
4383 && gimple_store_p (use_stmt)
4384 && !gimple_has_volatile_ops (use_stmt)
4385 && !stmt_can_throw_internal (fun, use_stmt)
4386 && is_gimple_assign (use_stmt))
4387 {
4388 tree elt_t = TREE_TYPE (CONSTRUCTOR_ELT (rhs, 0)->value);
4389 unsigned HOST_WIDE_INT elt_w
4390 = tree_to_uhwi (TYPE_SIZE (elt_t));
4391 unsigned HOST_WIDE_INT n
4392 = tree_to_uhwi (TYPE_SIZE (TREE_TYPE (rhs)));
4393 tree use_lhs = gimple_assign_lhs (use_stmt);
4394 if (auto_var_p (use_lhs))
4395 DECL_NOT_GIMPLE_REG_P (use_lhs) = 1;
4396 else if (TREE_CODE (use_lhs) == TARGET_MEM_REF)
4397 {
4398 gimple_stmt_iterator gsi2 = gsi_for_stmt (use_stmt);
4399 use_lhs = prepare_target_mem_ref_lvalue (use_lhs, &gsi2);
4400 }
4401 for (unsigned HOST_WIDE_INT bi = 0; bi < n; bi += elt_w)
4402 {
4403 unsigned HOST_WIDE_INT ci = bi / elt_w;
4404 tree new_rhs;
4405 if (ci < CONSTRUCTOR_NELTS (rhs))
4406 new_rhs = CONSTRUCTOR_ELT (rhs, ci)->value;
4407 else
4408 new_rhs = build_zero_cst (elt_t);
4409 tree new_lhs = build3 (BIT_FIELD_REF,
4410 elt_t,
4411 unshare_expr (use_lhs),
4412 bitsize_int (elt_w),
4413 bitsize_int (bi));
4414 gimple *new_stmt = gimple_build_assign (new_lhs, new_rhs);
4415 location_t loc = gimple_location (use_stmt);
4416 gimple_set_location (new_stmt, loc);
4417 gimple_set_vuse (new_stmt, gimple_vuse (use_stmt));
4418 gimple_set_vdef (new_stmt,
4419 make_ssa_name (gimple_vop (fun)));
4420 SSA_NAME_DEF_STMT (gimple_vdef (new_stmt)) = new_stmt;
4421 gimple_set_vuse (use_stmt, gimple_vdef (new_stmt));
4422 gimple_stmt_iterator gsi2 = gsi_for_stmt (use_stmt);
4423 gsi_insert_before (&gsi2, new_stmt, GSI_SAME_STMT);
4424 }
4425 gimple_stmt_iterator gsi2 = gsi_for_stmt (use_stmt);
4426 unlink_stmt_vdef (use_stmt);
4427 release_defs (use_stmt);
4428 gsi_remove (&gsi2, true);
4429 release_defs (stmt);
4430 gsi_remove (&gsi, true);
4431 }
4432 else
4433 gsi_next (&gsi);
4434 }
4435 else if (code == VEC_PERM_EXPR)
4436 {
4437 /* Find vectorized sequences, where we can reduce the lane
4438 utilization. The narrowing will be donw later and only
4439 if we find a pair of sequences that can be blended. */
4440 gassign *assign = dyn_cast <gassign *> (stmt);
4441 vec_perm_simplify_seq seq;
4442 if (recognise_vec_perm_simplify_seq (assign, &seq))
4443 append_vec_perm_simplify_seq_list (&vec_perm_simplify_seq_list,
4444 seq);
4445
4446 gsi_next (&gsi);
4447 }
4448 else
4449 gsi_next (&gsi);
4450 }
4451
4452 process_vec_perm_simplify_seq_list (&vec_perm_simplify_seq_list);
4453
4454 /* Combine stmts with the stmts defining their operands.
4455 Note we update GSI within the loop as necessary. */
4456 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4457 {
4458 gimple *stmt = gsi_stmt (gsi);
4459
4460 /* Mark stmt as potentially needing revisiting. */
4461 gimple_set_plf (stmt, GF_PLF_1, false);
4462
4463 bool can_make_abnormal_goto = (is_gimple_call (stmt)
4464 && stmt_can_make_abnormal_goto (stmt));
4465
4466 /* Substitute from our lattice. We need to do so only once. */
4467 bool substituted_p = false;
4468 use_operand_p usep;
4469 ssa_op_iter iter;
4470 FOR_EACH_SSA_USE_OPERAND (usep, stmt, iter, SSA_OP_USE)
4471 {
4472 tree use = USE_FROM_PTR (usep);
4473 tree val = fwprop_ssa_val (use);
4474 if (val && val != use)
4475 {
4476 if (!is_gimple_debug (stmt))
4477 bitmap_set_bit (simple_dce_worklist, SSA_NAME_VERSION (use));
4478 if (may_propagate_copy (use, val))
4479 {
4480 propagate_value (usep, val);
4481 substituted_p = true;
4482 }
4483 }
4484 }
4485 if (substituted_p
4486 && is_gimple_assign (stmt)
4487 && gimple_assign_rhs_code (stmt) == ADDR_EXPR)
4488 recompute_tree_invariant_for_addr_expr (gimple_assign_rhs1 (stmt));
4489 if (substituted_p
4490 && can_make_abnormal_goto
4491 && !stmt_can_make_abnormal_goto (stmt))
4492 bitmap_set_bit (need_ab_cleanup, bb->index);
4493
4494 bool changed;
4495 do
4496 {
4497 gimple *orig_stmt = stmt = gsi_stmt (gsi);
4498 bool was_noreturn = (is_gimple_call (stmt)
4499 && gimple_call_noreturn_p (stmt));
4500 changed = false;
4501
4502 auto_vec<tree, 8> uses;
4503 FOR_EACH_SSA_USE_OPERAND (usep, stmt, iter, SSA_OP_USE)
4504 if (uses.space (1))
4505 uses.quick_push (USE_FROM_PTR (usep));
4506
4507 if (fold_stmt (&gsi, fwprop_ssa_val, simple_dce_worklist))
4508 {
4509 changed = true;
4510 stmt = gsi_stmt (gsi);
4511 /* Cleanup the CFG if we simplified a condition to
4512 true or false. */
4513 if (gcond *cond = dyn_cast <gcond *> (stmt))
4514 if (gimple_cond_true_p (cond)
4515 || gimple_cond_false_p (cond))
4516 cfg_changed = true;
4517 /* Queue old uses for simple DCE if not debug statement. */
4518 if (!is_gimple_debug (stmt))
4519 for (tree use : uses)
4520 if (TREE_CODE (use) == SSA_NAME
4521 && !SSA_NAME_IS_DEFAULT_DEF (use))
4522 bitmap_set_bit (simple_dce_worklist,
4523 SSA_NAME_VERSION (use));
4524 }
4525
4526 if (changed || substituted_p)
4527 {
4528 if (maybe_clean_or_replace_eh_stmt (orig_stmt, stmt))
4529 bitmap_set_bit (to_purge, bb->index);
4530 if (!was_noreturn
4531 && is_gimple_call (stmt) && gimple_call_noreturn_p (stmt))
4532 to_fixup.safe_push (stmt);
4533 update_stmt (stmt);
4534 substituted_p = false;
4535 }
4536
4537 switch (gimple_code (stmt))
4538 {
4539 case GIMPLE_ASSIGN:
4540 {
4541 tree rhs1 = gimple_assign_rhs1 (stmt);
4542 enum tree_code code = gimple_assign_rhs_code (stmt);
4543
4544 if (TREE_CODE_CLASS (code) == tcc_comparison)
4545 {
4546 int did_something;
4547 did_something = forward_propagate_into_comparison (&gsi);
4548 if (maybe_clean_or_replace_eh_stmt (stmt, gsi_stmt (gsi)))
4549 bitmap_set_bit (to_purge, bb->index);
4550 if (did_something == 2)
4551 cfg_changed = true;
4552 changed = did_something != 0;
4553 }
4554 else if ((code == PLUS_EXPR
4555 || code == BIT_IOR_EXPR
4556 || code == BIT_XOR_EXPR)
4557 && simplify_rotate (&gsi))
4558 changed = true;
4559 else if (code == VEC_PERM_EXPR)
4560 {
4561 int did_something = simplify_permutation (&gsi);
4562 if (did_something == 2)
4563 cfg_changed = true;
4564 changed = did_something != 0;
4565 }
4566 else if (code == CONSTRUCTOR
4567 && TREE_CODE (TREE_TYPE (rhs1)) == VECTOR_TYPE)
4568 changed = simplify_vector_constructor (&gsi);
4569 else if (code == ARRAY_REF)
4570 changed = simplify_count_trailing_zeroes (&gsi);
4571 break;
4572 }
4573
4574 case GIMPLE_SWITCH:
4575 changed = simplify_gimple_switch (as_a <gswitch *> (stmt),
4576 edges_to_remove);
4577 break;
4578
4579 case GIMPLE_COND:
4580 {
4581 int did_something = forward_propagate_into_gimple_cond
4582 (as_a <gcond *> (stmt));
4583 if (did_something == 2)
4584 cfg_changed = true;
4585 changed = did_something != 0;
4586 break;
4587 }
4588
4589 case GIMPLE_CALL:
4590 {
4591 tree callee = gimple_call_fndecl (stmt);
4592 if (callee != NULL_TREE
4593 && fndecl_built_in_p (callee, BUILT_IN_NORMAL))
4594 changed = simplify_builtin_call (&gsi, callee);
4595 break;
4596 }
4597
4598 default:;
4599 }
4600
4601 if (changed)
4602 {
4603 /* If the stmt changed then re-visit it and the statements
4604 inserted before it. */
4605 for (; !gsi_end_p (gsi); gsi_prev (&gsi))
4606 if (gimple_plf (gsi_stmt (gsi), GF_PLF_1))
4607 break;
4608 if (gsi_end_p (gsi))
4609 gsi = gsi_start_bb (bb);
4610 else
4611 gsi_next (&gsi);
4612 }
4613 }
4614 while (changed);
4615
4616 /* Stmt no longer needs to be revisited. */
4617 stmt = gsi_stmt (gsi);
4618 gcc_checking_assert (!gimple_plf (stmt, GF_PLF_1));
4619 gimple_set_plf (stmt, GF_PLF_1, true);
4620
4621 /* Fill up the lattice. */
4622 if (gimple_assign_single_p (stmt))
4623 {
4624 tree lhs = gimple_assign_lhs (stmt);
4625 tree rhs = gimple_assign_rhs1 (stmt);
4626 if (TREE_CODE (lhs) == SSA_NAME)
4627 {
4628 tree val = lhs;
4629 if (TREE_CODE (rhs) == SSA_NAME)
4630 val = fwprop_ssa_val (rhs);
4631 else if (is_gimple_min_invariant (rhs))
4632 val = rhs;
4633 /* If we can propagate the lattice-value mark the
4634 stmt for removal. */
4635 if (val != lhs
4636 && may_propagate_copy (lhs, val))
4637 to_remove_defs.safe_push (SSA_NAME_VERSION (lhs));
4638 fwprop_set_lattice_val (lhs, val);
4639 }
4640 }
4641 else if (gimple_nop_p (stmt))
4642 to_remove.safe_push (stmt);
4643 }
4644
4645 /* Substitute in destination PHI arguments. */
4646 FOR_EACH_EDGE (e, ei, bb->succs)
4647 for (gphi_iterator gsi = gsi_start_phis (e->dest);
4648 !gsi_end_p (gsi); gsi_next (&gsi))
4649 {
4650 gphi *phi = gsi.phi ();
4651 use_operand_p use_p = PHI_ARG_DEF_PTR_FROM_EDGE (phi, e);
4652 tree arg = USE_FROM_PTR (use_p);
4653 if (TREE_CODE (arg) != SSA_NAME
4654 || virtual_operand_p (arg))
4655 continue;
4656 tree val = fwprop_ssa_val (arg);
4657 if (val != arg
4658 && may_propagate_copy (arg, val, !(e->flags & EDGE_ABNORMAL)))
4659 propagate_value (use_p, val);
4660 }
4661
4662 /* Mark outgoing exectuable edges. */
4663 if (edge e = find_taken_edge (bb, NULL))
4664 {
4665 e->flags |= EDGE_EXECUTABLE;
4666 if (EDGE_COUNT (bb->succs) > 1)
4667 cfg_changed = true;
4668 }
4669 else
4670 {
4671 FOR_EACH_EDGE (e, ei, bb->succs)
4672 e->flags |= EDGE_EXECUTABLE;
4673 }
4674 }
4675 free (postorder);
4676 free (bb_to_rpo);
4677 lattice.release ();
4678
4679 /* First remove chains of stmts where we check no uses remain. */
4680 simple_dce_from_worklist (simple_dce_worklist, to_purge);
4681
4682 auto remove = [](gimple *stmt)
4683 {
4684 if (dump_file && (dump_flags & TDF_DETAILS))
4685 {
4686 fprintf (dump_file, "Removing dead stmt ");
4687 print_gimple_stmt (dump_file, stmt, 0);
4688 fprintf (dump_file, "\n");
4689 }
4690 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
4691 if (gimple_code (stmt) == GIMPLE_PHI)
4692 remove_phi_node (&gsi, true);
4693 else
4694 {
4695 unlink_stmt_vdef (stmt);
4696 gsi_remove (&gsi, true);
4697 release_defs (stmt);
4698 }
4699 };
4700
4701 /* Then remove stmts we know we can remove even though we did not
4702 substitute in dead code regions, so uses can remain. Do so in reverse
4703 order to make debug stmt creation possible. */
4704 while (!to_remove_defs.is_empty())
4705 {
4706 tree def = ssa_name (to_remove_defs.pop ());
4707 /* For example remove_prop_source_from_use can remove stmts queued
4708 for removal. Deal with this gracefully. */
4709 if (!def)
4710 continue;
4711 gimple *stmt = SSA_NAME_DEF_STMT (def);
4712 remove (stmt);
4713 }
4714
4715 /* Wipe other queued stmts that do not have SSA defs. */
4716 while (!to_remove.is_empty())
4717 {
4718 gimple *stmt = to_remove.pop ();
4719 remove (stmt);
4720 }
4721
4722 /* Fixup stmts that became noreturn calls. This may require splitting
4723 blocks and thus isn't possible during the walk. Do this
4724 in reverse order so we don't inadvertedly remove a stmt we want to
4725 fixup by visiting a dominating now noreturn call first. */
4726 while (!to_fixup.is_empty ())
4727 {
4728 gimple *stmt = to_fixup.pop ();
4729 if (dump_file && dump_flags & TDF_DETAILS)
4730 {
4731 fprintf (dump_file, "Fixing up noreturn call ");
4732 print_gimple_stmt (dump_file, stmt, 0);
4733 fprintf (dump_file, "\n");
4734 }
4735 cfg_changed |= fixup_noreturn_call (stmt);
4736 }
4737
4738 cfg_changed |= gimple_purge_all_dead_eh_edges (to_purge);
4739 cfg_changed |= gimple_purge_all_dead_abnormal_call_edges (need_ab_cleanup);
4740 BITMAP_FREE (to_purge);
4741
4742 /* Remove edges queued from switch stmt simplification. */
4743 for (auto ep : edges_to_remove)
4744 {
4745 basic_block src = BASIC_BLOCK_FOR_FN (fun, ep.first);
4746 basic_block dest = BASIC_BLOCK_FOR_FN (fun, ep.second);
4747 edge e;
4748 if (src && dest && (e = find_edge (src, dest)))
4749 {
4750 free_dominance_info (CDI_DOMINATORS);
4751 remove_edge (e);
4752 cfg_changed = true;
4753 }
4754 }
4755
4756 if (get_range_query (fun) != get_global_range_query ())
4757 disable_ranger (fun);
4758
4759 if (cfg_changed)
4760 todoflags |= TODO_cleanup_cfg;
4761
4762 return todoflags;
4763 }
4764
4765 } // anon namespace
4766
4767 gimple_opt_pass *
4768 make_pass_forwprop (gcc::context *ctxt)
4769 {
4770 return new pass_forwprop (ctxt);
4771 }