Small fix for -fdump-ada-spec
[official-gcc.git] / gcc / tree-ssa-phiopt.cc
blobc3a889dc593a9554a0f45fe05cf7b14572a24b9c
1 /* Optimization of PHI nodes by converting them into straightline code.
2 Copyright (C) 2004-2023 Free Software Foundation, Inc.
4 This file is part of GCC.
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.
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.
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/>. */
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"
58 static unsigned int tree_ssa_phiopt_worker (bool, bool, bool);
59 static bool two_value_replacement (basic_block, basic_block, edge, gphi *,
60 tree, tree);
61 static bool match_simplify_replacement (basic_block, basic_block,
62 edge, edge, gphi *, tree, tree, bool);
63 static gphi *factor_out_conditional_conversion (edge, edge, gphi *, tree, tree,
64 gimple *);
65 static int value_replacement (basic_block, basic_block,
66 edge, edge, gphi *, tree, tree);
67 static bool minmax_replacement (basic_block, basic_block, basic_block,
68 edge, edge, gphi *, tree, tree, bool);
69 static bool spaceship_replacement (basic_block, basic_block,
70 edge, edge, gphi *, tree, tree);
71 static bool cond_removal_in_builtin_zero_pattern (basic_block, basic_block,
72 edge, edge, gphi *,
73 tree, tree);
74 static bool cond_store_replacement (basic_block, basic_block, edge, edge,
75 hash_set<tree> *);
76 static bool cond_if_else_store_replacement (basic_block, basic_block, basic_block);
77 static hash_set<tree> * get_non_trapping ();
78 static void hoist_adjacent_loads (basic_block, basic_block,
79 basic_block, basic_block);
80 static bool gate_hoist_loads (void);
82 /* This pass tries to transform conditional stores into unconditional
83 ones, enabling further simplifications with the simpler then and else
84 blocks. In particular it replaces this:
86 bb0:
87 if (cond) goto bb2; else goto bb1;
88 bb1:
89 *p = RHS;
90 bb2:
92 with
94 bb0:
95 if (cond) goto bb1; else goto bb2;
96 bb1:
97 condtmp' = *p;
98 bb2:
99 condtmp = PHI <RHS, condtmp'>
100 *p = condtmp;
102 This transformation can only be done under several constraints,
103 documented below. It also replaces:
105 bb0:
106 if (cond) goto bb2; else goto bb1;
107 bb1:
108 *p = RHS1;
109 goto bb3;
110 bb2:
111 *p = RHS2;
112 bb3:
114 with
116 bb0:
117 if (cond) goto bb3; else goto bb1;
118 bb1:
119 bb3:
120 condtmp = PHI <RHS1, RHS2>
121 *p = condtmp; */
123 static unsigned int
124 tree_ssa_cs_elim (void)
126 unsigned todo;
127 /* ??? We are not interested in loop related info, but the following
128 will create it, ICEing as we didn't init loops with pre-headers.
129 An interfacing issue of find_data_references_in_bb. */
130 loop_optimizer_init (LOOPS_NORMAL);
131 scev_initialize ();
132 todo = tree_ssa_phiopt_worker (true, false, false);
133 scev_finalize ();
134 loop_optimizer_finalize ();
135 return todo;
138 /* Return the singleton PHI in the SEQ of PHIs for edges E0 and E1. */
140 static gphi *
141 single_non_singleton_phi_for_edges (gimple_seq seq, edge e0, edge e1)
143 gimple_stmt_iterator i;
144 gphi *phi = NULL;
145 if (gimple_seq_singleton_p (seq))
146 return as_a <gphi *> (gsi_stmt (gsi_start (seq)));
147 for (i = gsi_start (seq); !gsi_end_p (i); gsi_next (&i))
149 gphi *p = as_a <gphi *> (gsi_stmt (i));
150 /* If the PHI arguments are equal then we can skip this PHI. */
151 if (operand_equal_for_phi_arg_p (gimple_phi_arg_def (p, e0->dest_idx),
152 gimple_phi_arg_def (p, e1->dest_idx)))
153 continue;
155 /* If we already have a PHI that has the two edge arguments are
156 different, then return it is not a singleton for these PHIs. */
157 if (phi)
158 return NULL;
160 phi = p;
162 return phi;
165 /* The core routine of conditional store replacement and normal
166 phi optimizations. Both share much of the infrastructure in how
167 to match applicable basic block patterns. DO_STORE_ELIM is true
168 when we want to do conditional store replacement, false otherwise.
169 DO_HOIST_LOADS is true when we want to hoist adjacent loads out
170 of diamond control flow patterns, false otherwise. */
171 static unsigned int
172 tree_ssa_phiopt_worker (bool do_store_elim, bool do_hoist_loads, bool early_p)
174 basic_block bb;
175 basic_block *bb_order;
176 unsigned n, i;
177 bool cfgchanged = false;
178 hash_set<tree> *nontrap = 0;
180 calculate_dominance_info (CDI_DOMINATORS);
182 if (do_store_elim)
183 /* Calculate the set of non-trapping memory accesses. */
184 nontrap = get_non_trapping ();
186 /* Search every basic block for COND_EXPR we may be able to optimize.
188 We walk the blocks in order that guarantees that a block with
189 a single predecessor is processed before the predecessor.
190 This ensures that we collapse inner ifs before visiting the
191 outer ones, and also that we do not try to visit a removed
192 block. */
193 bb_order = single_pred_before_succ_order ();
194 n = n_basic_blocks_for_fn (cfun) - NUM_FIXED_BLOCKS;
196 for (i = 0; i < n; i++)
198 gimple *cond_stmt;
199 gphi *phi;
200 basic_block bb1, bb2;
201 edge e1, e2;
202 tree arg0, arg1;
203 bool diamond_p = false;
205 bb = bb_order[i];
207 cond_stmt = last_stmt (bb);
208 /* Check to see if the last statement is a GIMPLE_COND. */
209 if (!cond_stmt
210 || gimple_code (cond_stmt) != GIMPLE_COND)
211 continue;
213 e1 = EDGE_SUCC (bb, 0);
214 bb1 = e1->dest;
215 e2 = EDGE_SUCC (bb, 1);
216 bb2 = e2->dest;
218 /* We cannot do the optimization on abnormal edges. */
219 if ((e1->flags & EDGE_ABNORMAL) != 0
220 || (e2->flags & EDGE_ABNORMAL) != 0)
221 continue;
223 /* If either bb1's succ or bb2 or bb2's succ is non NULL. */
224 if (EDGE_COUNT (bb1->succs) == 0
225 || EDGE_COUNT (bb2->succs) == 0)
226 continue;
228 /* Find the bb which is the fall through to the other. */
229 if (EDGE_SUCC (bb1, 0)->dest == bb2)
231 else if (EDGE_SUCC (bb2, 0)->dest == bb1)
233 std::swap (bb1, bb2);
234 std::swap (e1, e2);
236 else if (do_store_elim
237 && EDGE_SUCC (bb1, 0)->dest == EDGE_SUCC (bb2, 0)->dest)
239 basic_block bb3 = EDGE_SUCC (bb1, 0)->dest;
241 if (!single_succ_p (bb1)
242 || (EDGE_SUCC (bb1, 0)->flags & EDGE_FALLTHRU) == 0
243 || !single_succ_p (bb2)
244 || (EDGE_SUCC (bb2, 0)->flags & EDGE_FALLTHRU) == 0
245 || EDGE_COUNT (bb3->preds) != 2)
246 continue;
247 if (cond_if_else_store_replacement (bb1, bb2, bb3))
248 cfgchanged = true;
249 continue;
251 else if (do_hoist_loads
252 && EDGE_SUCC (bb1, 0)->dest == EDGE_SUCC (bb2, 0)->dest)
254 basic_block bb3 = EDGE_SUCC (bb1, 0)->dest;
256 if (!FLOAT_TYPE_P (TREE_TYPE (gimple_cond_lhs (cond_stmt)))
257 && single_succ_p (bb1)
258 && single_succ_p (bb2)
259 && single_pred_p (bb1)
260 && single_pred_p (bb2)
261 && EDGE_COUNT (bb->succs) == 2
262 && EDGE_COUNT (bb3->preds) == 2
263 /* If one edge or the other is dominant, a conditional move
264 is likely to perform worse than the well-predicted branch. */
265 && !predictable_edge_p (EDGE_SUCC (bb, 0))
266 && !predictable_edge_p (EDGE_SUCC (bb, 1)))
267 hoist_adjacent_loads (bb, bb1, bb2, bb3);
268 continue;
270 else if (EDGE_SUCC (bb1, 0)->dest == EDGE_SUCC (bb2, 0)->dest
271 && !empty_block_p (bb1))
273 diamond_p = true;
274 e2 = EDGE_SUCC (bb2, 0);
276 else
277 continue;
279 e1 = EDGE_SUCC (bb1, 0);
281 /* Make sure that bb1 is just a fall through. */
282 if (!single_succ_p (bb1)
283 || (e1->flags & EDGE_FALLTHRU) == 0)
284 continue;
286 if (do_store_elim && !diamond_p)
288 /* Also make sure that bb1 only have one predecessor and that it
289 is bb. */
290 if (!single_pred_p (bb1)
291 || single_pred (bb1) != bb)
292 continue;
294 /* bb1 is the middle block, bb2 the join block, bb the split block,
295 e1 the fallthrough edge from bb1 to bb2. We can't do the
296 optimization if the join block has more than two predecessors. */
297 if (EDGE_COUNT (bb2->preds) > 2)
298 continue;
299 if (cond_store_replacement (bb1, bb2, e1, e2, nontrap))
300 cfgchanged = true;
302 else
304 gimple_stmt_iterator gsi;
305 bool candorest = true;
307 /* Check that we're looking for nested phis. */
308 basic_block merge = diamond_p ? EDGE_SUCC (bb2, 0)->dest : bb2;
309 gimple_seq phis = phi_nodes (merge);
311 /* Value replacement can work with more than one PHI
312 so try that first. */
313 if (!early_p && !diamond_p)
314 for (gsi = gsi_start (phis); !gsi_end_p (gsi); gsi_next (&gsi))
316 phi = as_a <gphi *> (gsi_stmt (gsi));
317 arg0 = gimple_phi_arg_def (phi, e1->dest_idx);
318 arg1 = gimple_phi_arg_def (phi, e2->dest_idx);
319 if (value_replacement (bb, bb1, e1, e2, phi, arg0, arg1) == 2)
321 candorest = false;
322 cfgchanged = true;
323 break;
327 if (!candorest)
328 continue;
330 phi = single_non_singleton_phi_for_edges (phis, e1, e2);
331 if (!phi)
332 continue;
334 arg0 = gimple_phi_arg_def (phi, e1->dest_idx);
335 arg1 = gimple_phi_arg_def (phi, e2->dest_idx);
337 /* Something is wrong if we cannot find the arguments in the PHI
338 node. */
339 gcc_assert (arg0 != NULL_TREE && arg1 != NULL_TREE);
341 gphi *newphi;
342 if (single_pred_p (bb1)
343 && !diamond_p
344 && (newphi = factor_out_conditional_conversion (e1, e2, phi,
345 arg0, arg1,
346 cond_stmt)))
348 phi = newphi;
349 /* factor_out_conditional_conversion may create a new PHI in
350 BB2 and eliminate an existing PHI in BB2. Recompute values
351 that may be affected by that change. */
352 arg0 = gimple_phi_arg_def (phi, e1->dest_idx);
353 arg1 = gimple_phi_arg_def (phi, e2->dest_idx);
354 gcc_assert (arg0 != NULL_TREE && arg1 != NULL_TREE);
357 /* Do the replacement of conditional if it can be done. */
358 if (!early_p
359 && !diamond_p
360 && two_value_replacement (bb, bb1, e2, phi, arg0, arg1))
361 cfgchanged = true;
362 else if (!diamond_p
363 && match_simplify_replacement (bb, bb1, e1, e2, phi,
364 arg0, arg1, early_p))
365 cfgchanged = true;
366 else if (!early_p
367 && !diamond_p
368 && single_pred_p (bb1)
369 && cond_removal_in_builtin_zero_pattern (bb, bb1, e1, e2,
370 phi, arg0, arg1))
371 cfgchanged = true;
372 else if (minmax_replacement (bb, bb1, bb2, e1, e2, phi, arg0, arg1,
373 diamond_p))
374 cfgchanged = true;
375 else if (single_pred_p (bb1)
376 && !diamond_p
377 && spaceship_replacement (bb, bb1, e1, e2, phi, arg0, arg1))
378 cfgchanged = true;
382 free (bb_order);
384 if (do_store_elim)
385 delete nontrap;
386 /* If the CFG has changed, we should cleanup the CFG. */
387 if (cfgchanged && do_store_elim)
389 /* In cond-store replacement we have added some loads on edges
390 and new VOPS (as we moved the store, and created a load). */
391 gsi_commit_edge_inserts ();
392 return TODO_cleanup_cfg | TODO_update_ssa_only_virtuals;
394 else if (cfgchanged)
395 return TODO_cleanup_cfg;
396 return 0;
399 /* Replace PHI node element whose edge is E in block BB with variable NEW.
400 Remove the edge from COND_BLOCK which does not lead to BB (COND_BLOCK
401 is known to have two edges, one of which must reach BB). */
403 static void
404 replace_phi_edge_with_variable (basic_block cond_block,
405 edge e, gphi *phi, tree new_tree,
406 bitmap dce_ssa_names = auto_bitmap())
408 basic_block bb = gimple_bb (phi);
409 gimple_stmt_iterator gsi;
410 tree phi_result = PHI_RESULT (phi);
412 /* Duplicate range info if they are the only things setting the target PHI.
413 This is needed as later on, the new_tree will be replacing
414 The assignement of the PHI.
415 For an example:
416 bb1:
417 _4 = min<a_1, 255>
418 goto bb2
420 # RANGE [-INF, 255]
421 a_3 = PHI<_4(1)>
422 bb3:
424 use(a_3)
425 And _4 gets propagated into the use of a_3 and losing the range info.
426 This can't be done for more than 2 incoming edges as the propagation
427 won't happen.
428 The new_tree needs to be defined in the same basic block as the conditional. */
429 if (TREE_CODE (new_tree) == SSA_NAME
430 && EDGE_COUNT (gimple_bb (phi)->preds) == 2
431 && INTEGRAL_TYPE_P (TREE_TYPE (phi_result))
432 && !SSA_NAME_RANGE_INFO (new_tree)
433 && SSA_NAME_RANGE_INFO (phi_result)
434 && gimple_bb (SSA_NAME_DEF_STMT (new_tree)) == cond_block
435 && dbg_cnt (phiopt_edge_range))
436 duplicate_ssa_name_range_info (new_tree, phi_result);
438 /* Change the PHI argument to new. */
439 SET_USE (PHI_ARG_DEF_PTR (phi, e->dest_idx), new_tree);
441 /* Remove the empty basic block. */
442 edge edge_to_remove = NULL, keep_edge = NULL;
443 if (EDGE_SUCC (cond_block, 0)->dest == bb)
445 edge_to_remove = EDGE_SUCC (cond_block, 1);
446 keep_edge = EDGE_SUCC (cond_block, 0);
448 else if (EDGE_SUCC (cond_block, 1)->dest == bb)
450 edge_to_remove = EDGE_SUCC (cond_block, 0);
451 keep_edge = EDGE_SUCC (cond_block, 1);
453 else if ((keep_edge = find_edge (cond_block, e->src)))
455 else
456 gcc_unreachable ();
458 if (edge_to_remove && EDGE_COUNT (edge_to_remove->dest->preds) == 1)
460 e->flags |= EDGE_FALLTHRU;
461 e->flags &= ~(EDGE_TRUE_VALUE | EDGE_FALSE_VALUE);
462 e->probability = profile_probability::always ();
463 delete_basic_block (edge_to_remove->dest);
465 /* Eliminate the COND_EXPR at the end of COND_BLOCK. */
466 gsi = gsi_last_bb (cond_block);
467 gsi_remove (&gsi, true);
469 else
471 /* If there are other edges into the middle block make
472 CFG cleanup deal with the edge removal to avoid
473 updating dominators here in a non-trivial way. */
474 gcond *cond = as_a <gcond *> (last_stmt (cond_block));
475 if (keep_edge->flags & EDGE_FALSE_VALUE)
476 gimple_cond_make_false (cond);
477 else if (keep_edge->flags & EDGE_TRUE_VALUE)
478 gimple_cond_make_true (cond);
481 simple_dce_from_worklist (dce_ssa_names);
483 statistics_counter_event (cfun, "Replace PHI with variable", 1);
485 if (dump_file && (dump_flags & TDF_DETAILS))
486 fprintf (dump_file,
487 "COND_EXPR in block %d and PHI in block %d converted to straightline code.\n",
488 cond_block->index,
489 bb->index);
492 /* PR66726: Factor conversion out of COND_EXPR. If the arguments of the PHI
493 stmt are CONVERT_STMT, factor out the conversion and perform the conversion
494 to the result of PHI stmt. COND_STMT is the controlling predicate.
495 Return the newly-created PHI, if any. */
497 static gphi *
498 factor_out_conditional_conversion (edge e0, edge e1, gphi *phi,
499 tree arg0, tree arg1, gimple *cond_stmt)
501 gimple *arg0_def_stmt = NULL, *arg1_def_stmt = NULL, *new_stmt;
502 tree new_arg0 = NULL_TREE, new_arg1 = NULL_TREE;
503 tree temp, result;
504 gphi *newphi;
505 gimple_stmt_iterator gsi, gsi_for_def;
506 location_t locus = gimple_location (phi);
507 enum tree_code convert_code;
509 /* Handle only PHI statements with two arguments. TODO: If all
510 other arguments to PHI are INTEGER_CST or if their defining
511 statement have the same unary operation, we can handle more
512 than two arguments too. */
513 if (gimple_phi_num_args (phi) != 2)
514 return NULL;
516 /* First canonicalize to simplify tests. */
517 if (TREE_CODE (arg0) != SSA_NAME)
519 std::swap (arg0, arg1);
520 std::swap (e0, e1);
523 if (TREE_CODE (arg0) != SSA_NAME
524 || (TREE_CODE (arg1) != SSA_NAME
525 && TREE_CODE (arg1) != INTEGER_CST))
526 return NULL;
528 /* Check if arg0 is an SSA_NAME and the stmt which defines arg0 is
529 a conversion. */
530 arg0_def_stmt = SSA_NAME_DEF_STMT (arg0);
531 if (!gimple_assign_cast_p (arg0_def_stmt))
532 return NULL;
534 /* Use the RHS as new_arg0. */
535 convert_code = gimple_assign_rhs_code (arg0_def_stmt);
536 new_arg0 = gimple_assign_rhs1 (arg0_def_stmt);
537 if (convert_code == VIEW_CONVERT_EXPR)
539 new_arg0 = TREE_OPERAND (new_arg0, 0);
540 if (!is_gimple_reg_type (TREE_TYPE (new_arg0)))
541 return NULL;
543 if (TREE_CODE (new_arg0) == SSA_NAME
544 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_arg0))
545 return NULL;
547 if (TREE_CODE (arg1) == SSA_NAME)
549 /* Check if arg1 is an SSA_NAME and the stmt which defines arg1
550 is a conversion. */
551 arg1_def_stmt = SSA_NAME_DEF_STMT (arg1);
552 if (!is_gimple_assign (arg1_def_stmt)
553 || gimple_assign_rhs_code (arg1_def_stmt) != convert_code)
554 return NULL;
556 /* Either arg1_def_stmt or arg0_def_stmt should be conditional. */
557 if (dominated_by_p (CDI_DOMINATORS, gimple_bb (phi), gimple_bb (arg0_def_stmt))
558 && dominated_by_p (CDI_DOMINATORS,
559 gimple_bb (phi), gimple_bb (arg1_def_stmt)))
560 return NULL;
562 /* Use the RHS as new_arg1. */
563 new_arg1 = gimple_assign_rhs1 (arg1_def_stmt);
564 if (convert_code == VIEW_CONVERT_EXPR)
565 new_arg1 = TREE_OPERAND (new_arg1, 0);
566 if (TREE_CODE (new_arg1) == SSA_NAME
567 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (new_arg1))
568 return NULL;
570 else
572 /* arg0_def_stmt should be conditional. */
573 if (dominated_by_p (CDI_DOMINATORS, gimple_bb (phi), gimple_bb (arg0_def_stmt)))
574 return NULL;
575 /* If arg1 is an INTEGER_CST, fold it to new type. */
576 if (INTEGRAL_TYPE_P (TREE_TYPE (new_arg0))
577 && int_fits_type_p (arg1, TREE_TYPE (new_arg0)))
579 if (gimple_assign_cast_p (arg0_def_stmt))
581 /* For the INTEGER_CST case, we are just moving the
582 conversion from one place to another, which can often
583 hurt as the conversion moves further away from the
584 statement that computes the value. So, perform this
585 only if new_arg0 is an operand of COND_STMT, or
586 if arg0_def_stmt is the only non-debug stmt in
587 its basic block, because then it is possible this
588 could enable further optimizations (minmax replacement
589 etc.). See PR71016. */
590 if (new_arg0 != gimple_cond_lhs (cond_stmt)
591 && new_arg0 != gimple_cond_rhs (cond_stmt)
592 && gimple_bb (arg0_def_stmt) == e0->src)
594 gsi = gsi_for_stmt (arg0_def_stmt);
595 gsi_prev_nondebug (&gsi);
596 if (!gsi_end_p (gsi))
598 if (gassign *assign
599 = dyn_cast <gassign *> (gsi_stmt (gsi)))
601 tree lhs = gimple_assign_lhs (assign);
602 enum tree_code ass_code
603 = gimple_assign_rhs_code (assign);
604 if (ass_code != MAX_EXPR && ass_code != MIN_EXPR)
605 return NULL;
606 if (lhs != gimple_assign_rhs1 (arg0_def_stmt))
607 return NULL;
608 gsi_prev_nondebug (&gsi);
609 if (!gsi_end_p (gsi))
610 return NULL;
612 else
613 return NULL;
615 gsi = gsi_for_stmt (arg0_def_stmt);
616 gsi_next_nondebug (&gsi);
617 if (!gsi_end_p (gsi))
618 return NULL;
620 new_arg1 = fold_convert (TREE_TYPE (new_arg0), arg1);
622 else
623 return NULL;
625 else
626 return NULL;
629 /* If arg0/arg1 have > 1 use, then this transformation actually increases
630 the number of expressions evaluated at runtime. */
631 if (!has_single_use (arg0)
632 || (arg1_def_stmt && !has_single_use (arg1)))
633 return NULL;
635 /* If types of new_arg0 and new_arg1 are different bailout. */
636 if (!types_compatible_p (TREE_TYPE (new_arg0), TREE_TYPE (new_arg1)))
637 return NULL;
639 /* Create a new PHI stmt. */
640 result = PHI_RESULT (phi);
641 temp = make_ssa_name (TREE_TYPE (new_arg0), NULL);
642 newphi = create_phi_node (temp, gimple_bb (phi));
644 if (dump_file && (dump_flags & TDF_DETAILS))
646 fprintf (dump_file, "PHI ");
647 print_generic_expr (dump_file, gimple_phi_result (phi));
648 fprintf (dump_file,
649 " changed to factor conversion out from COND_EXPR.\n");
650 fprintf (dump_file, "New stmt with CAST that defines ");
651 print_generic_expr (dump_file, result);
652 fprintf (dump_file, ".\n");
655 /* Remove the old cast(s) that has single use. */
656 gsi_for_def = gsi_for_stmt (arg0_def_stmt);
657 gsi_remove (&gsi_for_def, true);
658 release_defs (arg0_def_stmt);
660 if (arg1_def_stmt)
662 gsi_for_def = gsi_for_stmt (arg1_def_stmt);
663 gsi_remove (&gsi_for_def, true);
664 release_defs (arg1_def_stmt);
667 add_phi_arg (newphi, new_arg0, e0, locus);
668 add_phi_arg (newphi, new_arg1, e1, locus);
670 /* Create the conversion stmt and insert it. */
671 if (convert_code == VIEW_CONVERT_EXPR)
673 temp = fold_build1 (VIEW_CONVERT_EXPR, TREE_TYPE (result), temp);
674 new_stmt = gimple_build_assign (result, temp);
676 else
677 new_stmt = gimple_build_assign (result, convert_code, temp);
678 gsi = gsi_after_labels (gimple_bb (phi));
679 gsi_insert_before (&gsi, new_stmt, GSI_SAME_STMT);
681 /* Remove the original PHI stmt. */
682 gsi = gsi_for_stmt (phi);
683 gsi_remove (&gsi, true);
685 statistics_counter_event (cfun, "factored out cast", 1);
687 return newphi;
690 /* Optimize
691 # x_5 in range [cst1, cst2] where cst2 = cst1 + 1
692 if (x_5 op cstN) # where op is == or != and N is 1 or 2
693 goto bb3;
694 else
695 goto bb4;
696 bb3:
697 bb4:
698 # r_6 = PHI<cst3(2), cst4(3)> # where cst3 == cst4 + 1 or cst4 == cst3 + 1
700 to r_6 = x_5 + (min (cst3, cst4) - cst1) or
701 r_6 = (min (cst3, cst4) + cst1) - x_5 depending on op, N and which
702 of cst3 and cst4 is smaller. */
704 static bool
705 two_value_replacement (basic_block cond_bb, basic_block middle_bb,
706 edge e1, gphi *phi, tree arg0, tree arg1)
708 /* Only look for adjacent integer constants. */
709 if (!INTEGRAL_TYPE_P (TREE_TYPE (arg0))
710 || !INTEGRAL_TYPE_P (TREE_TYPE (arg1))
711 || TREE_CODE (arg0) != INTEGER_CST
712 || TREE_CODE (arg1) != INTEGER_CST
713 || (tree_int_cst_lt (arg0, arg1)
714 ? wi::to_widest (arg0) + 1 != wi::to_widest (arg1)
715 : wi::to_widest (arg1) + 1 != wi::to_widest (arg0)))
716 return false;
718 if (!empty_block_p (middle_bb))
719 return false;
721 gimple *stmt = last_stmt (cond_bb);
722 tree lhs = gimple_cond_lhs (stmt);
723 tree rhs = gimple_cond_rhs (stmt);
725 if (TREE_CODE (lhs) != SSA_NAME
726 || !INTEGRAL_TYPE_P (TREE_TYPE (lhs))
727 || TREE_CODE (rhs) != INTEGER_CST)
728 return false;
730 switch (gimple_cond_code (stmt))
732 case EQ_EXPR:
733 case NE_EXPR:
734 break;
735 default:
736 return false;
739 /* Defer boolean x ? 0 : {1,-1} or x ? {1,-1} : 0 to
740 match_simplify_replacement. */
741 if (TREE_CODE (TREE_TYPE (lhs)) == BOOLEAN_TYPE
742 && (integer_zerop (arg0)
743 || integer_zerop (arg1)
744 || TREE_CODE (TREE_TYPE (arg0)) == BOOLEAN_TYPE
745 || (TYPE_PRECISION (TREE_TYPE (arg0))
746 <= TYPE_PRECISION (TREE_TYPE (lhs)))))
747 return false;
749 wide_int min, max;
750 value_range r;
751 get_range_query (cfun)->range_of_expr (r, lhs);
753 if (r.kind () == VR_RANGE)
755 min = r.lower_bound ();
756 max = r.upper_bound ();
758 else
760 int prec = TYPE_PRECISION (TREE_TYPE (lhs));
761 signop sgn = TYPE_SIGN (TREE_TYPE (lhs));
762 min = wi::min_value (prec, sgn);
763 max = wi::max_value (prec, sgn);
765 if (min + 1 != max
766 || (wi::to_wide (rhs) != min
767 && wi::to_wide (rhs) != max))
768 return false;
770 /* We need to know which is the true edge and which is the false
771 edge so that we know when to invert the condition below. */
772 edge true_edge, false_edge;
773 extract_true_false_edges_from_block (cond_bb, &true_edge, &false_edge);
774 if ((gimple_cond_code (stmt) == EQ_EXPR)
775 ^ (wi::to_wide (rhs) == max)
776 ^ (e1 == false_edge))
777 std::swap (arg0, arg1);
779 tree type;
780 if (TYPE_PRECISION (TREE_TYPE (lhs)) == TYPE_PRECISION (TREE_TYPE (arg0)))
782 /* Avoid performing the arithmetics in bool type which has different
783 semantics, otherwise prefer unsigned types from the two with
784 the same precision. */
785 if (TREE_CODE (TREE_TYPE (arg0)) == BOOLEAN_TYPE
786 || !TYPE_UNSIGNED (TREE_TYPE (arg0)))
787 type = TREE_TYPE (lhs);
788 else
789 type = TREE_TYPE (arg0);
791 else if (TYPE_PRECISION (TREE_TYPE (lhs)) > TYPE_PRECISION (TREE_TYPE (arg0)))
792 type = TREE_TYPE (lhs);
793 else
794 type = TREE_TYPE (arg0);
796 min = wide_int::from (min, TYPE_PRECISION (type),
797 TYPE_SIGN (TREE_TYPE (lhs)));
798 wide_int a = wide_int::from (wi::to_wide (arg0), TYPE_PRECISION (type),
799 TYPE_SIGN (TREE_TYPE (arg0)));
800 enum tree_code code;
801 wi::overflow_type ovf;
802 if (tree_int_cst_lt (arg0, arg1))
804 code = PLUS_EXPR;
805 a -= min;
806 if (!TYPE_UNSIGNED (type))
808 /* lhs is known to be in range [min, min+1] and we want to add a
809 to it. Check if that operation can overflow for those 2 values
810 and if yes, force unsigned type. */
811 wi::add (min + (wi::neg_p (a) ? 0 : 1), a, SIGNED, &ovf);
812 if (ovf)
813 type = unsigned_type_for (type);
816 else
818 code = MINUS_EXPR;
819 a += min;
820 if (!TYPE_UNSIGNED (type))
822 /* lhs is known to be in range [min, min+1] and we want to subtract
823 it from a. Check if that operation can overflow for those 2
824 values and if yes, force unsigned type. */
825 wi::sub (a, min + (wi::neg_p (min) ? 0 : 1), SIGNED, &ovf);
826 if (ovf)
827 type = unsigned_type_for (type);
831 tree arg = wide_int_to_tree (type, a);
832 gimple_seq stmts = NULL;
833 lhs = gimple_convert (&stmts, type, lhs);
834 tree new_rhs;
835 if (code == PLUS_EXPR)
836 new_rhs = gimple_build (&stmts, PLUS_EXPR, type, lhs, arg);
837 else
838 new_rhs = gimple_build (&stmts, MINUS_EXPR, type, arg, lhs);
839 new_rhs = gimple_convert (&stmts, TREE_TYPE (arg0), new_rhs);
840 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
841 gsi_insert_seq_before (&gsi, stmts, GSI_SAME_STMT);
843 replace_phi_edge_with_variable (cond_bb, e1, phi, new_rhs);
845 /* Note that we optimized this PHI. */
846 return true;
849 /* Return TRUE if SEQ/OP pair should be allowed during early phiopt.
850 Currently this is to allow MIN/MAX and ABS/NEGATE and constants. */
851 static bool
852 phiopt_early_allow (gimple_seq &seq, gimple_match_op &op)
854 /* Don't allow functions. */
855 if (!op.code.is_tree_code ())
856 return false;
857 tree_code code = (tree_code)op.code;
859 /* For non-empty sequence, only allow one statement. */
860 if (!gimple_seq_empty_p (seq))
862 /* Check to make sure op was already a SSA_NAME. */
863 if (code != SSA_NAME)
864 return false;
865 if (!gimple_seq_singleton_p (seq))
866 return false;
867 gimple *stmt = gimple_seq_first_stmt (seq);
868 /* Only allow assignments. */
869 if (!is_gimple_assign (stmt))
870 return false;
871 if (gimple_assign_lhs (stmt) != op.ops[0])
872 return false;
873 code = gimple_assign_rhs_code (stmt);
876 switch (code)
878 case MIN_EXPR:
879 case MAX_EXPR:
880 case ABS_EXPR:
881 case ABSU_EXPR:
882 case NEGATE_EXPR:
883 case SSA_NAME:
884 return true;
885 case INTEGER_CST:
886 case REAL_CST:
887 case VECTOR_CST:
888 case FIXED_CST:
889 return true;
890 default:
891 return false;
895 /* gimple_simplify_phiopt is like gimple_simplify but designed for PHIOPT.
896 Return NULL if nothing can be simplified or the resulting simplified value
897 with parts pushed if EARLY_P was true. Also rejects non allowed tree code
898 if EARLY_P is set.
899 Takes the comparison from COMP_STMT and two args, ARG0 and ARG1 and tries
900 to simplify CMP ? ARG0 : ARG1.
901 Also try to simplify (!CMP) ? ARG1 : ARG0 if the non-inverse failed. */
902 static tree
903 gimple_simplify_phiopt (bool early_p, tree type, gimple *comp_stmt,
904 tree arg0, tree arg1,
905 gimple_seq *seq)
907 tree result;
908 gimple_seq seq1 = NULL;
909 enum tree_code comp_code = gimple_cond_code (comp_stmt);
910 location_t loc = gimple_location (comp_stmt);
911 tree cmp0 = gimple_cond_lhs (comp_stmt);
912 tree cmp1 = gimple_cond_rhs (comp_stmt);
913 /* To handle special cases like floating point comparison, it is easier and
914 less error-prone to build a tree and gimplify it on the fly though it is
915 less efficient.
916 Don't use fold_build2 here as that might create (bool)a instead of just
917 "a != 0". */
918 tree cond = build2_loc (loc, comp_code, boolean_type_node,
919 cmp0, cmp1);
920 gimple_match_op op (gimple_match_cond::UNCOND,
921 COND_EXPR, type, cond, arg0, arg1);
923 if (op.resimplify (&seq1, follow_all_ssa_edges))
925 /* Early we want only to allow some generated tree codes. */
926 if (!early_p
927 || phiopt_early_allow (seq1, op))
929 result = maybe_push_res_to_seq (&op, &seq1);
930 if (result)
932 if (loc != UNKNOWN_LOCATION)
933 annotate_all_with_location (seq1, loc);
934 gimple_seq_add_seq_without_update (seq, seq1);
935 return result;
939 gimple_seq_discard (seq1);
940 seq1 = NULL;
942 /* Try the inverted comparison, that is !COMP ? ARG1 : ARG0. */
943 comp_code = invert_tree_comparison (comp_code, HONOR_NANS (cmp0));
945 if (comp_code == ERROR_MARK)
946 return NULL;
948 cond = build2_loc (loc,
949 comp_code, boolean_type_node,
950 cmp0, cmp1);
951 gimple_match_op op1 (gimple_match_cond::UNCOND,
952 COND_EXPR, type, cond, arg1, arg0);
954 if (op1.resimplify (&seq1, follow_all_ssa_edges))
956 /* Early we want only to allow some generated tree codes. */
957 if (!early_p
958 || phiopt_early_allow (seq1, op1))
960 result = maybe_push_res_to_seq (&op1, &seq1);
961 if (result)
963 if (loc != UNKNOWN_LOCATION)
964 annotate_all_with_location (seq1, loc);
965 gimple_seq_add_seq_without_update (seq, seq1);
966 return result;
970 gimple_seq_discard (seq1);
972 return NULL;
975 /* The function match_simplify_replacement does the main work of doing the
976 replacement using match and simplify. Return true if the replacement is done.
977 Otherwise return false.
978 BB is the basic block where the replacement is going to be done on. ARG0
979 is argument 0 from PHI. Likewise for ARG1. */
981 static bool
982 match_simplify_replacement (basic_block cond_bb, basic_block middle_bb,
983 edge e0, edge e1, gphi *phi,
984 tree arg0, tree arg1, bool early_p)
986 gimple *stmt;
987 gimple_stmt_iterator gsi;
988 edge true_edge, false_edge;
989 gimple_seq seq = NULL;
990 tree result;
991 gimple *stmt_to_move = NULL;
992 auto_bitmap inserted_exprs;
994 /* Special case A ? B : B as this will always simplify to B. */
995 if (operand_equal_for_phi_arg_p (arg0, arg1))
996 return false;
998 /* If the basic block only has a cheap preparation statement,
999 allow it and move it once the transformation is done. */
1000 if (!empty_block_p (middle_bb))
1002 if (!single_pred_p (middle_bb))
1003 return false;
1005 stmt_to_move = last_and_only_stmt (middle_bb);
1006 if (!stmt_to_move)
1007 return false;
1009 if (gimple_vuse (stmt_to_move))
1010 return false;
1012 if (gimple_could_trap_p (stmt_to_move)
1013 || gimple_has_side_effects (stmt_to_move))
1014 return false;
1016 if (gimple_uses_undefined_value_p (stmt_to_move))
1017 return false;
1019 /* Allow assignments and not no calls.
1020 As const calls don't match any of the above, yet they could
1021 still have some side-effects - they could contain
1022 gimple_could_trap_p statements, like floating point
1023 exceptions or integer division by zero. See PR70586.
1024 FIXME: perhaps gimple_has_side_effects or gimple_could_trap_p
1025 should handle this. */
1026 if (!is_gimple_assign (stmt_to_move))
1027 return false;
1029 tree lhs = gimple_assign_lhs (stmt_to_move);
1030 gimple *use_stmt;
1031 use_operand_p use_p;
1033 /* Allow only a statement which feeds into the phi. */
1034 if (!lhs || TREE_CODE (lhs) != SSA_NAME
1035 || !single_imm_use (lhs, &use_p, &use_stmt)
1036 || use_stmt != phi)
1037 return false;
1040 /* At this point we know we have a GIMPLE_COND with two successors.
1041 One successor is BB, the other successor is an empty block which
1042 falls through into BB.
1044 There is a single PHI node at the join point (BB).
1046 So, given the condition COND, and the two PHI arguments, match and simplify
1047 can happen on (COND) ? arg0 : arg1. */
1049 stmt = last_stmt (cond_bb);
1051 /* We need to know which is the true edge and which is the false
1052 edge so that we know when to invert the condition below. */
1053 extract_true_false_edges_from_block (cond_bb, &true_edge, &false_edge);
1054 if (e1 == true_edge || e0 == false_edge)
1055 std::swap (arg0, arg1);
1057 tree type = TREE_TYPE (gimple_phi_result (phi));
1058 result = gimple_simplify_phiopt (early_p, type, stmt,
1059 arg0, arg1,
1060 &seq);
1061 if (!result)
1062 return false;
1064 gsi = gsi_last_bb (cond_bb);
1065 /* Insert the sequence generated from gimple_simplify_phiopt. */
1066 if (seq)
1068 // Mark the lhs of the new statements maybe for dce
1069 gimple_stmt_iterator gsi1 = gsi_start (seq);
1070 for (; !gsi_end_p (gsi1); gsi_next (&gsi1))
1072 gimple *stmt = gsi_stmt (gsi1);
1073 tree name = gimple_get_lhs (stmt);
1074 if (name && TREE_CODE (name) == SSA_NAME)
1075 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (name));
1077 gsi_insert_seq_before (&gsi, seq, GSI_CONTINUE_LINKING);
1080 /* If there was a statement to move, move it to right before
1081 the original conditional. */
1082 if (stmt_to_move)
1084 if (dump_file && (dump_flags & TDF_DETAILS))
1086 fprintf (dump_file, "statement un-sinked:\n");
1087 print_gimple_stmt (dump_file, stmt_to_move, 0,
1088 TDF_VOPS|TDF_MEMSYMS);
1091 tree name = gimple_get_lhs (stmt_to_move);
1092 // Mark the name to be renamed if there is one.
1093 if (name && TREE_CODE (name) == SSA_NAME)
1094 bitmap_set_bit (inserted_exprs, SSA_NAME_VERSION (name));
1095 gimple_stmt_iterator gsi1 = gsi_for_stmt (stmt_to_move);
1096 gsi_move_before (&gsi1, &gsi);
1097 reset_flow_sensitive_info (gimple_assign_lhs (stmt_to_move));
1100 replace_phi_edge_with_variable (cond_bb, e1, phi, result, inserted_exprs);
1102 /* Add Statistic here even though replace_phi_edge_with_variable already
1103 does it as we want to be able to count when match-simplify happens vs
1104 the others. */
1105 statistics_counter_event (cfun, "match-simplify PHI replacement", 1);
1107 /* Note that we optimized this PHI. */
1108 return true;
1111 /* Update *ARG which is defined in STMT so that it contains the
1112 computed value if that seems profitable. Return true if the
1113 statement is made dead by that rewriting. */
1115 static bool
1116 jump_function_from_stmt (tree *arg, gimple *stmt)
1118 enum tree_code code = gimple_assign_rhs_code (stmt);
1119 if (code == ADDR_EXPR)
1121 /* For arg = &p->i transform it to p, if possible. */
1122 tree rhs1 = gimple_assign_rhs1 (stmt);
1123 poly_int64 offset;
1124 tree tem = get_addr_base_and_unit_offset (TREE_OPERAND (rhs1, 0),
1125 &offset);
1126 if (tem
1127 && TREE_CODE (tem) == MEM_REF
1128 && known_eq (mem_ref_offset (tem) + offset, 0))
1130 *arg = TREE_OPERAND (tem, 0);
1131 return true;
1134 /* TODO: Much like IPA-CP jump-functions we want to handle constant
1135 additions symbolically here, and we'd need to update the comparison
1136 code that compares the arg + cst tuples in our caller. For now the
1137 code above exactly handles the VEC_BASE pattern from vec.h. */
1138 return false;
1141 /* RHS is a source argument in a BIT_AND_EXPR which feeds a conditional
1142 of the form SSA_NAME NE 0.
1144 If RHS is fed by a simple EQ_EXPR comparison of two values, see if
1145 the two input values of the EQ_EXPR match arg0 and arg1.
1147 If so update *code and return TRUE. Otherwise return FALSE. */
1149 static bool
1150 rhs_is_fed_for_value_replacement (const_tree arg0, const_tree arg1,
1151 enum tree_code *code, const_tree rhs)
1153 /* Obviously if RHS is not an SSA_NAME, we can't look at the defining
1154 statement. */
1155 if (TREE_CODE (rhs) == SSA_NAME)
1157 gimple *def1 = SSA_NAME_DEF_STMT (rhs);
1159 /* Verify the defining statement has an EQ_EXPR on the RHS. */
1160 if (is_gimple_assign (def1) && gimple_assign_rhs_code (def1) == EQ_EXPR)
1162 /* Finally verify the source operands of the EQ_EXPR are equal
1163 to arg0 and arg1. */
1164 tree op0 = gimple_assign_rhs1 (def1);
1165 tree op1 = gimple_assign_rhs2 (def1);
1166 if ((operand_equal_for_phi_arg_p (arg0, op0)
1167 && operand_equal_for_phi_arg_p (arg1, op1))
1168 || (operand_equal_for_phi_arg_p (arg0, op1)
1169 && operand_equal_for_phi_arg_p (arg1, op0)))
1171 /* We will perform the optimization. */
1172 *code = gimple_assign_rhs_code (def1);
1173 return true;
1177 return false;
1180 /* Return TRUE if arg0/arg1 are equal to the rhs/lhs or lhs/rhs of COND.
1182 Also return TRUE if arg0/arg1 are equal to the source arguments of a
1183 an EQ comparison feeding a BIT_AND_EXPR which feeds COND.
1185 Return FALSE otherwise. */
1187 static bool
1188 operand_equal_for_value_replacement (const_tree arg0, const_tree arg1,
1189 enum tree_code *code, gimple *cond)
1191 gimple *def;
1192 tree lhs = gimple_cond_lhs (cond);
1193 tree rhs = gimple_cond_rhs (cond);
1195 if ((operand_equal_for_phi_arg_p (arg0, lhs)
1196 && operand_equal_for_phi_arg_p (arg1, rhs))
1197 || (operand_equal_for_phi_arg_p (arg1, lhs)
1198 && operand_equal_for_phi_arg_p (arg0, rhs)))
1199 return true;
1201 /* Now handle more complex case where we have an EQ comparison
1202 which feeds a BIT_AND_EXPR which feeds COND.
1204 First verify that COND is of the form SSA_NAME NE 0. */
1205 if (*code != NE_EXPR || !integer_zerop (rhs)
1206 || TREE_CODE (lhs) != SSA_NAME)
1207 return false;
1209 /* Now ensure that SSA_NAME is set by a BIT_AND_EXPR. */
1210 def = SSA_NAME_DEF_STMT (lhs);
1211 if (!is_gimple_assign (def) || gimple_assign_rhs_code (def) != BIT_AND_EXPR)
1212 return false;
1214 /* Now verify arg0/arg1 correspond to the source arguments of an
1215 EQ comparison feeding the BIT_AND_EXPR. */
1217 tree tmp = gimple_assign_rhs1 (def);
1218 if (rhs_is_fed_for_value_replacement (arg0, arg1, code, tmp))
1219 return true;
1221 tmp = gimple_assign_rhs2 (def);
1222 if (rhs_is_fed_for_value_replacement (arg0, arg1, code, tmp))
1223 return true;
1225 return false;
1228 /* Returns true if ARG is a neutral element for operation CODE
1229 on the RIGHT side. */
1231 static bool
1232 neutral_element_p (tree_code code, tree arg, bool right)
1234 switch (code)
1236 case PLUS_EXPR:
1237 case BIT_IOR_EXPR:
1238 case BIT_XOR_EXPR:
1239 return integer_zerop (arg);
1241 case LROTATE_EXPR:
1242 case RROTATE_EXPR:
1243 case LSHIFT_EXPR:
1244 case RSHIFT_EXPR:
1245 case MINUS_EXPR:
1246 case POINTER_PLUS_EXPR:
1247 return right && integer_zerop (arg);
1249 case MULT_EXPR:
1250 return integer_onep (arg);
1252 case TRUNC_DIV_EXPR:
1253 case CEIL_DIV_EXPR:
1254 case FLOOR_DIV_EXPR:
1255 case ROUND_DIV_EXPR:
1256 case EXACT_DIV_EXPR:
1257 return right && integer_onep (arg);
1259 case BIT_AND_EXPR:
1260 return integer_all_onesp (arg);
1262 default:
1263 return false;
1267 /* Returns true if ARG is an absorbing element for operation CODE. */
1269 static bool
1270 absorbing_element_p (tree_code code, tree arg, bool right, tree rval)
1272 switch (code)
1274 case BIT_IOR_EXPR:
1275 return integer_all_onesp (arg);
1277 case MULT_EXPR:
1278 case BIT_AND_EXPR:
1279 return integer_zerop (arg);
1281 case LSHIFT_EXPR:
1282 case RSHIFT_EXPR:
1283 case LROTATE_EXPR:
1284 case RROTATE_EXPR:
1285 return !right && integer_zerop (arg);
1287 case TRUNC_DIV_EXPR:
1288 case CEIL_DIV_EXPR:
1289 case FLOOR_DIV_EXPR:
1290 case ROUND_DIV_EXPR:
1291 case EXACT_DIV_EXPR:
1292 case TRUNC_MOD_EXPR:
1293 case CEIL_MOD_EXPR:
1294 case FLOOR_MOD_EXPR:
1295 case ROUND_MOD_EXPR:
1296 return (!right
1297 && integer_zerop (arg)
1298 && tree_single_nonzero_warnv_p (rval, NULL));
1300 default:
1301 return false;
1305 /* The function value_replacement does the main work of doing the value
1306 replacement. Return non-zero if the replacement is done. Otherwise return
1307 0. If we remove the middle basic block, return 2.
1308 BB is the basic block where the replacement is going to be done on. ARG0
1309 is argument 0 from the PHI. Likewise for ARG1. */
1311 static int
1312 value_replacement (basic_block cond_bb, basic_block middle_bb,
1313 edge e0, edge e1, gphi *phi, tree arg0, tree arg1)
1315 gimple_stmt_iterator gsi;
1316 gimple *cond;
1317 edge true_edge, false_edge;
1318 enum tree_code code;
1319 bool empty_or_with_defined_p = true;
1321 /* If the type says honor signed zeros we cannot do this
1322 optimization. */
1323 if (HONOR_SIGNED_ZEROS (arg1))
1324 return 0;
1326 /* If there is a statement in MIDDLE_BB that defines one of the PHI
1327 arguments, then adjust arg0 or arg1. */
1328 gsi = gsi_start_nondebug_after_labels_bb (middle_bb);
1329 while (!gsi_end_p (gsi))
1331 gimple *stmt = gsi_stmt (gsi);
1332 tree lhs;
1333 gsi_next_nondebug (&gsi);
1334 if (!is_gimple_assign (stmt))
1336 if (gimple_code (stmt) != GIMPLE_PREDICT
1337 && gimple_code (stmt) != GIMPLE_NOP)
1338 empty_or_with_defined_p = false;
1339 continue;
1341 /* Now try to adjust arg0 or arg1 according to the computation
1342 in the statement. */
1343 lhs = gimple_assign_lhs (stmt);
1344 if (!(lhs == arg0
1345 && jump_function_from_stmt (&arg0, stmt))
1346 || (lhs == arg1
1347 && jump_function_from_stmt (&arg1, stmt)))
1348 empty_or_with_defined_p = false;
1351 cond = last_stmt (cond_bb);
1352 code = gimple_cond_code (cond);
1354 /* This transformation is only valid for equality comparisons. */
1355 if (code != NE_EXPR && code != EQ_EXPR)
1356 return 0;
1358 /* We need to know which is the true edge and which is the false
1359 edge so that we know if have abs or negative abs. */
1360 extract_true_false_edges_from_block (cond_bb, &true_edge, &false_edge);
1362 /* At this point we know we have a COND_EXPR with two successors.
1363 One successor is BB, the other successor is an empty block which
1364 falls through into BB.
1366 The condition for the COND_EXPR is known to be NE_EXPR or EQ_EXPR.
1368 There is a single PHI node at the join point (BB) with two arguments.
1370 We now need to verify that the two arguments in the PHI node match
1371 the two arguments to the equality comparison. */
1373 bool equal_p = operand_equal_for_value_replacement (arg0, arg1, &code, cond);
1374 bool maybe_equal_p = false;
1375 if (!equal_p
1376 && empty_or_with_defined_p
1377 && TREE_CODE (gimple_cond_rhs (cond)) == INTEGER_CST
1378 && (operand_equal_for_phi_arg_p (gimple_cond_lhs (cond), arg0)
1379 ? TREE_CODE (arg1) == INTEGER_CST
1380 : (operand_equal_for_phi_arg_p (gimple_cond_lhs (cond), arg1)
1381 && TREE_CODE (arg0) == INTEGER_CST)))
1382 maybe_equal_p = true;
1383 if (equal_p || maybe_equal_p)
1385 edge e;
1386 tree arg;
1388 /* For NE_EXPR, we want to build an assignment result = arg where
1389 arg is the PHI argument associated with the true edge. For
1390 EQ_EXPR we want the PHI argument associated with the false edge. */
1391 e = (code == NE_EXPR ? true_edge : false_edge);
1393 /* Unfortunately, E may not reach BB (it may instead have gone to
1394 OTHER_BLOCK). If that is the case, then we want the single outgoing
1395 edge from OTHER_BLOCK which reaches BB and represents the desired
1396 path from COND_BLOCK. */
1397 if (e->dest == middle_bb)
1398 e = single_succ_edge (e->dest);
1400 /* Now we know the incoming edge to BB that has the argument for the
1401 RHS of our new assignment statement. */
1402 if (e0 == e)
1403 arg = arg0;
1404 else
1405 arg = arg1;
1407 /* If the middle basic block was empty or is defining the
1408 PHI arguments and this is a single phi where the args are different
1409 for the edges e0 and e1 then we can remove the middle basic block. */
1410 if (empty_or_with_defined_p
1411 && single_non_singleton_phi_for_edges (phi_nodes (gimple_bb (phi)),
1412 e0, e1) == phi)
1414 use_operand_p use_p;
1415 gimple *use_stmt;
1417 /* Even if arg0/arg1 isn't equal to second operand of cond, we
1418 can optimize away the bb if we can prove it doesn't care whether
1419 phi result is arg0/arg1 or second operand of cond. Consider:
1420 <bb 2> [local count: 118111600]:
1421 if (i_2(D) == 4)
1422 goto <bb 4>; [97.00%]
1423 else
1424 goto <bb 3>; [3.00%]
1426 <bb 3> [local count: 3540129]:
1428 <bb 4> [local count: 118111600]:
1429 # i_6 = PHI <i_2(D)(3), 6(2)>
1430 _3 = i_6 != 0;
1431 Here, carg is 4, oarg is 6, crhs is 0, and because
1432 (4 != 0) == (6 != 0), we don't care if i_6 is 4 or 6, both
1433 have the same outcome. So, can can optimize this to:
1434 _3 = i_2(D) != 0;
1435 If the single imm use of phi result >, >=, < or <=, similarly
1436 we can check if both carg and oarg compare the same against
1437 crhs using ccode. */
1438 if (maybe_equal_p
1439 && TREE_CODE (arg) != INTEGER_CST
1440 && single_imm_use (gimple_phi_result (phi), &use_p, &use_stmt))
1442 enum tree_code ccode = ERROR_MARK;
1443 tree clhs = NULL_TREE, crhs = NULL_TREE;
1444 tree carg = gimple_cond_rhs (cond);
1445 tree oarg = e0 == e ? arg1 : arg0;
1446 if (is_gimple_assign (use_stmt)
1447 && (TREE_CODE_CLASS (gimple_assign_rhs_code (use_stmt))
1448 == tcc_comparison))
1450 ccode = gimple_assign_rhs_code (use_stmt);
1451 clhs = gimple_assign_rhs1 (use_stmt);
1452 crhs = gimple_assign_rhs2 (use_stmt);
1454 else if (gimple_code (use_stmt) == GIMPLE_COND)
1456 ccode = gimple_cond_code (use_stmt);
1457 clhs = gimple_cond_lhs (use_stmt);
1458 crhs = gimple_cond_rhs (use_stmt);
1460 if (ccode != ERROR_MARK
1461 && clhs == gimple_phi_result (phi)
1462 && TREE_CODE (crhs) == INTEGER_CST)
1463 switch (ccode)
1465 case EQ_EXPR:
1466 case NE_EXPR:
1467 if (!tree_int_cst_equal (crhs, carg)
1468 && !tree_int_cst_equal (crhs, oarg))
1469 equal_p = true;
1470 break;
1471 case GT_EXPR:
1472 if (tree_int_cst_lt (crhs, carg)
1473 == tree_int_cst_lt (crhs, oarg))
1474 equal_p = true;
1475 break;
1476 case GE_EXPR:
1477 if (tree_int_cst_le (crhs, carg)
1478 == tree_int_cst_le (crhs, oarg))
1479 equal_p = true;
1480 break;
1481 case LT_EXPR:
1482 if (tree_int_cst_lt (carg, crhs)
1483 == tree_int_cst_lt (oarg, crhs))
1484 equal_p = true;
1485 break;
1486 case LE_EXPR:
1487 if (tree_int_cst_le (carg, crhs)
1488 == tree_int_cst_le (oarg, crhs))
1489 equal_p = true;
1490 break;
1491 default:
1492 break;
1494 if (equal_p)
1496 tree phires = gimple_phi_result (phi);
1497 if (SSA_NAME_RANGE_INFO (phires))
1499 /* After the optimization PHI result can have value
1500 which it couldn't have previously. */
1501 int_range_max r;
1502 if (get_global_range_query ()->range_of_expr (r, phires,
1503 phi))
1505 int_range<2> tmp (carg, carg);
1506 r.union_ (tmp);
1507 reset_flow_sensitive_info (phires);
1508 set_range_info (phires, r);
1510 else
1511 reset_flow_sensitive_info (phires);
1514 if (equal_p && MAY_HAVE_DEBUG_BIND_STMTS)
1516 imm_use_iterator imm_iter;
1517 tree phires = gimple_phi_result (phi);
1518 tree temp = NULL_TREE;
1519 bool reset_p = false;
1521 /* Add # DEBUG D#1 => arg != carg ? arg : oarg. */
1522 FOR_EACH_IMM_USE_STMT (use_stmt, imm_iter, phires)
1524 if (!is_gimple_debug (use_stmt))
1525 continue;
1526 if (temp == NULL_TREE)
1528 if (!single_pred_p (middle_bb)
1529 || EDGE_COUNT (gimple_bb (phi)->preds) != 2)
1531 /* But only if middle_bb has a single
1532 predecessor and phi bb has two, otherwise
1533 we could use a SSA_NAME not usable in that
1534 place or wrong-debug. */
1535 reset_p = true;
1536 break;
1538 gimple_stmt_iterator gsi
1539 = gsi_after_labels (gimple_bb (phi));
1540 tree type = TREE_TYPE (phires);
1541 temp = build_debug_expr_decl (type);
1542 tree t = build2 (NE_EXPR, boolean_type_node,
1543 arg, carg);
1544 t = build3 (COND_EXPR, type, t, arg, oarg);
1545 gimple *g = gimple_build_debug_bind (temp, t, phi);
1546 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
1548 FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
1549 replace_exp (use_p, temp);
1550 update_stmt (use_stmt);
1552 if (reset_p)
1553 reset_debug_uses (phi);
1556 if (equal_p)
1558 replace_phi_edge_with_variable (cond_bb, e1, phi, arg);
1559 /* Note that we optimized this PHI. */
1560 return 2;
1563 else if (equal_p)
1565 if (!single_pred_p (middle_bb))
1566 return 0;
1567 statistics_counter_event (cfun, "Replace PHI with "
1568 "variable/value_replacement", 1);
1570 /* Replace the PHI arguments with arg. */
1571 SET_PHI_ARG_DEF (phi, e0->dest_idx, arg);
1572 SET_PHI_ARG_DEF (phi, e1->dest_idx, arg);
1573 if (dump_file && (dump_flags & TDF_DETAILS))
1575 fprintf (dump_file, "PHI ");
1576 print_generic_expr (dump_file, gimple_phi_result (phi));
1577 fprintf (dump_file, " reduced for COND_EXPR in block %d to ",
1578 cond_bb->index);
1579 print_generic_expr (dump_file, arg);
1580 fprintf (dump_file, ".\n");
1582 return 1;
1586 if (!single_pred_p (middle_bb))
1587 return 0;
1589 /* Now optimize (x != 0) ? x + y : y to just x + y. */
1590 gsi = gsi_last_nondebug_bb (middle_bb);
1591 if (gsi_end_p (gsi))
1592 return 0;
1594 gimple *assign = gsi_stmt (gsi);
1595 if (!is_gimple_assign (assign)
1596 || (!INTEGRAL_TYPE_P (TREE_TYPE (arg0))
1597 && !POINTER_TYPE_P (TREE_TYPE (arg0))))
1598 return 0;
1600 if (gimple_assign_rhs_class (assign) != GIMPLE_BINARY_RHS)
1602 /* If last stmt of the middle_bb is a conversion, handle it like
1603 a preparation statement through constant evaluation with
1604 checking for UB. */
1605 enum tree_code sc = gimple_assign_rhs_code (assign);
1606 if (CONVERT_EXPR_CODE_P (sc))
1607 assign = NULL;
1608 else
1609 return 0;
1612 /* Punt if there are (degenerate) PHIs in middle_bb, there should not be. */
1613 if (!gimple_seq_empty_p (phi_nodes (middle_bb)))
1614 return 0;
1616 /* Allow up to 2 cheap preparation statements that prepare argument
1617 for assign, e.g.:
1618 if (y_4 != 0)
1619 goto <bb 3>;
1620 else
1621 goto <bb 4>;
1622 <bb 3>:
1623 _1 = (int) y_4;
1624 iftmp.0_6 = x_5(D) r<< _1;
1625 <bb 4>:
1626 # iftmp.0_2 = PHI <iftmp.0_6(3), x_5(D)(2)>
1628 if (y_3(D) == 0)
1629 goto <bb 4>;
1630 else
1631 goto <bb 3>;
1632 <bb 3>:
1633 y_4 = y_3(D) & 31;
1634 _1 = (int) y_4;
1635 _6 = x_5(D) r<< _1;
1636 <bb 4>:
1637 # _2 = PHI <x_5(D)(2), _6(3)> */
1638 gimple *prep_stmt[2] = { NULL, NULL };
1639 int prep_cnt;
1640 for (prep_cnt = 0; ; prep_cnt++)
1642 if (prep_cnt || assign)
1643 gsi_prev_nondebug (&gsi);
1644 if (gsi_end_p (gsi))
1645 break;
1647 gimple *g = gsi_stmt (gsi);
1648 if (gimple_code (g) == GIMPLE_LABEL)
1649 break;
1651 if (prep_cnt == 2 || !is_gimple_assign (g))
1652 return 0;
1654 tree lhs = gimple_assign_lhs (g);
1655 tree rhs1 = gimple_assign_rhs1 (g);
1656 use_operand_p use_p;
1657 gimple *use_stmt;
1658 if (TREE_CODE (lhs) != SSA_NAME
1659 || TREE_CODE (rhs1) != SSA_NAME
1660 || !INTEGRAL_TYPE_P (TREE_TYPE (lhs))
1661 || !INTEGRAL_TYPE_P (TREE_TYPE (rhs1))
1662 || !single_imm_use (lhs, &use_p, &use_stmt)
1663 || ((prep_cnt || assign)
1664 && use_stmt != (prep_cnt ? prep_stmt[prep_cnt - 1] : assign)))
1665 return 0;
1666 switch (gimple_assign_rhs_code (g))
1668 CASE_CONVERT:
1669 break;
1670 case PLUS_EXPR:
1671 case BIT_AND_EXPR:
1672 case BIT_IOR_EXPR:
1673 case BIT_XOR_EXPR:
1674 if (TREE_CODE (gimple_assign_rhs2 (g)) != INTEGER_CST)
1675 return 0;
1676 break;
1677 default:
1678 return 0;
1680 prep_stmt[prep_cnt] = g;
1683 /* Only transform if it removes the condition. */
1684 if (!single_non_singleton_phi_for_edges (phi_nodes (gimple_bb (phi)), e0, e1))
1685 return 0;
1687 /* Size-wise, this is always profitable. */
1688 if (optimize_bb_for_speed_p (cond_bb)
1689 /* The special case is useless if it has a low probability. */
1690 && profile_status_for_fn (cfun) != PROFILE_ABSENT
1691 && EDGE_PRED (middle_bb, 0)->probability < profile_probability::even ()
1692 /* If assign is cheap, there is no point avoiding it. */
1693 && estimate_num_insns_seq (bb_seq (middle_bb), &eni_time_weights)
1694 >= 3 * estimate_num_insns (cond, &eni_time_weights))
1695 return 0;
1697 tree cond_lhs = gimple_cond_lhs (cond);
1698 tree cond_rhs = gimple_cond_rhs (cond);
1700 /* Propagate the cond_rhs constant through preparation stmts,
1701 make sure UB isn't invoked while doing that. */
1702 for (int i = prep_cnt - 1; i >= 0; --i)
1704 gimple *g = prep_stmt[i];
1705 tree grhs1 = gimple_assign_rhs1 (g);
1706 if (!operand_equal_for_phi_arg_p (cond_lhs, grhs1))
1707 return 0;
1708 cond_lhs = gimple_assign_lhs (g);
1709 cond_rhs = fold_convert (TREE_TYPE (grhs1), cond_rhs);
1710 if (TREE_CODE (cond_rhs) != INTEGER_CST
1711 || TREE_OVERFLOW (cond_rhs))
1712 return 0;
1713 if (gimple_assign_rhs_class (g) == GIMPLE_BINARY_RHS)
1715 cond_rhs = int_const_binop (gimple_assign_rhs_code (g), cond_rhs,
1716 gimple_assign_rhs2 (g));
1717 if (TREE_OVERFLOW (cond_rhs))
1718 return 0;
1720 cond_rhs = fold_convert (TREE_TYPE (cond_lhs), cond_rhs);
1721 if (TREE_CODE (cond_rhs) != INTEGER_CST
1722 || TREE_OVERFLOW (cond_rhs))
1723 return 0;
1726 tree lhs, rhs1, rhs2;
1727 enum tree_code code_def;
1728 if (assign)
1730 lhs = gimple_assign_lhs (assign);
1731 rhs1 = gimple_assign_rhs1 (assign);
1732 rhs2 = gimple_assign_rhs2 (assign);
1733 code_def = gimple_assign_rhs_code (assign);
1735 else
1737 gcc_assert (prep_cnt > 0);
1738 lhs = cond_lhs;
1739 rhs1 = NULL_TREE;
1740 rhs2 = NULL_TREE;
1741 code_def = ERROR_MARK;
1744 if (((code == NE_EXPR && e1 == false_edge)
1745 || (code == EQ_EXPR && e1 == true_edge))
1746 && arg0 == lhs
1747 && ((assign == NULL
1748 && operand_equal_for_phi_arg_p (arg1, cond_rhs))
1749 || (assign
1750 && arg1 == rhs1
1751 && operand_equal_for_phi_arg_p (rhs2, cond_lhs)
1752 && neutral_element_p (code_def, cond_rhs, true))
1753 || (assign
1754 && arg1 == rhs2
1755 && operand_equal_for_phi_arg_p (rhs1, cond_lhs)
1756 && neutral_element_p (code_def, cond_rhs, false))
1757 || (assign
1758 && operand_equal_for_phi_arg_p (arg1, cond_rhs)
1759 && ((operand_equal_for_phi_arg_p (rhs2, cond_lhs)
1760 && absorbing_element_p (code_def, cond_rhs, true, rhs2))
1761 || (operand_equal_for_phi_arg_p (rhs1, cond_lhs)
1762 && absorbing_element_p (code_def,
1763 cond_rhs, false, rhs2))))))
1765 gsi = gsi_for_stmt (cond);
1766 /* Moving ASSIGN might change VR of lhs, e.g. when moving u_6
1767 def-stmt in:
1768 if (n_5 != 0)
1769 goto <bb 3>;
1770 else
1771 goto <bb 4>;
1773 <bb 3>:
1774 # RANGE [0, 4294967294]
1775 u_6 = n_5 + 4294967295;
1777 <bb 4>:
1778 # u_3 = PHI <u_6(3), 4294967295(2)> */
1779 reset_flow_sensitive_info (lhs);
1780 gimple_stmt_iterator gsi_from;
1781 for (int i = prep_cnt - 1; i >= 0; --i)
1783 tree plhs = gimple_assign_lhs (prep_stmt[i]);
1784 reset_flow_sensitive_info (plhs);
1785 gsi_from = gsi_for_stmt (prep_stmt[i]);
1786 gsi_move_before (&gsi_from, &gsi);
1788 if (assign)
1790 gsi_from = gsi_for_stmt (assign);
1791 gsi_move_before (&gsi_from, &gsi);
1793 replace_phi_edge_with_variable (cond_bb, e1, phi, lhs);
1794 return 2;
1797 return 0;
1800 /* If VAR is an SSA_NAME that points to a BIT_NOT_EXPR then return the TREE for
1801 the value being inverted. */
1803 static tree
1804 strip_bit_not (tree var)
1806 if (TREE_CODE (var) != SSA_NAME)
1807 return NULL_TREE;
1809 gimple *assign = SSA_NAME_DEF_STMT (var);
1810 if (gimple_code (assign) != GIMPLE_ASSIGN)
1811 return NULL_TREE;
1813 if (gimple_assign_rhs_code (assign) != BIT_NOT_EXPR)
1814 return NULL_TREE;
1816 return gimple_assign_rhs1 (assign);
1819 /* Invert a MIN to a MAX or a MAX to a MIN expression CODE. */
1821 enum tree_code
1822 invert_minmax_code (enum tree_code code)
1824 switch (code) {
1825 case MIN_EXPR:
1826 return MAX_EXPR;
1827 case MAX_EXPR:
1828 return MIN_EXPR;
1829 default:
1830 gcc_unreachable ();
1834 /* The function minmax_replacement does the main work of doing the minmax
1835 replacement. Return true if the replacement is done. Otherwise return
1836 false.
1837 BB is the basic block where the replacement is going to be done on. ARG0
1838 is argument 0 from the PHI. Likewise for ARG1.
1840 If THREEWAY_P then expect the BB to be laid out in diamond shape with each
1841 BB containing only a MIN or MAX expression. */
1843 static bool
1844 minmax_replacement (basic_block cond_bb, basic_block middle_bb, basic_block alt_middle_bb,
1845 edge e0, edge e1, gphi *phi, tree arg0, tree arg1, bool threeway_p)
1847 tree result;
1848 edge true_edge, false_edge;
1849 enum tree_code minmax, ass_code;
1850 tree smaller, larger, arg_true, arg_false;
1851 gimple_stmt_iterator gsi, gsi_from;
1853 tree type = TREE_TYPE (PHI_RESULT (phi));
1855 /* The optimization may be unsafe due to NaNs. */
1856 if (HONOR_NANS (type) || HONOR_SIGNED_ZEROS (type))
1857 return false;
1859 gcond *cond = as_a <gcond *> (last_stmt (cond_bb));
1860 enum tree_code cmp = gimple_cond_code (cond);
1861 tree rhs = gimple_cond_rhs (cond);
1863 /* Turn EQ/NE of extreme values to order comparisons. */
1864 if ((cmp == NE_EXPR || cmp == EQ_EXPR)
1865 && TREE_CODE (rhs) == INTEGER_CST
1866 && INTEGRAL_TYPE_P (TREE_TYPE (rhs)))
1868 if (wi::eq_p (wi::to_wide (rhs), wi::min_value (TREE_TYPE (rhs))))
1870 cmp = (cmp == EQ_EXPR) ? LT_EXPR : GE_EXPR;
1871 rhs = wide_int_to_tree (TREE_TYPE (rhs),
1872 wi::min_value (TREE_TYPE (rhs)) + 1);
1874 else if (wi::eq_p (wi::to_wide (rhs), wi::max_value (TREE_TYPE (rhs))))
1876 cmp = (cmp == EQ_EXPR) ? GT_EXPR : LE_EXPR;
1877 rhs = wide_int_to_tree (TREE_TYPE (rhs),
1878 wi::max_value (TREE_TYPE (rhs)) - 1);
1882 /* This transformation is only valid for order comparisons. Record which
1883 operand is smaller/larger if the result of the comparison is true. */
1884 tree alt_smaller = NULL_TREE;
1885 tree alt_larger = NULL_TREE;
1886 if (cmp == LT_EXPR || cmp == LE_EXPR)
1888 smaller = gimple_cond_lhs (cond);
1889 larger = rhs;
1890 /* If we have smaller < CST it is equivalent to smaller <= CST-1.
1891 Likewise smaller <= CST is equivalent to smaller < CST+1. */
1892 if (TREE_CODE (larger) == INTEGER_CST
1893 && INTEGRAL_TYPE_P (TREE_TYPE (larger)))
1895 if (cmp == LT_EXPR)
1897 wi::overflow_type overflow;
1898 wide_int alt = wi::sub (wi::to_wide (larger), 1,
1899 TYPE_SIGN (TREE_TYPE (larger)),
1900 &overflow);
1901 if (! overflow)
1902 alt_larger = wide_int_to_tree (TREE_TYPE (larger), alt);
1904 else
1906 wi::overflow_type overflow;
1907 wide_int alt = wi::add (wi::to_wide (larger), 1,
1908 TYPE_SIGN (TREE_TYPE (larger)),
1909 &overflow);
1910 if (! overflow)
1911 alt_larger = wide_int_to_tree (TREE_TYPE (larger), alt);
1915 else if (cmp == GT_EXPR || cmp == GE_EXPR)
1917 smaller = rhs;
1918 larger = gimple_cond_lhs (cond);
1919 /* If we have larger > CST it is equivalent to larger >= CST+1.
1920 Likewise larger >= CST is equivalent to larger > CST-1. */
1921 if (TREE_CODE (smaller) == INTEGER_CST
1922 && INTEGRAL_TYPE_P (TREE_TYPE (smaller)))
1924 wi::overflow_type overflow;
1925 if (cmp == GT_EXPR)
1927 wide_int alt = wi::add (wi::to_wide (smaller), 1,
1928 TYPE_SIGN (TREE_TYPE (smaller)),
1929 &overflow);
1930 if (! overflow)
1931 alt_smaller = wide_int_to_tree (TREE_TYPE (smaller), alt);
1933 else
1935 wide_int alt = wi::sub (wi::to_wide (smaller), 1,
1936 TYPE_SIGN (TREE_TYPE (smaller)),
1937 &overflow);
1938 if (! overflow)
1939 alt_smaller = wide_int_to_tree (TREE_TYPE (smaller), alt);
1943 else
1944 return false;
1946 /* Handle the special case of (signed_type)x < 0 being equivalent
1947 to x > MAX_VAL(signed_type) and (signed_type)x >= 0 equivalent
1948 to x <= MAX_VAL(signed_type). */
1949 if ((cmp == GE_EXPR || cmp == LT_EXPR)
1950 && INTEGRAL_TYPE_P (type)
1951 && TYPE_UNSIGNED (type)
1952 && integer_zerop (rhs))
1954 tree op = gimple_cond_lhs (cond);
1955 if (TREE_CODE (op) == SSA_NAME
1956 && INTEGRAL_TYPE_P (TREE_TYPE (op))
1957 && !TYPE_UNSIGNED (TREE_TYPE (op)))
1959 gimple *def_stmt = SSA_NAME_DEF_STMT (op);
1960 if (gimple_assign_cast_p (def_stmt))
1962 tree op1 = gimple_assign_rhs1 (def_stmt);
1963 if (INTEGRAL_TYPE_P (TREE_TYPE (op1))
1964 && TYPE_UNSIGNED (TREE_TYPE (op1))
1965 && (TYPE_PRECISION (TREE_TYPE (op))
1966 == TYPE_PRECISION (TREE_TYPE (op1)))
1967 && useless_type_conversion_p (type, TREE_TYPE (op1)))
1969 wide_int w1 = wi::max_value (TREE_TYPE (op));
1970 wide_int w2 = wi::add (w1, 1);
1971 if (cmp == LT_EXPR)
1973 larger = op1;
1974 smaller = wide_int_to_tree (TREE_TYPE (op1), w1);
1975 alt_smaller = wide_int_to_tree (TREE_TYPE (op1), w2);
1976 alt_larger = NULL_TREE;
1978 else
1980 smaller = op1;
1981 larger = wide_int_to_tree (TREE_TYPE (op1), w1);
1982 alt_larger = wide_int_to_tree (TREE_TYPE (op1), w2);
1983 alt_smaller = NULL_TREE;
1990 /* We need to know which is the true edge and which is the false
1991 edge so that we know if have abs or negative abs. */
1992 extract_true_false_edges_from_block (cond_bb, &true_edge, &false_edge);
1994 /* Forward the edges over the middle basic block. */
1995 if (true_edge->dest == middle_bb)
1996 true_edge = EDGE_SUCC (true_edge->dest, 0);
1997 if (false_edge->dest == middle_bb)
1998 false_edge = EDGE_SUCC (false_edge->dest, 0);
2000 /* When THREEWAY_P then e1 will point to the edge of the final transition
2001 from middle-bb to end. */
2002 if (true_edge == e0)
2004 if (!threeway_p)
2005 gcc_assert (false_edge == e1);
2006 arg_true = arg0;
2007 arg_false = arg1;
2009 else
2011 gcc_assert (false_edge == e0);
2012 if (!threeway_p)
2013 gcc_assert (true_edge == e1);
2014 arg_true = arg1;
2015 arg_false = arg0;
2018 if (empty_block_p (middle_bb))
2020 if ((operand_equal_for_phi_arg_p (arg_true, smaller)
2021 || (alt_smaller
2022 && operand_equal_for_phi_arg_p (arg_true, alt_smaller)))
2023 && (operand_equal_for_phi_arg_p (arg_false, larger)
2024 || (alt_larger
2025 && operand_equal_for_phi_arg_p (arg_true, alt_larger))))
2027 /* Case
2029 if (smaller < larger)
2030 rslt = smaller;
2031 else
2032 rslt = larger; */
2033 minmax = MIN_EXPR;
2035 else if ((operand_equal_for_phi_arg_p (arg_false, smaller)
2036 || (alt_smaller
2037 && operand_equal_for_phi_arg_p (arg_false, alt_smaller)))
2038 && (operand_equal_for_phi_arg_p (arg_true, larger)
2039 || (alt_larger
2040 && operand_equal_for_phi_arg_p (arg_true, alt_larger))))
2041 minmax = MAX_EXPR;
2042 else
2043 return false;
2045 else if (middle_bb != alt_middle_bb && threeway_p)
2047 /* Recognize the following case:
2049 if (smaller < larger)
2050 a = MIN (smaller, c);
2051 else
2052 b = MIN (larger, c);
2053 x = PHI <a, b>
2055 This is equivalent to
2057 a = MIN (smaller, c);
2058 x = MIN (larger, a); */
2060 gimple *assign = last_and_only_stmt (middle_bb);
2061 tree lhs, op0, op1, bound;
2062 tree alt_lhs, alt_op0, alt_op1;
2063 bool invert = false;
2065 if (!single_pred_p (middle_bb)
2066 || !single_pred_p (alt_middle_bb)
2067 || !single_succ_p (middle_bb)
2068 || !single_succ_p (alt_middle_bb))
2069 return false;
2071 /* When THREEWAY_P then e1 will point to the edge of the final transition
2072 from middle-bb to end. */
2073 if (true_edge == e0)
2074 gcc_assert (false_edge == EDGE_PRED (e1->src, 0));
2075 else
2076 gcc_assert (true_edge == EDGE_PRED (e1->src, 0));
2078 bool valid_minmax_p = false;
2079 gimple_stmt_iterator it1
2080 = gsi_start_nondebug_after_labels_bb (middle_bb);
2081 gimple_stmt_iterator it2
2082 = gsi_start_nondebug_after_labels_bb (alt_middle_bb);
2083 if (gsi_one_nondebug_before_end_p (it1)
2084 && gsi_one_nondebug_before_end_p (it2))
2086 gimple *stmt1 = gsi_stmt (it1);
2087 gimple *stmt2 = gsi_stmt (it2);
2088 if (is_gimple_assign (stmt1) && is_gimple_assign (stmt2))
2090 enum tree_code code1 = gimple_assign_rhs_code (stmt1);
2091 enum tree_code code2 = gimple_assign_rhs_code (stmt2);
2092 valid_minmax_p = (code1 == MIN_EXPR || code1 == MAX_EXPR)
2093 && (code2 == MIN_EXPR || code2 == MAX_EXPR);
2097 if (!valid_minmax_p)
2098 return false;
2100 if (!assign
2101 || gimple_code (assign) != GIMPLE_ASSIGN)
2102 return false;
2104 lhs = gimple_assign_lhs (assign);
2105 ass_code = gimple_assign_rhs_code (assign);
2106 if (ass_code != MAX_EXPR && ass_code != MIN_EXPR)
2107 return false;
2109 op0 = gimple_assign_rhs1 (assign);
2110 op1 = gimple_assign_rhs2 (assign);
2112 assign = last_and_only_stmt (alt_middle_bb);
2113 if (!assign
2114 || gimple_code (assign) != GIMPLE_ASSIGN)
2115 return false;
2117 alt_lhs = gimple_assign_lhs (assign);
2118 if (ass_code != gimple_assign_rhs_code (assign))
2119 return false;
2121 if (!operand_equal_for_phi_arg_p (lhs, arg_true)
2122 || !operand_equal_for_phi_arg_p (alt_lhs, arg_false))
2123 return false;
2125 alt_op0 = gimple_assign_rhs1 (assign);
2126 alt_op1 = gimple_assign_rhs2 (assign);
2128 if ((operand_equal_for_phi_arg_p (op0, smaller)
2129 || (alt_smaller
2130 && operand_equal_for_phi_arg_p (op0, alt_smaller)))
2131 && (operand_equal_for_phi_arg_p (alt_op0, larger)
2132 || (alt_larger
2133 && operand_equal_for_phi_arg_p (alt_op0, alt_larger))))
2135 /* We got here if the condition is true, i.e., SMALLER < LARGER. */
2136 if (!operand_equal_for_phi_arg_p (op1, alt_op1))
2137 return false;
2139 if ((arg0 = strip_bit_not (op0)) != NULL
2140 && (arg1 = strip_bit_not (alt_op0)) != NULL
2141 && (bound = strip_bit_not (op1)) != NULL)
2143 minmax = MAX_EXPR;
2144 ass_code = invert_minmax_code (ass_code);
2145 invert = true;
2147 else
2149 bound = op1;
2150 minmax = MIN_EXPR;
2151 arg0 = op0;
2152 arg1 = alt_op0;
2155 else if ((operand_equal_for_phi_arg_p (op0, larger)
2156 || (alt_larger
2157 && operand_equal_for_phi_arg_p (op0, alt_larger)))
2158 && (operand_equal_for_phi_arg_p (alt_op0, smaller)
2159 || (alt_smaller
2160 && operand_equal_for_phi_arg_p (alt_op0, alt_smaller))))
2162 /* We got here if the condition is true, i.e., SMALLER > LARGER. */
2163 if (!operand_equal_for_phi_arg_p (op1, alt_op1))
2164 return false;
2166 if ((arg0 = strip_bit_not (op0)) != NULL
2167 && (arg1 = strip_bit_not (alt_op0)) != NULL
2168 && (bound = strip_bit_not (op1)) != NULL)
2170 minmax = MIN_EXPR;
2171 ass_code = invert_minmax_code (ass_code);
2172 invert = true;
2174 else
2176 bound = op1;
2177 minmax = MAX_EXPR;
2178 arg0 = op0;
2179 arg1 = alt_op0;
2182 else
2183 return false;
2185 /* Emit the statement to compute min/max. */
2186 location_t locus = gimple_location (last_stmt (cond_bb));
2187 gimple_seq stmts = NULL;
2188 tree phi_result = PHI_RESULT (phi);
2189 result = gimple_build (&stmts, locus, minmax, TREE_TYPE (phi_result),
2190 arg0, arg1);
2191 result = gimple_build (&stmts, locus, ass_code, TREE_TYPE (phi_result),
2192 result, bound);
2193 if (invert)
2194 result = gimple_build (&stmts, locus, BIT_NOT_EXPR, TREE_TYPE (phi_result),
2195 result);
2197 gsi = gsi_last_bb (cond_bb);
2198 gsi_insert_seq_before (&gsi, stmts, GSI_NEW_STMT);
2200 replace_phi_edge_with_variable (cond_bb, e1, phi, result);
2202 return true;
2204 else
2206 /* Recognize the following case, assuming d <= u:
2208 if (a <= u)
2209 b = MAX (a, d);
2210 x = PHI <b, u>
2212 This is equivalent to
2214 b = MAX (a, d);
2215 x = MIN (b, u); */
2217 gimple *assign = last_and_only_stmt (middle_bb);
2218 tree lhs, op0, op1, bound;
2220 if (!single_pred_p (middle_bb))
2221 return false;
2223 if (!assign
2224 || gimple_code (assign) != GIMPLE_ASSIGN)
2225 return false;
2227 lhs = gimple_assign_lhs (assign);
2228 ass_code = gimple_assign_rhs_code (assign);
2229 if (ass_code != MAX_EXPR && ass_code != MIN_EXPR)
2230 return false;
2231 op0 = gimple_assign_rhs1 (assign);
2232 op1 = gimple_assign_rhs2 (assign);
2234 if (true_edge->src == middle_bb)
2236 /* We got here if the condition is true, i.e., SMALLER < LARGER. */
2237 if (!operand_equal_for_phi_arg_p (lhs, arg_true))
2238 return false;
2240 if (operand_equal_for_phi_arg_p (arg_false, larger)
2241 || (alt_larger
2242 && operand_equal_for_phi_arg_p (arg_false, alt_larger)))
2244 /* Case
2246 if (smaller < larger)
2248 r' = MAX_EXPR (smaller, bound)
2250 r = PHI <r', larger> --> to be turned to MIN_EXPR. */
2251 if (ass_code != MAX_EXPR)
2252 return false;
2254 minmax = MIN_EXPR;
2255 if (operand_equal_for_phi_arg_p (op0, smaller)
2256 || (alt_smaller
2257 && operand_equal_for_phi_arg_p (op0, alt_smaller)))
2258 bound = op1;
2259 else if (operand_equal_for_phi_arg_p (op1, smaller)
2260 || (alt_smaller
2261 && operand_equal_for_phi_arg_p (op1, alt_smaller)))
2262 bound = op0;
2263 else
2264 return false;
2266 /* We need BOUND <= LARGER. */
2267 if (!integer_nonzerop (fold_build2 (LE_EXPR, boolean_type_node,
2268 bound, larger)))
2269 return false;
2271 else if (operand_equal_for_phi_arg_p (arg_false, smaller)
2272 || (alt_smaller
2273 && operand_equal_for_phi_arg_p (arg_false, alt_smaller)))
2275 /* Case
2277 if (smaller < larger)
2279 r' = MIN_EXPR (larger, bound)
2281 r = PHI <r', smaller> --> to be turned to MAX_EXPR. */
2282 if (ass_code != MIN_EXPR)
2283 return false;
2285 minmax = MAX_EXPR;
2286 if (operand_equal_for_phi_arg_p (op0, larger)
2287 || (alt_larger
2288 && operand_equal_for_phi_arg_p (op0, alt_larger)))
2289 bound = op1;
2290 else if (operand_equal_for_phi_arg_p (op1, larger)
2291 || (alt_larger
2292 && operand_equal_for_phi_arg_p (op1, alt_larger)))
2293 bound = op0;
2294 else
2295 return false;
2297 /* We need BOUND >= SMALLER. */
2298 if (!integer_nonzerop (fold_build2 (GE_EXPR, boolean_type_node,
2299 bound, smaller)))
2300 return false;
2302 else
2303 return false;
2305 else
2307 /* We got here if the condition is false, i.e., SMALLER > LARGER. */
2308 if (!operand_equal_for_phi_arg_p (lhs, arg_false))
2309 return false;
2311 if (operand_equal_for_phi_arg_p (arg_true, larger)
2312 || (alt_larger
2313 && operand_equal_for_phi_arg_p (arg_true, alt_larger)))
2315 /* Case
2317 if (smaller > larger)
2319 r' = MIN_EXPR (smaller, bound)
2321 r = PHI <r', larger> --> to be turned to MAX_EXPR. */
2322 if (ass_code != MIN_EXPR)
2323 return false;
2325 minmax = MAX_EXPR;
2326 if (operand_equal_for_phi_arg_p (op0, smaller)
2327 || (alt_smaller
2328 && operand_equal_for_phi_arg_p (op0, alt_smaller)))
2329 bound = op1;
2330 else if (operand_equal_for_phi_arg_p (op1, smaller)
2331 || (alt_smaller
2332 && operand_equal_for_phi_arg_p (op1, alt_smaller)))
2333 bound = op0;
2334 else
2335 return false;
2337 /* We need BOUND >= LARGER. */
2338 if (!integer_nonzerop (fold_build2 (GE_EXPR, boolean_type_node,
2339 bound, larger)))
2340 return false;
2342 else if (operand_equal_for_phi_arg_p (arg_true, smaller)
2343 || (alt_smaller
2344 && operand_equal_for_phi_arg_p (arg_true, alt_smaller)))
2346 /* Case
2348 if (smaller > larger)
2350 r' = MAX_EXPR (larger, bound)
2352 r = PHI <r', smaller> --> to be turned to MIN_EXPR. */
2353 if (ass_code != MAX_EXPR)
2354 return false;
2356 minmax = MIN_EXPR;
2357 if (operand_equal_for_phi_arg_p (op0, larger))
2358 bound = op1;
2359 else if (operand_equal_for_phi_arg_p (op1, larger))
2360 bound = op0;
2361 else
2362 return false;
2364 /* We need BOUND <= SMALLER. */
2365 if (!integer_nonzerop (fold_build2 (LE_EXPR, boolean_type_node,
2366 bound, smaller)))
2367 return false;
2369 else
2370 return false;
2373 /* Move the statement from the middle block. */
2374 gsi = gsi_last_bb (cond_bb);
2375 gsi_from = gsi_last_nondebug_bb (middle_bb);
2376 reset_flow_sensitive_info (SINGLE_SSA_TREE_OPERAND (gsi_stmt (gsi_from),
2377 SSA_OP_DEF));
2378 gsi_move_before (&gsi_from, &gsi);
2381 /* Emit the statement to compute min/max. */
2382 gimple_seq stmts = NULL;
2383 tree phi_result = PHI_RESULT (phi);
2384 result = gimple_build (&stmts, minmax, TREE_TYPE (phi_result), arg0, arg1);
2386 gsi = gsi_last_bb (cond_bb);
2387 gsi_insert_seq_before (&gsi, stmts, GSI_NEW_STMT);
2389 replace_phi_edge_with_variable (cond_bb, e1, phi, result);
2391 return true;
2394 /* Attempt to optimize (x <=> y) cmp 0 and similar comparisons.
2395 For strong ordering <=> try to match something like:
2396 <bb 2> : // cond3_bb (== cond2_bb)
2397 if (x_4(D) != y_5(D))
2398 goto <bb 3>; [INV]
2399 else
2400 goto <bb 6>; [INV]
2402 <bb 3> : // cond_bb
2403 if (x_4(D) < y_5(D))
2404 goto <bb 6>; [INV]
2405 else
2406 goto <bb 4>; [INV]
2408 <bb 4> : // middle_bb
2410 <bb 6> : // phi_bb
2411 # iftmp.0_2 = PHI <1(4), 0(2), -1(3)>
2412 _1 = iftmp.0_2 == 0;
2414 and for partial ordering <=> something like:
2416 <bb 2> : // cond3_bb
2417 if (a_3(D) == b_5(D))
2418 goto <bb 6>; [50.00%]
2419 else
2420 goto <bb 3>; [50.00%]
2422 <bb 3> [local count: 536870913]: // cond2_bb
2423 if (a_3(D) < b_5(D))
2424 goto <bb 6>; [50.00%]
2425 else
2426 goto <bb 4>; [50.00%]
2428 <bb 4> [local count: 268435456]: // cond_bb
2429 if (a_3(D) > b_5(D))
2430 goto <bb 6>; [50.00%]
2431 else
2432 goto <bb 5>; [50.00%]
2434 <bb 5> [local count: 134217728]: // middle_bb
2436 <bb 6> [local count: 1073741824]: // phi_bb
2437 # SR.27_4 = PHI <0(2), -1(3), 1(4), 2(5)>
2438 _2 = SR.27_4 > 0; */
2440 static bool
2441 spaceship_replacement (basic_block cond_bb, basic_block middle_bb,
2442 edge e0, edge e1, gphi *phi,
2443 tree arg0, tree arg1)
2445 tree phires = PHI_RESULT (phi);
2446 if (!INTEGRAL_TYPE_P (TREE_TYPE (phires))
2447 || TYPE_UNSIGNED (TREE_TYPE (phires))
2448 || !tree_fits_shwi_p (arg0)
2449 || !tree_fits_shwi_p (arg1)
2450 || !IN_RANGE (tree_to_shwi (arg0), -1, 2)
2451 || !IN_RANGE (tree_to_shwi (arg1), -1, 2))
2452 return false;
2454 basic_block phi_bb = gimple_bb (phi);
2455 gcc_assert (phi_bb == e0->dest && phi_bb == e1->dest);
2456 if (!IN_RANGE (EDGE_COUNT (phi_bb->preds), 3, 4))
2457 return false;
2459 use_operand_p use_p;
2460 gimple *use_stmt;
2461 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (phires))
2462 return false;
2463 if (!single_imm_use (phires, &use_p, &use_stmt))
2464 return false;
2465 enum tree_code cmp;
2466 tree lhs, rhs;
2467 gimple *orig_use_stmt = use_stmt;
2468 tree orig_use_lhs = NULL_TREE;
2469 int prec = TYPE_PRECISION (TREE_TYPE (phires));
2470 bool is_cast = false;
2472 /* Deal with the case when match.pd has rewritten the (res & ~1) == 0
2473 into res <= 1 and has left a type-cast for signed types. */
2474 if (gimple_assign_cast_p (use_stmt))
2476 orig_use_lhs = gimple_assign_lhs (use_stmt);
2477 /* match.pd would have only done this for a signed type,
2478 so the conversion must be to an unsigned one. */
2479 tree ty1 = TREE_TYPE (gimple_assign_rhs1 (use_stmt));
2480 tree ty2 = TREE_TYPE (orig_use_lhs);
2482 if (!TYPE_UNSIGNED (ty2) || !INTEGRAL_TYPE_P (ty2))
2483 return false;
2484 if (TYPE_PRECISION (ty1) > TYPE_PRECISION (ty2))
2485 return false;
2486 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (orig_use_lhs))
2487 return false;
2488 if (!single_imm_use (orig_use_lhs, &use_p, &use_stmt))
2489 return false;
2491 is_cast = true;
2493 else if (is_gimple_assign (use_stmt)
2494 && gimple_assign_rhs_code (use_stmt) == BIT_AND_EXPR
2495 && TREE_CODE (gimple_assign_rhs2 (use_stmt)) == INTEGER_CST
2496 && (wi::to_wide (gimple_assign_rhs2 (use_stmt))
2497 == wi::shifted_mask (1, prec - 1, false, prec)))
2499 /* For partial_ordering result operator>= with unspec as second
2500 argument is (res & 1) == res, folded by match.pd into
2501 (res & ~1) == 0. */
2502 orig_use_lhs = gimple_assign_lhs (use_stmt);
2503 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (orig_use_lhs))
2504 return false;
2505 if (!single_imm_use (orig_use_lhs, &use_p, &use_stmt))
2506 return false;
2508 if (gimple_code (use_stmt) == GIMPLE_COND)
2510 cmp = gimple_cond_code (use_stmt);
2511 lhs = gimple_cond_lhs (use_stmt);
2512 rhs = gimple_cond_rhs (use_stmt);
2514 else if (is_gimple_assign (use_stmt))
2516 if (gimple_assign_rhs_class (use_stmt) == GIMPLE_BINARY_RHS)
2518 cmp = gimple_assign_rhs_code (use_stmt);
2519 lhs = gimple_assign_rhs1 (use_stmt);
2520 rhs = gimple_assign_rhs2 (use_stmt);
2522 else if (gimple_assign_rhs_code (use_stmt) == COND_EXPR)
2524 tree cond = gimple_assign_rhs1 (use_stmt);
2525 if (!COMPARISON_CLASS_P (cond))
2526 return false;
2527 cmp = TREE_CODE (cond);
2528 lhs = TREE_OPERAND (cond, 0);
2529 rhs = TREE_OPERAND (cond, 1);
2531 else
2532 return false;
2534 else
2535 return false;
2536 switch (cmp)
2538 case EQ_EXPR:
2539 case NE_EXPR:
2540 case LT_EXPR:
2541 case GT_EXPR:
2542 case LE_EXPR:
2543 case GE_EXPR:
2544 break;
2545 default:
2546 return false;
2548 if (lhs != (orig_use_lhs ? orig_use_lhs : phires)
2549 || !tree_fits_shwi_p (rhs)
2550 || !IN_RANGE (tree_to_shwi (rhs), -1, 1))
2551 return false;
2553 if (is_cast)
2555 if (TREE_CODE (rhs) != INTEGER_CST)
2556 return false;
2557 /* As for -ffast-math we assume the 2 return to be
2558 impossible, canonicalize (unsigned) res <= 1U or
2559 (unsigned) res < 2U into res >= 0 and (unsigned) res > 1U
2560 or (unsigned) res >= 2U as res < 0. */
2561 switch (cmp)
2563 case LE_EXPR:
2564 if (!integer_onep (rhs))
2565 return false;
2566 cmp = GE_EXPR;
2567 break;
2568 case LT_EXPR:
2569 if (wi::ne_p (wi::to_widest (rhs), 2))
2570 return false;
2571 cmp = GE_EXPR;
2572 break;
2573 case GT_EXPR:
2574 if (!integer_onep (rhs))
2575 return false;
2576 cmp = LT_EXPR;
2577 break;
2578 case GE_EXPR:
2579 if (wi::ne_p (wi::to_widest (rhs), 2))
2580 return false;
2581 cmp = LT_EXPR;
2582 break;
2583 default:
2584 return false;
2586 rhs = build_zero_cst (TREE_TYPE (phires));
2588 else if (orig_use_lhs)
2590 if ((cmp != EQ_EXPR && cmp != NE_EXPR) || !integer_zerop (rhs))
2591 return false;
2592 /* As for -ffast-math we assume the 2 return to be
2593 impossible, canonicalize (res & ~1) == 0 into
2594 res >= 0 and (res & ~1) != 0 as res < 0. */
2595 cmp = cmp == EQ_EXPR ? GE_EXPR : LT_EXPR;
2598 if (!empty_block_p (middle_bb))
2599 return false;
2601 gcond *cond1 = as_a <gcond *> (last_stmt (cond_bb));
2602 enum tree_code cmp1 = gimple_cond_code (cond1);
2603 switch (cmp1)
2605 case LT_EXPR:
2606 case LE_EXPR:
2607 case GT_EXPR:
2608 case GE_EXPR:
2609 break;
2610 default:
2611 return false;
2613 tree lhs1 = gimple_cond_lhs (cond1);
2614 tree rhs1 = gimple_cond_rhs (cond1);
2615 /* The optimization may be unsafe due to NaNs. */
2616 if (HONOR_NANS (TREE_TYPE (lhs1)))
2617 return false;
2618 if (TREE_CODE (lhs1) == SSA_NAME && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (lhs1))
2619 return false;
2620 if (TREE_CODE (rhs1) == SSA_NAME && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (rhs1))
2621 return false;
2623 if (!single_pred_p (cond_bb) || !cond_only_block_p (cond_bb))
2624 return false;
2626 basic_block cond2_bb = single_pred (cond_bb);
2627 if (EDGE_COUNT (cond2_bb->succs) != 2)
2628 return false;
2629 edge cond2_phi_edge;
2630 if (EDGE_SUCC (cond2_bb, 0)->dest == cond_bb)
2632 if (EDGE_SUCC (cond2_bb, 1)->dest != phi_bb)
2633 return false;
2634 cond2_phi_edge = EDGE_SUCC (cond2_bb, 1);
2636 else if (EDGE_SUCC (cond2_bb, 0)->dest != phi_bb)
2637 return false;
2638 else
2639 cond2_phi_edge = EDGE_SUCC (cond2_bb, 0);
2640 tree arg2 = gimple_phi_arg_def (phi, cond2_phi_edge->dest_idx);
2641 if (!tree_fits_shwi_p (arg2))
2642 return false;
2643 gimple *cond2 = last_stmt (cond2_bb);
2644 if (cond2 == NULL || gimple_code (cond2) != GIMPLE_COND)
2645 return false;
2646 enum tree_code cmp2 = gimple_cond_code (cond2);
2647 tree lhs2 = gimple_cond_lhs (cond2);
2648 tree rhs2 = gimple_cond_rhs (cond2);
2649 if (lhs2 == lhs1)
2651 if (!operand_equal_p (rhs2, rhs1, 0))
2653 if ((cmp2 == EQ_EXPR || cmp2 == NE_EXPR)
2654 && TREE_CODE (rhs1) == INTEGER_CST
2655 && TREE_CODE (rhs2) == INTEGER_CST)
2657 /* For integers, we can have cond2 x == 5
2658 and cond1 x < 5, x <= 4, x <= 5, x < 6,
2659 x > 5, x >= 6, x >= 5 or x > 4. */
2660 if (tree_int_cst_lt (rhs1, rhs2))
2662 if (wi::ne_p (wi::to_wide (rhs1) + 1, wi::to_wide (rhs2)))
2663 return false;
2664 if (cmp1 == LE_EXPR)
2665 cmp1 = LT_EXPR;
2666 else if (cmp1 == GT_EXPR)
2667 cmp1 = GE_EXPR;
2668 else
2669 return false;
2671 else
2673 gcc_checking_assert (tree_int_cst_lt (rhs2, rhs1));
2674 if (wi::ne_p (wi::to_wide (rhs2) + 1, wi::to_wide (rhs1)))
2675 return false;
2676 if (cmp1 == LT_EXPR)
2677 cmp1 = LE_EXPR;
2678 else if (cmp1 == GE_EXPR)
2679 cmp1 = GT_EXPR;
2680 else
2681 return false;
2683 rhs1 = rhs2;
2685 else
2686 return false;
2689 else if (lhs2 == rhs1)
2691 if (rhs2 != lhs1)
2692 return false;
2694 else
2695 return false;
2697 tree arg3 = arg2;
2698 basic_block cond3_bb = cond2_bb;
2699 edge cond3_phi_edge = cond2_phi_edge;
2700 gimple *cond3 = cond2;
2701 enum tree_code cmp3 = cmp2;
2702 tree lhs3 = lhs2;
2703 tree rhs3 = rhs2;
2704 if (EDGE_COUNT (phi_bb->preds) == 4)
2706 if (absu_hwi (tree_to_shwi (arg2)) != 1)
2707 return false;
2708 if (e1->flags & EDGE_TRUE_VALUE)
2710 if (tree_to_shwi (arg0) != 2
2711 || absu_hwi (tree_to_shwi (arg1)) != 1
2712 || wi::to_widest (arg1) == wi::to_widest (arg2))
2713 return false;
2715 else if (tree_to_shwi (arg1) != 2
2716 || absu_hwi (tree_to_shwi (arg0)) != 1
2717 || wi::to_widest (arg0) == wi::to_widest (arg1))
2718 return false;
2719 switch (cmp2)
2721 case LT_EXPR:
2722 case LE_EXPR:
2723 case GT_EXPR:
2724 case GE_EXPR:
2725 break;
2726 default:
2727 return false;
2729 /* if (x < y) goto phi_bb; else fallthru;
2730 if (x > y) goto phi_bb; else fallthru;
2731 bbx:;
2732 phi_bb:;
2733 is ok, but if x and y are swapped in one of the comparisons,
2734 or the comparisons are the same and operands not swapped,
2735 or the true and false edges are swapped, it is not. */
2736 if ((lhs2 == lhs1)
2737 ^ (((cond2_phi_edge->flags
2738 & ((cmp2 == LT_EXPR || cmp2 == LE_EXPR)
2739 ? EDGE_TRUE_VALUE : EDGE_FALSE_VALUE)) != 0)
2740 != ((e1->flags
2741 & ((cmp1 == LT_EXPR || cmp1 == LE_EXPR)
2742 ? EDGE_TRUE_VALUE : EDGE_FALSE_VALUE)) != 0)))
2743 return false;
2744 if (!single_pred_p (cond2_bb) || !cond_only_block_p (cond2_bb))
2745 return false;
2746 cond3_bb = single_pred (cond2_bb);
2747 if (EDGE_COUNT (cond2_bb->succs) != 2)
2748 return false;
2749 if (EDGE_SUCC (cond3_bb, 0)->dest == cond2_bb)
2751 if (EDGE_SUCC (cond3_bb, 1)->dest != phi_bb)
2752 return false;
2753 cond3_phi_edge = EDGE_SUCC (cond3_bb, 1);
2755 else if (EDGE_SUCC (cond3_bb, 0)->dest != phi_bb)
2756 return false;
2757 else
2758 cond3_phi_edge = EDGE_SUCC (cond3_bb, 0);
2759 arg3 = gimple_phi_arg_def (phi, cond3_phi_edge->dest_idx);
2760 cond3 = last_stmt (cond3_bb);
2761 if (cond3 == NULL || gimple_code (cond3) != GIMPLE_COND)
2762 return false;
2763 cmp3 = gimple_cond_code (cond3);
2764 lhs3 = gimple_cond_lhs (cond3);
2765 rhs3 = gimple_cond_rhs (cond3);
2766 if (lhs3 == lhs1)
2768 if (!operand_equal_p (rhs3, rhs1, 0))
2769 return false;
2771 else if (lhs3 == rhs1)
2773 if (rhs3 != lhs1)
2774 return false;
2776 else
2777 return false;
2779 else if (absu_hwi (tree_to_shwi (arg0)) != 1
2780 || absu_hwi (tree_to_shwi (arg1)) != 1
2781 || wi::to_widest (arg0) == wi::to_widest (arg1))
2782 return false;
2784 if (!integer_zerop (arg3) || (cmp3 != EQ_EXPR && cmp3 != NE_EXPR))
2785 return false;
2786 if ((cond3_phi_edge->flags & (cmp3 == EQ_EXPR
2787 ? EDGE_TRUE_VALUE : EDGE_FALSE_VALUE)) == 0)
2788 return false;
2790 /* lhs1 one_cmp rhs1 results in phires of 1. */
2791 enum tree_code one_cmp;
2792 if ((cmp1 == LT_EXPR || cmp1 == LE_EXPR)
2793 ^ (!integer_onep ((e1->flags & EDGE_TRUE_VALUE) ? arg1 : arg0)))
2794 one_cmp = LT_EXPR;
2795 else
2796 one_cmp = GT_EXPR;
2798 enum tree_code res_cmp;
2799 switch (cmp)
2801 case EQ_EXPR:
2802 if (integer_zerop (rhs))
2803 res_cmp = EQ_EXPR;
2804 else if (integer_minus_onep (rhs))
2805 res_cmp = one_cmp == LT_EXPR ? GT_EXPR : LT_EXPR;
2806 else if (integer_onep (rhs))
2807 res_cmp = one_cmp;
2808 else
2809 return false;
2810 break;
2811 case NE_EXPR:
2812 if (integer_zerop (rhs))
2813 res_cmp = NE_EXPR;
2814 else if (integer_minus_onep (rhs))
2815 res_cmp = one_cmp == LT_EXPR ? LE_EXPR : GE_EXPR;
2816 else if (integer_onep (rhs))
2817 res_cmp = one_cmp == LT_EXPR ? GE_EXPR : LE_EXPR;
2818 else
2819 return false;
2820 break;
2821 case LT_EXPR:
2822 if (integer_onep (rhs))
2823 res_cmp = one_cmp == LT_EXPR ? GE_EXPR : LE_EXPR;
2824 else if (integer_zerop (rhs))
2825 res_cmp = one_cmp == LT_EXPR ? GT_EXPR : LT_EXPR;
2826 else
2827 return false;
2828 break;
2829 case LE_EXPR:
2830 if (integer_zerop (rhs))
2831 res_cmp = one_cmp == LT_EXPR ? GE_EXPR : LE_EXPR;
2832 else if (integer_minus_onep (rhs))
2833 res_cmp = one_cmp == LT_EXPR ? GT_EXPR : LT_EXPR;
2834 else
2835 return false;
2836 break;
2837 case GT_EXPR:
2838 if (integer_minus_onep (rhs))
2839 res_cmp = one_cmp == LT_EXPR ? LE_EXPR : GE_EXPR;
2840 else if (integer_zerop (rhs))
2841 res_cmp = one_cmp;
2842 else
2843 return false;
2844 break;
2845 case GE_EXPR:
2846 if (integer_zerop (rhs))
2847 res_cmp = one_cmp == LT_EXPR ? LE_EXPR : GE_EXPR;
2848 else if (integer_onep (rhs))
2849 res_cmp = one_cmp;
2850 else
2851 return false;
2852 break;
2853 default:
2854 gcc_unreachable ();
2857 if (gimple_code (use_stmt) == GIMPLE_COND)
2859 gcond *use_cond = as_a <gcond *> (use_stmt);
2860 gimple_cond_set_code (use_cond, res_cmp);
2861 gimple_cond_set_lhs (use_cond, lhs1);
2862 gimple_cond_set_rhs (use_cond, rhs1);
2864 else if (gimple_assign_rhs_class (use_stmt) == GIMPLE_BINARY_RHS)
2866 gimple_assign_set_rhs_code (use_stmt, res_cmp);
2867 gimple_assign_set_rhs1 (use_stmt, lhs1);
2868 gimple_assign_set_rhs2 (use_stmt, rhs1);
2870 else
2872 tree cond = build2 (res_cmp, TREE_TYPE (gimple_assign_rhs1 (use_stmt)),
2873 lhs1, rhs1);
2874 gimple_assign_set_rhs1 (use_stmt, cond);
2876 update_stmt (use_stmt);
2878 if (MAY_HAVE_DEBUG_BIND_STMTS)
2880 use_operand_p use_p;
2881 imm_use_iterator iter;
2882 bool has_debug_uses = false;
2883 bool has_cast_debug_uses = false;
2884 FOR_EACH_IMM_USE_FAST (use_p, iter, phires)
2886 gimple *use_stmt = USE_STMT (use_p);
2887 if (orig_use_lhs && use_stmt == orig_use_stmt)
2888 continue;
2889 gcc_assert (is_gimple_debug (use_stmt));
2890 has_debug_uses = true;
2891 break;
2893 if (orig_use_lhs)
2895 if (!has_debug_uses || is_cast)
2896 FOR_EACH_IMM_USE_FAST (use_p, iter, orig_use_lhs)
2898 gimple *use_stmt = USE_STMT (use_p);
2899 gcc_assert (is_gimple_debug (use_stmt));
2900 has_debug_uses = true;
2901 if (is_cast)
2902 has_cast_debug_uses = true;
2904 gimple_stmt_iterator gsi = gsi_for_stmt (orig_use_stmt);
2905 tree zero = build_zero_cst (TREE_TYPE (orig_use_lhs));
2906 gimple_assign_set_rhs_with_ops (&gsi, INTEGER_CST, zero);
2907 update_stmt (orig_use_stmt);
2910 if (has_debug_uses)
2912 /* If there are debug uses, emit something like:
2913 # DEBUG D#1 => i_2(D) > j_3(D) ? 1 : -1
2914 # DEBUG D#2 => i_2(D) == j_3(D) ? 0 : D#1
2915 where > stands for the comparison that yielded 1
2916 and replace debug uses of phi result with that D#2.
2917 Ignore the value of 2, because if NaNs aren't expected,
2918 all floating point numbers should be comparable. */
2919 gimple_stmt_iterator gsi = gsi_after_labels (gimple_bb (phi));
2920 tree type = TREE_TYPE (phires);
2921 tree temp1 = build_debug_expr_decl (type);
2922 tree t = build2 (one_cmp, boolean_type_node, lhs1, rhs2);
2923 t = build3 (COND_EXPR, type, t, build_one_cst (type),
2924 build_int_cst (type, -1));
2925 gimple *g = gimple_build_debug_bind (temp1, t, phi);
2926 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
2927 tree temp2 = build_debug_expr_decl (type);
2928 t = build2 (EQ_EXPR, boolean_type_node, lhs1, rhs2);
2929 t = build3 (COND_EXPR, type, t, build_zero_cst (type), temp1);
2930 g = gimple_build_debug_bind (temp2, t, phi);
2931 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
2932 replace_uses_by (phires, temp2);
2933 if (orig_use_lhs)
2935 if (has_cast_debug_uses)
2937 tree temp3 = make_node (DEBUG_EXPR_DECL);
2938 DECL_ARTIFICIAL (temp3) = 1;
2939 TREE_TYPE (temp3) = TREE_TYPE (orig_use_lhs);
2940 SET_DECL_MODE (temp3, TYPE_MODE (type));
2941 t = fold_convert (TREE_TYPE (temp3), temp2);
2942 g = gimple_build_debug_bind (temp3, t, phi);
2943 gsi_insert_before (&gsi, g, GSI_SAME_STMT);
2944 replace_uses_by (orig_use_lhs, temp3);
2946 else
2947 replace_uses_by (orig_use_lhs, temp2);
2952 if (orig_use_lhs)
2954 gimple_stmt_iterator gsi = gsi_for_stmt (orig_use_stmt);
2955 gsi_remove (&gsi, true);
2958 gimple_stmt_iterator psi = gsi_for_stmt (phi);
2959 remove_phi_node (&psi, true);
2960 statistics_counter_event (cfun, "spaceship replacement", 1);
2962 return true;
2965 /* Optimize x ? __builtin_fun (x) : C, where C is __builtin_fun (0).
2966 Convert
2968 <bb 2>
2969 if (b_4(D) != 0)
2970 goto <bb 3>
2971 else
2972 goto <bb 4>
2974 <bb 3>
2975 _2 = (unsigned long) b_4(D);
2976 _9 = __builtin_popcountl (_2);
2978 _9 = __builtin_popcountl (b_4(D));
2980 <bb 4>
2981 c_12 = PHI <0(2), _9(3)>
2983 Into
2984 <bb 2>
2985 _2 = (unsigned long) b_4(D);
2986 _9 = __builtin_popcountl (_2);
2988 _9 = __builtin_popcountl (b_4(D));
2990 <bb 4>
2991 c_12 = PHI <_9(2)>
2993 Similarly for __builtin_clz or __builtin_ctz if
2994 C?Z_DEFINED_VALUE_AT_ZERO is 2, optab is present and
2995 instead of 0 above it uses the value from that macro. */
2997 static bool
2998 cond_removal_in_builtin_zero_pattern (basic_block cond_bb,
2999 basic_block middle_bb,
3000 edge e1, edge e2, gphi *phi,
3001 tree arg0, tree arg1)
3003 gimple *cond;
3004 gimple_stmt_iterator gsi, gsi_from;
3005 gimple *call;
3006 gimple *cast = NULL;
3007 tree lhs, arg;
3009 /* Check that
3010 _2 = (unsigned long) b_4(D);
3011 _9 = __builtin_popcountl (_2);
3013 _9 = __builtin_popcountl (b_4(D));
3014 are the only stmts in the middle_bb. */
3016 gsi = gsi_start_nondebug_after_labels_bb (middle_bb);
3017 if (gsi_end_p (gsi))
3018 return false;
3019 cast = gsi_stmt (gsi);
3020 gsi_next_nondebug (&gsi);
3021 if (!gsi_end_p (gsi))
3023 call = gsi_stmt (gsi);
3024 gsi_next_nondebug (&gsi);
3025 if (!gsi_end_p (gsi))
3026 return false;
3028 else
3030 call = cast;
3031 cast = NULL;
3034 /* Check that we have a popcount/clz/ctz builtin. */
3035 if (!is_gimple_call (call) || gimple_call_num_args (call) != 1)
3036 return false;
3038 arg = gimple_call_arg (call, 0);
3039 lhs = gimple_get_lhs (call);
3041 if (lhs == NULL_TREE)
3042 return false;
3044 combined_fn cfn = gimple_call_combined_fn (call);
3045 internal_fn ifn = IFN_LAST;
3046 int val = 0;
3047 switch (cfn)
3049 case CFN_BUILT_IN_BSWAP16:
3050 case CFN_BUILT_IN_BSWAP32:
3051 case CFN_BUILT_IN_BSWAP64:
3052 case CFN_BUILT_IN_BSWAP128:
3053 CASE_CFN_FFS:
3054 CASE_CFN_PARITY:
3055 CASE_CFN_POPCOUNT:
3056 break;
3057 CASE_CFN_CLZ:
3058 if (INTEGRAL_TYPE_P (TREE_TYPE (arg)))
3060 tree type = TREE_TYPE (arg);
3061 if (direct_internal_fn_supported_p (IFN_CLZ, type, OPTIMIZE_FOR_BOTH)
3062 && CLZ_DEFINED_VALUE_AT_ZERO (SCALAR_INT_TYPE_MODE (type),
3063 val) == 2)
3065 ifn = IFN_CLZ;
3066 break;
3069 return false;
3070 CASE_CFN_CTZ:
3071 if (INTEGRAL_TYPE_P (TREE_TYPE (arg)))
3073 tree type = TREE_TYPE (arg);
3074 if (direct_internal_fn_supported_p (IFN_CTZ, type, OPTIMIZE_FOR_BOTH)
3075 && CTZ_DEFINED_VALUE_AT_ZERO (SCALAR_INT_TYPE_MODE (type),
3076 val) == 2)
3078 ifn = IFN_CTZ;
3079 break;
3082 return false;
3083 case CFN_BUILT_IN_CLRSB:
3084 val = TYPE_PRECISION (integer_type_node) - 1;
3085 break;
3086 case CFN_BUILT_IN_CLRSBL:
3087 val = TYPE_PRECISION (long_integer_type_node) - 1;
3088 break;
3089 case CFN_BUILT_IN_CLRSBLL:
3090 val = TYPE_PRECISION (long_long_integer_type_node) - 1;
3091 break;
3092 default:
3093 return false;
3096 if (cast)
3098 /* We have a cast stmt feeding popcount/clz/ctz builtin. */
3099 /* Check that we have a cast prior to that. */
3100 if (gimple_code (cast) != GIMPLE_ASSIGN
3101 || !CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (cast)))
3102 return false;
3103 /* Result of the cast stmt is the argument to the builtin. */
3104 if (arg != gimple_assign_lhs (cast))
3105 return false;
3106 arg = gimple_assign_rhs1 (cast);
3109 cond = last_stmt (cond_bb);
3111 /* Cond_bb has a check for b_4 [!=|==] 0 before calling the popcount/clz/ctz
3112 builtin. */
3113 if (gimple_code (cond) != GIMPLE_COND
3114 || (gimple_cond_code (cond) != NE_EXPR
3115 && gimple_cond_code (cond) != EQ_EXPR)
3116 || !integer_zerop (gimple_cond_rhs (cond))
3117 || arg != gimple_cond_lhs (cond))
3118 return false;
3120 /* Canonicalize. */
3121 if ((e2->flags & EDGE_TRUE_VALUE
3122 && gimple_cond_code (cond) == NE_EXPR)
3123 || (e1->flags & EDGE_TRUE_VALUE
3124 && gimple_cond_code (cond) == EQ_EXPR))
3126 std::swap (arg0, arg1);
3127 std::swap (e1, e2);
3130 /* Check PHI arguments. */
3131 if (lhs != arg0
3132 || TREE_CODE (arg1) != INTEGER_CST
3133 || wi::to_wide (arg1) != val)
3134 return false;
3136 /* And insert the popcount/clz/ctz builtin and cast stmt before the
3137 cond_bb. */
3138 gsi = gsi_last_bb (cond_bb);
3139 if (cast)
3141 gsi_from = gsi_for_stmt (cast);
3142 gsi_move_before (&gsi_from, &gsi);
3143 reset_flow_sensitive_info (gimple_get_lhs (cast));
3145 gsi_from = gsi_for_stmt (call);
3146 if (ifn == IFN_LAST || gimple_call_internal_p (call))
3147 gsi_move_before (&gsi_from, &gsi);
3148 else
3150 /* For __builtin_c[lt]z* force .C[LT]Z ifn, because only
3151 the latter is well defined at zero. */
3152 call = gimple_build_call_internal (ifn, 1, gimple_call_arg (call, 0));
3153 gimple_call_set_lhs (call, lhs);
3154 gsi_insert_before (&gsi, call, GSI_SAME_STMT);
3155 gsi_remove (&gsi_from, true);
3157 reset_flow_sensitive_info (lhs);
3159 /* Now update the PHI and remove unneeded bbs. */
3160 replace_phi_edge_with_variable (cond_bb, e2, phi, lhs);
3161 return true;
3164 /* Auxiliary functions to determine the set of memory accesses which
3165 can't trap because they are preceded by accesses to the same memory
3166 portion. We do that for MEM_REFs, so we only need to track
3167 the SSA_NAME of the pointer indirectly referenced. The algorithm
3168 simply is a walk over all instructions in dominator order. When
3169 we see an MEM_REF we determine if we've already seen a same
3170 ref anywhere up to the root of the dominator tree. If we do the
3171 current access can't trap. If we don't see any dominating access
3172 the current access might trap, but might also make later accesses
3173 non-trapping, so we remember it. We need to be careful with loads
3174 or stores, for instance a load might not trap, while a store would,
3175 so if we see a dominating read access this doesn't mean that a later
3176 write access would not trap. Hence we also need to differentiate the
3177 type of access(es) seen.
3179 ??? We currently are very conservative and assume that a load might
3180 trap even if a store doesn't (write-only memory). This probably is
3181 overly conservative.
3183 We currently support a special case that for !TREE_ADDRESSABLE automatic
3184 variables, it could ignore whether something is a load or store because the
3185 local stack should be always writable. */
3187 /* A hash-table of references (MEM_REF/ARRAY_REF/COMPONENT_REF), and in which
3188 basic block an *_REF through it was seen, which would constitute a
3189 no-trap region for same accesses.
3191 Size is needed to support 2 MEM_REFs of different types, like
3192 MEM<double>(s_1) and MEM<long>(s_1), which would compare equal with
3193 OEP_ADDRESS_OF. */
3194 struct ref_to_bb
3196 tree exp;
3197 HOST_WIDE_INT size;
3198 unsigned int phase;
3199 basic_block bb;
3202 /* Hashtable helpers. */
3204 struct refs_hasher : free_ptr_hash<ref_to_bb>
3206 static inline hashval_t hash (const ref_to_bb *);
3207 static inline bool equal (const ref_to_bb *, const ref_to_bb *);
3210 /* Used for quick clearing of the hash-table when we see calls.
3211 Hash entries with phase < nt_call_phase are invalid. */
3212 static unsigned int nt_call_phase;
3214 /* The hash function. */
3216 inline hashval_t
3217 refs_hasher::hash (const ref_to_bb *n)
3219 inchash::hash hstate;
3220 inchash::add_expr (n->exp, hstate, OEP_ADDRESS_OF);
3221 hstate.add_hwi (n->size);
3222 return hstate.end ();
3225 /* The equality function of *P1 and *P2. */
3227 inline bool
3228 refs_hasher::equal (const ref_to_bb *n1, const ref_to_bb *n2)
3230 return operand_equal_p (n1->exp, n2->exp, OEP_ADDRESS_OF)
3231 && n1->size == n2->size;
3234 class nontrapping_dom_walker : public dom_walker
3236 public:
3237 nontrapping_dom_walker (cdi_direction direction, hash_set<tree> *ps)
3238 : dom_walker (direction), m_nontrapping (ps), m_seen_refs (128)
3241 edge before_dom_children (basic_block) final override;
3242 void after_dom_children (basic_block) final override;
3244 private:
3246 /* We see the expression EXP in basic block BB. If it's an interesting
3247 expression (an MEM_REF through an SSA_NAME) possibly insert the
3248 expression into the set NONTRAP or the hash table of seen expressions.
3249 STORE is true if this expression is on the LHS, otherwise it's on
3250 the RHS. */
3251 void add_or_mark_expr (basic_block, tree, bool);
3253 hash_set<tree> *m_nontrapping;
3255 /* The hash table for remembering what we've seen. */
3256 hash_table<refs_hasher> m_seen_refs;
3259 /* Called by walk_dominator_tree, when entering the block BB. */
3260 edge
3261 nontrapping_dom_walker::before_dom_children (basic_block bb)
3263 edge e;
3264 edge_iterator ei;
3265 gimple_stmt_iterator gsi;
3267 /* If we haven't seen all our predecessors, clear the hash-table. */
3268 FOR_EACH_EDGE (e, ei, bb->preds)
3269 if ((((size_t)e->src->aux) & 2) == 0)
3271 nt_call_phase++;
3272 break;
3275 /* Mark this BB as being on the path to dominator root and as visited. */
3276 bb->aux = (void*)(1 | 2);
3278 /* And walk the statements in order. */
3279 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
3281 gimple *stmt = gsi_stmt (gsi);
3283 if ((gimple_code (stmt) == GIMPLE_ASM && gimple_vdef (stmt))
3284 || (is_gimple_call (stmt)
3285 && (!nonfreeing_call_p (stmt) || !nonbarrier_call_p (stmt))))
3286 nt_call_phase++;
3287 else if (gimple_assign_single_p (stmt) && !gimple_has_volatile_ops (stmt))
3289 add_or_mark_expr (bb, gimple_assign_lhs (stmt), true);
3290 add_or_mark_expr (bb, gimple_assign_rhs1 (stmt), false);
3293 return NULL;
3296 /* Called by walk_dominator_tree, when basic block BB is exited. */
3297 void
3298 nontrapping_dom_walker::after_dom_children (basic_block bb)
3300 /* This BB isn't on the path to dominator root anymore. */
3301 bb->aux = (void*)2;
3304 /* We see the expression EXP in basic block BB. If it's an interesting
3305 expression of:
3306 1) MEM_REF
3307 2) ARRAY_REF
3308 3) COMPONENT_REF
3309 possibly insert the expression into the set NONTRAP or the hash table
3310 of seen expressions. STORE is true if this expression is on the LHS,
3311 otherwise it's on the RHS. */
3312 void
3313 nontrapping_dom_walker::add_or_mark_expr (basic_block bb, tree exp, bool store)
3315 HOST_WIDE_INT size;
3317 if ((TREE_CODE (exp) == MEM_REF || TREE_CODE (exp) == ARRAY_REF
3318 || TREE_CODE (exp) == COMPONENT_REF)
3319 && (size = int_size_in_bytes (TREE_TYPE (exp))) > 0)
3321 struct ref_to_bb map;
3322 ref_to_bb **slot;
3323 struct ref_to_bb *r2bb;
3324 basic_block found_bb = 0;
3326 if (!store)
3328 tree base = get_base_address (exp);
3329 /* Only record a LOAD of a local variable without address-taken, as
3330 the local stack is always writable. This allows cselim on a STORE
3331 with a dominating LOAD. */
3332 if (!auto_var_p (base) || TREE_ADDRESSABLE (base))
3333 return;
3336 /* Try to find the last seen *_REF, which can trap. */
3337 map.exp = exp;
3338 map.size = size;
3339 slot = m_seen_refs.find_slot (&map, INSERT);
3340 r2bb = *slot;
3341 if (r2bb && r2bb->phase >= nt_call_phase)
3342 found_bb = r2bb->bb;
3344 /* If we've found a trapping *_REF, _and_ it dominates EXP
3345 (it's in a basic block on the path from us to the dominator root)
3346 then we can't trap. */
3347 if (found_bb && (((size_t)found_bb->aux) & 1) == 1)
3349 m_nontrapping->add (exp);
3351 else
3353 /* EXP might trap, so insert it into the hash table. */
3354 if (r2bb)
3356 r2bb->phase = nt_call_phase;
3357 r2bb->bb = bb;
3359 else
3361 r2bb = XNEW (struct ref_to_bb);
3362 r2bb->phase = nt_call_phase;
3363 r2bb->bb = bb;
3364 r2bb->exp = exp;
3365 r2bb->size = size;
3366 *slot = r2bb;
3372 /* This is the entry point of gathering non trapping memory accesses.
3373 It will do a dominator walk over the whole function, and it will
3374 make use of the bb->aux pointers. It returns a set of trees
3375 (the MEM_REFs itself) which can't trap. */
3376 static hash_set<tree> *
3377 get_non_trapping (void)
3379 nt_call_phase = 0;
3380 hash_set<tree> *nontrap = new hash_set<tree>;
3382 nontrapping_dom_walker (CDI_DOMINATORS, nontrap)
3383 .walk (cfun->cfg->x_entry_block_ptr);
3385 clear_aux_for_blocks ();
3386 return nontrap;
3389 /* Do the main work of conditional store replacement. We already know
3390 that the recognized pattern looks like so:
3392 split:
3393 if (cond) goto MIDDLE_BB; else goto JOIN_BB (edge E1)
3394 MIDDLE_BB:
3395 something
3396 fallthrough (edge E0)
3397 JOIN_BB:
3398 some more
3400 We check that MIDDLE_BB contains only one store, that that store
3401 doesn't trap (not via NOTRAP, but via checking if an access to the same
3402 memory location dominates us, or the store is to a local addressable
3403 object) and that the store has a "simple" RHS. */
3405 static bool
3406 cond_store_replacement (basic_block middle_bb, basic_block join_bb,
3407 edge e0, edge e1, hash_set<tree> *nontrap)
3409 gimple *assign = last_and_only_stmt (middle_bb);
3410 tree lhs, rhs, name, name2;
3411 gphi *newphi;
3412 gassign *new_stmt;
3413 gimple_stmt_iterator gsi;
3414 location_t locus;
3416 /* Check if middle_bb contains of only one store. */
3417 if (!assign
3418 || !gimple_assign_single_p (assign)
3419 || gimple_has_volatile_ops (assign))
3420 return false;
3422 /* And no PHI nodes so all uses in the single stmt are also
3423 available where we insert to. */
3424 if (!gimple_seq_empty_p (phi_nodes (middle_bb)))
3425 return false;
3427 locus = gimple_location (assign);
3428 lhs = gimple_assign_lhs (assign);
3429 rhs = gimple_assign_rhs1 (assign);
3430 if ((!REFERENCE_CLASS_P (lhs)
3431 && !DECL_P (lhs))
3432 || !is_gimple_reg_type (TREE_TYPE (lhs)))
3433 return false;
3435 /* Prove that we can move the store down. We could also check
3436 TREE_THIS_NOTRAP here, but in that case we also could move stores,
3437 whose value is not available readily, which we want to avoid. */
3438 if (!nontrap->contains (lhs))
3440 /* If LHS is an access to a local variable without address-taken
3441 (or when we allow data races) and known not to trap, we could
3442 always safely move down the store. */
3443 tree base = get_base_address (lhs);
3444 if (!auto_var_p (base)
3445 || (TREE_ADDRESSABLE (base) && !flag_store_data_races)
3446 || tree_could_trap_p (lhs))
3447 return false;
3450 /* Now we've checked the constraints, so do the transformation:
3451 1) Remove the single store. */
3452 gsi = gsi_for_stmt (assign);
3453 unlink_stmt_vdef (assign);
3454 gsi_remove (&gsi, true);
3455 release_defs (assign);
3457 /* Make both store and load use alias-set zero as we have to
3458 deal with the case of the store being a conditional change
3459 of the dynamic type. */
3460 lhs = unshare_expr (lhs);
3461 tree *basep = &lhs;
3462 while (handled_component_p (*basep))
3463 basep = &TREE_OPERAND (*basep, 0);
3464 if (TREE_CODE (*basep) == MEM_REF
3465 || TREE_CODE (*basep) == TARGET_MEM_REF)
3466 TREE_OPERAND (*basep, 1)
3467 = fold_convert (ptr_type_node, TREE_OPERAND (*basep, 1));
3468 else
3469 *basep = build2 (MEM_REF, TREE_TYPE (*basep),
3470 build_fold_addr_expr (*basep),
3471 build_zero_cst (ptr_type_node));
3473 /* 2) Insert a load from the memory of the store to the temporary
3474 on the edge which did not contain the store. */
3475 name = make_temp_ssa_name (TREE_TYPE (lhs), NULL, "cstore");
3476 new_stmt = gimple_build_assign (name, lhs);
3477 gimple_set_location (new_stmt, locus);
3478 lhs = unshare_expr (lhs);
3480 /* Set the no-warning bit on the rhs of the load to avoid uninit
3481 warnings. */
3482 tree rhs1 = gimple_assign_rhs1 (new_stmt);
3483 suppress_warning (rhs1, OPT_Wuninitialized);
3485 gsi_insert_on_edge (e1, new_stmt);
3487 /* 3) Create a PHI node at the join block, with one argument
3488 holding the old RHS, and the other holding the temporary
3489 where we stored the old memory contents. */
3490 name2 = make_temp_ssa_name (TREE_TYPE (lhs), NULL, "cstore");
3491 newphi = create_phi_node (name2, join_bb);
3492 add_phi_arg (newphi, rhs, e0, locus);
3493 add_phi_arg (newphi, name, e1, locus);
3495 new_stmt = gimple_build_assign (lhs, PHI_RESULT (newphi));
3497 /* 4) Insert that PHI node. */
3498 gsi = gsi_after_labels (join_bb);
3499 if (gsi_end_p (gsi))
3501 gsi = gsi_last_bb (join_bb);
3502 gsi_insert_after (&gsi, new_stmt, GSI_NEW_STMT);
3504 else
3505 gsi_insert_before (&gsi, new_stmt, GSI_NEW_STMT);
3507 if (dump_file && (dump_flags & TDF_DETAILS))
3509 fprintf (dump_file, "\nConditional store replacement happened!");
3510 fprintf (dump_file, "\nReplaced the store with a load.");
3511 fprintf (dump_file, "\nInserted a new PHI statement in joint block:\n");
3512 print_gimple_stmt (dump_file, new_stmt, 0, TDF_VOPS|TDF_MEMSYMS);
3514 statistics_counter_event (cfun, "conditional store replacement", 1);
3516 return true;
3519 /* Do the main work of conditional store replacement. */
3521 static bool
3522 cond_if_else_store_replacement_1 (basic_block then_bb, basic_block else_bb,
3523 basic_block join_bb, gimple *then_assign,
3524 gimple *else_assign)
3526 tree lhs_base, lhs, then_rhs, else_rhs, name;
3527 location_t then_locus, else_locus;
3528 gimple_stmt_iterator gsi;
3529 gphi *newphi;
3530 gassign *new_stmt;
3532 if (then_assign == NULL
3533 || !gimple_assign_single_p (then_assign)
3534 || gimple_clobber_p (then_assign)
3535 || gimple_has_volatile_ops (then_assign)
3536 || else_assign == NULL
3537 || !gimple_assign_single_p (else_assign)
3538 || gimple_clobber_p (else_assign)
3539 || gimple_has_volatile_ops (else_assign))
3540 return false;
3542 lhs = gimple_assign_lhs (then_assign);
3543 if (!is_gimple_reg_type (TREE_TYPE (lhs))
3544 || !operand_equal_p (lhs, gimple_assign_lhs (else_assign), 0))
3545 return false;
3547 lhs_base = get_base_address (lhs);
3548 if (lhs_base == NULL_TREE
3549 || (!DECL_P (lhs_base) && TREE_CODE (lhs_base) != MEM_REF))
3550 return false;
3552 then_rhs = gimple_assign_rhs1 (then_assign);
3553 else_rhs = gimple_assign_rhs1 (else_assign);
3554 then_locus = gimple_location (then_assign);
3555 else_locus = gimple_location (else_assign);
3557 /* Now we've checked the constraints, so do the transformation:
3558 1) Remove the stores. */
3559 gsi = gsi_for_stmt (then_assign);
3560 unlink_stmt_vdef (then_assign);
3561 gsi_remove (&gsi, true);
3562 release_defs (then_assign);
3564 gsi = gsi_for_stmt (else_assign);
3565 unlink_stmt_vdef (else_assign);
3566 gsi_remove (&gsi, true);
3567 release_defs (else_assign);
3569 /* 2) Create a PHI node at the join block, with one argument
3570 holding the old RHS, and the other holding the temporary
3571 where we stored the old memory contents. */
3572 name = make_temp_ssa_name (TREE_TYPE (lhs), NULL, "cstore");
3573 newphi = create_phi_node (name, join_bb);
3574 add_phi_arg (newphi, then_rhs, EDGE_SUCC (then_bb, 0), then_locus);
3575 add_phi_arg (newphi, else_rhs, EDGE_SUCC (else_bb, 0), else_locus);
3577 new_stmt = gimple_build_assign (lhs, PHI_RESULT (newphi));
3579 /* 3) Insert that PHI node. */
3580 gsi = gsi_after_labels (join_bb);
3581 if (gsi_end_p (gsi))
3583 gsi = gsi_last_bb (join_bb);
3584 gsi_insert_after (&gsi, new_stmt, GSI_NEW_STMT);
3586 else
3587 gsi_insert_before (&gsi, new_stmt, GSI_NEW_STMT);
3589 statistics_counter_event (cfun, "if-then-else store replacement", 1);
3591 return true;
3594 /* Return the single store in BB with VDEF or NULL if there are
3595 other stores in the BB or loads following the store. */
3597 static gimple *
3598 single_trailing_store_in_bb (basic_block bb, tree vdef)
3600 if (SSA_NAME_IS_DEFAULT_DEF (vdef))
3601 return NULL;
3602 gimple *store = SSA_NAME_DEF_STMT (vdef);
3603 if (gimple_bb (store) != bb
3604 || gimple_code (store) == GIMPLE_PHI)
3605 return NULL;
3607 /* Verify there is no other store in this BB. */
3608 if (!SSA_NAME_IS_DEFAULT_DEF (gimple_vuse (store))
3609 && gimple_bb (SSA_NAME_DEF_STMT (gimple_vuse (store))) == bb
3610 && gimple_code (SSA_NAME_DEF_STMT (gimple_vuse (store))) != GIMPLE_PHI)
3611 return NULL;
3613 /* Verify there is no load or store after the store. */
3614 use_operand_p use_p;
3615 imm_use_iterator imm_iter;
3616 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, gimple_vdef (store))
3617 if (USE_STMT (use_p) != store
3618 && gimple_bb (USE_STMT (use_p)) == bb)
3619 return NULL;
3621 return store;
3624 /* Conditional store replacement. We already know
3625 that the recognized pattern looks like so:
3627 split:
3628 if (cond) goto THEN_BB; else goto ELSE_BB (edge E1)
3629 THEN_BB:
3631 X = Y;
3633 goto JOIN_BB;
3634 ELSE_BB:
3636 X = Z;
3638 fallthrough (edge E0)
3639 JOIN_BB:
3640 some more
3642 We check that it is safe to sink the store to JOIN_BB by verifying that
3643 there are no read-after-write or write-after-write dependencies in
3644 THEN_BB and ELSE_BB. */
3646 static bool
3647 cond_if_else_store_replacement (basic_block then_bb, basic_block else_bb,
3648 basic_block join_bb)
3650 vec<data_reference_p> then_datarefs, else_datarefs;
3651 vec<ddr_p> then_ddrs, else_ddrs;
3652 gimple *then_store, *else_store;
3653 bool found, ok = false, res;
3654 struct data_dependence_relation *ddr;
3655 data_reference_p then_dr, else_dr;
3656 int i, j;
3657 tree then_lhs, else_lhs;
3658 basic_block blocks[3];
3660 /* Handle the case with single store in THEN_BB and ELSE_BB. That is
3661 cheap enough to always handle as it allows us to elide dependence
3662 checking. */
3663 gphi *vphi = NULL;
3664 for (gphi_iterator si = gsi_start_phis (join_bb); !gsi_end_p (si);
3665 gsi_next (&si))
3666 if (virtual_operand_p (gimple_phi_result (si.phi ())))
3668 vphi = si.phi ();
3669 break;
3671 if (!vphi)
3672 return false;
3673 tree then_vdef = PHI_ARG_DEF_FROM_EDGE (vphi, single_succ_edge (then_bb));
3674 tree else_vdef = PHI_ARG_DEF_FROM_EDGE (vphi, single_succ_edge (else_bb));
3675 gimple *then_assign = single_trailing_store_in_bb (then_bb, then_vdef);
3676 if (then_assign)
3678 gimple *else_assign = single_trailing_store_in_bb (else_bb, else_vdef);
3679 if (else_assign)
3680 return cond_if_else_store_replacement_1 (then_bb, else_bb, join_bb,
3681 then_assign, else_assign);
3684 /* If either vectorization or if-conversion is disabled then do
3685 not sink any stores. */
3686 if (param_max_stores_to_sink == 0
3687 || (!flag_tree_loop_vectorize && !flag_tree_slp_vectorize)
3688 || !flag_tree_loop_if_convert)
3689 return false;
3691 /* Find data references. */
3692 then_datarefs.create (1);
3693 else_datarefs.create (1);
3694 if ((find_data_references_in_bb (NULL, then_bb, &then_datarefs)
3695 == chrec_dont_know)
3696 || !then_datarefs.length ()
3697 || (find_data_references_in_bb (NULL, else_bb, &else_datarefs)
3698 == chrec_dont_know)
3699 || !else_datarefs.length ())
3701 free_data_refs (then_datarefs);
3702 free_data_refs (else_datarefs);
3703 return false;
3706 /* Find pairs of stores with equal LHS. */
3707 auto_vec<gimple *, 1> then_stores, else_stores;
3708 FOR_EACH_VEC_ELT (then_datarefs, i, then_dr)
3710 if (DR_IS_READ (then_dr))
3711 continue;
3713 then_store = DR_STMT (then_dr);
3714 then_lhs = gimple_get_lhs (then_store);
3715 if (then_lhs == NULL_TREE)
3716 continue;
3717 found = false;
3719 FOR_EACH_VEC_ELT (else_datarefs, j, else_dr)
3721 if (DR_IS_READ (else_dr))
3722 continue;
3724 else_store = DR_STMT (else_dr);
3725 else_lhs = gimple_get_lhs (else_store);
3726 if (else_lhs == NULL_TREE)
3727 continue;
3729 if (operand_equal_p (then_lhs, else_lhs, 0))
3731 found = true;
3732 break;
3736 if (!found)
3737 continue;
3739 then_stores.safe_push (then_store);
3740 else_stores.safe_push (else_store);
3743 /* No pairs of stores found. */
3744 if (!then_stores.length ()
3745 || then_stores.length () > (unsigned) param_max_stores_to_sink)
3747 free_data_refs (then_datarefs);
3748 free_data_refs (else_datarefs);
3749 return false;
3752 /* Compute and check data dependencies in both basic blocks. */
3753 then_ddrs.create (1);
3754 else_ddrs.create (1);
3755 if (!compute_all_dependences (then_datarefs, &then_ddrs,
3756 vNULL, false)
3757 || !compute_all_dependences (else_datarefs, &else_ddrs,
3758 vNULL, false))
3760 free_dependence_relations (then_ddrs);
3761 free_dependence_relations (else_ddrs);
3762 free_data_refs (then_datarefs);
3763 free_data_refs (else_datarefs);
3764 return false;
3766 blocks[0] = then_bb;
3767 blocks[1] = else_bb;
3768 blocks[2] = join_bb;
3769 renumber_gimple_stmt_uids_in_blocks (blocks, 3);
3771 /* Check that there are no read-after-write or write-after-write dependencies
3772 in THEN_BB. */
3773 FOR_EACH_VEC_ELT (then_ddrs, i, ddr)
3775 struct data_reference *dra = DDR_A (ddr);
3776 struct data_reference *drb = DDR_B (ddr);
3778 if (DDR_ARE_DEPENDENT (ddr) != chrec_known
3779 && ((DR_IS_READ (dra) && DR_IS_WRITE (drb)
3780 && gimple_uid (DR_STMT (dra)) > gimple_uid (DR_STMT (drb)))
3781 || (DR_IS_READ (drb) && DR_IS_WRITE (dra)
3782 && gimple_uid (DR_STMT (drb)) > gimple_uid (DR_STMT (dra)))
3783 || (DR_IS_WRITE (dra) && DR_IS_WRITE (drb))))
3785 free_dependence_relations (then_ddrs);
3786 free_dependence_relations (else_ddrs);
3787 free_data_refs (then_datarefs);
3788 free_data_refs (else_datarefs);
3789 return false;
3793 /* Check that there are no read-after-write or write-after-write dependencies
3794 in ELSE_BB. */
3795 FOR_EACH_VEC_ELT (else_ddrs, i, ddr)
3797 struct data_reference *dra = DDR_A (ddr);
3798 struct data_reference *drb = DDR_B (ddr);
3800 if (DDR_ARE_DEPENDENT (ddr) != chrec_known
3801 && ((DR_IS_READ (dra) && DR_IS_WRITE (drb)
3802 && gimple_uid (DR_STMT (dra)) > gimple_uid (DR_STMT (drb)))
3803 || (DR_IS_READ (drb) && DR_IS_WRITE (dra)
3804 && gimple_uid (DR_STMT (drb)) > gimple_uid (DR_STMT (dra)))
3805 || (DR_IS_WRITE (dra) && DR_IS_WRITE (drb))))
3807 free_dependence_relations (then_ddrs);
3808 free_dependence_relations (else_ddrs);
3809 free_data_refs (then_datarefs);
3810 free_data_refs (else_datarefs);
3811 return false;
3815 /* Sink stores with same LHS. */
3816 FOR_EACH_VEC_ELT (then_stores, i, then_store)
3818 else_store = else_stores[i];
3819 res = cond_if_else_store_replacement_1 (then_bb, else_bb, join_bb,
3820 then_store, else_store);
3821 ok = ok || res;
3824 free_dependence_relations (then_ddrs);
3825 free_dependence_relations (else_ddrs);
3826 free_data_refs (then_datarefs);
3827 free_data_refs (else_datarefs);
3829 return ok;
3832 /* Return TRUE if STMT has a VUSE whose corresponding VDEF is in BB. */
3834 static bool
3835 local_mem_dependence (gimple *stmt, basic_block bb)
3837 tree vuse = gimple_vuse (stmt);
3838 gimple *def;
3840 if (!vuse)
3841 return false;
3843 def = SSA_NAME_DEF_STMT (vuse);
3844 return (def && gimple_bb (def) == bb);
3847 /* Given a "diamond" control-flow pattern where BB0 tests a condition,
3848 BB1 and BB2 are "then" and "else" blocks dependent on this test,
3849 and BB3 rejoins control flow following BB1 and BB2, look for
3850 opportunities to hoist loads as follows. If BB3 contains a PHI of
3851 two loads, one each occurring in BB1 and BB2, and the loads are
3852 provably of adjacent fields in the same structure, then move both
3853 loads into BB0. Of course this can only be done if there are no
3854 dependencies preventing such motion.
3856 One of the hoisted loads will always be speculative, so the
3857 transformation is currently conservative:
3859 - The fields must be strictly adjacent.
3860 - The two fields must occupy a single memory block that is
3861 guaranteed to not cross a page boundary.
3863 The last is difficult to prove, as such memory blocks should be
3864 aligned on the minimum of the stack alignment boundary and the
3865 alignment guaranteed by heap allocation interfaces. Thus we rely
3866 on a parameter for the alignment value.
3868 Provided a good value is used for the last case, the first
3869 restriction could possibly be relaxed. */
3871 static void
3872 hoist_adjacent_loads (basic_block bb0, basic_block bb1,
3873 basic_block bb2, basic_block bb3)
3875 int param_align = param_l1_cache_line_size;
3876 unsigned param_align_bits = (unsigned) (param_align * BITS_PER_UNIT);
3877 gphi_iterator gsi;
3879 /* Walk the phis in bb3 looking for an opportunity. We are looking
3880 for phis of two SSA names, one each of which is defined in bb1 and
3881 bb2. */
3882 for (gsi = gsi_start_phis (bb3); !gsi_end_p (gsi); gsi_next (&gsi))
3884 gphi *phi_stmt = gsi.phi ();
3885 gimple *def1, *def2;
3886 tree arg1, arg2, ref1, ref2, field1, field2;
3887 tree tree_offset1, tree_offset2, tree_size2, next;
3888 int offset1, offset2, size2;
3889 unsigned align1;
3890 gimple_stmt_iterator gsi2;
3891 basic_block bb_for_def1, bb_for_def2;
3893 if (gimple_phi_num_args (phi_stmt) != 2
3894 || virtual_operand_p (gimple_phi_result (phi_stmt)))
3895 continue;
3897 arg1 = gimple_phi_arg_def (phi_stmt, 0);
3898 arg2 = gimple_phi_arg_def (phi_stmt, 1);
3900 if (TREE_CODE (arg1) != SSA_NAME
3901 || TREE_CODE (arg2) != SSA_NAME
3902 || SSA_NAME_IS_DEFAULT_DEF (arg1)
3903 || SSA_NAME_IS_DEFAULT_DEF (arg2))
3904 continue;
3906 def1 = SSA_NAME_DEF_STMT (arg1);
3907 def2 = SSA_NAME_DEF_STMT (arg2);
3909 if ((gimple_bb (def1) != bb1 || gimple_bb (def2) != bb2)
3910 && (gimple_bb (def2) != bb1 || gimple_bb (def1) != bb2))
3911 continue;
3913 /* Check the mode of the arguments to be sure a conditional move
3914 can be generated for it. */
3915 if (optab_handler (movcc_optab, TYPE_MODE (TREE_TYPE (arg1)))
3916 == CODE_FOR_nothing)
3917 continue;
3919 /* Both statements must be assignments whose RHS is a COMPONENT_REF. */
3920 if (!gimple_assign_single_p (def1)
3921 || !gimple_assign_single_p (def2)
3922 || gimple_has_volatile_ops (def1)
3923 || gimple_has_volatile_ops (def2))
3924 continue;
3926 ref1 = gimple_assign_rhs1 (def1);
3927 ref2 = gimple_assign_rhs1 (def2);
3929 if (TREE_CODE (ref1) != COMPONENT_REF
3930 || TREE_CODE (ref2) != COMPONENT_REF)
3931 continue;
3933 /* The zeroth operand of the two component references must be
3934 identical. It is not sufficient to compare get_base_address of
3935 the two references, because this could allow for different
3936 elements of the same array in the two trees. It is not safe to
3937 assume that the existence of one array element implies the
3938 existence of a different one. */
3939 if (!operand_equal_p (TREE_OPERAND (ref1, 0), TREE_OPERAND (ref2, 0), 0))
3940 continue;
3942 field1 = TREE_OPERAND (ref1, 1);
3943 field2 = TREE_OPERAND (ref2, 1);
3945 /* Check for field adjacency, and ensure field1 comes first. */
3946 for (next = DECL_CHAIN (field1);
3947 next && TREE_CODE (next) != FIELD_DECL;
3948 next = DECL_CHAIN (next))
3951 if (next != field2)
3953 for (next = DECL_CHAIN (field2);
3954 next && TREE_CODE (next) != FIELD_DECL;
3955 next = DECL_CHAIN (next))
3958 if (next != field1)
3959 continue;
3961 std::swap (field1, field2);
3962 std::swap (def1, def2);
3965 bb_for_def1 = gimple_bb (def1);
3966 bb_for_def2 = gimple_bb (def2);
3968 /* Check for proper alignment of the first field. */
3969 tree_offset1 = bit_position (field1);
3970 tree_offset2 = bit_position (field2);
3971 tree_size2 = DECL_SIZE (field2);
3973 if (!tree_fits_uhwi_p (tree_offset1)
3974 || !tree_fits_uhwi_p (tree_offset2)
3975 || !tree_fits_uhwi_p (tree_size2))
3976 continue;
3978 offset1 = tree_to_uhwi (tree_offset1);
3979 offset2 = tree_to_uhwi (tree_offset2);
3980 size2 = tree_to_uhwi (tree_size2);
3981 align1 = DECL_ALIGN (field1) % param_align_bits;
3983 if (offset1 % BITS_PER_UNIT != 0)
3984 continue;
3986 /* For profitability, the two field references should fit within
3987 a single cache line. */
3988 if (align1 + offset2 - offset1 + size2 > param_align_bits)
3989 continue;
3991 /* The two expressions cannot be dependent upon vdefs defined
3992 in bb1/bb2. */
3993 if (local_mem_dependence (def1, bb_for_def1)
3994 || local_mem_dependence (def2, bb_for_def2))
3995 continue;
3997 /* The conditions are satisfied; hoist the loads from bb1 and bb2 into
3998 bb0. We hoist the first one first so that a cache miss is handled
3999 efficiently regardless of hardware cache-fill policy. */
4000 gsi2 = gsi_for_stmt (def1);
4001 gsi_move_to_bb_end (&gsi2, bb0);
4002 gsi2 = gsi_for_stmt (def2);
4003 gsi_move_to_bb_end (&gsi2, bb0);
4004 statistics_counter_event (cfun, "hoisted loads", 1);
4006 if (dump_file && (dump_flags & TDF_DETAILS))
4008 fprintf (dump_file,
4009 "\nHoisting adjacent loads from %d and %d into %d: \n",
4010 bb_for_def1->index, bb_for_def2->index, bb0->index);
4011 print_gimple_stmt (dump_file, def1, 0, TDF_VOPS|TDF_MEMSYMS);
4012 print_gimple_stmt (dump_file, def2, 0, TDF_VOPS|TDF_MEMSYMS);
4017 /* Determine whether we should attempt to hoist adjacent loads out of
4018 diamond patterns in pass_phiopt. Always hoist loads if
4019 -fhoist-adjacent-loads is specified and the target machine has
4020 both a conditional move instruction and a defined cache line size. */
4022 static bool
4023 gate_hoist_loads (void)
4025 return (flag_hoist_adjacent_loads == 1
4026 && param_l1_cache_line_size
4027 && HAVE_conditional_move);
4030 /* This pass tries to replaces an if-then-else block with an
4031 assignment. We have four kinds of transformations. Some of these
4032 transformations are also performed by the ifcvt RTL optimizer.
4034 Conditional Replacement
4035 -----------------------
4037 This transformation, implemented in match_simplify_replacement,
4038 replaces
4040 bb0:
4041 if (cond) goto bb2; else goto bb1;
4042 bb1:
4043 bb2:
4044 x = PHI <0 (bb1), 1 (bb0), ...>;
4046 with
4048 bb0:
4049 x' = cond;
4050 goto bb2;
4051 bb2:
4052 x = PHI <x' (bb0), ...>;
4054 We remove bb1 as it becomes unreachable. This occurs often due to
4055 gimplification of conditionals.
4057 Value Replacement
4058 -----------------
4060 This transformation, implemented in value_replacement, replaces
4062 bb0:
4063 if (a != b) goto bb2; else goto bb1;
4064 bb1:
4065 bb2:
4066 x = PHI <a (bb1), b (bb0), ...>;
4068 with
4070 bb0:
4071 bb2:
4072 x = PHI <b (bb0), ...>;
4074 This opportunity can sometimes occur as a result of other
4075 optimizations.
4078 Another case caught by value replacement looks like this:
4080 bb0:
4081 t1 = a == CONST;
4082 t2 = b > c;
4083 t3 = t1 & t2;
4084 if (t3 != 0) goto bb1; else goto bb2;
4085 bb1:
4086 bb2:
4087 x = PHI (CONST, a)
4089 Gets replaced with:
4090 bb0:
4091 bb2:
4092 t1 = a == CONST;
4093 t2 = b > c;
4094 t3 = t1 & t2;
4095 x = a;
4097 ABS Replacement
4098 ---------------
4100 This transformation, implemented in match_simplify_replacement, replaces
4102 bb0:
4103 if (a >= 0) goto bb2; else goto bb1;
4104 bb1:
4105 x = -a;
4106 bb2:
4107 x = PHI <x (bb1), a (bb0), ...>;
4109 with
4111 bb0:
4112 x' = ABS_EXPR< a >;
4113 bb2:
4114 x = PHI <x' (bb0), ...>;
4116 MIN/MAX Replacement
4117 -------------------
4119 This transformation, minmax_replacement replaces
4121 bb0:
4122 if (a <= b) goto bb2; else goto bb1;
4123 bb1:
4124 bb2:
4125 x = PHI <b (bb1), a (bb0), ...>;
4127 with
4129 bb0:
4130 x' = MIN_EXPR (a, b)
4131 bb2:
4132 x = PHI <x' (bb0), ...>;
4134 A similar transformation is done for MAX_EXPR.
4137 This pass also performs a fifth transformation of a slightly different
4138 flavor.
4140 Factor conversion in COND_EXPR
4141 ------------------------------
4143 This transformation factors the conversion out of COND_EXPR with
4144 factor_out_conditional_conversion.
4146 For example:
4147 if (a <= CST) goto <bb 3>; else goto <bb 4>;
4148 <bb 3>:
4149 tmp = (int) a;
4150 <bb 4>:
4151 tmp = PHI <tmp, CST>
4153 Into:
4154 if (a <= CST) goto <bb 3>; else goto <bb 4>;
4155 <bb 3>:
4156 <bb 4>:
4157 a = PHI <a, CST>
4158 tmp = (int) a;
4160 Adjacent Load Hoisting
4161 ----------------------
4163 This transformation replaces
4165 bb0:
4166 if (...) goto bb2; else goto bb1;
4167 bb1:
4168 x1 = (<expr>).field1;
4169 goto bb3;
4170 bb2:
4171 x2 = (<expr>).field2;
4172 bb3:
4173 # x = PHI <x1, x2>;
4175 with
4177 bb0:
4178 x1 = (<expr>).field1;
4179 x2 = (<expr>).field2;
4180 if (...) goto bb2; else goto bb1;
4181 bb1:
4182 goto bb3;
4183 bb2:
4184 bb3:
4185 # x = PHI <x1, x2>;
4187 The purpose of this transformation is to enable generation of conditional
4188 move instructions such as Intel CMOVE or PowerPC ISEL. Because one of
4189 the loads is speculative, the transformation is restricted to very
4190 specific cases to avoid introducing a page fault. We are looking for
4191 the common idiom:
4193 if (...)
4194 x = y->left;
4195 else
4196 x = y->right;
4198 where left and right are typically adjacent pointers in a tree structure. */
4200 namespace {
4202 const pass_data pass_data_phiopt =
4204 GIMPLE_PASS, /* type */
4205 "phiopt", /* name */
4206 OPTGROUP_NONE, /* optinfo_flags */
4207 TV_TREE_PHIOPT, /* tv_id */
4208 ( PROP_cfg | PROP_ssa ), /* properties_required */
4209 0, /* properties_provided */
4210 0, /* properties_destroyed */
4211 0, /* todo_flags_start */
4212 0, /* todo_flags_finish */
4215 class pass_phiopt : public gimple_opt_pass
4217 public:
4218 pass_phiopt (gcc::context *ctxt)
4219 : gimple_opt_pass (pass_data_phiopt, ctxt), early_p (false)
4222 /* opt_pass methods: */
4223 opt_pass * clone () final override { return new pass_phiopt (m_ctxt); }
4224 void set_pass_param (unsigned n, bool param) final override
4226 gcc_assert (n == 0);
4227 early_p = param;
4229 bool gate (function *) final override { return flag_ssa_phiopt; }
4230 unsigned int execute (function *) final override
4232 return tree_ssa_phiopt_worker (false,
4233 !early_p ? gate_hoist_loads () : false,
4234 early_p);
4237 private:
4238 bool early_p;
4239 }; // class pass_phiopt
4241 } // anon namespace
4243 gimple_opt_pass *
4244 make_pass_phiopt (gcc::context *ctxt)
4246 return new pass_phiopt (ctxt);
4249 namespace {
4251 const pass_data pass_data_cselim =
4253 GIMPLE_PASS, /* type */
4254 "cselim", /* name */
4255 OPTGROUP_NONE, /* optinfo_flags */
4256 TV_TREE_PHIOPT, /* tv_id */
4257 ( PROP_cfg | PROP_ssa ), /* properties_required */
4258 0, /* properties_provided */
4259 0, /* properties_destroyed */
4260 0, /* todo_flags_start */
4261 0, /* todo_flags_finish */
4264 class pass_cselim : public gimple_opt_pass
4266 public:
4267 pass_cselim (gcc::context *ctxt)
4268 : gimple_opt_pass (pass_data_cselim, ctxt)
4271 /* opt_pass methods: */
4272 bool gate (function *) final override { return flag_tree_cselim; }
4273 unsigned int execute (function *) final override
4275 return tree_ssa_cs_elim ();
4278 }; // class pass_cselim
4280 } // anon namespace
4282 gimple_opt_pass *
4283 make_pass_cselim (gcc::context *ctxt)
4285 return new pass_cselim (ctxt);