Debian Codegraph @

gcc/tree-ssa-phiopt.cc

raw
1 /* Optimization of PHI nodes by converting them into straightline code.
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 it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 3, or (at your option) any
9 later version.
10
11 GCC is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 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 "insn-codes.h"
25 #include "rtl.h"
26 #include "tree.h"
27 #include "gimple.h"
28 #include "cfghooks.h"
29 #include "tree-pass.h"
30 #include "ssa.h"
31 #include "tree-ssa.h"
32 #include "optabs-tree.h"
33 #include "insn-config.h"
34 #include "gimple-pretty-print.h"
35 #include "fold-const.h"
36 #include "stor-layout.h"
37 #include "cfganal.h"
38 #include "gimplify.h"
39 #include "gimple-iterator.h"
40 #include "gimplify-me.h"
41 #include "tree-cfg.h"
42 #include "tree-dfa.h"
43 #include "domwalk.h"
44 #include "cfgloop.h"
45 #include "tree-data-ref.h"
46 #include "tree-scalar-evolution.h"
47 #include "tree-inline.h"
48 #include "case-cfn-macros.h"
49 #include "tree-eh.h"
50 #include "gimple-fold.h"
51 #include "internal-fn.h"
52 #include "gimple-range.h"
53 #include "gimple-match.h"
54 #include "dbgcnt.h"
55 #include "tree-ssa-propagate.h"
56 #include "tree-ssa-dce.h"
57 #include "calls.h"
58 #include "tree-ssa-loop-niter.h"
59
60 /* Return the singleton PHI in the SEQ of PHIs for edges E0 and E1. */
61
62 static gphi *
63 single_non_singleton_phi_for_edges (gimple_seq seq, edge e0, edge e1)
64 {
65 gimple_stmt_iterator i;
66 gphi *phi = NULL;
67 for (i = gsi_start (seq); !gsi_end_p (i); gsi_next (&i))
68 {
69 gphi *p = as_a <gphi *> (gsi_stmt (i));
70 /* If the PHI arguments are equal then we can skip this PHI. */
71 if (operand_equal_for_phi_arg_p (gimple_phi_arg_def (p, e0->dest_idx),
72 gimple_phi_arg_def (p, e1->dest_idx)))
73 continue;
74
75 /* Punt on virtual phis with different arguments from the edges. */
76 if (virtual_operand_p (gimple_phi_result (p)))
77 return NULL;
78
79 /* If we already have a PHI that has the two edge arguments are
80 different, then return it is not a singleton for these PHIs. */
81 if (phi)
82 return NULL;
83
84 phi = p;
85 }
86 return phi;
87 }
88
89 /* Replace PHI node element whose edge is E in block BB with variable NEW.
90 Remove the edge from COND_BLOCK which does not lead to BB (COND_BLOCK
91 is known to have two edges, one of which must reach BB). */
92
93 static void
94 replace_phi_edge_with_variable (basic_block cond_block,
95 edge e, gphi *phi, tree new_tree,
96 bitmap dce_ssa_names = nullptr)
97 {
98 basic_block bb = gimple_bb (phi);
99 gimple_stmt_iterator gsi;
100 tree phi_result = gimple_phi_result (phi);
101 bool deleteboth = false;
102
103 /* Duplicate range info if they are the only things setting the target PHI.
104 This is needed as later on, the new_tree will be replacing
105 The assignement of the PHI.
106 For an example:
107 bb1:
108 _4 = min<a_1, 255>
109 goto bb2
110
111 # RANGE [-INF, 255]
112 a_3 = PHI<_4(1)>
113 bb3:
114
115 use(a_3)
116 And _4 gets propagated into the use of a_3 and losing the range info.
117 This can't be done for more than 2 incoming edges as the propagation
118 won't happen.
119 The new_tree needs to be defined in the same basic block as the conditional. */
120 if (TREE_CODE (new_tree) == SSA_NAME
121 && EDGE_COUNT (gimple_bb (phi)->preds) == 2
122 && INTEGRAL_TYPE_P (TREE_TYPE (phi_result))
123 && !SSA_NAME_RANGE_INFO (new_tree)
124 && SSA_NAME_RANGE_INFO (phi_result)
125 && gimple_bb (SSA_NAME_DEF_STMT (new_tree)) == cond_block
126 && dbg_cnt (phiopt_edge_range))
127 duplicate_ssa_name_range_info (new_tree, phi_result);
128
129 /* Change the PHI argument to new. */
130 SET_USE (PHI_ARG_DEF_PTR (phi, e->dest_idx), new_tree);
131
132 /* Remove the empty basic block. */
133 edge edge_to_remove = NULL, keep_edge = NULL;
134 if (EDGE_SUCC (cond_block, 0)->dest == bb)
135 {
136 edge_to_remove = EDGE_SUCC (cond_block, 1);
137 keep_edge = EDGE_SUCC (cond_block, 0);
138 }
139 else if (EDGE_SUCC (cond_block, 1)->dest == bb)
140 {
141 edge_to_remove = EDGE_SUCC (cond_block, 0);
142 keep_edge = EDGE_SUCC (cond_block, 1);
143 }
144 else if ((keep_edge = find_edge (cond_block, e->src)))
145 {
146 basic_block bb1 = EDGE_SUCC (cond_block, 0)->dest;
147 basic_block bb2 = EDGE_SUCC (cond_block, 1)->dest;
148 if (single_pred_p (bb1) && single_pred_p (bb2)
149 && single_succ_p (bb1) && single_succ_p (bb2)
150 && empty_block_p (bb1) && empty_block_p (bb2))
151 deleteboth = true;
152 }
153 else
154 gcc_unreachable ();
155
156 /* If we are removing the cond on a loop exit,
157 reset number of iteration information of the loop. */
158 if (loop_exits_from_bb_p (cond_block->loop_father, cond_block))
159 {
160 auto loop = cond_block->loop_father;
161 free_numbers_of_iterations_estimates (loop);
162 loop->any_upper_bound = false;
163 loop->any_likely_upper_bound = false;
164 }
165
166 if (edge_to_remove && EDGE_COUNT (edge_to_remove->dest->preds) == 1)
167 {
168 e->flags |= EDGE_FALLTHRU;
169 e->flags &= ~(EDGE_TRUE_VALUE | EDGE_FALSE_VALUE);
170 e->probability = profile_probability::always ();
171 delete_basic_block (edge_to_remove->dest);
172
173 /* Eliminate the COND_EXPR at the end of COND_BLOCK. */
174 gsi = gsi_last_bb (cond_block);
175 gsi_remove (&gsi, true);
176 }
177 else if (deleteboth)
178 {
179 basic_block bb1 = EDGE_SUCC (cond_block, 0)->dest;
180 basic_block bb2 = EDGE_SUCC (cond_block, 1)->dest;
181
182 edge newedge = redirect_edge_and_branch (keep_edge, bb);
183
184 /* The new edge should be the same. */
185 gcc_assert (newedge == keep_edge);
186
187 keep_edge->flags |= EDGE_FALLTHRU;
188 keep_edge->flags &= ~(EDGE_TRUE_VALUE | EDGE_FALSE_VALUE);
189 keep_edge->probability = profile_probability::always ();
190
191 /* Copy the edge's phi entry from the old one. */
192 copy_phi_arg_into_existing_phi (e, keep_edge);
193
194 /* Delete the old 2 empty basic blocks */
195 delete_basic_block (bb1);
196 delete_basic_block (bb2);
197
198 /* Eliminate the COND_EXPR at the end of COND_BLOCK. */
199 gsi = gsi_last_bb (cond_block);
200 gsi_remove (&gsi, true);
201 }
202 else
203 {
204 /* If there are other edges into the middle block make
205 CFG cleanup deal with the edge removal to avoid
206 updating dominators here in a non-trivial way. */
207 gcond *cond = as_a <gcond *> (*gsi_last_bb (cond_block));
208 if (keep_edge->flags & EDGE_FALSE_VALUE)
209 gimple_cond_make_false (cond);
210 else if (keep_edge->flags & EDGE_TRUE_VALUE)
211 gimple_cond_make_true (cond);
212 }
213
214 if (dce_ssa_names)
215 simple_dce_from_worklist (dce_ssa_names);
216
217 statistics_counter_event (cfun, "Replace PHI with variable", 1);
218
219 if (dump_file && (dump_flags & TDF_DETAILS))
220 fprintf (dump_file,
221 "COND_EXPR in block %d and PHI in block %d converted to straightline code.\n",
222 cond_block->index,
223 bb->index);
224 }
225
226 /* Returns true if the ARG used from DEF_STMT is profitable to move
227 to a PHI node of the basic block MERGE where the new statement
228 will be located. */
229 static bool
230 is_factor_profitable (gimple *def_stmt, basic_block merge, tree arg)
231 {
232 /* The defining statement should be conditional. */
233 if (dominated_by_p (CDI_DOMINATORS, merge,
234 gimple_bb (def_stmt)))
235 return false;
236
237 /* If the arg is invariant, then there is
238 no extending of the live range. */
239 if (is_gimple_min_invariant (arg))
240 return true;
241
242 /* Otherwise, the arg needs to be a ssa name. */
243 if (TREE_CODE (arg) != SSA_NAME)
244 return false;
245
246 /* We should not increase the live range of arg
247 across too many statements or calls. */
248 gimple_stmt_iterator gsi = gsi_for_stmt (def_stmt);
249 gsi_next_nondebug (&gsi);
250
251 /* Skip past nops and predicates. */
252 while (!gsi_end_p (gsi)
253 && (gimple_code (gsi_stmt (gsi)) == GIMPLE_NOP
254 || gimple_code (gsi_stmt (gsi)) == GIMPLE_PREDICT))
255 gsi_next_nondebug (&gsi);
256
257 /* If the defining statement is at the end of the bb, then it is
258 always profitable to be to move. */
259 if (gsi_end_p (gsi))
260 return true;
261
262 /* Check if the uses of arg is dominated by merge block, this is a quick and
263 rough estimate if arg is still alive at the merge bb. */
264 /* FIXME: extend to a more complete live range detection. */
265 use_operand_p use_p;
266 imm_use_iterator iter;
267 FOR_EACH_IMM_USE_FAST (use_p, iter, arg)
268 {
269 gimple *use_stmt = USE_STMT (use_p);
270 if (is_gimple_debug (use_stmt))
271 continue;
272 basic_block use_bb = gimple_bb (use_stmt);
273 if (dominated_by_p (CDI_DOMINATORS, merge, use_bb))
274 return true;
275 }
276
277 /* If there are a few (non-call/asm) statements between
278 the old defining statement and end of the bb, then
279 the live range of new arg does not increase enough. */
280 int max_statements = param_phiopt_factor_max_stmts_live;
281
282 while (!gsi_end_p (gsi))
283 {
284 gimple *stmt = gsi_stmt (gsi);
285 auto gcode = gimple_code (stmt);
286 /* Skip over NOPs and predicts. */
287 if (gcode == GIMPLE_NOP
288 || gcode == GIMPLE_PREDICT)
289 {
290 gsi_next_nondebug (&gsi);
291 continue;
292 }
293 /* Non-assigns will extend the live range too much. */
294 if (gcode != GIMPLE_ASSIGN)
295 return false;
296 max_statements --;
297 if (max_statements == 0)
298 return false;
299 gsi_next_nondebug (&gsi);
300 }
301 return true;
302 }
303
304 /* PR66726: Factor operations out of COND_EXPR. If the arguments of the PHI
305 stmt are Unary operator, factor out the operation and perform the operation
306 to the result of PHI stmt. COND_STMT is the controlling predicate.
307 Return true if the operation was factored out; false otherwise. */
308
309 static bool
310 factor_out_conditional_operation (edge e0, edge e1, basic_block merge,
311 gphi *phi, gimple *cond_stmt)
312 {
313 gimple *arg0_def_stmt = NULL, *arg1_def_stmt = NULL;
314 tree temp, result;
315 gphi *newphi;
316 gimple_stmt_iterator gsi, gsi_for_def;
317 location_t locus = gimple_location (phi);
318 gimple_match_op arg0_op, arg1_op;
319
320 /* We should only get here if the phi had two arguments. */
321 gcc_assert (gimple_phi_num_args (phi) == 2);
322
323 /* Virtual operands are never handled. */
324 if (virtual_operand_p (gimple_phi_result (phi)))
325 return false;
326
327 tree arg0 = gimple_phi_arg_def (phi, e0->dest_idx);
328 tree arg1 = gimple_phi_arg_def (phi, e1->dest_idx);
329 gcc_assert (arg0 != NULL_TREE && arg1 != NULL_TREE);
330
331 /* Arugments that are the same don't have anything to be
332 done to them. */
333 if (operand_equal_for_phi_arg_p (arg0, arg1))
334 return false;
335
336 /* First canonicalize to simplify tests. */
337 if (TREE_CODE (arg0) != SSA_NAME)
338 {
339 std::swap (arg0, arg1);
340 std::swap (e0, e1);
341 }
342
343 if (TREE_CODE (arg0) != SSA_NAME
344 || (TREE_CODE (arg1) != SSA_NAME
345 && TREE_CODE (arg1) != INTEGER_CST))
346 return false;
347
348 /* Check if arg0 is an SSA_NAME and the stmt which defines arg0 is
349 an unary operation. */
350 arg0_def_stmt = SSA_NAME_DEF_STMT (arg0);
351 if (!gimple_extract_op (arg0_def_stmt, &arg0_op))
352 return false;
353
354 /* Check to make sure none of the operands are in abnormal phis. */
355 if (arg0_op.operands_occurs_in_abnormal_phi ())
356 return false;
357
358 /* Currently just support one operand expressions. */
359 if (arg0_op.num_ops != 1)
360 return false;
361
362 tree new_arg0 = arg0_op.ops[0];
363 tree new_arg1;
364
365 /* If arg0 have > 1 use, then this transformation actually increases
366 the number of expressions evaluated at runtime. */
367 if (!has_single_use (arg0))
368 return false;
369 if (!is_factor_profitable (arg0_def_stmt, merge, new_arg0))
370 return false;
371
372 if (TREE_CODE (arg1) == SSA_NAME)
373 {
374 /* Check if arg1 is an SSA_NAME. */
375 arg1_def_stmt = SSA_NAME_DEF_STMT (arg1);
376 if (!gimple_extract_op (arg1_def_stmt, &arg1_op))
377 return false;
378 if (arg1_op.code != arg0_op.code)
379 return false;
380 if (arg1_op.num_ops != arg0_op.num_ops)
381 return false;
382 if (arg1_op.operands_occurs_in_abnormal_phi ())
383 return false;
384
385 /* If arg1 have > 1 use, then this transformation actually increases
386 the number of expressions evaluated at runtime. */
387 if (!has_single_use (arg1))
388 return false;
389
390 new_arg1 = arg1_op.ops[0];
391
392 if (!is_factor_profitable (arg1_def_stmt, merge, new_arg1))
393 return false;
394 }
395 else
396 {
397 /* For constants only handle if the phi was the only one. */
398 if (single_non_singleton_phi_for_edges (phi_nodes (merge), e0, e1) == NULL)
399 return false;
400 /* TODO: handle more than just casts here. */
401 if (!gimple_assign_cast_p (arg0_def_stmt))
402 return false;
403
404 /* arg0_def_stmt should be conditional. */
405 if (dominated_by_p (CDI_DOMINATORS, gimple_bb (phi), gimple_bb (arg0_def_stmt)))
406 return false;
407
408 /* If arg1 is an INTEGER_CST, fold it to new type if it fits, or else
409 if the bits will not be modified during the conversion, except for
410 boolean types whose precision is not 1 (see int_fits_type_p). */
411 if (!INTEGRAL_TYPE_P (TREE_TYPE (new_arg0))
412 || !(int_fits_type_p (arg1, TREE_TYPE (new_arg0))
413 || (TYPE_PRECISION (TREE_TYPE (new_arg0))
414 == TYPE_PRECISION (TREE_TYPE (arg1))
415 && (TREE_CODE (TREE_TYPE (new_arg0)) != BOOLEAN_TYPE
416 || TYPE_PRECISION (TREE_TYPE (new_arg0)) == 1))))
417 return false;
418
419 /* For the INTEGER_CST case, we are just moving the
420 conversion from one place to another, which can often
421 hurt as the conversion moves further away from the
422 statement that computes the value. So, perform this
423 only if new_arg0 is an operand of COND_STMT, or
424 if arg0_def_stmt is the only non-debug stmt in
425 its basic block, because then it is possible this
426 could enable further optimizations (minmax replacement
427 etc.). See PR71016.
428 Note no-op conversions don't have this issue as
429 it will not generate any zero/sign extend in that case. */
430 if ((TYPE_PRECISION (TREE_TYPE (new_arg0))
431 != TYPE_PRECISION (TREE_TYPE (arg1)))
432 && new_arg0 != gimple_cond_lhs (cond_stmt)
433 && new_arg0 != gimple_cond_rhs (cond_stmt)
434 && gimple_bb (arg0_def_stmt) == e0->src)
435 {
436 gsi = gsi_for_stmt (arg0_def_stmt);
437 gsi_prev_nondebug (&gsi);
438 /* Ignore nops, predicates and labels. */
439 while (!gsi_end_p (gsi)
440 && (gimple_code (gsi_stmt (gsi)) == GIMPLE_NOP
441 || gimple_code (gsi_stmt (gsi)) == GIMPLE_PREDICT
442 || gimple_code (gsi_stmt (gsi)) == GIMPLE_LABEL))
443 gsi_prev_nondebug (&gsi);
444
445 if (!gsi_end_p (gsi))
446 {
447 gimple *stmt = gsi_stmt (gsi);
448 if (gassign *assign = dyn_cast <gassign *> (stmt))
449 {
450 tree lhs = gimple_assign_lhs (assign);
451 tree lhst = TREE_TYPE (lhs);
452 enum tree_code ass_code
453 = gimple_assign_rhs_code (assign);
454 if (ass_code != MAX_EXPR && ass_code != MIN_EXPR
455 /* Conversions from boolean like types is ok
456 as `a?1:b` and `a?0:b` will always simplify
457 to `a & b` or `a | b`.
458 See PR 116890. */
459 && !(INTEGRAL_TYPE_P (lhst)
460 && TYPE_UNSIGNED (lhst)
461 && TYPE_PRECISION (lhst) == 1))
462 return false;
463 if (lhs != gimple_assign_rhs1 (arg0_def_stmt))
464 return false;
465 gsi_prev_nondebug (&gsi);
466 if (!gsi_end_p (gsi))
467 return false;
468 }
469 else
470 return false;
471 }
472 }
473 new_arg1 = fold_convert (TREE_TYPE (new_arg0), arg1);
474
475 /* Drop the overlow that fold_convert might add. */
476 if (TREE_OVERFLOW (new_arg1))
477 new_arg1 = drop_tree_overflow (new_arg1);
478 }
479
480 /* If types of new_arg0 and new_arg1 are different bailout. */
481 if (!types_compatible_p (TREE_TYPE (new_arg0), TREE_TYPE (new_arg1)))
482 return false;
483
484 /* Create a new PHI stmt. */
485 result = gimple_phi_result (phi);
486 temp = make_ssa_name (TREE_TYPE (new_arg0), NULL);
487
488 gimple_match_op new_op = arg0_op;
489
490 /* Create the operation stmt if possible and insert it. */
491 new_op.ops[0] = temp;
492 gimple_seq seq = NULL;
493 result = maybe_push_res_to_seq (&new_op, &seq, result);
494
495 /* If we can't create the new statement, release the temp name
496 and return back. */
497 if (!result)
498 {
499 release_ssa_name (temp);
500 return false;
501 }
502
503 gsi = gsi_after_labels (gimple_bb (phi));
504 gsi_insert_seq_before (&gsi, seq, GSI_CONTINUE_LINKING);
505
506 newphi = create_phi_node (temp, gimple_bb (phi));
507
508 if (dump_file && (dump_flags & TDF_DETAILS))
509 {
510 fprintf (dump_file, "PHI ");
511 print_generic_expr (dump_file, gimple_phi_result (phi));
512 fprintf (dump_file,
513 " changed to factor operation out from COND_EXPR.\n");
514 fprintf (dump_file, "New stmt with OPERATION that defines ");
515 print_generic_expr (dump_file, result);
516 fprintf (dump_file, ".\n");
517 }
518
519 /* Remove the old operation(s) that has single use. */
520 gsi_for_def = gsi_for_stmt (arg0_def_stmt);
521 gsi_remove (&gsi_for_def, true);
522 release_defs (arg0_def_stmt);
523
524 if (arg1_def_stmt)
525 {
526 gsi_for_def = gsi_for_stmt (arg1_def_stmt);
527 gsi_remove (&gsi_for_def, true);
528 release_defs (arg1_def_stmt);
529 }
530
531 add_phi_arg (newphi, new_arg0, e0, locus);
532 add_phi_arg (newphi, new_arg1, e1, locus);
533
534 /* Remove the original PHI stmt. */
535 gsi = gsi_for_stmt (phi);
536 gsi_remove (&gsi, true);
537
538 statistics_counter_event (cfun, "factored out operation", 1);
539
540 return true;
541 }
542
543
544 /* Return TRUE if SEQ/OP pair should be allowed during early phiopt.
545 Currently this is to allow MIN/MAX and ABS/NEGATE and constants. */
546 static bool
547 phiopt_early_allow (gimple_seq &seq, gimple_match_op &op)
548 {
549 /* Don't allow functions. */
550 if (!op.code.is_tree_code ())
551 return false;
552 tree_code code = (tree_code)op.code;
553
554 /* For non-empty sequence, only allow one statement
555 except for MIN/MAX, allow max 2 statements,
556 each with MIN/MAX. */
557 if (!gimple_seq_empty_p (seq))
558 {
559 if (code == MIN_EXPR || code == MAX_EXPR)
560 {
561 if (!gimple_seq_singleton_p (seq))
562 return false;
563
564 gimple *stmt = gimple_seq_first_stmt (seq);
565 /* Only allow assignments. */
566 if (!is_gimple_assign (stmt))
567 return false;
568 code = gimple_assign_rhs_code (stmt);
569 return code == MIN_EXPR || code == MAX_EXPR;
570 }
571 /* Check to make sure op was already a SSA_NAME. */
572 if (code != SSA_NAME)
573 return false;
574 if (!gimple_seq_singleton_p (seq))
575 return false;
576 gimple *stmt = gimple_seq_first_stmt (seq);
577 /* Only allow assignments. */
578 if (!is_gimple_assign (stmt))
579 return false;
580 if (gimple_assign_lhs (stmt) != op.ops[0])
581 return false;
582 code = gimple_assign_rhs_code (stmt);
583 }
584
585 switch (code)
586 {
587 case MIN_EXPR:
588 case MAX_EXPR:
589 case ABS_EXPR:
590 case ABSU_EXPR:
591 case NEGATE_EXPR:
592 case SSA_NAME:
593 return true;
594 case INTEGER_CST:
595 case REAL_CST:
596 case VECTOR_CST:
597 case FIXED_CST:
598 return true;
599 default:
600 return false;
601 }
602 }
603
604 /* gimple_simplify_phiopt is like gimple_simplify but designed for PHIOPT.
605 Return NULL if nothing can be simplified or the resulting simplified value
606 with parts pushed if EARLY_P was true. Also rejects non allowed tree code
607 if EARLY_P is set.
608 Takes the comparison from COMP_STMT and two args, ARG0 and ARG1 and tries
609 to simplify CMP ? ARG0 : ARG1.
610 Also try to simplify (!CMP) ? ARG1 : ARG0 if the non-inverse failed. */
611 static tree
612 gimple_simplify_phiopt (bool early_p, tree type, gimple *comp_stmt,
613 tree arg0, tree arg1,
614 gimple_seq *seq)
615 {
616 gimple_seq seq1 = NULL;
617 enum tree_code comp_code = gimple_cond_code (comp_stmt);
618 location_t loc = gimple_location (comp_stmt);
619 tree cmp0 = gimple_cond_lhs (comp_stmt);
620 tree cmp1 = gimple_cond_rhs (comp_stmt);
621 /* To handle special cases like floating point comparison, it is easier and
622 less error-prone to build a tree and gimplify it on the fly though it is
623 less efficient.
624 Don't use fold_build2 here as that might create (bool)a instead of just
625 "a != 0". */
626 tree cond = build2_loc (loc, comp_code, boolean_type_node,
627 cmp0, cmp1);
628
629 if (dump_file && (dump_flags & TDF_FOLDING))
630 {
631 fprintf (dump_file, "\nphiopt match-simplify trying:\n\t");
632 print_generic_expr (dump_file, cond);
633 fprintf (dump_file, " ? ");
634 print_generic_expr (dump_file, arg0);
635 fprintf (dump_file, " : ");
636 print_generic_expr (dump_file, arg1);
637 fprintf (dump_file, "\n");
638 }
639
640 gimple_match_op op (gimple_match_cond::UNCOND,
641 COND_EXPR, type, cond, arg0, arg1);
642
643 if (op.resimplify (&seq1, follow_all_ssa_edges))
644 {
645 bool allowed = !early_p || phiopt_early_allow (seq1, op);
646 tree result = maybe_push_res_to_seq (&op, &seq1);
647 if (dump_file && (dump_flags & TDF_FOLDING))
648 {
649 fprintf (dump_file, "\nphiopt match-simplify back:\n");
650 if (seq1)
651 print_gimple_seq (dump_file, seq1, 0, TDF_VOPS|TDF_MEMSYMS);
652 fprintf (dump_file, "result: ");
653 if (result)
654 print_generic_expr (dump_file, result);
655 else
656 fprintf (dump_file, " (none)");
657 fprintf (dump_file, "\n");
658 if (!allowed)
659 fprintf (dump_file, "rejected because early\n");
660 }
661 /* Early we want only to allow some generated tree codes. */
662 if (allowed && result)
663 {
664 if (loc != UNKNOWN_LOCATION)
665 annotate_all_with_location (seq1, loc);
666 gimple_seq_add_seq_without_update (seq, seq1);
667 return result;
668 }
669 }
670 gimple_seq_discard (seq1);
671 seq1 = NULL;
672
673 /* Try the inverted comparison, that is !COMP ? ARG1 : ARG0. */
674 comp_code = invert_tree_comparison (comp_code, HONOR_NANS (cmp0));
675
676 if (comp_code == ERROR_MARK)
677 return NULL;
678
679 cond = build2_loc (loc,
680 comp_code, boolean_type_node,
681 cmp0, cmp1);
682
683 if (dump_file && (dump_flags & TDF_FOLDING))
684 {
685 fprintf (dump_file, "\nphiopt match-simplify trying:\n\t");
686 print_generic_expr (dump_file, cond);
687 fprintf (dump_file, " ? ");
688 print_generic_expr (dump_file, arg1);
689 fprintf (dump_file, " : ");
690 print_generic_expr (dump_file, arg0);
691 fprintf (dump_file, "\n");
692 }
693
694 gimple_match_op op1 (gimple_match_cond::UNCOND,
695 COND_EXPR, type, cond, arg1, arg0);
696
697 if (op1.resimplify (&seq1, follow_all_ssa_edges))
698 {
699 bool allowed = !early_p || phiopt_early_allow (seq1, op1);
700 tree result = maybe_push_res_to_seq (&op1, &seq1);
701 if (dump_file && (dump_flags & TDF_FOLDING))
702 {
703 fprintf (dump_file, "\nphiopt match-simplify back:\n");
704 if (seq1)
705 print_gimple_seq (dump_file, seq1, 0, TDF_VOPS|TDF_MEMSYMS);
706 fprintf (dump_file, "result: ");
707 if (result)
708 print_generic_expr (dump_file, result);
709 else
710 fprintf (dump_file, " (none)");
711 fprintf (dump_file, "\n");
712 if (!allowed)
713 fprintf (dump_file, "rejected because early\n");
714 }
715 /* Early we want only to allow some generated tree codes. */
716 if (allowed && result)
717 {
718 if (loc != UNKNOWN_LOCATION)
719 annotate_all_with_location (seq1, loc);
720 gimple_seq_add_seq_without_update (seq, seq1);
721 return result;
722 }
723 }
724 gimple_seq_discard (seq1);
725
726 return NULL;
727 }
728
729 /* empty_bb_or_one_feeding_into_p returns true if bb was empty basic block
730 or it has one cheap preparation statement that feeds into the PHI
731 statement and it sets STMT to that statement. */
732 static bool
733 empty_bb_or_one_feeding_into_p (basic_block bb,
734 gimple *phi,
735 gimple *&stmt)
736 {
737 stmt = nullptr;
738 gimple *stmt_to_move = nullptr;
739 tree lhs;
740
741 if (empty_block_p (bb))
742 return true;
743
744 if (!single_pred_p (bb))
745 return false;
746
747 /* The middle bb cannot have phi nodes as we don't
748 move those assignments yet. */
749 if (!gimple_seq_empty_p (phi_nodes (bb)))
750 return false;
751
752 gimple_stmt_iterator gsi;
753
754 gsi = gsi_start_nondebug_after_labels_bb (bb);
755 while (!gsi_end_p (gsi))
756 {
757 gimple *s = gsi_stmt (gsi);
758 gsi_next_nondebug (&gsi);
759 /* Skip over Predict and nop statements. */
760 if (gimple_code (s) == GIMPLE_PREDICT
761 || gimple_code (s) == GIMPLE_NOP)
762 continue;
763 /* If there is more one statement return false. */
764 if (stmt_to_move)
765 return false;
766 stmt_to_move = s;
767 }
768
769 /* The only statement here was a Predict or a nop statement
770 so return true. */
771 if (!stmt_to_move)
772 return true;
773
774 if (gimple_vuse (stmt_to_move))
775 return false;
776
777 if (gimple_could_trap_p (stmt_to_move)
778 || gimple_has_side_effects (stmt_to_move))
779 return false;
780
781 ssa_op_iter it;
782 tree use;
783 FOR_EACH_SSA_TREE_OPERAND (use, stmt_to_move, it, SSA_OP_USE)
784 if (ssa_name_maybe_undef_p (use))
785 return false;
786
787 /* Allow assignments but allow some builtin/internal calls.
788 As const calls don't match any of the above, yet they could
789 still have some side-effects - they could contain
790 gimple_could_trap_p statements, like floating point
791 exceptions or integer division by zero. See PR70586.
792 FIXME: perhaps gimple_has_side_effects or gimple_could_trap_p
793 should handle this.
794 Allow some known builtin/internal calls that are known not to
795 trap: logical functions (e.g. bswap and bit counting). */
796 if (!is_gimple_assign (stmt_to_move))
797 {
798 if (!is_gimple_call (stmt_to_move))
799 return false;
800 combined_fn cfn = gimple_call_combined_fn (stmt_to_move);
801 switch (cfn)
802 {
803 default:
804 return false;
805 case CFN_BUILT_IN_BSWAP16:
806 case CFN_BUILT_IN_BSWAP32:
807 case CFN_BUILT_IN_BSWAP64:
808 case CFN_BUILT_IN_BSWAP128:
809 CASE_CFN_FFS:
810 CASE_CFN_PARITY:
811 CASE_CFN_POPCOUNT:
812 CASE_CFN_CLZ:
813 CASE_CFN_CTZ:
814 case CFN_BUILT_IN_CLRSB:
815 case CFN_BUILT_IN_CLRSBL:
816 case CFN_BUILT_IN_CLRSBLL:
817 lhs = gimple_call_lhs (stmt_to_move);
818 break;
819 }
820 }
821 else
822 lhs = gimple_assign_lhs (stmt_to_move);
823
824 gimple *use_stmt;
825 use_operand_p use_p;
826
827 /* Allow only a statement which feeds into the other stmt. */
828 if (!lhs || TREE_CODE (lhs) != SSA_NAME
829 || !single_imm_use (lhs, &use_p, &use_stmt)
830 || use_stmt != phi)
831 return false;
832
833 stmt = stmt_to_move;
834 return true;
835 }
836
837 /* Move STMT to before GSI and insert its defining
838 name into INSERTED_EXPRS bitmap.
839 Also rewrite its if it might be undefined when unconditionalized. */
840 static void
841 move_stmt (gimple *stmt, gimple_stmt_iterator *gsi, auto_bitmap &inserted_exprs)
842 {
843 if (!stmt)
844 return;
845 if (dump_file && (dump_flags & TDF_DETAILS))
846 {
847 fprintf (dump_file, "statement un-sinked:\n");
848 print_gimple_stmt (dump_file, stmt, 0,
849 TDF_VOPS|TDF_MEMSYMS);
850 }
851
852 tree name = gimple_get_lhs (stmt);
853 // Mark the name to be renamed if there is one.
854 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (name));
855 gimple_stmt_iterator gsi1 = gsi_for_stmt (stmt);
856 gsi_move_before (&gsi1, gsi);
857 reset_flow_sensitive_info (name);
858
859 /* Rewrite some code which might be undefined when
860 unconditionalized. */
861 if (gimple_assign_single_p (stmt))
862 {
863 tree rhs = gimple_assign_rhs1 (stmt);
864 /* VCE from integral types to another integral types but with
865 different precisions need to be changed into casts
866 to be well defined when unconditional. */
867 if (gimple_assign_rhs_code (stmt) == VIEW_CONVERT_EXPR
868 && INTEGRAL_TYPE_P (TREE_TYPE (name))
869 && INTEGRAL_TYPE_P (TREE_TYPE (TREE_OPERAND (rhs, 0))))
870 {
871 if (dump_file && (dump_flags & TDF_DETAILS))
872 {
873 fprintf (dump_file, "rewriting stmt with maybe undefined VCE ");
874 print_gimple_stmt (dump_file, stmt, 0, TDF_SLIM);
875 }
876 tree new_rhs = TREE_OPERAND (rhs, 0);
877 gcc_assert (is_gimple_val (new_rhs));
878 gimple_assign_set_rhs_code (stmt, NOP_EXPR);
879 gimple_assign_set_rhs1 (stmt, new_rhs);
880 update_stmt (stmt);
881 }
882 }
883 }
884
885 /* RAII style class to temporarily remove flow sensitive
886 from ssa names defined by a gimple statement. */
887 class auto_flow_sensitive
888 {
889 public:
890 auto_flow_sensitive (gimple *s);
891 ~auto_flow_sensitive ();
892 private:
893 auto_vec<std::pair<tree, flow_sensitive_info_storage>, 2> stack;
894 };
895
896 /* Constructor for auto_flow_sensitive. Saves
897 off the ssa names' flow sensitive information
898 that was defined by gimple statement S and
899 resets it to be non-flow based ones. */
900
901 auto_flow_sensitive::auto_flow_sensitive (gimple *s)
902 {
903 if (!s)
904 return;
905 ssa_op_iter it;
906 tree def;
907 FOR_EACH_SSA_TREE_OPERAND (def, s, it, SSA_OP_DEF)
908 {
909 flow_sensitive_info_storage storage;
910 storage.save_and_clear (def);
911 stack.safe_push (std::make_pair (def, storage));
912 }
913 }
914
915 /* Deconstructor, restores the flow sensitive information
916 for the SSA names that had been saved off. */
917
918 auto_flow_sensitive::~auto_flow_sensitive ()
919 {
920 for (auto p : stack)
921 p.second.restore (p.first);
922 }
923
924 /* The function match_simplify_replacement does the main work of doing the
925 replacement using match and simplify. Return true if the replacement is done.
926 Otherwise return false.
927 BB is the basic block where the replacement is going to be done on. ARG0
928 is argument 0 from PHI. Likewise for ARG1. */
929
930 static bool
931 match_simplify_replacement (basic_block cond_bb, basic_block middle_bb,
932 basic_block middle_bb_alt,
933 edge e0, edge e1, gphi *phi,
934 tree arg0, tree arg1, bool early_p,
935 bool threeway_p)
936 {
937 gimple *stmt;
938 gimple_stmt_iterator gsi;
939 edge true_edge, false_edge;
940 gimple_seq seq = NULL;
941 tree result;
942 gimple *stmt_to_move = NULL;
943 gimple *stmt_to_move_alt = NULL;
944 tree arg_true, arg_false;
945
946 /* Special case A ? B : B as this will always simplify to B. */
947 if (operand_equal_for_phi_arg_p (arg0, arg1))
948 return false;
949
950 /* If the basic block only has a cheap preparation statement,
951 allow it and move it once the transformation is done. */
952 if (!empty_bb_or_one_feeding_into_p (middle_bb, phi, stmt_to_move))
953 return false;
954
955 if (threeway_p
956 && middle_bb != middle_bb_alt
957 && !empty_bb_or_one_feeding_into_p (middle_bb_alt, phi,
958 stmt_to_move_alt))
959 return false;
960
961 /* Do not make conditional undefs unconditional. */
962 if ((TREE_CODE (arg0) == SSA_NAME
963 && ssa_name_maybe_undef_p (arg0))
964 || (TREE_CODE (arg1) == SSA_NAME
965 && ssa_name_maybe_undef_p (arg1)))
966 return false;
967
968 /* At this point we know we have a GIMPLE_COND with two successors.
969 One successor is BB, the other successor is an empty block which
970 falls through into BB.
971
972 There is a single PHI node at the join point (BB).
973
974 So, given the condition COND, and the two PHI arguments, match and simplify
975 can happen on (COND) ? arg0 : arg1. */
976
977 stmt = last_nondebug_stmt (cond_bb);
978
979 /* We need to know which is the true edge and which is the false
980 edge so that we know when to invert the condition below. */
981 extract_true_false_edges_from_block (cond_bb, &true_edge, &false_edge);
982
983 /* Forward the edges over the middle basic block. */
984 if (true_edge->dest == middle_bb)
985 true_edge = EDGE_SUCC (true_edge->dest, 0);
986 if (false_edge->dest == middle_bb)
987 false_edge = EDGE_SUCC (false_edge->dest, 0);
988
989 /* When THREEWAY_P then e1 will point to the edge of the final transition
990 from middle-bb to end. */
991 if (true_edge == e0)
992 {
993 if (!threeway_p)
994 gcc_assert (false_edge == e1);
995 arg_true = arg0;
996 arg_false = arg1;
997 }
998 else
999 {
1000 gcc_assert (false_edge == e0);
1001 if (!threeway_p)
1002 gcc_assert (true_edge == e1);
1003 arg_true = arg1;
1004 arg_false = arg0;
1005 }
1006
1007 tree type = TREE_TYPE (gimple_phi_result (phi));
1008 {
1009 auto_flow_sensitive s1(stmt_to_move);
1010 auto_flow_sensitive s_alt(stmt_to_move_alt);
1011
1012 result = gimple_simplify_phiopt (early_p, type, stmt,
1013 arg_true, arg_false,
1014 &seq);
1015 }
1016
1017 if (!result)
1018 return false;
1019 if (dump_file && (dump_flags & TDF_FOLDING))
1020 fprintf (dump_file, "accepted the phiopt match-simplify.\n");
1021
1022 auto_bitmap exprs_maybe_dce;
1023
1024 /* Mark the cond statements' lhs/rhs as maybe dce. */
1025 if (TREE_CODE (gimple_cond_lhs (stmt)) == SSA_NAME
1026 && !SSA_NAME_IS_DEFAULT_DEF (gimple_cond_lhs (stmt)))
1027 bitmap_set_bit (exprs_maybe_dce,
1028 SSA_NAME_VERSION (gimple_cond_lhs (stmt)));
1029 if (TREE_CODE (gimple_cond_rhs (stmt)) == SSA_NAME
1030 && !SSA_NAME_IS_DEFAULT_DEF (gimple_cond_rhs (stmt)))
1031 bitmap_set_bit (exprs_maybe_dce,
1032 SSA_NAME_VERSION (gimple_cond_rhs (stmt)));
1033
1034 gsi = gsi_last_bb (cond_bb);
1035 /* Insert the sequence generated from gimple_simplify_phiopt. */
1036 if (seq)
1037 {
1038 // Mark the lhs of the new statements maybe for dce
1039 gimple_stmt_iterator gsi1 = gsi_start (seq);
1040 for (; !gsi_end_p (gsi1); gsi_next (&gsi1))
1041 {
1042 gimple *stmt = gsi_stmt (gsi1);
1043 tree name = gimple_get_lhs (stmt);
1044 if (name && TREE_CODE (name) == SSA_NAME)
1045 bitmap_set_bit (exprs_maybe_dce, SSA_NAME_VERSION (name));
1046 }
1047 gsi_insert_seq_before (&gsi, seq, GSI_CONTINUE_LINKING);
1048 }
1049
1050 /* If there was a statement to move, move it to right before
1051 the original conditional. */
1052 move_stmt (stmt_to_move, &gsi, exprs_maybe_dce);
1053 move_stmt (stmt_to_move_alt, &gsi, exprs_maybe_dce);
1054
1055 replace_phi_edge_with_variable (cond_bb, e1, phi, result, exprs_maybe_dce);
1056
1057 /* Add Statistic here even though replace_phi_edge_with_variable already
1058 does it as we want to be able to count when match-simplify happens vs
1059 the others. */
1060 statistics_counter_event (cfun, "match-simplify PHI replacement", 1);
1061
1062 /* Note that we optimized this PHI. */
1063 return true;
1064 }
1065
1066 /* Update *ARG which is defined in STMT so that it contains the
1067 computed value if that seems profitable. Return true if the
1068 statement is made dead by that rewriting. */
1069
1070 static bool
1071 jump_function_from_stmt (tree *arg, gimple *stmt)
1072 {
1073 enum tree_code code = gimple_assign_rhs_code (stmt);
1074 if (code == ADDR_EXPR)
1075 {
1076 /* For arg = &p->i transform it to p, if possible. */
1077 tree rhs1 = gimple_assign_rhs1 (stmt);
1078 poly_int64 offset;
1079 tree tem = get_addr_base_and_unit_offset (TREE_OPERAND (rhs1, 0),
1080 &offset);
1081 if (tem
1082 && TREE_CODE (tem) == MEM_REF
1083 && known_eq (mem_ref_offset (tem) + offset, 0))
1084 {
1085 *arg = TREE_OPERAND (tem, 0);
1086 return true;
1087 }
1088 }
1089 /* TODO: Much like IPA-CP jump-functions we want to handle constant
1090 additions symbolically here, and we'd need to update the comparison
1091 code that compares the arg + cst tuples in our caller. For now the
1092 code above exactly handles the VEC_BASE pattern from vec.h. */
1093 return false;
1094 }
1095
1096 /* RHS is a source argument in a BIT_AND_EXPR or BIT_IOR_EXPR which feeds
1097 a conditional of the form SSA_NAME NE 0.
1098
1099 If RHS is fed by a simple EQ_EXPR or NE_EXPR comparison of two values,
1100 see if the two input values of the comparison match arg0 and arg1.
1101
1102 If so update *code and return TRUE. Otherwise return FALSE. */
1103
1104 static bool
1105 rhs_is_fed_for_value_replacement (const_tree arg0, const_tree arg1,
1106 enum tree_code *code, const_tree rhs,
1107 enum tree_code bit_expression_code)
1108 {
1109 /* Obviously if RHS is not an SSA_NAME, we can't look at the defining
1110 statement. */
1111 if (TREE_CODE (rhs) == SSA_NAME)
1112 {
1113 gimple *def1 = SSA_NAME_DEF_STMT (rhs);
1114
1115 /* Verify the defining statement has an EQ_EXPR or NE_EXPR on the RHS. */
1116 if (is_gimple_assign (def1)
1117 && ((bit_expression_code == BIT_AND_EXPR
1118 && gimple_assign_rhs_code (def1) == EQ_EXPR)
1119 || (bit_expression_code == BIT_IOR_EXPR
1120 && gimple_assign_rhs_code (def1) == NE_EXPR)))
1121 {
1122 /* Finally verify the source operands of the EQ_EXPR or NE_EXPR
1123 are equal to arg0 and arg1. */
1124 tree op0 = gimple_assign_rhs1 (def1);
1125 tree op1 = gimple_assign_rhs2 (def1);
1126 if ((operand_equal_for_phi_arg_p (arg0, op0)
1127 && operand_equal_for_phi_arg_p (arg1, op1))
1128 || (operand_equal_for_phi_arg_p (arg0, op1)
1129 && operand_equal_for_phi_arg_p (arg1, op0)))
1130 {
1131 /* We will perform the optimization. */
1132 *code = gimple_assign_rhs_code (def1);
1133 return true;
1134 }
1135 }
1136 }
1137 return false;
1138 }
1139
1140 /* Return TRUE if arg0/arg1 are equal to the rhs/lhs or lhs/rhs of COND.
1141
1142 Also return TRUE if arg0/arg1 are equal to the source arguments of an
1143 EQ comparison feeding a BIT_AND_EXPR, or NE comparison feeding a
1144 BIT_IOR_EXPR which feeds COND.
1145
1146 Return FALSE otherwise. */
1147
1148 static bool
1149 operand_equal_for_value_replacement (const_tree arg0, const_tree arg1,
1150 enum tree_code *code, gimple *cond)
1151 {
1152 gimple *def;
1153 tree lhs = gimple_cond_lhs (cond);
1154 tree rhs = gimple_cond_rhs (cond);
1155
1156 if ((operand_equal_for_phi_arg_p (arg0, lhs)
1157 && operand_equal_for_phi_arg_p (arg1, rhs))
1158 || (operand_equal_for_phi_arg_p (arg1, lhs)
1159 && operand_equal_for_phi_arg_p (arg0, rhs)))
1160 return true;
1161
1162 /* Now handle more complex case where we have an EQ comparison
1163 feeding a BIT_AND_EXPR, or a NE comparison feeding a BIT_IOR_EXPR,
1164 which then feeds into COND.
1165
1166 First verify that COND is of the form SSA_NAME NE 0. */
1167 if (*code != NE_EXPR || !integer_zerop (rhs)
1168 || TREE_CODE (lhs) != SSA_NAME)
1169 return false;
1170
1171 /* Now ensure that SSA_NAME is set by a BIT_AND_EXPR or BIT_OR_EXPR. */
1172 def = SSA_NAME_DEF_STMT (lhs);
1173 if (!is_gimple_assign (def)
1174 || (gimple_assign_rhs_code (def) != BIT_AND_EXPR
1175 && gimple_assign_rhs_code (def) != BIT_IOR_EXPR))
1176 return false;
1177
1178 /* Now verify arg0/arg1 correspond to the source arguments of an EQ
1179 comparison feeding the BIT_AND_EXPR or a NE comparison feeding the
1180 BIT_IOR_EXPR. */
1181
1182 tree tmp = gimple_assign_rhs1 (def);
1183 if (rhs_is_fed_for_value_replacement (arg0, arg1, code, tmp,
1184 gimple_assign_rhs_code (def)))
1185 return true;
1186
1187 tmp = gimple_assign_rhs2 (def);
1188 if (rhs_is_fed_for_value_replacement (arg0, arg1, code, tmp,
1189 gimple_assign_rhs_code (def)))
1190 return true;
1191
1192 return false;
1193 }
1194
1195 /* Returns true if ARG is a neutral element for operation CODE
1196 on the RIGHT side. */
1197
1198 static bool
1199 neutral_element_p (tree_code code, tree arg, bool right)
1200 {
1201 switch (code)
1202 {
1203 case PLUS_EXPR:
1204 case BIT_IOR_EXPR:
1205 case BIT_XOR_EXPR:
1206 return integer_zerop (arg);
1207
1208 case LROTATE_EXPR:
1209 case RROTATE_EXPR:
1210 case LSHIFT_EXPR:
1211 case RSHIFT_EXPR:
1212 case MINUS_EXPR:
1213 case POINTER_PLUS_EXPR:
1214 return right && integer_zerop (arg);
1215
1216 case MULT_EXPR:
1217 return integer_onep (arg);
1218
1219 case TRUNC_DIV_EXPR:
1220 case CEIL_DIV_EXPR:
1221 case FLOOR_DIV_EXPR:
1222 case ROUND_DIV_EXPR:
1223 case EXACT_DIV_EXPR:
1224 return right && integer_onep (arg);
1225
1226 case BIT_AND_EXPR:
1227 return integer_all_onesp (arg);
1228
1229 default:
1230 return false;
1231 }
1232 }
1233
1234 /* Returns true if ARG is an absorbing element for operation CODE. */
1235
1236 static bool
1237 absorbing_element_p (tree_code code, tree arg, bool right, tree rval)
1238 {
1239 switch (code)
1240 {
1241 case BIT_IOR_EXPR:
1242 return integer_all_onesp (arg);
1243
1244 case MULT_EXPR:
1245 case BIT_AND_EXPR:
1246 return integer_zerop (arg);
1247
1248 case LSHIFT_EXPR:
1249 case RSHIFT_EXPR:
1250 case LROTATE_EXPR:
1251 case RROTATE_EXPR:
1252 return !right && integer_zerop (arg);
1253
1254 case TRUNC_DIV_EXPR:
1255 case CEIL_DIV_EXPR:
1256 case FLOOR_DIV_EXPR:
1257 case ROUND_DIV_EXPR:
1258 case EXACT_DIV_EXPR:
1259 case TRUNC_MOD_EXPR:
1260 case CEIL_MOD_EXPR:
1261 case FLOOR_MOD_EXPR:
1262 case ROUND_MOD_EXPR:
1263 return (!right
1264 && integer_zerop (arg)
1265 && tree_single_nonzero_warnv_p (rval, NULL));
1266
1267 default:
1268 return false;
1269 }
1270 }
1271
1272 /* The function value_replacement does the main work of doing the value
1273 replacement. Return non-zero if the replacement is done. Otherwise return
1274 0. If we remove the middle basic block, return 2.
1275 BB is the basic block where the replacement is going to be done on. ARG0
1276 is argument 0 from the PHI. Likewise for ARG1. */
1277
1278 static int
1279 value_replacement (basic_block cond_bb, basic_block middle_bb,
1280 edge e0, edge e1, gphi *phi, tree arg0, tree arg1)
1281 {
1282 gimple_stmt_iterator gsi;
1283 edge true_edge, false_edge;
1284 enum tree_code code;
1285 bool empty_or_with_defined_p = true;
1286
1287 /* Virtual operands don't need to be handled. */
1288 if (virtual_operand_p (arg1))
1289 return 0;
1290
1291 /* Special case A ? B : B as this will always simplify to B. */
1292 if (operand_equal_for_phi_arg_p (arg0, arg1))
1293 return 0;
1294
1295 gcond *cond = as_a <gcond *> (*gsi_last_bb (cond_bb));
1296 code = gimple_cond_code (cond);
1297
1298 /* This transformation is only valid for equality comparisons. */
1299 if (code != NE_EXPR && code != EQ_EXPR)
1300 return 0;
1301
1302 /* Do not make conditional undefs unconditional. */
1303 if ((TREE_CODE (arg0) == SSA_NAME
1304 && ssa_name_maybe_undef_p (arg0))
1305 || (TREE_CODE (arg1) == SSA_NAME
1306 && ssa_name_maybe_undef_p (arg1)))
1307 return false;
1308
1309 /* If the type says honor signed zeros we cannot do this
1310 optimization. */
1311 if (HONOR_SIGNED_ZEROS (arg1))
1312 return 0;
1313
1314 /* If there is a statement in MIDDLE_BB that defines one of the PHI
1315 arguments, then adjust arg0 or arg1. */
1316 gsi = gsi_start_nondebug_after_labels_bb (middle_bb);
1317 while (!gsi_end_p (gsi))
1318 {
1319 gimple *stmt = gsi_stmt (gsi);
1320 tree lhs;
1321 gsi_next_nondebug (&gsi);
1322 if (!is_gimple_assign (stmt))
1323 {
1324 if (gimple_code (stmt) != GIMPLE_PREDICT
1325 && gimple_code (stmt) != GIMPLE_NOP)
1326 empty_or_with_defined_p = false;
1327 continue;
1328 }
1329 /* Now try to adjust arg0 or arg1 according to the computation
1330 in the statement. */
1331 lhs = gimple_assign_lhs (stmt);
1332 if (!(lhs == arg0
1333 && jump_function_from_stmt (&arg0, stmt))
1334 || (lhs == arg1
1335 && jump_function_from_stmt (&arg1, stmt)))
1336 empty_or_with_defined_p = false;
1337 }
1338
1339 /* The middle bb is not empty if there are any phi nodes. */
1340 if (phi_nodes (middle_bb))
1341 empty_or_with_defined_p = false;
1342
1343 /* We need to know which is the true edge and which is the false
1344 edge so that we know if have abs or negative abs. */
1345 extract_true_false_edges_from_block (cond_bb, &true_edge, &false_edge);
1346
1347 /* At this point we know we have a COND_EXPR with two successors.
1348 One successor is BB, the other successor is an empty block which
1349 falls through into BB.
1350
1351 The condition for the COND_EXPR is known to be NE_EXPR or EQ_EXPR.
1352
1353 There is a single PHI node at the join point (BB) with two arguments.
1354
1355 We now need to verify that the two arguments in the PHI node match
1356 the two arguments to the equality comparison. */
1357
1358 bool equal_p = operand_equal_for_value_replacement (arg0, arg1, &code, cond);
1359 bool maybe_equal_p = false;
1360 if (!equal_p
1361 && empty_or_with_defined_p
1362 && TREE_CODE (gimple_cond_rhs (cond)) == INTEGER_CST
1363 && (operand_equal_for_phi_arg_p (gimple_cond_lhs (cond), arg0)
1364 ? TREE_CODE (arg1) == INTEGER_CST
1365 : (operand_equal_for_phi_arg_p (gimple_cond_lhs (cond), arg1)
1366 && TREE_CODE (arg0) == INTEGER_CST)))
1367 maybe_equal_p = true;
1368 if (equal_p || maybe_equal_p)
1369 {
1370 edge e;
1371 tree arg;
1372
1373 /* For NE_EXPR, we want to build an assignment result = arg where
1374 arg is the PHI argument associated with the true edge. For
1375 EQ_EXPR we want the PHI argument associated with the false edge. */
1376 e = (code == NE_EXPR ? true_edge : false_edge);
1377
1378 /* Unfortunately, E may not reach BB (it may instead have gone to
1379 OTHER_BLOCK). If that is the case, then we want the single outgoing
1380 edge from OTHER_BLOCK which reaches BB and represents the desired
1381 path from COND_BLOCK. */
1382 if (e->dest == middle_bb)
1383 e = single_succ_edge (e->dest);
1384
1385 /* Now we know the incoming edge to BB that has the argument for the
1386 RHS of our new assignment statement. */
1387 if (e0 == e)
1388 arg = arg0;
1389 else
1390 arg = arg1;
1391
1392 /* If the middle basic block was empty or is defining the
1393 PHI arguments and this is a single phi where the args are different
1394 for the edges e0 and e1 then we can remove the middle basic block. */
1395 if (empty_or_with_defined_p
1396 && single_non_singleton_phi_for_edges (phi_nodes (gimple_bb (phi)),
1397 e0, e1) == phi)
1398 {
1399 use_operand_p use_p;
1400 gimple *use_stmt;
1401
1402 /* Even if arg0/arg1 isn't equal to second operand of cond, we
1403 can optimize away the bb if we can prove it doesn't care whether
1404 phi result is arg0/arg1 or second operand of cond. Consider:
1405 <bb 2> [local count: 118111600]:
1406 if (i_2(D) == 4)
1407 goto <bb 4>; [97.00%]
1408 else
1409 goto <bb 3>; [3.00%]
1410
1411 <bb 3> [local count: 3540129]:
1412
1413 <bb 4> [local count: 118111600]:
1414 # i_6 = PHI <i_2(D)(3), 6(2)>
1415 _3 = i_6 != 0;
1416 Here, carg is 4, oarg is 6, crhs is 0, and because
1417 (4 != 0) == (6 != 0), we don't care if i_6 is 4 or 6, both
1418 have the same outcome. So, we can optimize this to:
1419 _3 = i_2(D) != 0;
1420 If the single imm use of phi result >, >=, < or <=, similarly
1421 we can check if both carg and oarg compare the same against
1422 crhs using ccode. */
1423 if (maybe_equal_p
1424 && TREE_CODE (arg) != INTEGER_CST
1425 && single_imm_use (gimple_phi_result (phi), &use_p, &use_stmt))
1426 {
1427 enum tree_code ccode = ERROR_MARK;
1428 tree clhs = NULL_TREE, crhs = NULL_TREE;
1429 tree carg = gimple_cond_rhs (cond);
1430 tree oarg = e0 == e ? arg1 : arg0;
1431 if (is_gimple_assign (use_stmt)
1432 && (TREE_CODE_CLASS (gimple_assign_rhs_code (use_stmt))
1433 == tcc_comparison))
1434 {
1435 ccode = gimple_assign_rhs_code (use_stmt);
1436 clhs = gimple_assign_rhs1 (use_stmt);
1437 crhs = gimple_assign_rhs2 (use_stmt);
1438 }
1439 else if (gimple_code (use_stmt) == GIMPLE_COND)
1440 {
1441 ccode = gimple_cond_code (use_stmt);
1442 clhs = gimple_cond_lhs (use_stmt);
1443 crhs = gimple_cond_rhs (use_stmt);
1444 }
1445 if (ccode != ERROR_MARK
1446 && clhs == gimple_phi_result (phi)
1447 && TREE_CODE (crhs) == INTEGER_CST)
1448 switch (ccode)
1449 {
1450 case EQ_EXPR:
1451 case NE_EXPR:
1452 if (!tree_int_cst_equal (crhs, carg)
1453 && !tree_int_cst_equal (crhs, oarg))
1454 equal_p = true;
1455 break;
1456 case GT_EXPR:
1457 if (tree_int_cst_lt (crhs, carg)
1458 == tree_int_cst_lt (crhs, oarg))
1459 equal_p = true;
1460 break;
1461 case GE_EXPR:
1462 if (tree_int_cst_le (crhs, carg)
1463 == tree_int_cst_le (crhs, oarg))
1464 equal_p = true;
1465 break;
1466 case LT_EXPR:
1467 if (tree_int_cst_lt (carg, crhs)
1468 == tree_int_cst_lt (oarg, crhs))
1469 equal_p = true;
1470 break;
1471 case LE_EXPR:
1472 if (tree_int_cst_le (carg, crhs)
1473 == tree_int_cst_le (oarg, crhs))
1474 equal_p = true;
1475 break;
1476 default:
1477 break;
1478 }
1479 if (equal_p)
1480 {
1481 tree phires = gimple_phi_result (phi);
1482 if (SSA_NAME_RANGE_INFO (phires))
1483 {
1484 /* After the optimization PHI result can have value
1485 which it couldn't have previously. */
1486 value_range r (TREE_TYPE (phires));
1487 if (get_global_range_query ()->range_of_expr (r, phires,
1488 phi))
1489 {
1490 value_range tmp (carg, carg);
1491 r.union_ (tmp);
1492 reset_flow_sensitive_info (phires);
1493 set_range_info (phires, r);
1494 }
1495 else
1496 reset_flow_sensitive_info (phires);
1497 }
1498 }
1499 if (equal_p && MAY_HAVE_DEBUG_BIND_STMTS)
1500 {
1501 imm_use_iterator imm_iter;
1502 tree phires = gimple_phi_result (phi);
1503 tree temp = NULL_TREE;
1504 bool reset_p = false;
1505
1506 /* Add # DEBUG D#1 => arg != carg ? arg : oarg. */
1507 FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, phires)
1508 {
1509 if (!is_gimple_debug (use_stmt))
1510 continue;
1511 if (temp == NULL_TREE)
1512 {
1513 if (!single_pred_p (middle_bb)
1514 || EDGE_COUNT (gimple_bb (phi)->preds) != 2)
1515 {
1516 /* But only if middle_bb has a single
1517 predecessor and phi bb has two, otherwise
1518 we could use a SSA_NAME not usable in that
1519 place or wrong-debug. */
1520 reset_p = true;
1521 break;
1522 }
1523 gimple_stmt_iterator gsi
1524 = gsi_after_labels (gimple_bb (phi));
1525 tree type = TREE_TYPE (phires);
1526 temp = build_debug_expr_decl (type);
1527 tree t = build2 (NE_EXPR, boolean_type_node,
1528 arg, carg);
1529 t = build3 (COND_EXPR, type, t, arg, oarg);
1530 gimple *g = gimple_build_debug_bind (temp, t, phi);
1531 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
1532 }
1533 FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
1534 replace_exp (use_p, temp);
1535 update_stmt (use_stmt);
1536 }
1537 if (reset_p)
1538 reset_debug_uses (phi);
1539 }
1540 }
1541 if (equal_p)
1542 {
1543 replace_phi_edge_with_variable (cond_bb, e1, phi, arg);
1544 /* Note that we optimized this PHI. */
1545 return 2;
1546 }
1547 }
1548 else if (equal_p)
1549 {
1550 if (!single_pred_p (middle_bb))
1551 return 0;
1552 statistics_counter_event (cfun, "Replace PHI with "
1553 "variable/value_replacement", 1);
1554
1555 /* Replace the PHI arguments with arg. */
1556 SET_PHI_ARG_DEF (phi, e0->dest_idx, arg);
1557 SET_PHI_ARG_DEF (phi, e1->dest_idx, arg);
1558 if (dump_file && (dump_flags & TDF_DETAILS))
1559 {
1560 fprintf (dump_file, "PHI ");
1561 print_generic_expr (dump_file, gimple_phi_result (phi));
1562 fprintf (dump_file, " reduced for COND_EXPR in block %d to ",
1563 cond_bb->index);
1564 print_generic_expr (dump_file, arg);
1565 fprintf (dump_file, ".\n");
1566 }
1567 return 1;
1568 }
1569 }
1570
1571 if (!single_pred_p (middle_bb))
1572 return 0;
1573
1574 /* Now optimize (x != 0) ? x + y : y to just x + y. */
1575 gsi = gsi_last_nondebug_bb (middle_bb);
1576 if (gsi_end_p (gsi))
1577 return 0;
1578
1579 gimple *assign = gsi_stmt (gsi);
1580 if (!is_gimple_assign (assign)
1581 || (!INTEGRAL_TYPE_P (TREE_TYPE (arg0))
1582 && !POINTER_TYPE_P (TREE_TYPE (arg0))))
1583 return 0;
1584
1585 if (gimple_assign_rhs_class (assign) != GIMPLE_BINARY_RHS)
1586 {
1587 /* If last stmt of the middle_bb is a conversion, handle it like
1588 a preparation statement through constant evaluation with
1589 checking for UB. */
1590 enum tree_code sc = gimple_assign_rhs_code (assign);
1591 if (CONVERT_EXPR_CODE_P (sc))
1592 assign = NULL;
1593 else
1594 return 0;
1595 }
1596
1597 /* Punt if there are (degenerate) PHIs in middle_bb, there should not be. */
1598 if (!gimple_seq_empty_p (phi_nodes (middle_bb)))
1599 return 0;
1600
1601 /* Allow up to 2 cheap preparation statements that prepare argument
1602 for assign, e.g.:
1603 if (y_4 != 0)
1604 goto <bb 3>;
1605 else
1606 goto <bb 4>;
1607 <bb 3>:
1608 _1 = (int) y_4;
1609 iftmp.0_6 = x_5(D) r<< _1;
1610 <bb 4>:
1611 # iftmp.0_2 = PHI <iftmp.0_6(3), x_5(D)(2)>
1612 or:
1613 if (y_3(D) == 0)
1614 goto <bb 4>;
1615 else
1616 goto <bb 3>;
1617 <bb 3>:
1618 y_4 = y_3(D) & 31;
1619 _1 = (int) y_4;
1620 _6 = x_5(D) r<< _1;
1621 <bb 4>:
1622 # _2 = PHI <x_5(D)(2), _6(3)> */
1623 gimple *prep_stmt[2] = { NULL, NULL };
1624 int prep_cnt;
1625 for (prep_cnt = 0; ; prep_cnt++)
1626 {
1627 if (prep_cnt || assign)
1628 gsi_prev_nondebug (&gsi);
1629 if (gsi_end_p (gsi))
1630 break;
1631
1632 gimple *g = gsi_stmt (gsi);
1633 if (gimple_code (g) == GIMPLE_LABEL)
1634 break;
1635
1636 if (prep_cnt == 2 || !is_gimple_assign (g))
1637 return 0;
1638
1639 tree lhs = gimple_assign_lhs (g);
1640 tree rhs1 = gimple_assign_rhs1 (g);
1641 use_operand_p use_p;
1642 gimple *use_stmt;
1643 if (TREE_CODE (lhs) != SSA_NAME
1644 || TREE_CODE (rhs1) != SSA_NAME
1645 || !INTEGRAL_TYPE_P (TREE_TYPE (lhs))
1646 || !INTEGRAL_TYPE_P (TREE_TYPE (rhs1))
1647 || !single_imm_use (lhs, &use_p, &use_stmt)
1648 || ((prep_cnt || assign)
1649 && use_stmt != (prep_cnt ? prep_stmt[prep_cnt - 1] : assign)))
1650 return 0;
1651 switch (gimple_assign_rhs_code (g))
1652 {
1653 CASE_CONVERT:
1654 break;
1655 case PLUS_EXPR:
1656 case BIT_AND_EXPR:
1657 case BIT_IOR_EXPR:
1658 case BIT_XOR_EXPR:
1659 if (TREE_CODE (gimple_assign_rhs2 (g)) != INTEGER_CST)
1660 return 0;
1661 break;
1662 default:
1663 return 0;
1664 }
1665 prep_stmt[prep_cnt] = g;
1666 }
1667
1668 /* Only transform if it removes the condition. */
1669 if (!single_non_singleton_phi_for_edges (phi_nodes (gimple_bb (phi)), e0, e1))
1670 return 0;
1671
1672 /* Size-wise, this is always profitable. */
1673 if (optimize_bb_for_speed_p (cond_bb)
1674 /* The special case is useless if it has a low probability. */
1675 && profile_status_for_fn (cfun) != PROFILE_ABSENT
1676 && EDGE_PRED (middle_bb, 0)->probability < profile_probability::even ()
1677 /* If assign is cheap, there is no point avoiding it. */
1678 && estimate_num_insns_seq (bb_seq (middle_bb), &eni_time_weights)
1679 >= 3 * estimate_num_insns (cond, &eni_time_weights))
1680 return 0;
1681
1682 tree cond_lhs = gimple_cond_lhs (cond);
1683 tree cond_rhs = gimple_cond_rhs (cond);
1684
1685 /* Propagate the cond_rhs constant through preparation stmts,
1686 make sure UB isn't invoked while doing that. */
1687 for (int i = prep_cnt - 1; i >= 0; --i)
1688 {
1689 gimple *g = prep_stmt[i];
1690 tree grhs1 = gimple_assign_rhs1 (g);
1691 if (!operand_equal_for_phi_arg_p (cond_lhs, grhs1))
1692 return 0;
1693 cond_lhs = gimple_assign_lhs (g);
1694 cond_rhs = fold_convert (TREE_TYPE (grhs1), cond_rhs);
1695 if (TREE_CODE (cond_rhs) != INTEGER_CST
1696 || TREE_OVERFLOW (cond_rhs))
1697 return 0;
1698 if (gimple_assign_rhs_class (g) == GIMPLE_BINARY_RHS)
1699 {
1700 cond_rhs = int_const_binop (gimple_assign_rhs_code (g), cond_rhs,
1701 gimple_assign_rhs2 (g));
1702 if (TREE_OVERFLOW (cond_rhs))
1703 return 0;
1704 }
1705 cond_rhs = fold_convert (TREE_TYPE (cond_lhs), cond_rhs);
1706 if (TREE_CODE (cond_rhs) != INTEGER_CST
1707 || TREE_OVERFLOW (cond_rhs))
1708 return 0;
1709 }
1710
1711 tree lhs, rhs1, rhs2;
1712 enum tree_code code_def;
1713 if (assign)
1714 {
1715 lhs = gimple_assign_lhs (assign);
1716 rhs1 = gimple_assign_rhs1 (assign);
1717 rhs2 = gimple_assign_rhs2 (assign);
1718 code_def = gimple_assign_rhs_code (assign);
1719 }
1720 else
1721 {
1722 gcc_assert (prep_cnt > 0);
1723 lhs = cond_lhs;
1724 rhs1 = NULL_TREE;
1725 rhs2 = NULL_TREE;
1726 code_def = ERROR_MARK;
1727 }
1728
1729 if (((code == NE_EXPR && e1 == false_edge)
1730 || (code == EQ_EXPR && e1 == true_edge))
1731 && arg0 == lhs
1732 && ((assign == NULL
1733 && operand_equal_for_phi_arg_p (arg1, cond_rhs))
1734 || (assign
1735 && arg1 == rhs1
1736 && operand_equal_for_phi_arg_p (rhs2, cond_lhs)
1737 && neutral_element_p (code_def, cond_rhs, true))
1738 || (assign
1739 && arg1 == rhs2
1740 && operand_equal_for_phi_arg_p (rhs1, cond_lhs)
1741 && neutral_element_p (code_def, cond_rhs, false))
1742 || (assign
1743 && operand_equal_for_phi_arg_p (arg1, cond_rhs)
1744 && ((operand_equal_for_phi_arg_p (rhs2, cond_lhs)
1745 && absorbing_element_p (code_def, cond_rhs, true, rhs2))
1746 || (operand_equal_for_phi_arg_p (rhs1, cond_lhs)
1747 && absorbing_element_p (code_def,
1748 cond_rhs, false, rhs2))))))
1749 {
1750 gsi = gsi_for_stmt (cond);
1751 /* Moving ASSIGN might change VR of lhs, e.g. when moving u_6
1752 def-stmt in:
1753 if (n_5 != 0)
1754 goto <bb 3>;
1755 else
1756 goto <bb 4>;
1757
1758 <bb 3>:
1759 # RANGE [0, 4294967294]
1760 u_6 = n_5 + 4294967295;
1761
1762 <bb 4>:
1763 # u_3 = PHI <u_6(3), 4294967295(2)> */
1764 reset_flow_sensitive_info (lhs);
1765 gimple_stmt_iterator gsi_from;
1766 for (int i = prep_cnt - 1; i >= 0; --i)
1767 {
1768 tree plhs = gimple_assign_lhs (prep_stmt[i]);
1769 reset_flow_sensitive_info (plhs);
1770 gsi_from = gsi_for_stmt (prep_stmt[i]);
1771 gsi_move_before (&gsi_from, &gsi);
1772 }
1773 if (assign)
1774 {
1775 gsi_from = gsi_for_stmt (assign);
1776 gsi_move_before (&gsi_from, &gsi);
1777 }
1778 replace_phi_edge_with_variable (cond_bb, e1, phi, lhs);
1779 return 2;
1780 }
1781
1782 return 0;
1783 }
1784
1785 /* If VAR is an SSA_NAME that points to a BIT_NOT_EXPR then return the TREE for
1786 the value being inverted. */
1787
1788 static tree
1789 strip_bit_not (tree var)
1790 {
1791 if (TREE_CODE (var) != SSA_NAME)
1792 return NULL_TREE;
1793
1794 gimple *assign = SSA_NAME_DEF_STMT (var);
1795 if (gimple_code (assign) != GIMPLE_ASSIGN)
1796 return NULL_TREE;
1797
1798 if (gimple_assign_rhs_code (assign) != BIT_NOT_EXPR)
1799 return NULL_TREE;
1800
1801 return gimple_assign_rhs1 (assign);
1802 }
1803
1804 /* Invert a MIN to a MAX or a MAX to a MIN expression CODE. */
1805
1806 enum tree_code
1807 invert_minmax_code (enum tree_code code)
1808 {
1809 switch (code) {
1810 case MIN_EXPR:
1811 return MAX_EXPR;
1812 case MAX_EXPR:
1813 return MIN_EXPR;
1814 default:
1815 gcc_unreachable ();
1816 }
1817 }
1818
1819 /* The function minmax_replacement does the main work of doing the minmax
1820 replacement. Return true if the replacement is done. Otherwise return
1821 false.
1822 BB is the basic block where the replacement is going to be done on. ARG0
1823 is argument 0 from the PHI. Likewise for ARG1.
1824
1825 If THREEWAY_P then expect the BB to be laid out in diamond shape with each
1826 BB containing only a MIN or MAX expression. */
1827
1828 static bool
1829 minmax_replacement (basic_block cond_bb, basic_block middle_bb, basic_block alt_middle_bb,
1830 edge e0, edge e1, gphi *phi, tree arg0, tree arg1, bool threeway_p)
1831 {
1832 tree result;
1833 edge true_edge, false_edge;
1834 enum tree_code minmax, ass_code;
1835 tree smaller, larger, arg_true, arg_false;
1836 gimple_stmt_iterator gsi, gsi_from;
1837
1838 tree type = TREE_TYPE (gimple_phi_result (phi));
1839
1840 gcond *cond = as_a <gcond *> (*gsi_last_bb (cond_bb));
1841 enum tree_code cmp = gimple_cond_code (cond);
1842 tree rhs = gimple_cond_rhs (cond);
1843
1844 /* Turn EQ/NE of extreme values to order comparisons. */
1845 if ((cmp == NE_EXPR || cmp == EQ_EXPR)
1846 && TREE_CODE (rhs) == INTEGER_CST
1847 && INTEGRAL_TYPE_P (TREE_TYPE (rhs)))
1848 {
1849 if (wi::eq_p (wi::to_wide (rhs), wi::min_value (TREE_TYPE (rhs))))
1850 {
1851 cmp = (cmp == EQ_EXPR) ? LT_EXPR : GE_EXPR;
1852 rhs = wide_int_to_tree (TREE_TYPE (rhs),
1853 wi::min_value (TREE_TYPE (rhs)) + 1);
1854 }
1855 else if (wi::eq_p (wi::to_wide (rhs), wi::max_value (TREE_TYPE (rhs))))
1856 {
1857 cmp = (cmp == EQ_EXPR) ? GT_EXPR : LE_EXPR;
1858 rhs = wide_int_to_tree (TREE_TYPE (rhs),
1859 wi::max_value (TREE_TYPE (rhs)) - 1);
1860 }
1861 }
1862
1863 /* This transformation is only valid for order comparisons. Record which
1864 operand is smaller/larger if the result of the comparison is true. */
1865 tree alt_smaller = NULL_TREE;
1866 tree alt_larger = NULL_TREE;
1867 if (cmp == LT_EXPR || cmp == LE_EXPR)
1868 {
1869 smaller = gimple_cond_lhs (cond);
1870 larger = rhs;
1871 /* If we have smaller < CST it is equivalent to smaller <= CST-1.
1872 Likewise smaller <= CST is equivalent to smaller < CST+1. */
1873 if (TREE_CODE (larger) == INTEGER_CST
1874 && INTEGRAL_TYPE_P (TREE_TYPE (larger)))
1875 {
1876 if (cmp == LT_EXPR)
1877 {
1878 wi::overflow_type overflow;
1879 wide_int alt = wi::sub (wi::to_wide (larger), 1,
1880 TYPE_SIGN (TREE_TYPE (larger)),
1881 &overflow);
1882 if (! overflow)
1883 alt_larger = wide_int_to_tree (TREE_TYPE (larger), alt);
1884 }
1885 else
1886 {
1887 wi::overflow_type overflow;
1888 wide_int alt = wi::add (wi::to_wide (larger), 1,
1889 TYPE_SIGN (TREE_TYPE (larger)),
1890 &overflow);
1891 if (! overflow)
1892 alt_larger = wide_int_to_tree (TREE_TYPE (larger), alt);
1893 }
1894 }
1895 }
1896 else if (cmp == GT_EXPR || cmp == GE_EXPR)
1897 {
1898 smaller = rhs;
1899 larger = gimple_cond_lhs (cond);
1900 /* If we have larger > CST it is equivalent to larger >= CST+1.
1901 Likewise larger >= CST is equivalent to larger > CST-1. */
1902 if (TREE_CODE (smaller) == INTEGER_CST
1903 && INTEGRAL_TYPE_P (TREE_TYPE (smaller)))
1904 {
1905 wi::overflow_type overflow;
1906 if (cmp == GT_EXPR)
1907 {
1908 wide_int alt = wi::add (wi::to_wide (smaller), 1,
1909 TYPE_SIGN (TREE_TYPE (smaller)),
1910 &overflow);
1911 if (! overflow)
1912 alt_smaller = wide_int_to_tree (TREE_TYPE (smaller), alt);
1913 }
1914 else
1915 {
1916 wide_int alt = wi::sub (wi::to_wide (smaller), 1,
1917 TYPE_SIGN (TREE_TYPE (smaller)),
1918 &overflow);
1919 if (! overflow)
1920 alt_smaller = wide_int_to_tree (TREE_TYPE (smaller), alt);
1921 }
1922 }
1923 }
1924 else
1925 return false;
1926
1927 /* Handle the special case of (signed_type)x < 0 being equivalent
1928 to x > MAX_VAL(signed_type) and (signed_type)x >= 0 equivalent
1929 to x <= MAX_VAL(signed_type). */
1930 if ((cmp == GE_EXPR || cmp == LT_EXPR)
1931 && INTEGRAL_TYPE_P (type)
1932 && TYPE_UNSIGNED (type)
1933 && integer_zerop (rhs))
1934 {
1935 tree op = gimple_cond_lhs (cond);
1936 if (TREE_CODE (op) == SSA_NAME
1937 && INTEGRAL_TYPE_P (TREE_TYPE (op))
1938 && !TYPE_UNSIGNED (TREE_TYPE (op)))
1939 {
1940 gimple *def_stmt = SSA_NAME_DEF_STMT (op);
1941 if (gimple_assign_cast_p (def_stmt))
1942 {
1943 tree op1 = gimple_assign_rhs1 (def_stmt);
1944 if (INTEGRAL_TYPE_P (TREE_TYPE (op1))
1945 && TYPE_UNSIGNED (TREE_TYPE (op1))
1946 && (TYPE_PRECISION (TREE_TYPE (op))
1947 == TYPE_PRECISION (TREE_TYPE (op1)))
1948 && useless_type_conversion_p (type, TREE_TYPE (op1)))
1949 {
1950 wide_int w1 = wi::max_value (TREE_TYPE (op));
1951 wide_int w2 = wi::add (w1, 1);
1952 if (cmp == LT_EXPR)
1953 {
1954 larger = op1;
1955 smaller = wide_int_to_tree (TREE_TYPE (op1), w1);
1956 alt_smaller = wide_int_to_tree (TREE_TYPE (op1), w2);
1957 alt_larger = NULL_TREE;
1958 }
1959 else
1960 {
1961 smaller = op1;
1962 larger = wide_int_to_tree (TREE_TYPE (op1), w1);
1963 alt_larger = wide_int_to_tree (TREE_TYPE (op1), w2);
1964 alt_smaller = NULL_TREE;
1965 }
1966 }
1967 }
1968 }
1969 }
1970
1971 /* We need to know which is the true edge and which is the false
1972 edge so that we know if have abs or negative abs. */
1973 extract_true_false_edges_from_block (cond_bb, &true_edge, &false_edge);
1974
1975 /* Forward the edges over the middle basic block. */
1976 if (true_edge->dest == middle_bb)
1977 true_edge = EDGE_SUCC (true_edge->dest, 0);
1978 if (false_edge->dest == middle_bb)
1979 false_edge = EDGE_SUCC (false_edge->dest, 0);
1980
1981 /* When THREEWAY_P then e1 will point to the edge of the final transition
1982 from middle-bb to end. */
1983 if (true_edge == e0)
1984 {
1985 if (!threeway_p)
1986 gcc_assert (false_edge == e1);
1987 arg_true = arg0;
1988 arg_false = arg1;
1989 }
1990 else
1991 {
1992 gcc_assert (false_edge == e0);
1993 if (!threeway_p)
1994 gcc_assert (true_edge == e1);
1995 arg_true = arg1;
1996 arg_false = arg0;
1997 }
1998
1999 if (empty_block_p (middle_bb)
2000 && (!threeway_p
2001 || empty_block_p (alt_middle_bb)))
2002 {
2003 if ((operand_equal_for_phi_arg_p (arg_true, smaller)
2004 || (alt_smaller
2005 && operand_equal_for_phi_arg_p (arg_true, alt_smaller)))
2006 && (operand_equal_for_phi_arg_p (arg_false, larger)
2007 || (alt_larger
2008 && operand_equal_for_phi_arg_p (arg_true, alt_larger))))
2009 {
2010 /* Case
2011
2012 if (smaller < larger)
2013 rslt = smaller;
2014 else
2015 rslt = larger; */
2016 minmax = MIN_EXPR;
2017 }
2018 else if ((operand_equal_for_phi_arg_p (arg_false, smaller)
2019 || (alt_smaller
2020 && operand_equal_for_phi_arg_p (arg_false, alt_smaller)))
2021 && (operand_equal_for_phi_arg_p (arg_true, larger)
2022 || (alt_larger
2023 && operand_equal_for_phi_arg_p (arg_true, alt_larger))))
2024 minmax = MAX_EXPR;
2025 else
2026 return false;
2027 }
2028 else if (HONOR_NANS (type) || HONOR_SIGNED_ZEROS (type))
2029 /* The optimization may be unsafe due to NaNs. */
2030 return false;
2031 else if (middle_bb != alt_middle_bb && threeway_p)
2032 {
2033 /* Recognize the following case:
2034
2035 if (smaller < larger)
2036 a = MIN (smaller, c);
2037 else
2038 b = MIN (larger, c);
2039 x = PHI <a, b>
2040
2041 This is equivalent to
2042
2043 a = MIN (smaller, c);
2044 x = MIN (larger, a); */
2045
2046 gimple *assign = last_and_only_stmt (middle_bb);
2047 tree lhs, op0, op1, bound;
2048 tree alt_lhs, alt_op0, alt_op1;
2049 bool invert = false;
2050
2051 /* When THREEWAY_P then e1 will point to the edge of the final transition
2052 from middle-bb to end. */
2053 if (true_edge == e0)
2054 gcc_assert (false_edge == EDGE_PRED (e1->src, 0));
2055 else
2056 gcc_assert (true_edge == EDGE_PRED (e1->src, 0));
2057
2058 bool valid_minmax_p = false;
2059 gimple_stmt_iterator it1
2060 = gsi_start_nondebug_after_labels_bb (middle_bb);
2061 gimple_stmt_iterator it2
2062 = gsi_start_nondebug_after_labels_bb (alt_middle_bb);
2063 if (gsi_one_nondebug_before_end_p (it1)
2064 && gsi_one_nondebug_before_end_p (it2))
2065 {
2066 gimple *stmt1 = gsi_stmt (it1);
2067 gimple *stmt2 = gsi_stmt (it2);
2068 if (is_gimple_assign (stmt1) && is_gimple_assign (stmt2))
2069 {
2070 enum tree_code code1 = gimple_assign_rhs_code (stmt1);
2071 enum tree_code code2 = gimple_assign_rhs_code (stmt2);
2072 valid_minmax_p = (code1 == MIN_EXPR || code1 == MAX_EXPR)
2073 && (code2 == MIN_EXPR || code2 == MAX_EXPR);
2074 }
2075 }
2076
2077 if (!valid_minmax_p)
2078 return false;
2079
2080 if (!assign
2081 || gimple_code (assign) != GIMPLE_ASSIGN)
2082 return false;
2083
2084 /* There cannot be any phi nodes in the middle bb. */
2085 if (!gimple_seq_empty_p (phi_nodes (middle_bb)))
2086 return false;
2087
2088 lhs = gimple_assign_lhs (assign);
2089 ass_code = gimple_assign_rhs_code (assign);
2090 if (ass_code != MAX_EXPR && ass_code != MIN_EXPR)
2091 return false;
2092
2093 op0 = gimple_assign_rhs1 (assign);
2094 op1 = gimple_assign_rhs2 (assign);
2095
2096 assign = last_and_only_stmt (alt_middle_bb);
2097 if (!assign
2098 || gimple_code (assign) != GIMPLE_ASSIGN)
2099 return false;
2100
2101 /* There cannot be any phi nodes in the alt middle bb. */
2102 if (!gimple_seq_empty_p (phi_nodes (alt_middle_bb)))
2103 return false;
2104
2105 alt_lhs = gimple_assign_lhs (assign);
2106 if (ass_code != gimple_assign_rhs_code (assign))
2107 return false;
2108
2109 if (!operand_equal_for_phi_arg_p (lhs, arg_true)
2110 || !operand_equal_for_phi_arg_p (alt_lhs, arg_false))
2111 return false;
2112
2113 alt_op0 = gimple_assign_rhs1 (assign);
2114 alt_op1 = gimple_assign_rhs2 (assign);
2115
2116 if ((operand_equal_for_phi_arg_p (op0, smaller)
2117 || (alt_smaller
2118 && operand_equal_for_phi_arg_p (op0, alt_smaller)))
2119 && (operand_equal_for_phi_arg_p (alt_op0, larger)
2120 || (alt_larger
2121 && operand_equal_for_phi_arg_p (alt_op0, alt_larger))))
2122 {
2123 /* We got here if the condition is true, i.e., SMALLER < LARGER. */
2124 if (!operand_equal_for_phi_arg_p (op1, alt_op1))
2125 return false;
2126
2127 if ((arg0 = strip_bit_not (op0)) != NULL
2128 && (arg1 = strip_bit_not (alt_op0)) != NULL
2129 && (bound = strip_bit_not (op1)) != NULL)
2130 {
2131 minmax = MAX_EXPR;
2132 ass_code = invert_minmax_code (ass_code);
2133 invert = true;
2134 }
2135 else
2136 {
2137 bound = op1;
2138 minmax = MIN_EXPR;
2139 arg0 = op0;
2140 arg1 = alt_op0;
2141 }
2142 }
2143 else if ((operand_equal_for_phi_arg_p (op0, larger)
2144 || (alt_larger
2145 && operand_equal_for_phi_arg_p (op0, alt_larger)))
2146 && (operand_equal_for_phi_arg_p (alt_op0, smaller)
2147 || (alt_smaller
2148 && operand_equal_for_phi_arg_p (alt_op0, alt_smaller))))
2149 {
2150 /* We got here if the condition is true, i.e., SMALLER > LARGER. */
2151 if (!operand_equal_for_phi_arg_p (op1, alt_op1))
2152 return false;
2153
2154 if ((arg0 = strip_bit_not (op0)) != NULL
2155 && (arg1 = strip_bit_not (alt_op0)) != NULL
2156 && (bound = strip_bit_not (op1)) != NULL)
2157 {
2158 minmax = MIN_EXPR;
2159 ass_code = invert_minmax_code (ass_code);
2160 invert = true;
2161 }
2162 else
2163 {
2164 bound = op1;
2165 minmax = MAX_EXPR;
2166 arg0 = op0;
2167 arg1 = alt_op0;
2168 }
2169 }
2170 else
2171 return false;
2172
2173 /* Emit the statement to compute min/max. */
2174 location_t locus = gimple_location (last_nondebug_stmt (cond_bb));
2175 gimple_seq stmts = NULL;
2176 tree phi_result = gimple_phi_result (phi);
2177 result = gimple_build (&stmts, locus, minmax, TREE_TYPE (phi_result),
2178 arg0, arg1);
2179 result = gimple_build (&stmts, locus, ass_code, TREE_TYPE (phi_result),
2180 result, bound);
2181 if (invert)
2182 result = gimple_build (&stmts, locus, BIT_NOT_EXPR, TREE_TYPE (phi_result),
2183 result);
2184
2185 gsi = gsi_last_bb (cond_bb);
2186 gsi_insert_seq_before (&gsi, stmts, GSI_NEW_STMT);
2187
2188 replace_phi_edge_with_variable (cond_bb, e1, phi, result);
2189
2190 return true;
2191 }
2192 else if (!threeway_p
2193 || empty_block_p (alt_middle_bb))
2194 {
2195 /* Recognize the following case, assuming d <= u:
2196
2197 if (a <= u)
2198 b = MAX (a, d);
2199 x = PHI <b, u>
2200
2201 This is equivalent to
2202
2203 b = MAX (a, d);
2204 x = MIN (b, u); */
2205
2206 gimple *assign = last_and_only_stmt (middle_bb);
2207 tree lhs, op0, op1, bound;
2208
2209 if (!single_pred_p (middle_bb))
2210 return false;
2211
2212 if (!assign
2213 || gimple_code (assign) != GIMPLE_ASSIGN)
2214 return false;
2215
2216 /* There cannot be any phi nodes in the middle bb. */
2217 if (!gimple_seq_empty_p (phi_nodes (middle_bb)))
2218 return false;
2219
2220 lhs = gimple_assign_lhs (assign);
2221 ass_code = gimple_assign_rhs_code (assign);
2222 if (ass_code != MAX_EXPR && ass_code != MIN_EXPR)
2223 return false;
2224 op0 = gimple_assign_rhs1 (assign);
2225 op1 = gimple_assign_rhs2 (assign);
2226
2227 if (true_edge->src == middle_bb)
2228 {
2229 /* We got here if the condition is true, i.e., SMALLER < LARGER. */
2230 if (!operand_equal_for_phi_arg_p (lhs, arg_true))
2231 return false;
2232
2233 if (operand_equal_for_phi_arg_p (arg_false, larger)
2234 || (alt_larger
2235 && operand_equal_for_phi_arg_p (arg_false, alt_larger)))
2236 {
2237 /* Case
2238
2239 if (smaller < larger)
2240 {
2241 r' = MAX_EXPR (smaller, bound)
2242 }
2243 r = PHI <r', larger> --> to be turned to MIN_EXPR. */
2244 if (ass_code != MAX_EXPR)
2245 return false;
2246
2247 minmax = MIN_EXPR;
2248 if (operand_equal_for_phi_arg_p (op0, smaller)
2249 || (alt_smaller
2250 && operand_equal_for_phi_arg_p (op0, alt_smaller)))
2251 bound = op1;
2252 else if (operand_equal_for_phi_arg_p (op1, smaller)
2253 || (alt_smaller
2254 && operand_equal_for_phi_arg_p (op1, alt_smaller)))
2255 bound = op0;
2256 else
2257 return false;
2258
2259 /* We need BOUND <= LARGER. */
2260 if (!integer_nonzerop (fold_build2 (LE_EXPR, boolean_type_node,
2261 bound, arg_false)))
2262 return false;
2263 }
2264 else if (operand_equal_for_phi_arg_p (arg_false, smaller)
2265 || (alt_smaller
2266 && operand_equal_for_phi_arg_p (arg_false, alt_smaller)))
2267 {
2268 /* Case
2269
2270 if (smaller < larger)
2271 {
2272 r' = MIN_EXPR (larger, bound)
2273 }
2274 r = PHI <r', smaller> --> to be turned to MAX_EXPR. */
2275 if (ass_code != MIN_EXPR)
2276 return false;
2277
2278 minmax = MAX_EXPR;
2279 if (operand_equal_for_phi_arg_p (op0, larger)
2280 || (alt_larger
2281 && operand_equal_for_phi_arg_p (op0, alt_larger)))
2282 bound = op1;
2283 else if (operand_equal_for_phi_arg_p (op1, larger)
2284 || (alt_larger
2285 && operand_equal_for_phi_arg_p (op1, alt_larger)))
2286 bound = op0;
2287 else
2288 return false;
2289
2290 /* We need BOUND >= SMALLER. */
2291 if (!integer_nonzerop (fold_build2 (GE_EXPR, boolean_type_node,
2292 bound, arg_false)))
2293 return false;
2294 }
2295 else
2296 return false;
2297 }
2298 else
2299 {
2300 /* We got here if the condition is false, i.e., SMALLER > LARGER. */
2301 if (!operand_equal_for_phi_arg_p (lhs, arg_false))
2302 return false;
2303
2304 if (operand_equal_for_phi_arg_p (arg_true, larger)
2305 || (alt_larger
2306 && operand_equal_for_phi_arg_p (arg_true, alt_larger)))
2307 {
2308 /* Case
2309
2310 if (smaller > larger)
2311 {
2312 r' = MIN_EXPR (smaller, bound)
2313 }
2314 r = PHI <r', larger> --> to be turned to MAX_EXPR. */
2315 if (ass_code != MIN_EXPR)
2316 return false;
2317
2318 minmax = MAX_EXPR;
2319 if (operand_equal_for_phi_arg_p (op0, smaller)
2320 || (alt_smaller
2321 && operand_equal_for_phi_arg_p (op0, alt_smaller)))
2322 bound = op1;
2323 else if (operand_equal_for_phi_arg_p (op1, smaller)
2324 || (alt_smaller
2325 && operand_equal_for_phi_arg_p (op1, alt_smaller)))
2326 bound = op0;
2327 else
2328 return false;
2329
2330 /* We need BOUND >= LARGER. */
2331 if (!integer_nonzerop (fold_build2 (GE_EXPR, boolean_type_node,
2332 bound, arg_true)))
2333 return false;
2334 }
2335 else if (operand_equal_for_phi_arg_p (arg_true, smaller)
2336 || (alt_smaller
2337 && operand_equal_for_phi_arg_p (arg_true, alt_smaller)))
2338 {
2339 /* Case
2340
2341 if (smaller > larger)
2342 {
2343 r' = MAX_EXPR (larger, bound)
2344 }
2345 r = PHI <r', smaller> --> to be turned to MIN_EXPR. */
2346 if (ass_code != MAX_EXPR)
2347 return false;
2348
2349 minmax = MIN_EXPR;
2350 if (operand_equal_for_phi_arg_p (op0, larger))
2351 bound = op1;
2352 else if (operand_equal_for_phi_arg_p (op1, larger))
2353 bound = op0;
2354 else
2355 return false;
2356
2357 /* We need BOUND <= SMALLER. */
2358 if (!integer_nonzerop (fold_build2 (LE_EXPR, boolean_type_node,
2359 bound, arg_true)))
2360 return false;
2361 }
2362 else
2363 return false;
2364 }
2365
2366 /* Move the statement from the middle block. */
2367 gsi = gsi_last_bb (cond_bb);
2368 gsi_from = gsi_last_nondebug_bb (middle_bb);
2369 reset_flow_sensitive_info (SINGLE_SSA_TREE_OPERAND (gsi_stmt (gsi_from),
2370 SSA_OP_DEF));
2371 gsi_move_before (&gsi_from, &gsi);
2372 }
2373 else
2374 return false;
2375
2376 /* Emit the statement to compute min/max. */
2377 gimple_seq stmts = NULL;
2378 tree phi_result = gimple_phi_result (phi);
2379
2380 /* When we can't use a MIN/MAX_EXPR still make sure the expression
2381 stays in a form to be recognized by ISA that map to IEEE x > y ? x : y
2382 semantics (that's not IEEE max semantics). */
2383 if (HONOR_NANS (type) || HONOR_SIGNED_ZEROS (type))
2384 {
2385 result = gimple_build (&stmts, cmp, boolean_type_node,
2386 gimple_cond_lhs (cond), rhs);
2387 result = gimple_build (&stmts, COND_EXPR, TREE_TYPE (phi_result),
2388 result, arg_true, arg_false);
2389 }
2390 else
2391 result = gimple_build (&stmts, minmax, TREE_TYPE (phi_result), arg0, arg1);
2392
2393 gsi = gsi_last_bb (cond_bb);
2394 gsi_insert_seq_before (&gsi, stmts, GSI_NEW_STMT);
2395
2396 replace_phi_edge_with_variable (cond_bb, e1, phi, result);
2397
2398 return true;
2399 }
2400
2401 /* Attempt to optimize (x <=> y) cmp 0 and similar comparisons.
2402 For strong ordering <=> try to match something like:
2403 <bb 2> : // cond3_bb (== cond2_bb)
2404 if (x_4(D) != y_5(D))
2405 goto <bb 3>; [INV]
2406 else
2407 goto <bb 6>; [INV]
2408
2409 <bb 3> : // cond_bb
2410 if (x_4(D) < y_5(D))
2411 goto <bb 6>; [INV]
2412 else
2413 goto <bb 4>; [INV]
2414
2415 <bb 4> : // middle_bb
2416
2417 <bb 6> : // phi_bb
2418 # iftmp.0_2 = PHI <1(4), 0(2), -1(3)>
2419 _1 = iftmp.0_2 == 0;
2420
2421 and for partial ordering <=> something like:
2422
2423 <bb 2> : // cond3_bb
2424 if (a_3(D) == b_5(D))
2425 goto <bb 6>; [50.00%]
2426 else
2427 goto <bb 3>; [50.00%]
2428
2429 <bb 3> [local count: 536870913]: // cond2_bb
2430 if (a_3(D) < b_5(D))
2431 goto <bb 6>; [50.00%]
2432 else
2433 goto <bb 4>; [50.00%]
2434
2435 <bb 4> [local count: 268435456]: // cond_bb
2436 if (a_3(D) > b_5(D))
2437 goto <bb 6>; [50.00%]
2438 else
2439 goto <bb 5>; [50.00%]
2440
2441 <bb 5> [local count: 134217728]: // middle_bb
2442
2443 <bb 6> [local count: 1073741824]: // phi_bb
2444 # SR.27_4 = PHI <0(2), -1(3), 1(4), 2(5)>
2445 _2 = SR.27_4 > 0; */
2446
2447 static bool
2448 spaceship_replacement (basic_block cond_bb, basic_block middle_bb,
2449 edge e0, edge e1, gphi *phi,
2450 tree arg0, tree arg1)
2451 {
2452 tree phires = gimple_phi_result (phi);
2453 if (!INTEGRAL_TYPE_P (TREE_TYPE (phires))
2454 || TYPE_UNSIGNED (TREE_TYPE (phires))
2455 || !tree_fits_shwi_p (arg0)
2456 || !tree_fits_shwi_p (arg1)
2457 || !IN_RANGE (tree_to_shwi (arg0), -1, 2)
2458 || !IN_RANGE (tree_to_shwi (arg1), -1, 2))
2459 return false;
2460
2461 basic_block phi_bb = gimple_bb (phi);
2462 gcc_assert (phi_bb == e0->dest && phi_bb == e1->dest);
2463 if (!IN_RANGE (EDGE_COUNT (phi_bb->preds), 3, 4))
2464 return false;
2465
2466 use_operand_p use_p;
2467 gimple *use_stmt;
2468 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (phires))
2469 return false;
2470 if (!single_imm_use (phires, &use_p, &use_stmt))
2471 return false;
2472 enum tree_code cmp;
2473 tree lhs, rhs;
2474 gimple *orig_use_stmt = use_stmt;
2475 tree orig_use_lhs = NULL_TREE;
2476 int prec = TYPE_PRECISION (TREE_TYPE (phires));
2477 bool is_cast = false;
2478
2479 /* Deal with the case when match.pd has rewritten the (res & ~1) == 0
2480 into res <= 1 and has left a type-cast for signed types. */
2481 if (gimple_assign_cast_p (use_stmt))
2482 {
2483 orig_use_lhs = gimple_assign_lhs (use_stmt);
2484 /* match.pd would have only done this for a signed type,
2485 so the conversion must be to an unsigned one. */
2486 tree ty1 = TREE_TYPE (gimple_assign_rhs1 (use_stmt));
2487 tree ty2 = TREE_TYPE (orig_use_lhs);
2488
2489 if (!TYPE_UNSIGNED (ty2) || !INTEGRAL_TYPE_P (ty2))
2490 return false;
2491 if (TYPE_PRECISION (ty1) > TYPE_PRECISION (ty2))
2492 return false;
2493 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (orig_use_lhs))
2494 return false;
2495 if (!single_imm_use (orig_use_lhs, &use_p, &use_stmt))
2496 return false;
2497
2498 is_cast = true;
2499 }
2500 else if (is_gimple_assign (use_stmt)
2501 && gimple_assign_rhs_code (use_stmt) == BIT_AND_EXPR
2502 && TREE_CODE (gimple_assign_rhs2 (use_stmt)) == INTEGER_CST
2503 && (wi::to_wide (gimple_assign_rhs2 (use_stmt))
2504 == wi::shifted_mask (1, prec - 1, false, prec)))
2505 {
2506 /* For partial_ordering result operator>= with unspec as second
2507 argument is (res & 1) == res, folded by match.pd into
2508 (res & ~1) == 0. */
2509 orig_use_lhs = gimple_assign_lhs (use_stmt);
2510 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (orig_use_lhs))
2511 return false;
2512 if (!single_imm_use (orig_use_lhs, &use_p, &use_stmt))
2513 return false;
2514 }
2515 if (gimple_code (use_stmt) == GIMPLE_COND)
2516 {
2517 cmp = gimple_cond_code (use_stmt);
2518 lhs = gimple_cond_lhs (use_stmt);
2519 rhs = gimple_cond_rhs (use_stmt);
2520 }
2521 else if (is_gimple_assign (use_stmt))
2522 {
2523 if (gimple_assign_rhs_class (use_stmt) == GIMPLE_BINARY_RHS)
2524 {
2525 cmp = gimple_assign_rhs_code (use_stmt);
2526 lhs = gimple_assign_rhs1 (use_stmt);
2527 rhs = gimple_assign_rhs2 (use_stmt);
2528 }
2529 else if (gimple_assign_rhs_code (use_stmt) == COND_EXPR)
2530 {
2531 tree cond = gimple_assign_rhs1 (use_stmt);
2532 if (!COMPARISON_CLASS_P (cond))
2533 return false;
2534 cmp = TREE_CODE (cond);
2535 lhs = TREE_OPERAND (cond, 0);
2536 rhs = TREE_OPERAND (cond, 1);
2537 }
2538 else
2539 return false;
2540 }
2541 else
2542 return false;
2543 switch (cmp)
2544 {
2545 case EQ_EXPR:
2546 case NE_EXPR:
2547 case LT_EXPR:
2548 case GT_EXPR:
2549 case LE_EXPR:
2550 case GE_EXPR:
2551 break;
2552 default:
2553 return false;
2554 }
2555 if (lhs != (orig_use_lhs ? orig_use_lhs : phires)
2556 || !tree_fits_shwi_p (rhs)
2557 || !IN_RANGE (tree_to_shwi (rhs), -1, 1))
2558 return false;
2559
2560 if (is_cast)
2561 {
2562 if (TREE_CODE (rhs) != INTEGER_CST)
2563 return false;
2564 /* As for -ffast-math we assume the 2 return to be
2565 impossible, canonicalize (unsigned) res <= 1U or
2566 (unsigned) res < 2U into res >= 0 and (unsigned) res > 1U
2567 or (unsigned) res >= 2U as res < 0. */
2568 switch (cmp)
2569 {
2570 case LE_EXPR:
2571 if (!integer_onep (rhs))
2572 return false;
2573 cmp = GE_EXPR;
2574 break;
2575 case LT_EXPR:
2576 if (wi::ne_p (wi::to_widest (rhs), 2))
2577 return false;
2578 cmp = GE_EXPR;
2579 break;
2580 case GT_EXPR:
2581 if (!integer_onep (rhs))
2582 return false;
2583 cmp = LT_EXPR;
2584 break;
2585 case GE_EXPR:
2586 if (wi::ne_p (wi::to_widest (rhs), 2))
2587 return false;
2588 cmp = LT_EXPR;
2589 break;
2590 default:
2591 return false;
2592 }
2593 rhs = build_zero_cst (TREE_TYPE (phires));
2594 }
2595 else if (orig_use_lhs)
2596 {
2597 if ((cmp != EQ_EXPR && cmp != NE_EXPR) || !integer_zerop (rhs))
2598 return false;
2599 /* As for -ffast-math we assume the 2 return to be
2600 impossible, canonicalize (res & ~1) == 0 into
2601 res >= 0 and (res & ~1) != 0 as res < 0. */
2602 cmp = cmp == EQ_EXPR ? GE_EXPR : LT_EXPR;
2603 }
2604
2605 if (!empty_block_p (middle_bb))
2606 return false;
2607
2608 gcond *cond1 = as_a <gcond *> (*gsi_last_bb (cond_bb));
2609 enum tree_code cmp1 = gimple_cond_code (cond1);
2610 switch (cmp1)
2611 {
2612 case LT_EXPR:
2613 case LE_EXPR:
2614 case GT_EXPR:
2615 case GE_EXPR:
2616 break;
2617 default:
2618 return false;
2619 }
2620 tree lhs1 = gimple_cond_lhs (cond1);
2621 tree rhs1 = gimple_cond_rhs (cond1);
2622 if (TREE_CODE (lhs1) == SSA_NAME && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs1))
2623 return false;
2624 if (TREE_CODE (rhs1) == SSA_NAME && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (rhs1))
2625 return false;
2626
2627 if (!single_pred_p (cond_bb) || !cond_only_block_p (cond_bb))
2628 return false;
2629
2630 basic_block cond2_bb = single_pred (cond_bb);
2631 if (EDGE_COUNT (cond2_bb->succs) != 2)
2632 return false;
2633 edge cond2_phi_edge;
2634 if (EDGE_SUCC (cond2_bb, 0)->dest == cond_bb)
2635 {
2636 if (EDGE_SUCC (cond2_bb, 1)->dest != phi_bb)
2637 return false;
2638 cond2_phi_edge = EDGE_SUCC (cond2_bb, 1);
2639 }
2640 else if (EDGE_SUCC (cond2_bb, 0)->dest != phi_bb)
2641 return false;
2642 else
2643 cond2_phi_edge = EDGE_SUCC (cond2_bb, 0);
2644 tree arg2 = gimple_phi_arg_def (phi, cond2_phi_edge->dest_idx);
2645 if (!tree_fits_shwi_p (arg2))
2646 return false;
2647 gcond *cond2 = safe_dyn_cast <gcond *> (*gsi_last_bb (cond2_bb));
2648 if (!cond2)
2649 return false;
2650 enum tree_code cmp2 = gimple_cond_code (cond2);
2651 tree lhs2 = gimple_cond_lhs (cond2);
2652 tree rhs2 = gimple_cond_rhs (cond2);
2653 if (lhs2 == lhs1)
2654 {
2655 if (!operand_equal_p (rhs2, rhs1, 0))
2656 {
2657 if ((cmp2 == EQ_EXPR || cmp2 == NE_EXPR)
2658 && TREE_CODE (rhs1) == INTEGER_CST
2659 && TREE_CODE (rhs2) == INTEGER_CST)
2660 {
2661 /* For integers, we can have cond2 x == 5
2662 and cond1 x < 5, x <= 4, x <= 5, x < 6,
2663 x > 5, x >= 6, x >= 5 or x > 4. */
2664 if (tree_int_cst_lt (rhs1, rhs2))
2665 {
2666 if (wi::ne_p (wi::to_wide (rhs1) + 1, wi::to_wide (rhs2)))
2667 return false;
2668 if (cmp1 == LE_EXPR)
2669 cmp1 = LT_EXPR;
2670 else if (cmp1 == GT_EXPR)
2671 cmp1 = GE_EXPR;
2672 else
2673 return false;
2674 }
2675 else
2676 {
2677 gcc_checking_assert (tree_int_cst_lt (rhs2, rhs1));
2678 if (wi::ne_p (wi::to_wide (rhs2) + 1, wi::to_wide (rhs1)))
2679 return false;
2680 if (cmp1 == LT_EXPR)
2681 cmp1 = LE_EXPR;
2682 else if (cmp1 == GE_EXPR)
2683 cmp1 = GT_EXPR;
2684 else
2685 return false;
2686 }
2687 rhs1 = rhs2;
2688 }
2689 else
2690 return false;
2691 }
2692 }
2693 else if (lhs2 == rhs1)
2694 {
2695 if (rhs2 != lhs1)
2696 return false;
2697 }
2698 else
2699 return false;
2700
2701 tree arg3 = arg2;
2702 basic_block cond3_bb = cond2_bb;
2703 edge cond3_phi_edge = cond2_phi_edge;
2704 gcond *cond3 = cond2;
2705 enum tree_code cmp3 = cmp2;
2706 tree lhs3 = lhs2;
2707 tree rhs3 = rhs2;
2708 if (EDGE_COUNT (phi_bb->preds) == 4)
2709 {
2710 if (absu_hwi (tree_to_shwi (arg2)) != 1)
2711 return false;
2712 if ((cond2_phi_edge->flags & EDGE_FALSE_VALUE)
2713 && HONOR_NANS (TREE_TYPE (lhs1)))
2714 return false;
2715 if (e1->flags & EDGE_TRUE_VALUE)
2716 {
2717 if (tree_to_shwi (arg0) != 2
2718 || absu_hwi (tree_to_shwi (arg1)) != 1
2719 || wi::to_widest (arg1) == wi::to_widest (arg2))
2720 return false;
2721 }
2722 else if (tree_to_shwi (arg1) != 2
2723 || absu_hwi (tree_to_shwi (arg0)) != 1
2724 || wi::to_widest (arg0) == wi::to_widest (arg2))
2725 return false;
2726 switch (cmp2)
2727 {
2728 case LT_EXPR:
2729 case LE_EXPR:
2730 case GT_EXPR:
2731 case GE_EXPR:
2732 break;
2733 default:
2734 return false;
2735 }
2736 /* if (x < y) goto phi_bb; else fallthru;
2737 if (x > y) goto phi_bb; else fallthru;
2738 bbx:;
2739 phi_bb:;
2740 is ok, but if x and y are swapped in one of the comparisons,
2741 or the comparisons are the same and operands not swapped,
2742 or the true and false edges are swapped, it is not.
2743 For HONOR_NANS, the edge flags are irrelevant and the comparisons
2744 must be different for non-swapped operands and same for swapped
2745 operands. */
2746 if ((lhs2 == lhs1)
2747 ^ (HONOR_NANS (TREE_TYPE (lhs1))
2748 ? ((cmp2 == LT_EXPR || cmp2 == LE_EXPR)
2749 != (cmp1 == LT_EXPR || cmp1 == LE_EXPR))
2750 : (((cond2_phi_edge->flags
2751 & ((cmp2 == LT_EXPR || cmp2 == LE_EXPR)
2752 ? EDGE_TRUE_VALUE : EDGE_FALSE_VALUE)) != 0)
2753 != ((e1->flags
2754 & ((cmp1 == LT_EXPR || cmp1 == LE_EXPR)
2755 ? EDGE_TRUE_VALUE : EDGE_FALSE_VALUE)) != 0))))
2756 return false;
2757 if (!single_pred_p (cond2_bb) || !cond_only_block_p (cond2_bb))
2758 return false;
2759 cond3_bb = single_pred (cond2_bb);
2760 if (EDGE_COUNT (cond2_bb->succs) != 2)
2761 return false;
2762 if (EDGE_SUCC (cond3_bb, 0)->dest == cond2_bb)
2763 {
2764 if (EDGE_SUCC (cond3_bb, 1)->dest != phi_bb)
2765 return false;
2766 cond3_phi_edge = EDGE_SUCC (cond3_bb, 1);
2767 }
2768 else if (EDGE_SUCC (cond3_bb, 0)->dest != phi_bb)
2769 return false;
2770 else
2771 cond3_phi_edge = EDGE_SUCC (cond3_bb, 0);
2772 arg3 = gimple_phi_arg_def (phi, cond3_phi_edge->dest_idx);
2773 cond3 = safe_dyn_cast <gcond *> (*gsi_last_bb (cond3_bb));
2774 if (!cond3)
2775 return false;
2776 cmp3 = gimple_cond_code (cond3);
2777 lhs3 = gimple_cond_lhs (cond3);
2778 rhs3 = gimple_cond_rhs (cond3);
2779 if (lhs3 == lhs1)
2780 {
2781 if (!operand_equal_p (rhs3, rhs1, 0))
2782 return false;
2783 }
2784 else if (lhs3 == rhs1)
2785 {
2786 if (rhs3 != lhs1)
2787 return false;
2788 }
2789 else
2790 return false;
2791 }
2792 else if (absu_hwi (tree_to_shwi (arg0)) != 1
2793 || absu_hwi (tree_to_shwi (arg1)) != 1
2794 || wi::to_widest (arg0) == wi::to_widest (arg1)
2795 || HONOR_NANS (TREE_TYPE (lhs1)))
2796 return false;
2797
2798 if (!integer_zerop (arg3) || (cmp3 != EQ_EXPR && cmp3 != NE_EXPR))
2799 return false;
2800 if ((cond3_phi_edge->flags & (cmp3 == EQ_EXPR
2801 ? EDGE_TRUE_VALUE : EDGE_FALSE_VALUE)) == 0)
2802 return false;
2803
2804 /* lhs1 one_cmp rhs1 results in phires of 1. */
2805 enum tree_code one_cmp;
2806 if ((cmp1 == LT_EXPR || cmp1 == LE_EXPR)
2807 ^ (!integer_onep ((e1->flags & EDGE_TRUE_VALUE) ? arg1 : arg0)))
2808 one_cmp = LT_EXPR;
2809 else
2810 one_cmp = GT_EXPR;
2811
2812 enum tree_code res_cmp;
2813 bool negate_p = false;
2814 switch (cmp)
2815 {
2816 case EQ_EXPR:
2817 if (integer_zerop (rhs) && !HONOR_NANS (TREE_TYPE (lhs1)))
2818 res_cmp = EQ_EXPR;
2819 else if (integer_minus_onep (rhs))
2820 res_cmp = one_cmp == LT_EXPR ? GT_EXPR : LT_EXPR;
2821 else if (integer_onep (rhs))
2822 res_cmp = one_cmp;
2823 else
2824 return false;
2825 break;
2826 case NE_EXPR:
2827 if (integer_zerop (rhs) && !HONOR_NANS (TREE_TYPE (lhs1)))
2828 res_cmp = NE_EXPR;
2829 else if (integer_minus_onep (rhs))
2830 res_cmp = one_cmp == LT_EXPR ? LE_EXPR : GE_EXPR;
2831 else if (integer_onep (rhs))
2832 res_cmp = one_cmp == LT_EXPR ? GE_EXPR : LE_EXPR;
2833 else
2834 return false;
2835 if (HONOR_NANS (TREE_TYPE (lhs1)))
2836 negate_p = true;
2837 break;
2838 case LT_EXPR:
2839 if (integer_onep (rhs))
2840 res_cmp = one_cmp == LT_EXPR ? GE_EXPR : LE_EXPR;
2841 else if (integer_zerop (rhs))
2842 {
2843 if (HONOR_NANS (TREE_TYPE (lhs1)) && orig_use_lhs)
2844 negate_p = true;
2845 res_cmp = one_cmp == LT_EXPR ? GT_EXPR : LT_EXPR;
2846 }
2847 else
2848 return false;
2849 break;
2850 case LE_EXPR:
2851 if (integer_zerop (rhs))
2852 res_cmp = one_cmp == LT_EXPR ? GE_EXPR : LE_EXPR;
2853 else if (integer_minus_onep (rhs))
2854 res_cmp = one_cmp == LT_EXPR ? GT_EXPR : LT_EXPR;
2855 else
2856 return false;
2857 break;
2858 case GT_EXPR:
2859 if (integer_minus_onep (rhs))
2860 res_cmp = one_cmp == LT_EXPR ? LE_EXPR : GE_EXPR;
2861 else if (integer_zerop (rhs))
2862 res_cmp = one_cmp;
2863 else
2864 return false;
2865 if (HONOR_NANS (TREE_TYPE (lhs1)))
2866 negate_p = true;
2867 break;
2868 case GE_EXPR:
2869 if (integer_zerop (rhs))
2870 {
2871 if (HONOR_NANS (TREE_TYPE (lhs1)) && !orig_use_lhs)
2872 negate_p = true;
2873 res_cmp = one_cmp == LT_EXPR ? LE_EXPR : GE_EXPR;
2874 }
2875 else if (integer_onep (rhs))
2876 {
2877 if (HONOR_NANS (TREE_TYPE (lhs1)))
2878 negate_p = true;
2879 res_cmp = one_cmp;
2880 }
2881 else
2882 return false;
2883 break;
2884 default:
2885 gcc_unreachable ();
2886 }
2887
2888 tree clhs1 = lhs1, crhs1 = rhs1;
2889 if (negate_p)
2890 {
2891 if (cfun->can_throw_non_call_exceptions)
2892 return false;
2893 res_cmp = invert_tree_comparison (res_cmp, false);
2894 clhs1 = make_ssa_name (boolean_type_node);
2895 gimple *g = gimple_build_assign (clhs1, res_cmp, lhs1, rhs1);
2896 gimple_stmt_iterator gsi = gsi_for_stmt (use_stmt);
2897 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
2898 crhs1 = boolean_false_node;
2899 res_cmp = EQ_EXPR;
2900 }
2901
2902 if (gimple_code (use_stmt) == GIMPLE_COND)
2903 {
2904 gcond *use_cond = as_a <gcond *> (use_stmt);
2905 gimple_cond_set_code (use_cond, res_cmp);
2906 gimple_cond_set_lhs (use_cond, clhs1);
2907 gimple_cond_set_rhs (use_cond, crhs1);
2908 }
2909 else if (gimple_assign_rhs_class (use_stmt) == GIMPLE_BINARY_RHS)
2910 {
2911 gimple_assign_set_rhs_code (use_stmt, res_cmp);
2912 gimple_assign_set_rhs1 (use_stmt, clhs1);
2913 gimple_assign_set_rhs2 (use_stmt, crhs1);
2914 }
2915 else
2916 {
2917 tree cond = build2 (res_cmp, TREE_TYPE (gimple_assign_rhs1 (use_stmt)),
2918 clhs1, crhs1);
2919 gimple_assign_set_rhs1 (use_stmt, cond);
2920 }
2921 update_stmt (use_stmt);
2922
2923 if (MAY_HAVE_DEBUG_BIND_STMTS)
2924 {
2925 use_operand_p use_p;
2926 imm_use_iterator iter;
2927 bool has_debug_uses = false;
2928 bool has_cast_debug_uses = false;
2929 FOR_EACH_IMM_USE_FAST (use_p, iter, phires)
2930 {
2931 gimple *use_stmt = USE_STMT (use_p);
2932 if (orig_use_lhs && use_stmt == orig_use_stmt)
2933 continue;
2934 gcc_assert (is_gimple_debug (use_stmt));
2935 has_debug_uses = true;
2936 break;
2937 }
2938 if (orig_use_lhs)
2939 {
2940 if (!has_debug_uses || is_cast)
2941 FOR_EACH_IMM_USE_FAST (use_p, iter, orig_use_lhs)
2942 {
2943 gimple *use_stmt = USE_STMT (use_p);
2944 gcc_assert (is_gimple_debug (use_stmt));
2945 has_debug_uses = true;
2946 if (is_cast)
2947 has_cast_debug_uses = true;
2948 }
2949 gimple_stmt_iterator gsi = gsi_for_stmt (orig_use_stmt);
2950 tree zero = build_zero_cst (TREE_TYPE (orig_use_lhs));
2951 gimple_assign_set_rhs_with_ops (&gsi, INTEGER_CST, zero);
2952 update_stmt (orig_use_stmt);
2953 }
2954
2955 if (has_debug_uses)
2956 {
2957 /* If there are debug uses, emit something like:
2958 # DEBUG D#1 => i_2(D) > j_3(D) ? 1 : -1
2959 # DEBUG D#2 => i_2(D) == j_3(D) ? 0 : D#1
2960 where > stands for the comparison that yielded 1
2961 and replace debug uses of phi result with that D#2.
2962 Ignore the value of 2 if !HONOR_NANS, because if NaNs
2963 aren't expected, all floating point numbers should be
2964 comparable. If HONOR_NANS, emit something like:
2965 # DEBUG D#1 => i_2(D) < j_3(D) ? -1 : 2
2966 # DEBUG D#2 => i_2(D) > j_3(D) ? 1 : D#1
2967 # DEBUG D#3 => i_2(D) == j_3(D) ? 0 : D#2
2968 instead. */
2969 gimple_stmt_iterator gsi = gsi_after_labels (gimple_bb (phi));
2970 tree type = TREE_TYPE (phires);
2971 tree minus_one = build_int_cst (type, -1);
2972 if (HONOR_NANS (TREE_TYPE (lhs1)))
2973 {
2974 tree temp3 = build_debug_expr_decl (type);
2975 tree t = build2 (one_cmp == LT_EXPR ? GT_EXPR : LT_EXPR,
2976 boolean_type_node, lhs1, rhs2);
2977 t = build3 (COND_EXPR, type, t, minus_one,
2978 build_int_cst (type, 2));
2979 gimple *g = gimple_build_debug_bind (temp3, t, phi);
2980 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
2981 minus_one = temp3;
2982 }
2983 tree temp1 = build_debug_expr_decl (type);
2984 tree t = build2 (one_cmp, boolean_type_node, lhs1, rhs2);
2985 t = build3 (COND_EXPR, type, t, build_one_cst (type),
2986 minus_one);
2987 gimple *g = gimple_build_debug_bind (temp1, t, phi);
2988 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
2989 tree temp2 = build_debug_expr_decl (type);
2990 t = build2 (EQ_EXPR, boolean_type_node, lhs1, rhs2);
2991 t = build3 (COND_EXPR, type, t, build_zero_cst (type), temp1);
2992 g = gimple_build_debug_bind (temp2, t, phi);
2993 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
2994 replace_uses_by (phires, temp2);
2995 if (orig_use_lhs)
2996 {
2997 if (has_cast_debug_uses
2998 || (HONOR_NANS (TREE_TYPE (lhs1)) && !is_cast))
2999 {
3000 tree temp3
3001 = build_debug_expr_decl (TREE_TYPE (orig_use_lhs));
3002 if (has_cast_debug_uses)
3003 t = fold_convert (TREE_TYPE (temp3), temp2);
3004 else
3005 t = build2 (BIT_AND_EXPR, TREE_TYPE (temp3),
3006 temp2, build_int_cst (TREE_TYPE (temp3),
3007 ~1));
3008 g = gimple_build_debug_bind (temp3, t, phi);
3009 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
3010 replace_uses_by (orig_use_lhs, temp3);
3011 }
3012 else
3013 replace_uses_by (orig_use_lhs, temp2);
3014 }
3015 }
3016 }
3017
3018 if (orig_use_lhs)
3019 {
3020 gimple_stmt_iterator gsi = gsi_for_stmt (orig_use_stmt);
3021 gsi_remove (&gsi, true);
3022 }
3023
3024 gimple_stmt_iterator psi = gsi_for_stmt (phi);
3025 remove_phi_node (&psi, true);
3026 statistics_counter_event (cfun, "spaceship replacement", 1);
3027
3028 return true;
3029 }
3030
3031 /* Optimize x ? __builtin_fun (x) : C, where C is __builtin_fun (0).
3032 Convert
3033
3034 <bb 2>
3035 if (b_4(D) != 0)
3036 goto <bb 3>
3037 else
3038 goto <bb 4>
3039
3040 <bb 3>
3041 _2 = (unsigned long) b_4(D);
3042 _9 = __builtin_popcountl (_2);
3043 OR
3044 _9 = __builtin_popcountl (b_4(D));
3045
3046 <bb 4>
3047 c_12 = PHI <0(2), _9(3)>
3048
3049 Into
3050 <bb 2>
3051 _2 = (unsigned long) b_4(D);
3052 _9 = __builtin_popcountl (_2);
3053 OR
3054 _9 = __builtin_popcountl (b_4(D));
3055
3056 <bb 4>
3057 c_12 = PHI <_9(2)>
3058
3059 Similarly for __builtin_clz or __builtin_ctz if
3060 C?Z_DEFINED_VALUE_AT_ZERO is 2, optab is present and
3061 instead of 0 above it uses the value from that macro. */
3062
3063 static bool
3064 cond_removal_in_builtin_zero_pattern (basic_block cond_bb,
3065 basic_block middle_bb,
3066 edge e1, edge e2, gphi *phi,
3067 tree arg0, tree arg1)
3068 {
3069 gimple_stmt_iterator gsi, gsi_from;
3070 gimple *call;
3071 gimple *cast = NULL;
3072 tree lhs, arg;
3073
3074 /* Check that
3075 _2 = (unsigned long) b_4(D);
3076 _9 = __builtin_popcountl (_2);
3077 OR
3078 _9 = __builtin_popcountl (b_4(D));
3079 are the only stmts in the middle_bb. */
3080
3081 gsi = gsi_start_nondebug_after_labels_bb (middle_bb);
3082 if (gsi_end_p (gsi))
3083 return false;
3084 cast = gsi_stmt (gsi);
3085 gsi_next_nondebug (&gsi);
3086 if (!gsi_end_p (gsi))
3087 {
3088 call = gsi_stmt (gsi);
3089 gsi_next_nondebug (&gsi);
3090 if (!gsi_end_p (gsi))
3091 return false;
3092 }
3093 else
3094 {
3095 call = cast;
3096 cast = NULL;
3097 }
3098
3099 /* Check that we have a popcount/clz/ctz builtin. */
3100 if (!is_gimple_call (call))
3101 return false;
3102
3103 lhs = gimple_get_lhs (call);
3104
3105 if (lhs == NULL_TREE)
3106 return false;
3107
3108 combined_fn cfn = gimple_call_combined_fn (call);
3109 if (gimple_call_num_args (call) != 1
3110 && (gimple_call_num_args (call) != 2
3111 || cfn == CFN_CLZ
3112 || cfn == CFN_CTZ))
3113 return false;
3114
3115 arg = gimple_call_arg (call, 0);
3116
3117 internal_fn ifn = IFN_LAST;
3118 int val = 0;
3119 bool any_val = false;
3120 switch (cfn)
3121 {
3122 case CFN_BUILT_IN_BSWAP16:
3123 case CFN_BUILT_IN_BSWAP32:
3124 case CFN_BUILT_IN_BSWAP64:
3125 case CFN_BUILT_IN_BSWAP128:
3126 CASE_CFN_FFS:
3127 CASE_CFN_PARITY:
3128 CASE_CFN_POPCOUNT:
3129 break;
3130 CASE_CFN_CLZ:
3131 if (INTEGRAL_TYPE_P (TREE_TYPE (arg)))
3132 {
3133 tree type = TREE_TYPE (arg);
3134 if (TREE_CODE (type) == BITINT_TYPE)
3135 {
3136 if (gimple_call_num_args (call) == 1)
3137 {
3138 any_val = true;
3139 ifn = IFN_CLZ;
3140 break;
3141 }
3142 if (!tree_fits_shwi_p (gimple_call_arg (call, 1)))
3143 return false;
3144 HOST_WIDE_INT at_zero = tree_to_shwi (gimple_call_arg (call, 1));
3145 if ((int) at_zero != at_zero)
3146 return false;
3147 ifn = IFN_CLZ;
3148 val = at_zero;
3149 break;
3150 }
3151 if (direct_internal_fn_supported_p (IFN_CLZ, type, OPTIMIZE_FOR_BOTH)
3152 && CLZ_DEFINED_VALUE_AT_ZERO (SCALAR_INT_TYPE_MODE (type),
3153 val) == 2)
3154 {
3155 ifn = IFN_CLZ;
3156 break;
3157 }
3158 }
3159 return false;
3160 CASE_CFN_CTZ:
3161 if (INTEGRAL_TYPE_P (TREE_TYPE (arg)))
3162 {
3163 tree type = TREE_TYPE (arg);
3164 if (TREE_CODE (type) == BITINT_TYPE)
3165 {
3166 if (gimple_call_num_args (call) == 1)
3167 {
3168 any_val = true;
3169 ifn = IFN_CTZ;
3170 break;
3171 }
3172 if (!tree_fits_shwi_p (gimple_call_arg (call, 1)))
3173 return false;
3174 HOST_WIDE_INT at_zero = tree_to_shwi (gimple_call_arg (call, 1));
3175 if ((int) at_zero != at_zero)
3176 return false;
3177 ifn = IFN_CTZ;
3178 val = at_zero;
3179 break;
3180 }
3181 if (direct_internal_fn_supported_p (IFN_CTZ, type, OPTIMIZE_FOR_BOTH)
3182 && CTZ_DEFINED_VALUE_AT_ZERO (SCALAR_INT_TYPE_MODE (type),
3183 val) == 2)
3184 {
3185 ifn = IFN_CTZ;
3186 break;
3187 }
3188 }
3189 return false;
3190 case CFN_BUILT_IN_CLRSB:
3191 val = TYPE_PRECISION (integer_type_node) - 1;
3192 break;
3193 case CFN_BUILT_IN_CLRSBL:
3194 val = TYPE_PRECISION (long_integer_type_node) - 1;
3195 break;
3196 case CFN_BUILT_IN_CLRSBLL:
3197 val = TYPE_PRECISION (long_long_integer_type_node) - 1;
3198 break;
3199 default:
3200 return false;
3201 }
3202
3203 if (cast)
3204 {
3205 /* We have a cast stmt feeding popcount/clz/ctz builtin. */
3206 /* Check that we have a cast prior to that. */
3207 if (gimple_code (cast) != GIMPLE_ASSIGN
3208 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (cast)))
3209 return false;
3210 /* Result of the cast stmt is the argument to the builtin. */
3211 if (arg != gimple_assign_lhs (cast))
3212 return false;
3213 arg = gimple_assign_rhs1 (cast);
3214 }
3215
3216 gcond *cond = dyn_cast <gcond *> (*gsi_last_bb (cond_bb));
3217
3218 /* Cond_bb has a check for b_4 [!=|==] 0 before calling the popcount/clz/ctz
3219 builtin. */
3220 if (!cond
3221 || (gimple_cond_code (cond) != NE_EXPR
3222 && gimple_cond_code (cond) != EQ_EXPR)
3223 || !integer_zerop (gimple_cond_rhs (cond))
3224 || arg != gimple_cond_lhs (cond))
3225 return false;
3226
3227 edge true_edge, false_edge;
3228 /* We need to know which is the true edge and which is the false
3229 edge so that we know when to invert the condition below. */
3230 extract_true_false_edges_from_block (cond_bb, &true_edge, &false_edge);
3231
3232 /* Forward the edges over the middle basic block. */
3233 if (true_edge->dest == middle_bb)
3234 true_edge = EDGE_SUCC (true_edge->dest, 0);
3235 if (false_edge->dest == middle_bb)
3236 false_edge = EDGE_SUCC (false_edge->dest, 0);
3237
3238 /* Canonicalize the args with respect to the edges,
3239 arg0 is from the true edge and arg1 is from the
3240 false edge.
3241 That is `cond ? arg0 : arg1`.*/
3242 if (true_edge == e1)
3243 gcc_assert (false_edge == e2);
3244 else
3245 {
3246 gcc_assert (false_edge == e1);
3247 gcc_assert (true_edge == e2);
3248 std::swap (arg0, arg1);
3249 }
3250
3251 /* Canonicalize the args such that we get:
3252 `arg != 0 ? arg0 : arg1`. So swap arg0/arg1
3253 around if cond was an equals. */
3254 if (gimple_cond_code (cond) == EQ_EXPR)
3255 std::swap (arg0, arg1);
3256
3257 /* Check PHI arguments. */
3258 if (lhs != arg0
3259 || TREE_CODE (arg1) != INTEGER_CST)
3260 return false;
3261 if (any_val)
3262 {
3263 if (!tree_fits_shwi_p (arg1))
3264 return false;
3265 HOST_WIDE_INT at_zero = tree_to_shwi (arg1);
3266 if ((int) at_zero != at_zero)
3267 return false;
3268 val = at_zero;
3269 }
3270 else if (wi::to_wide (arg1) != val)
3271 return false;
3272
3273 /* And insert the popcount/clz/ctz builtin and cast stmt before the
3274 cond_bb. */
3275 gsi = gsi_last_bb (cond_bb);
3276 if (cast)
3277 {
3278 gsi_from = gsi_for_stmt (cast);
3279 gsi_move_before (&gsi_from, &gsi);
3280 reset_flow_sensitive_info (gimple_get_lhs (cast));
3281 }
3282 gsi_from = gsi_for_stmt (call);
3283 if (ifn == IFN_LAST
3284 || (gimple_call_internal_p (call) && gimple_call_num_args (call) == 2))
3285 gsi_move_before (&gsi_from, &gsi);
3286 else
3287 {
3288 /* For __builtin_c[lt]z* force .C[LT]Z ifn, because only
3289 the latter is well defined at zero. */
3290 call = gimple_build_call_internal (ifn, 2, gimple_call_arg (call, 0),
3291 build_int_cst (integer_type_node, val));
3292 gimple_call_set_lhs (call, lhs);
3293 gsi_insert_before (&gsi, call, GSI_SAME_STMT);
3294 gsi_remove (&gsi_from, true);
3295 }
3296 reset_flow_sensitive_info (lhs);
3297
3298 /* Now update the PHI and remove unneeded bbs. */
3299 replace_phi_edge_with_variable (cond_bb, e2, phi, lhs);
3300 return true;
3301 }
3302
3303 /* Auxiliary functions to determine the set of memory accesses which
3304 can't trap because they are preceded by accesses to the same memory
3305 portion. We do that for MEM_REFs, so we only need to track
3306 the SSA_NAME of the pointer indirectly referenced. The algorithm
3307 simply is a walk over all instructions in dominator order. When
3308 we see an MEM_REF we determine if we've already seen a same
3309 ref anywhere up to the root of the dominator tree. If we do the
3310 current access can't trap. If we don't see any dominating access
3311 the current access might trap, but might also make later accesses
3312 non-trapping, so we remember it. We need to be careful with loads
3313 or stores, for instance a load might not trap, while a store would,
3314 so if we see a dominating read access this doesn't mean that a later
3315 write access would not trap. Hence we also need to differentiate the
3316 type of access(es) seen.
3317
3318 ??? We currently are very conservative and assume that a load might
3319 trap even if a store doesn't (write-only memory). This probably is
3320 overly conservative.
3321
3322 We currently support a special case that for !TREE_ADDRESSABLE automatic
3323 variables, it could ignore whether something is a load or store because the
3324 local stack should be always writable. */
3325
3326 /* A hash-table of references (MEM_REF/ARRAY_REF/COMPONENT_REF), and in which
3327 basic block an *_REF through it was seen, which would constitute a
3328 no-trap region for same accesses.
3329
3330 Size is needed to support 2 MEM_REFs of different types, like
3331 MEM<double>(s_1) and MEM<long>(s_1), which would compare equal with
3332 OEP_ADDRESS_OF. */
3333 struct ref_to_bb
3334 {
3335 tree exp;
3336 HOST_WIDE_INT size;
3337 unsigned int phase;
3338 basic_block bb;
3339 };
3340
3341 /* Hashtable helpers. */
3342
3343 struct refs_hasher : free_ptr_hash<ref_to_bb>
3344 {
3345 static inline hashval_t hash (const ref_to_bb *);
3346 static inline bool equal (const ref_to_bb *, const ref_to_bb *);
3347 };
3348
3349 /* Used for quick clearing of the hash-table when we see calls.
3350 Hash entries with phase < nt_call_phase are invalid. */
3351 static unsigned int nt_call_phase;
3352
3353 /* The hash function. */
3354
3355 inline hashval_t
3356 refs_hasher::hash (const ref_to_bb *n)
3357 {
3358 inchash::hash hstate;
3359 inchash::add_expr (n->exp, hstate, OEP_ADDRESS_OF);
3360 hstate.add_hwi (n->size);
3361 return hstate.end ();
3362 }
3363
3364 /* The equality function of *P1 and *P2. */
3365
3366 inline bool
3367 refs_hasher::equal (const ref_to_bb *n1, const ref_to_bb *n2)
3368 {
3369 return operand_equal_p (n1->exp, n2->exp, OEP_ADDRESS_OF)
3370 && n1->size == n2->size;
3371 }
3372
3373 class nontrapping_dom_walker : public dom_walker
3374 {
3375 public:
3376 nontrapping_dom_walker (cdi_direction direction, hash_set<tree> *ps)
3377 : dom_walker (direction), m_nontrapping (ps), m_seen_refs (128)
3378 {}
3379
3380 edge before_dom_children (basic_block) final override;
3381 void after_dom_children (basic_block) final override;
3382
3383 private:
3384
3385 /* We see the expression EXP in basic block BB. If it's an interesting
3386 expression (an MEM_REF through an SSA_NAME) possibly insert the
3387 expression into the set NONTRAP or the hash table of seen expressions.
3388 STORE is true if this expression is on the LHS, otherwise it's on
3389 the RHS. */
3390 void add_or_mark_expr (basic_block, tree, bool);
3391
3392 hash_set<tree> *m_nontrapping;
3393
3394 /* The hash table for remembering what we've seen. */
3395 hash_table<refs_hasher> m_seen_refs;
3396 };
3397
3398 /* Called by walk_dominator_tree, when entering the block BB. */
3399 edge
3400 nontrapping_dom_walker::before_dom_children (basic_block bb)
3401 {
3402 edge e;
3403 edge_iterator ei;
3404 gimple_stmt_iterator gsi;
3405
3406 /* If we haven't seen all our predecessors, clear the hash-table. */
3407 FOR_EACH_EDGE (e, ei, bb->preds)
3408 if ((((size_t)e->src->aux) & 2) == 0)
3409 {
3410 nt_call_phase++;
3411 break;
3412 }
3413
3414 /* Mark this BB as being on the path to dominator root and as visited. */
3415 bb->aux = (void*)(1 | 2);
3416
3417 /* And walk the statements in order. */
3418 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3419 {
3420 gimple *stmt = gsi_stmt (gsi);
3421
3422 if ((gimple_code (stmt) == GIMPLE_ASM && gimple_vdef (stmt))
3423 || (is_gimple_call (stmt)
3424 && (!nonfreeing_call_p (stmt) || !nonbarrier_call_p (stmt))))
3425 nt_call_phase++;
3426 else if (gimple_assign_single_p (stmt) && !gimple_has_volatile_ops (stmt))
3427 {
3428 add_or_mark_expr (bb, gimple_assign_lhs (stmt), true);
3429 add_or_mark_expr (bb, gimple_assign_rhs1 (stmt), false);
3430 }
3431 }
3432 return NULL;
3433 }
3434
3435 /* Called by walk_dominator_tree, when basic block BB is exited. */
3436 void
3437 nontrapping_dom_walker::after_dom_children (basic_block bb)
3438 {
3439 /* This BB isn't on the path to dominator root anymore. */
3440 bb->aux = (void*)2;
3441 }
3442
3443 /* We see the expression EXP in basic block BB. If it's an interesting
3444 expression of:
3445 1) MEM_REF
3446 2) ARRAY_REF
3447 3) COMPONENT_REF
3448 possibly insert the expression into the set NONTRAP or the hash table
3449 of seen expressions. STORE is true if this expression is on the LHS,
3450 otherwise it's on the RHS. */
3451 void
3452 nontrapping_dom_walker::add_or_mark_expr (basic_block bb, tree exp, bool store)
3453 {
3454 HOST_WIDE_INT size;
3455
3456 if ((TREE_CODE (exp) == MEM_REF || TREE_CODE (exp) == ARRAY_REF
3457 || TREE_CODE (exp) == COMPONENT_REF)
3458 && (size = int_size_in_bytes (TREE_TYPE (exp))) > 0)
3459 {
3460 struct ref_to_bb map;
3461 ref_to_bb **slot;
3462 struct ref_to_bb *r2bb;
3463 basic_block found_bb = 0;
3464
3465 if (!store)
3466 {
3467 tree base = get_base_address (exp);
3468 /* Only record a LOAD of a local variable without address-taken, as
3469 the local stack is always writable. This allows cselim on a STORE
3470 with a dominating LOAD. */
3471 if (!auto_var_p (base) || TREE_ADDRESSABLE (base))
3472 return;
3473 }
3474
3475 /* Try to find the last seen *_REF, which can trap. */
3476 map.exp = exp;
3477 map.size = size;
3478 slot = m_seen_refs.find_slot (&map, INSERT);
3479 r2bb = *slot;
3480 if (r2bb && r2bb->phase >= nt_call_phase)
3481 found_bb = r2bb->bb;
3482
3483 /* If we've found a trapping *_REF, _and_ it dominates EXP
3484 (it's in a basic block on the path from us to the dominator root)
3485 then we can't trap. */
3486 if (found_bb && (((size_t)found_bb->aux) & 1) == 1)
3487 {
3488 m_nontrapping->add (exp);
3489 }
3490 else
3491 {
3492 /* EXP might trap, so insert it into the hash table. */
3493 if (r2bb)
3494 {
3495 r2bb->phase = nt_call_phase;
3496 r2bb->bb = bb;
3497 }
3498 else
3499 {
3500 r2bb = XNEW (struct ref_to_bb);
3501 r2bb->phase = nt_call_phase;
3502 r2bb->bb = bb;
3503 r2bb->exp = exp;
3504 r2bb->size = size;
3505 *slot = r2bb;
3506 }
3507 }
3508 }
3509 }
3510
3511 /* This is the entry point of gathering non trapping memory accesses.
3512 It will do a dominator walk over the whole function, and it will
3513 make use of the bb->aux pointers. It returns a set of trees
3514 (the MEM_REFs itself) which can't trap. */
3515 static hash_set<tree> *
3516 get_non_trapping (void)
3517 {
3518 nt_call_phase = 0;
3519 hash_set<tree> *nontrap = new hash_set<tree>;
3520
3521 nontrapping_dom_walker (CDI_DOMINATORS, nontrap)
3522 .walk (cfun->cfg->x_entry_block_ptr);
3523
3524 clear_aux_for_blocks ();
3525 return nontrap;
3526 }
3527
3528 /* Do the main work of conditional store replacement. We already know
3529 that the recognized pattern looks like so:
3530
3531 split:
3532 if (cond) goto MIDDLE_BB; else goto JOIN_BB (edge E1)
3533 MIDDLE_BB:
3534 something
3535 fallthrough (edge E0)
3536 JOIN_BB:
3537 some more
3538
3539 We check that MIDDLE_BB contains only one store, that that store
3540 doesn't trap (not via NOTRAP, but via checking if an access to the same
3541 memory location dominates us, or the store is to a local addressable
3542 object) and that the store has a "simple" RHS. */
3543
3544 static bool
3545 cond_store_replacement (basic_block middle_bb, basic_block join_bb,
3546 edge e0, edge e1, hash_set<tree> *nontrap)
3547 {
3548 gimple *assign = last_and_only_stmt (middle_bb);
3549 tree lhs, rhs, name, name2;
3550 gphi *newphi;
3551 gassign *new_stmt;
3552 gimple_stmt_iterator gsi;
3553 location_t locus;
3554
3555 /* Check if middle_bb contains of only one store. */
3556 if (!assign
3557 || !gimple_assign_single_p (assign)
3558 || gimple_has_volatile_ops (assign))
3559 return false;
3560
3561 /* And no PHI nodes so all uses in the single stmt are also
3562 available where we insert to. */
3563 if (!gimple_seq_empty_p (phi_nodes (middle_bb)))
3564 return false;
3565
3566 locus = gimple_location (assign);
3567 lhs = gimple_assign_lhs (assign);
3568 rhs = gimple_assign_rhs1 (assign);
3569 if ((!REFERENCE_CLASS_P (lhs)
3570 && !DECL_P (lhs))
3571 || !is_gimple_reg_type (TREE_TYPE (lhs)))
3572 return false;
3573
3574 /* Prove that we can move the store down. We could also check
3575 TREE_THIS_NOTRAP here, but in that case we also could move stores,
3576 whose value is not available readily, which we want to avoid. */
3577 if (!nontrap->contains (lhs))
3578 {
3579 /* If LHS is an access to a local variable without address-taken
3580 (or when we allow data races) and known not to trap, we could
3581 always safely move down the store. */
3582 tree base;
3583 if (ref_can_have_store_data_races (lhs)
3584 || tree_could_trap_p (lhs)
3585 /* tree_could_trap_p is a predicate for rvalues, so check
3586 for readonly memory explicitly. */
3587 || ((base = get_base_address (lhs))
3588 && ((DECL_P (base)
3589 && TREE_READONLY (base))
3590 || TREE_CODE (base) == STRING_CST)))
3591 return false;
3592 }
3593
3594 /* Now we've checked the constraints, so do the transformation:
3595 1) Remove the single store. */
3596 gsi = gsi_for_stmt (assign);
3597 unlink_stmt_vdef (assign);
3598 gsi_remove (&gsi, true);
3599 release_defs (assign);
3600
3601 /* Make both store and load use alias-set zero as we have to
3602 deal with the case of the store being a conditional change
3603 of the dynamic type. */
3604 lhs = unshare_expr (lhs);
3605 tree *basep = &lhs;
3606 while (handled_component_p (*basep))
3607 basep = &TREE_OPERAND (*basep, 0);
3608 if (TREE_CODE (*basep) == MEM_REF
3609 || TREE_CODE (*basep) == TARGET_MEM_REF)
3610 TREE_OPERAND (*basep, 1)
3611 = fold_convert (ptr_type_node, TREE_OPERAND (*basep, 1));
3612 else
3613 *basep = build2 (MEM_REF, TREE_TYPE (*basep),
3614 build_fold_addr_expr (*basep),
3615 build_zero_cst (ptr_type_node));
3616
3617 /* 2) Insert a load from the memory of the store to the temporary
3618 on the edge which did not contain the store. */
3619 name = make_temp_ssa_name (TREE_TYPE (lhs), NULL, "cstore");
3620 new_stmt = gimple_build_assign (name, lhs);
3621 gimple_set_location (new_stmt, locus);
3622 lhs = unshare_expr (lhs);
3623 {
3624 /* Set the no-warning bit on the rhs of the load to avoid uninit
3625 warnings. */
3626 tree rhs1 = gimple_assign_rhs1 (new_stmt);
3627 suppress_warning (rhs1, OPT_Wuninitialized);
3628 }
3629 gsi_insert_on_edge (e1, new_stmt);
3630
3631 /* 3) Create a PHI node at the join block, with one argument
3632 holding the old RHS, and the other holding the temporary
3633 where we stored the old memory contents. */
3634 name2 = make_temp_ssa_name (TREE_TYPE (lhs), NULL, "cstore");
3635 newphi = create_phi_node (name2, join_bb);
3636 add_phi_arg (newphi, rhs, e0, locus);
3637 add_phi_arg (newphi, name, e1, locus);
3638
3639 new_stmt = gimple_build_assign (lhs, gimple_phi_result (newphi));
3640
3641 /* 4) Insert that PHI node. */
3642 gsi = gsi_after_labels (join_bb);
3643 if (gsi_end_p (gsi))
3644 {
3645 gsi = gsi_last_bb (join_bb);
3646 gsi_insert_after (&gsi, new_stmt, GSI_NEW_STMT);
3647 }
3648 else
3649 gsi_insert_before (&gsi, new_stmt, GSI_NEW_STMT);
3650
3651 if (dump_file && (dump_flags & TDF_DETAILS))
3652 {
3653 fprintf (dump_file, "\nConditional store replacement happened!");
3654 fprintf (dump_file, "\nReplaced the store with a load.");
3655 fprintf (dump_file, "\nInserted a new PHI statement in joint block:\n");
3656 print_gimple_stmt (dump_file, new_stmt, 0, TDF_VOPS|TDF_MEMSYMS);
3657 }
3658 statistics_counter_event (cfun, "conditional store replacement", 1);
3659
3660 return true;
3661 }
3662
3663 /* Do the main work of conditional store replacement. */
3664
3665 static bool
3666 cond_if_else_store_replacement_1 (basic_block then_bb, basic_block else_bb,
3667 basic_block join_bb, gimple *then_assign,
3668 gimple *else_assign)
3669 {
3670 tree lhs_base, lhs, then_rhs, else_rhs, name;
3671 location_t then_locus, else_locus;
3672 gimple_stmt_iterator gsi;
3673 gphi *newphi;
3674 gassign *new_stmt;
3675
3676 if (then_assign == NULL
3677 || !gimple_assign_single_p (then_assign)
3678 || gimple_clobber_p (then_assign)
3679 || gimple_has_volatile_ops (then_assign)
3680 || else_assign == NULL
3681 || !gimple_assign_single_p (else_assign)
3682 || gimple_clobber_p (else_assign)
3683 || gimple_has_volatile_ops (else_assign)
3684 || stmt_references_abnormal_ssa_name (then_assign)
3685 || stmt_references_abnormal_ssa_name (else_assign))
3686 return false;
3687
3688 lhs = gimple_assign_lhs (then_assign);
3689 if (!is_gimple_reg_type (TREE_TYPE (lhs))
3690 || !operand_equal_p (lhs, gimple_assign_lhs (else_assign), 0))
3691 return false;
3692
3693 lhs_base = get_base_address (lhs);
3694 if (lhs_base == NULL_TREE
3695 || (!DECL_P (lhs_base) && TREE_CODE (lhs_base) != MEM_REF))
3696 return false;
3697
3698 then_rhs = gimple_assign_rhs1 (then_assign);
3699 else_rhs = gimple_assign_rhs1 (else_assign);
3700 then_locus = gimple_location (then_assign);
3701 else_locus = gimple_location (else_assign);
3702
3703 if (dump_file && (dump_flags & TDF_DETAILS))
3704 {
3705 fprintf(dump_file, "factoring out stores:\n\tthen:\n");
3706 print_gimple_stmt (dump_file, then_assign, 0,
3707 TDF_VOPS|TDF_MEMSYMS);
3708 fprintf(dump_file, "\telse:\n");
3709 print_gimple_stmt (dump_file, else_assign, 0,
3710 TDF_VOPS|TDF_MEMSYMS);
3711 fprintf (dump_file, "\n");
3712 }
3713
3714 /* Now we've checked the constraints, so do the transformation:
3715 1) Remove the stores. */
3716 gsi = gsi_for_stmt (then_assign);
3717 unlink_stmt_vdef (then_assign);
3718 gsi_remove (&gsi, true);
3719 release_defs (then_assign);
3720
3721 gsi = gsi_for_stmt (else_assign);
3722 unlink_stmt_vdef (else_assign);
3723 gsi_remove (&gsi, true);
3724 release_defs (else_assign);
3725
3726 /* 2) Create a PHI node at the join block, with one argument
3727 holding the old RHS, and the other holding the temporary
3728 where we stored the old memory contents. */
3729 name = make_temp_ssa_name (TREE_TYPE (lhs), NULL, "cstore");
3730 newphi = create_phi_node (name, join_bb);
3731 add_phi_arg (newphi, then_rhs, EDGE_SUCC (then_bb, 0), then_locus);
3732 add_phi_arg (newphi, else_rhs, EDGE_SUCC (else_bb, 0), else_locus);
3733
3734 new_stmt = gimple_build_assign (lhs, gimple_phi_result (newphi));
3735 if (dump_file && (dump_flags & TDF_DETAILS))
3736 {
3737 fprintf(dump_file, "to use phi:\n");
3738 print_gimple_stmt (dump_file, newphi, 0,
3739 TDF_VOPS|TDF_MEMSYMS);
3740 fprintf(dump_file, "\n");
3741 print_gimple_stmt (dump_file, new_stmt, 0,
3742 TDF_VOPS|TDF_MEMSYMS);
3743 fprintf(dump_file, "\n\n");
3744 }
3745
3746 /* 3) Insert that PHI node. */
3747 gsi = gsi_after_labels (join_bb);
3748 if (gsi_end_p (gsi))
3749 {
3750 gsi = gsi_last_bb (join_bb);
3751 gsi_insert_after (&gsi, new_stmt, GSI_NEW_STMT);
3752 }
3753 else
3754 gsi_insert_before (&gsi, new_stmt, GSI_NEW_STMT);
3755
3756 statistics_counter_event (cfun, "if-then-else store replacement", 1);
3757
3758 return true;
3759 }
3760
3761 /* Return the single store in BB with VDEF or NULL if there are
3762 other stores in the BB or loads following the store. */
3763
3764 static gimple *
3765 single_trailing_store_in_bb (basic_block bb, tree vdef)
3766 {
3767 if (SSA_NAME_IS_DEFAULT_DEF (vdef))
3768 return NULL;
3769 gimple *store = SSA_NAME_DEF_STMT (vdef);
3770 if (gimple_bb (store) != bb
3771 || gimple_code (store) == GIMPLE_PHI)
3772 return NULL;
3773
3774 /* Verify there is no other store in this BB. */
3775 if (!SSA_NAME_IS_DEFAULT_DEF (gimple_vuse (store))
3776 && gimple_bb (SSA_NAME_DEF_STMT (gimple_vuse (store))) == bb
3777 && gimple_code (SSA_NAME_DEF_STMT (gimple_vuse (store))) != GIMPLE_PHI)
3778 return NULL;
3779
3780 /* Verify there is no load or store after the store. */
3781 use_operand_p use_p;
3782 imm_use_iterator imm_iter;
3783 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, gimple_vdef (store))
3784 if (USE_STMT (use_p) != store
3785 && gimple_bb (USE_STMT (use_p)) == bb)
3786 return NULL;
3787
3788 return store;
3789 }
3790
3791 /* Conditional store replacement. We already know
3792 that the recognized pattern looks like so:
3793
3794 split:
3795 if (cond) goto THEN_BB; else goto ELSE_BB (edge E1)
3796 THEN_BB:
3797 ...
3798 X = Y;
3799 ...
3800 goto JOIN_BB;
3801 ELSE_BB:
3802 ...
3803 X = Z;
3804 ...
3805 fallthrough (edge E0)
3806 JOIN_BB:
3807 some more
3808
3809 We check that it is safe to sink the store to JOIN_BB by verifying that
3810 there are no read-after-write or write-after-write dependencies in
3811 THEN_BB and ELSE_BB. */
3812
3813 static bool
3814 cond_if_else_store_replacement (basic_block then_bb, basic_block else_bb,
3815 basic_block join_bb)
3816 {
3817 vec<data_reference_p> then_datarefs, else_datarefs;
3818 vec<ddr_p> then_ddrs, else_ddrs;
3819 gimple *then_store, *else_store;
3820 bool found, ok = false, res;
3821 tree then_lhs, else_lhs;
3822 basic_block blocks[3];
3823
3824 /* Handle the case with single store in THEN_BB and ELSE_BB. That is
3825 cheap enough to always handle as it allows us to elide dependence
3826 checking. */
3827 gphi *vphi = NULL;
3828 for (gphi_iterator si = gsi_start_phis (join_bb); !gsi_end_p (si);
3829 gsi_next (&si))
3830 if (virtual_operand_p (gimple_phi_result (si.phi ())))
3831 {
3832 vphi = si.phi ();
3833 break;
3834 }
3835 if (!vphi)
3836 return false;
3837 tree then_vdef = PHI_ARG_DEF_FROM_EDGE (vphi, single_succ_edge (then_bb));
3838 tree else_vdef = PHI_ARG_DEF_FROM_EDGE (vphi, single_succ_edge (else_bb));
3839 gimple *then_assign = single_trailing_store_in_bb (then_bb, then_vdef);
3840 if (then_assign)
3841 {
3842 gimple *else_assign = single_trailing_store_in_bb (else_bb, else_vdef);
3843 if (else_assign)
3844 return cond_if_else_store_replacement_1 (then_bb, else_bb, join_bb,
3845 then_assign, else_assign);
3846 }
3847
3848 /* If either vectorization or if-conversion is disabled then do
3849 not sink any stores. */
3850 if (param_max_stores_to_sink == 0
3851 || (!flag_tree_loop_vectorize && !flag_tree_slp_vectorize)
3852 || !flag_tree_loop_if_convert)
3853 return false;
3854
3855 /* Find data references. */
3856 then_datarefs.create (1);
3857 else_datarefs.create (1);
3858 if ((find_data_references_in_bb (NULL, then_bb, &then_datarefs)
3859 == chrec_dont_know)
3860 || !then_datarefs.length ()
3861 || (find_data_references_in_bb (NULL, else_bb, &else_datarefs)
3862 == chrec_dont_know)
3863 || !else_datarefs.length ())
3864 {
3865 free_data_refs (then_datarefs);
3866 free_data_refs (else_datarefs);
3867 return false;
3868 }
3869
3870 /* Clear visited on else stores, we want to make sure to pick each store
3871 at most once to avoid quadratic behavior. */
3872 for (auto else_dr : else_datarefs)
3873 {
3874 if (DR_IS_READ (else_dr))
3875 continue;
3876 gimple_set_visited (DR_STMT (else_dr), false);
3877 }
3878
3879 /* Find pairs of stores with equal LHS. Work from the end to avoid
3880 re-ordering stores unnecessarily. */
3881 auto_vec<std::pair<gimple *, gimple *>, 1> stores_pairs;
3882 unsigned i;
3883 data_reference_p then_dr;
3884 FOR_EACH_VEC_ELT_REVERSE (then_datarefs, i, then_dr)
3885 {
3886 if (DR_IS_READ (then_dr))
3887 continue;
3888
3889 then_store = DR_STMT (then_dr);
3890 then_lhs = gimple_get_lhs (then_store);
3891 if (then_lhs == NULL_TREE)
3892 continue;
3893 found = false;
3894
3895 unsigned j;
3896 data_reference_p else_dr;
3897 FOR_EACH_VEC_ELT_REVERSE (else_datarefs, j, else_dr)
3898 {
3899 if (DR_IS_READ (else_dr))
3900 continue;
3901
3902 else_store = DR_STMT (else_dr);
3903 if (gimple_visited_p (else_store))
3904 continue;
3905 else_lhs = gimple_get_lhs (else_store);
3906 if (else_lhs == NULL_TREE)
3907 continue;
3908
3909 if (operand_equal_p (then_lhs, else_lhs, 0))
3910 {
3911 found = true;
3912 break;
3913 }
3914 }
3915
3916 if (!found)
3917 continue;
3918
3919 gimple_set_visited (else_store, true);
3920 stores_pairs.safe_push (std::make_pair (then_store, else_store));
3921 }
3922
3923 /* No pairs of stores found. */
3924 if (!stores_pairs.length ()
3925 || stores_pairs.length () > (unsigned) param_max_stores_to_sink)
3926 {
3927 free_data_refs (then_datarefs);
3928 free_data_refs (else_datarefs);
3929 return false;
3930 }
3931
3932 /* Compute and check data dependencies in both basic blocks. */
3933 then_ddrs.create (1);
3934 else_ddrs.create (1);
3935 if (!compute_all_dependences (then_datarefs, &then_ddrs,
3936 vNULL, false)
3937 || !compute_all_dependences (else_datarefs, &else_ddrs,
3938 vNULL, false))
3939 {
3940 free_dependence_relations (then_ddrs);
3941 free_dependence_relations (else_ddrs);
3942 free_data_refs (then_datarefs);
3943 free_data_refs (else_datarefs);
3944 return false;
3945 }
3946 blocks[0] = then_bb;
3947 blocks[1] = else_bb;
3948 blocks[2] = join_bb;
3949 renumber_gimple_stmt_uids_in_blocks (blocks, 3);
3950
3951 /* Check that there are no read-after-write or write-after-write dependencies
3952 in THEN_BB. */
3953 for (auto ddr : then_ddrs)
3954 {
3955 struct data_reference *dra = DDR_A (ddr);
3956 struct data_reference *drb = DDR_B (ddr);
3957
3958 if (DDR_ARE_DEPENDENT (ddr) != chrec_known
3959 && ((DR_IS_READ (dra) && DR_IS_WRITE (drb)
3960 && gimple_uid (DR_STMT (dra)) > gimple_uid (DR_STMT (drb)))
3961 || (DR_IS_READ (drb) && DR_IS_WRITE (dra)
3962 && gimple_uid (DR_STMT (drb)) > gimple_uid (DR_STMT (dra)))
3963 || (DR_IS_WRITE (dra) && DR_IS_WRITE (drb))))
3964 {
3965 free_dependence_relations (then_ddrs);
3966 free_dependence_relations (else_ddrs);
3967 free_data_refs (then_datarefs);
3968 free_data_refs (else_datarefs);
3969 return false;
3970 }
3971 }
3972
3973 /* Check that there are no read-after-write or write-after-write dependencies
3974 in ELSE_BB. */
3975 for (auto ddr : else_ddrs)
3976 {
3977 struct data_reference *dra = DDR_A (ddr);
3978 struct data_reference *drb = DDR_B (ddr);
3979
3980 if (DDR_ARE_DEPENDENT (ddr) != chrec_known
3981 && ((DR_IS_READ (dra) && DR_IS_WRITE (drb)
3982 && gimple_uid (DR_STMT (dra)) > gimple_uid (DR_STMT (drb)))
3983 || (DR_IS_READ (drb) && DR_IS_WRITE (dra)
3984 && gimple_uid (DR_STMT (drb)) > gimple_uid (DR_STMT (dra)))
3985 || (DR_IS_WRITE (dra) && DR_IS_WRITE (drb))))
3986 {
3987 free_dependence_relations (then_ddrs);
3988 free_dependence_relations (else_ddrs);
3989 free_data_refs (then_datarefs);
3990 free_data_refs (else_datarefs);
3991 return false;
3992 }
3993 }
3994
3995 /* Sink stores with same LHS. */
3996 for (auto &store_pair : stores_pairs)
3997 {
3998 then_store = store_pair.first;
3999 else_store = store_pair.second;
4000 res = cond_if_else_store_replacement_1 (then_bb, else_bb, join_bb,
4001 then_store, else_store);
4002 ok = ok || res;
4003 }
4004
4005 free_dependence_relations (then_ddrs);
4006 free_dependence_relations (else_ddrs);
4007 free_data_refs (then_datarefs);
4008 free_data_refs (else_datarefs);
4009
4010 return ok;
4011 }
4012
4013 /* Return TRUE if STMT has a VUSE whose corresponding VDEF is in BB. */
4014
4015 static bool
4016 local_mem_dependence (gimple *stmt, basic_block bb)
4017 {
4018 tree vuse = gimple_vuse (stmt);
4019 gimple *def;
4020
4021 if (!vuse)
4022 return false;
4023
4024 def = SSA_NAME_DEF_STMT (vuse);
4025 return (def && gimple_bb (def) == bb);
4026 }
4027
4028 /* Given a "diamond" control-flow pattern where BB0 tests a condition,
4029 BB1 and BB2 are "then" and "else" blocks dependent on this test,
4030 and BB3 rejoins control flow following BB1 and BB2, look for
4031 opportunities to hoist loads as follows. If BB3 contains a PHI of
4032 two loads, one each occurring in BB1 and BB2, and the loads are
4033 provably of adjacent fields in the same structure, then move both
4034 loads into BB0. Of course this can only be done if there are no
4035 dependencies preventing such motion.
4036
4037 One of the hoisted loads will always be speculative, so the
4038 transformation is currently conservative:
4039
4040 - The fields must be strictly adjacent.
4041 - The two fields must occupy a single memory block that is
4042 guaranteed to not cross a page boundary.
4043
4044 The last is difficult to prove, as such memory blocks should be
4045 aligned on the minimum of the stack alignment boundary and the
4046 alignment guaranteed by heap allocation interfaces. Thus we rely
4047 on a parameter for the alignment value.
4048
4049 Provided a good value is used for the last case, the first
4050 restriction could possibly be relaxed. */
4051
4052 static void
4053 hoist_adjacent_loads (basic_block bb0, basic_block bb1,
4054 basic_block bb2, basic_block bb3)
4055 {
4056 unsigned HOST_WIDE_INT param_align = param_l1_cache_line_size;
4057 unsigned HOST_WIDE_INT param_align_bits = param_align * BITS_PER_UNIT;
4058 gphi_iterator gsi;
4059
4060 /* Walk the phis in bb3 looking for an opportunity. We are looking
4061 for phis of two SSA names, one each of which is defined in bb1 and
4062 bb2. */
4063 for (gsi = gsi_start_phis (bb3); !gsi_end_p (gsi); gsi_next (&gsi))
4064 {
4065 gphi *phi_stmt = gsi.phi ();
4066 gimple *def1, *def2;
4067 tree arg1, arg2, ref1, ref2, field1, field2;
4068 tree tree_offset1, tree_offset2, tree_size2, next;
4069 unsigned HOST_WIDE_INT offset1, offset2, size2, align1;
4070 gimple_stmt_iterator gsi2;
4071 basic_block bb_for_def1, bb_for_def2;
4072
4073 if (gimple_phi_num_args (phi_stmt) != 2
4074 || virtual_operand_p (gimple_phi_result (phi_stmt)))
4075 continue;
4076
4077 arg1 = gimple_phi_arg_def (phi_stmt, 0);
4078 arg2 = gimple_phi_arg_def (phi_stmt, 1);
4079
4080 if (TREE_CODE (arg1) != SSA_NAME
4081 || TREE_CODE (arg2) != SSA_NAME
4082 || SSA_NAME_IS_DEFAULT_DEF (arg1)
4083 || SSA_NAME_IS_DEFAULT_DEF (arg2))
4084 continue;
4085
4086 def1 = SSA_NAME_DEF_STMT (arg1);
4087 def2 = SSA_NAME_DEF_STMT (arg2);
4088
4089 if ((gimple_bb (def1) != bb1 || gimple_bb (def2) != bb2)
4090 && (gimple_bb (def2) != bb1 || gimple_bb (def1) != bb2))
4091 continue;
4092
4093 /* Check the mode of the arguments to be sure a conditional move
4094 can be generated for it. */
4095 if (optab_handler (movcc_optab, TYPE_MODE (TREE_TYPE (arg1)))
4096 == CODE_FOR_nothing)
4097 continue;
4098
4099 /* Both statements must be assignments whose RHS is a COMPONENT_REF. */
4100 if (!gimple_assign_single_p (def1)
4101 || !gimple_assign_single_p (def2)
4102 || gimple_has_volatile_ops (def1)
4103 || gimple_has_volatile_ops (def2))
4104 continue;
4105
4106 ref1 = gimple_assign_rhs1 (def1);
4107 ref2 = gimple_assign_rhs1 (def2);
4108
4109 if (TREE_CODE (ref1) != COMPONENT_REF
4110 || TREE_CODE (ref2) != COMPONENT_REF)
4111 continue;
4112
4113 /* The zeroth operand of the two component references must be
4114 identical. It is not sufficient to compare get_base_address of
4115 the two references, because this could allow for different
4116 elements of the same array in the two trees. It is not safe to
4117 assume that the existence of one array element implies the
4118 existence of a different one. */
4119 if (!operand_equal_p (TREE_OPERAND (ref1, 0), TREE_OPERAND (ref2, 0), 0))
4120 continue;
4121
4122 field1 = TREE_OPERAND (ref1, 1);
4123 field2 = TREE_OPERAND (ref2, 1);
4124
4125 /* Check for field adjacency, and ensure field1 comes first. */
4126 for (next = DECL_CHAIN (field1);
4127 next && TREE_CODE (next) != FIELD_DECL;
4128 next = DECL_CHAIN (next))
4129 ;
4130
4131 if (next != field2)
4132 {
4133 for (next = DECL_CHAIN (field2);
4134 next && TREE_CODE (next) != FIELD_DECL;
4135 next = DECL_CHAIN (next))
4136 ;
4137
4138 if (next != field1)
4139 continue;
4140
4141 std::swap (field1, field2);
4142 std::swap (def1, def2);
4143 }
4144
4145 bb_for_def1 = gimple_bb (def1);
4146 bb_for_def2 = gimple_bb (def2);
4147
4148 /* Check for proper alignment of the first field. */
4149 tree_offset1 = bit_position (field1);
4150 tree_offset2 = bit_position (field2);
4151 tree_size2 = DECL_SIZE (field2);
4152
4153 if (!tree_fits_uhwi_p (tree_offset1)
4154 || !tree_fits_uhwi_p (tree_offset2)
4155 || !tree_fits_uhwi_p (tree_size2))
4156 continue;
4157
4158 offset1 = tree_to_uhwi (tree_offset1);
4159 offset2 = tree_to_uhwi (tree_offset2);
4160 size2 = tree_to_uhwi (tree_size2);
4161 align1 = DECL_ALIGN (field1) % param_align_bits;
4162
4163 if (offset1 % BITS_PER_UNIT != 0)
4164 continue;
4165
4166 /* For profitability, the two field references should fit within
4167 a single cache line. */
4168 if (align1 + offset2 - offset1 + size2 > param_align_bits)
4169 continue;
4170
4171 /* The two expressions cannot be dependent upon vdefs defined
4172 in bb1/bb2. */
4173 if (local_mem_dependence (def1, bb_for_def1)
4174 || local_mem_dependence (def2, bb_for_def2))
4175 continue;
4176
4177 /* The conditions are satisfied; hoist the loads from bb1 and bb2 into
4178 bb0. We hoist the first one first so that a cache miss is handled
4179 efficiently regardless of hardware cache-fill policy. */
4180 gsi2 = gsi_for_stmt (def1);
4181 gsi_move_to_bb_end (&gsi2, bb0);
4182 gsi2 = gsi_for_stmt (def2);
4183 gsi_move_to_bb_end (&gsi2, bb0);
4184 statistics_counter_event (cfun, "hoisted loads", 1);
4185
4186 if (dump_file && (dump_flags & TDF_DETAILS))
4187 {
4188 fprintf (dump_file,
4189 "\nHoisting adjacent loads from %d and %d into %d: \n",
4190 bb_for_def1->index, bb_for_def2->index, bb0->index);
4191 print_gimple_stmt (dump_file, def1, 0, TDF_VOPS|TDF_MEMSYMS);
4192 print_gimple_stmt (dump_file, def2, 0, TDF_VOPS|TDF_MEMSYMS);
4193 }
4194 }
4195 }
4196
4197 /* Determine whether we should attempt to hoist adjacent loads out of
4198 diamond patterns in pass_phiopt. Always hoist loads if
4199 -fhoist-adjacent-loads is specified and the target machine has
4200 both a conditional move instruction and a defined cache line size. */
4201
4202 static bool
4203 gate_hoist_loads (void)
4204 {
4205 return (flag_hoist_adjacent_loads == 1
4206 && param_l1_cache_line_size
4207 && HAVE_conditional_move);
4208 }
4209
4210 template <class func_type>
4211 static void
4212 execute_over_cond_phis (func_type func)
4213 {
4214 unsigned n, i;
4215 basic_block *bb_order;
4216 basic_block bb;
4217 /* Search every basic block for COND_EXPR we may be able to optimize.
4218
4219 We walk the blocks in order that guarantees that a block with
4220 a single predecessor is processed before the predecessor.
4221 This ensures that we collapse inner ifs before visiting the
4222 outer ones, and also that we do not try to visit a removed
4223 block. */
4224 bb_order = single_pred_before_succ_order ();
4225 n = n_basic_blocks_for_fn (cfun) - NUM_FIXED_BLOCKS;
4226
4227 for (i = 0; i < n; i++)
4228 {
4229 basic_block bb1, bb2;
4230 edge e1, e2;
4231 bool diamond_p = false;
4232
4233 bb = bb_order[i];
4234
4235 /* Check to see if the last statement is a GIMPLE_COND. */
4236 gcond *cond_stmt = safe_dyn_cast <gcond *> (*gsi_last_bb (bb));
4237 if (!cond_stmt)
4238 continue;
4239
4240 e1 = EDGE_SUCC (bb, 0);
4241 bb1 = e1->dest;
4242 e2 = EDGE_SUCC (bb, 1);
4243 bb2 = e2->dest;
4244
4245 /* We cannot do the optimization on abnormal edges. */
4246 if ((e1->flags & EDGE_ABNORMAL) != 0
4247 || (e2->flags & EDGE_ABNORMAL) != 0)
4248 continue;
4249
4250 /* If either bb1's succ or bb2 or bb2's succ is non NULL. */
4251 if (EDGE_COUNT (bb1->succs) == 0
4252 || EDGE_COUNT (bb2->succs) == 0)
4253 continue;
4254
4255 /* Find the bb which is the fall through to the other. */
4256 if (EDGE_SUCC (bb1, 0)->dest == bb2)
4257 ;
4258 else if (EDGE_SUCC (bb2, 0)->dest == bb1)
4259 {
4260 std::swap (bb1, bb2);
4261 std::swap (e1, e2);
4262 }
4263 else if (EDGE_SUCC (bb1, 0)->dest == EDGE_SUCC (bb2, 0)->dest
4264 && single_succ_p (bb2))
4265 {
4266 diamond_p = true;
4267 e2 = EDGE_SUCC (bb2, 0);
4268 /* Make sure bb2 is just a fall through. */
4269 if ((e2->flags & EDGE_FALLTHRU) == 0)
4270 continue;
4271 }
4272 else
4273 continue;
4274
4275 e1 = EDGE_SUCC (bb1, 0);
4276
4277 /* Make sure that bb1 is just a fall through. */
4278 if (!single_succ_p (bb1)
4279 || (e1->flags & EDGE_FALLTHRU) == 0)
4280 continue;
4281
4282 func (bb, bb1, bb2, e1, e2, diamond_p, cond_stmt);
4283 }
4284 free (bb_order);
4285 }
4286
4287 /* This pass tries to replaces an if-then-else block with an
4288 assignment. We have different kinds of transformations.
4289 Some of these transformations are also performed by the ifcvt
4290 RTL optimizer.
4291
4292 PHI-OPT using Match-and-simplify infrastructure
4293 -----------------------
4294
4295 The PHI-OPT pass will try to use match-and-simplify infrastructure
4296 (gimple_simplify) to do transformations. This is implemented in
4297 match_simplify_replacement.
4298
4299 The way it works is it replaces:
4300 bb0:
4301 if (cond) goto bb2; else goto bb1;
4302 bb1:
4303 bb2:
4304 x = PHI <a (bb1), b (bb0), ...>;
4305
4306 with a statement if it gets simplified from `cond ? b : a`.
4307
4308 bb0:
4309 x1 = cond ? b : a;
4310 bb2:
4311 x = PHI <a (bb1), x1 (bb0), ...>;
4312 Bb1 might be removed as it becomes unreachable when doing the replacement.
4313 Though bb1 does not have to be considered a forwarding basic block from bb0.
4314
4315 Will try to see if `(!cond) ? a : b` gets simplified (iff !cond simplifies);
4316 this is done not to have an explosion of patterns in match.pd.
4317 Note bb1 does not need to be completely empty, it can contain
4318 one statement which is known not to trap.
4319
4320 It also can handle the case where we have two forwarding bbs (diamond):
4321 bb0:
4322 if (cond) goto bb2; else goto bb1;
4323 bb1: goto bb3;
4324 bb2: goto bb3;
4325 bb3:
4326 x = PHI <a (bb1), b (bb2), ...>;
4327 And that is replaced with a statement if it is simplified
4328 from `cond ? b : a`.
4329 Again bb1 and bb2 does not have to be completely empty but
4330 each can contain one statement which is known not to trap.
4331 But in this case bb1/bb2 can only be forwarding basic blocks.
4332
4333 This fully replaces the old "Conditional Replacement",
4334 "ABS Replacement" transformations as they are now
4335 implmeneted in match.pd.
4336 Some parts of the "MIN/MAX Replacement" are re-implemented in match.pd.
4337
4338 Value Replacement
4339 -----------------
4340
4341 This transformation, implemented in value_replacement, replaces
4342
4343 bb0:
4344 if (a != b) goto bb2; else goto bb1;
4345 bb1:
4346 bb2:
4347 x = PHI <a (bb1), b (bb0), ...>;
4348
4349 with
4350
4351 bb0:
4352 bb2:
4353 x = PHI <b (bb0), ...>;
4354
4355 This opportunity can sometimes occur as a result of other
4356 optimizations.
4357
4358
4359 Another case caught by value replacement looks like this:
4360
4361 bb0:
4362 t1 = a == CONST;
4363 t2 = b > c;
4364 t3 = t1 & t2;
4365 if (t3 != 0) goto bb1; else goto bb2;
4366 bb1:
4367 bb2:
4368 x = PHI (CONST, a)
4369
4370 Gets replaced with:
4371 bb0:
4372 bb2:
4373 t1 = a == CONST;
4374 t2 = b > c;
4375 t3 = t1 & t2;
4376 x = a;
4377
4378 MIN/MAX Replacement
4379 -------------------
4380
4381 This transformation, minmax_replacement replaces
4382
4383 bb0:
4384 if (a <= b) goto bb2; else goto bb1;
4385 bb1:
4386 bb2:
4387 x = PHI <b (bb1), a (bb0), ...>;
4388
4389 with
4390
4391 bb0:
4392 x' = MIN_EXPR (a, b)
4393 bb2:
4394 x = PHI <x' (bb0), ...>;
4395
4396 A similar transformation is done for MAX_EXPR.
4397
4398
4399 This pass also performs a fifth transformation of a slightly different
4400 flavor.
4401
4402 Factor operations in COND_EXPR
4403 ------------------------------
4404
4405 This transformation factors the unary operations out of COND_EXPR with
4406 factor_out_conditional_operation.
4407
4408 For example:
4409 if (a <= CST) goto <bb 3>; else goto <bb 4>;
4410 <bb 3>:
4411 tmp = (int) a;
4412 <bb 4>:
4413 tmp = PHI <tmp, CST>
4414
4415 Into:
4416 if (a <= CST) goto <bb 3>; else goto <bb 4>;
4417 <bb 3>:
4418 <bb 4>:
4419 a = PHI <a, CST>
4420 tmp = (int) a;
4421
4422 Adjacent Load Hoisting
4423 ----------------------
4424
4425 This transformation replaces
4426
4427 bb0:
4428 if (...) goto bb2; else goto bb1;
4429 bb1:
4430 x1 = (<expr>).field1;
4431 goto bb3;
4432 bb2:
4433 x2 = (<expr>).field2;
4434 bb3:
4435 # x = PHI <x1, x2>;
4436
4437 with
4438
4439 bb0:
4440 x1 = (<expr>).field1;
4441 x2 = (<expr>).field2;
4442 if (...) goto bb2; else goto bb1;
4443 bb1:
4444 goto bb3;
4445 bb2:
4446 bb3:
4447 # x = PHI <x1, x2>;
4448
4449 The purpose of this transformation is to enable generation of conditional
4450 move instructions such as Intel CMOVE or PowerPC ISEL. Because one of
4451 the loads is speculative, the transformation is restricted to very
4452 specific cases to avoid introducing a page fault. We are looking for
4453 the common idiom:
4454
4455 if (...)
4456 x = y->left;
4457 else
4458 x = y->right;
4459
4460 where left and right are typically adjacent pointers in a tree structure. */
4461
4462 namespace {
4463
4464 const pass_data pass_data_phiopt =
4465 {
4466 GIMPLE_PASS, /* type */
4467 "phiopt", /* name */
4468 OPTGROUP_NONE, /* optinfo_flags */
4469 TV_TREE_PHIOPT, /* tv_id */
4470 ( PROP_cfg | PROP_ssa ), /* properties_required */
4471 0, /* properties_provided */
4472 0, /* properties_destroyed */
4473 0, /* todo_flags_start */
4474 0, /* todo_flags_finish */
4475 };
4476
4477 class pass_phiopt : public gimple_opt_pass
4478 {
4479 public:
4480 pass_phiopt (gcc::context *ctxt)
4481 : gimple_opt_pass (pass_data_phiopt, ctxt), early_p (false)
4482 {}
4483
4484 /* opt_pass methods: */
4485 opt_pass * clone () final override { return new pass_phiopt (m_ctxt); }
4486 void set_pass_param (unsigned n, bool param) final override
4487 {
4488 gcc_assert (n == 0);
4489 early_p = param;
4490 }
4491 bool gate (function *) final override { return flag_ssa_phiopt; }
4492 unsigned int execute (function *) final override;
4493
4494 private:
4495 bool early_p;
4496 }; // class pass_phiopt
4497
4498 } // anon namespace
4499
4500 gimple_opt_pass *
4501 make_pass_phiopt (gcc::context *ctxt)
4502 {
4503 return new pass_phiopt (ctxt);
4504 }
4505
4506 unsigned int
4507 pass_phiopt::execute (function *)
4508 {
4509 bool do_hoist_loads = !early_p ? gate_hoist_loads () : false;
4510 bool cfgchanged = false;
4511
4512 calculate_dominance_info (CDI_DOMINATORS);
4513 mark_ssa_maybe_undefs ();
4514
4515 auto phiopt_exec = [&] (basic_block bb, basic_block bb1,
4516 basic_block bb2, edge e1, edge e2,
4517 bool diamond_p, gcond *cond_stmt)
4518 {
4519 if (diamond_p)
4520 {
4521 basic_block bb3 = e1->dest;
4522
4523 if (!single_pred_p (bb1)
4524 || !single_pred_p (bb2))
4525 return;
4526
4527 if (do_hoist_loads
4528 && !FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (cond_stmt)))
4529 && EDGE_COUNT (bb->succs) == 2
4530 && EDGE_COUNT (bb3->preds) == 2
4531 /* If one edge or the other is dominant, a conditional move
4532 is likely to perform worse than the well-predicted branch. */
4533 && !predictable_edge_p (EDGE_SUCC (bb, 0))
4534 && !predictable_edge_p (EDGE_SUCC (bb, 1)))
4535 hoist_adjacent_loads (bb, bb1, bb2, bb3);
4536 }
4537
4538 gimple_stmt_iterator gsi;
4539
4540 /* Check that we're looking for nested phis. */
4541 basic_block merge = diamond_p ? EDGE_SUCC (bb2, 0)->dest : bb2;
4542 gimple_seq phis = phi_nodes (merge);
4543
4544 if (gimple_seq_empty_p (phis))
4545 return;
4546
4547 /* Factor out operations from the phi if possible. */
4548 if (single_pred_p (bb1)
4549 && EDGE_COUNT (merge->preds) == 2)
4550 {
4551 for (gsi = gsi_start (phis); !gsi_end_p (gsi); )
4552 {
4553 gphi *phi = as_a <gphi *> (gsi_stmt (gsi));
4554
4555 if (factor_out_conditional_operation (e1, e2, merge, phi,
4556 cond_stmt))
4557 {
4558 /* Start over if there was an operation that was factored out because the new phi might have another opportunity. */
4559 phis = phi_nodes (merge);
4560 gsi = gsi_start (phis);
4561 }
4562 else
4563 gsi_next (&gsi);
4564 }
4565 }
4566
4567 /* Value replacement can work with more than one PHI
4568 so try that first. */
4569 if (!early_p && !diamond_p)
4570 for (gsi = gsi_start (phis); !gsi_end_p (gsi); gsi_next (&gsi))
4571 {
4572 gphi *phi = as_a <gphi *> (gsi_stmt (gsi));
4573 tree arg0 = gimple_phi_arg_def (phi, e1->dest_idx);
4574 tree arg1 = gimple_phi_arg_def (phi, e2->dest_idx);
4575 if (value_replacement (bb, bb1, e1, e2, phi, arg0, arg1) == 2)
4576 {
4577 cfgchanged = true;
4578 return;
4579 }
4580 }
4581
4582 gphi *phi = single_non_singleton_phi_for_edges (phis, e1, e2);
4583 if (!phi)
4584 return;
4585
4586 tree arg0 = gimple_phi_arg_def (phi, e1->dest_idx);
4587 tree arg1 = gimple_phi_arg_def (phi, e2->dest_idx);
4588
4589 /* Something is wrong if we cannot find the arguments in the PHI
4590 node. */
4591 gcc_assert (arg0 != NULL_TREE && arg1 != NULL_TREE);
4592
4593
4594 /* Do the replacement of conditional if it can be done. */
4595 if (match_simplify_replacement (bb, bb1, bb2, e1, e2, phi,
4596 arg0, arg1, early_p, diamond_p))
4597 cfgchanged = true;
4598 else if (!early_p
4599 && !diamond_p
4600 && single_pred_p (bb1)
4601 && cond_removal_in_builtin_zero_pattern (bb, bb1, e1, e2,
4602 phi, arg0, arg1))
4603 cfgchanged = true;
4604 else if (minmax_replacement (bb, bb1, bb2, e1, e2, phi, arg0, arg1,
4605 diamond_p))
4606 cfgchanged = true;
4607 else if (single_pred_p (bb1)
4608 && !diamond_p
4609 && spaceship_replacement (bb, bb1, e1, e2, phi, arg0, arg1))
4610 cfgchanged = true;
4611 };
4612
4613 execute_over_cond_phis (phiopt_exec);
4614
4615 if (cfgchanged)
4616 return TODO_cleanup_cfg;
4617 return 0;
4618 }
4619
4620 /* This pass tries to transform conditional stores into unconditional
4621 ones, enabling further simplifications with the simpler then and else
4622 blocks. In particular it replaces this:
4623
4624 bb0:
4625 if (cond) goto bb2; else goto bb1;
4626 bb1:
4627 *p = RHS;
4628 bb2:
4629
4630 with
4631
4632 bb0:
4633 if (cond) goto bb1; else goto bb2;
4634 bb1:
4635 condtmp' = *p;
4636 bb2:
4637 condtmp = PHI <RHS, condtmp'>
4638 *p = condtmp;
4639
4640 This transformation can only be done under several constraints,
4641 documented below. It also replaces:
4642
4643 bb0:
4644 if (cond) goto bb2; else goto bb1;
4645 bb1:
4646 *p = RHS1;
4647 goto bb3;
4648 bb2:
4649 *p = RHS2;
4650 bb3:
4651
4652 with
4653
4654 bb0:
4655 if (cond) goto bb3; else goto bb1;
4656 bb1:
4657 bb3:
4658 condtmp = PHI <RHS1, RHS2>
4659 *p = condtmp; */
4660
4661 namespace {
4662
4663 const pass_data pass_data_cselim =
4664 {
4665 GIMPLE_PASS, /* type */
4666 "cselim", /* name */
4667 OPTGROUP_NONE, /* optinfo_flags */
4668 TV_TREE_PHIOPT, /* tv_id */
4669 ( PROP_cfg | PROP_ssa ), /* properties_required */
4670 0, /* properties_provided */
4671 0, /* properties_destroyed */
4672 0, /* todo_flags_start */
4673 0, /* todo_flags_finish */
4674 };
4675
4676 class pass_cselim : public gimple_opt_pass
4677 {
4678 public:
4679 pass_cselim (gcc::context *ctxt)
4680 : gimple_opt_pass (pass_data_cselim, ctxt)
4681 {}
4682
4683 /* opt_pass methods: */
4684 bool gate (function *) final override { return flag_tree_cselim; }
4685 unsigned int execute (function *) final override;
4686
4687 }; // class pass_cselim
4688
4689 } // anon namespace
4690
4691 gimple_opt_pass *
4692 make_pass_cselim (gcc::context *ctxt)
4693 {
4694 return new pass_cselim (ctxt);
4695 }
4696
4697 unsigned int
4698 pass_cselim::execute (function *)
4699 {
4700 bool cfgchanged = false;
4701 hash_set<tree> *nontrap = 0;
4702 unsigned todo = 0;
4703
4704 /* ??? We are not interested in loop related info, but the following
4705 will create it, ICEing as we didn't init loops with pre-headers.
4706 An interfacing issue of find_data_references_in_bb. */
4707 loop_optimizer_init (LOOPS_NORMAL);
4708 scev_initialize ();
4709
4710 calculate_dominance_info (CDI_DOMINATORS);
4711
4712 /* Calculate the set of non-trapping memory accesses. */
4713 nontrap = get_non_trapping ();
4714
4715 auto cselim_exec = [&] (basic_block bb, basic_block bb1,
4716 basic_block bb2, edge e1, edge e2,
4717 bool diamond_p, gcond *)
4718 {
4719 if (diamond_p)
4720 {
4721 basic_block bb3 = e1->dest;
4722
4723 /* Only handle sinking of store from 2 bbs only,
4724 The middle bbs don't need to come from the
4725 if always since we are sinking rather than
4726 hoisting. */
4727 if (EDGE_COUNT (bb3->preds) != 2)
4728 return;
4729 if (cond_if_else_store_replacement (bb1, bb2, bb3))
4730 cfgchanged = true;
4731 return;
4732 }
4733
4734 /* Also make sure that bb1 only have one predecessor and that it
4735 is bb. */
4736 if (!single_pred_p (bb1)
4737 || single_pred (bb1) != bb)
4738 return;
4739
4740 /* bb1 is the middle block, bb2 the join block, bb the split block,
4741 e1 the fallthrough edge from bb1 to bb2. We can't do the
4742 optimization if the join block has more than two predecessors. */
4743 if (EDGE_COUNT (bb2->preds) > 2)
4744 return;
4745 if (cond_store_replacement (bb1, bb2, e1, e2, nontrap))
4746 cfgchanged = true;
4747 };
4748
4749 execute_over_cond_phis (cselim_exec);
4750
4751 delete nontrap;
4752 /* If the CFG has changed, we should cleanup the CFG. */
4753 if (cfgchanged)
4754 {
4755 /* In cond-store replacement we have added some loads on edges
4756 and new VOPS (as we moved the store, and created a load). */
4757 gsi_commit_edge_inserts ();
4758 todo = TODO_cleanup_cfg | TODO_update_ssa_only_virtuals;
4759 }
4760 scev_finalize ();
4761 loop_optimizer_finalize ();
4762 return todo;
4763 }