libcpp, c, middle-end: Optimize initializers using #embed in C
[official-gcc.git] / gcc / tree-ssa-sink.cc
blob8c551e42a4d2fac856ae8bfa4911d6cb331409bc
1 /* Code sinking for trees
2 Copyright (C) 2001-2024 Free Software Foundation, Inc.
3 Contributed by Daniel Berlin <dan@dberlin.org>
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "backend.h"
25 #include "tree.h"
26 #include "gimple.h"
27 #include "cfghooks.h"
28 #include "tree-pass.h"
29 #include "ssa.h"
30 #include "gimple-pretty-print.h"
31 #include "fold-const.h"
32 #include "stor-layout.h"
33 #include "cfganal.h"
34 #include "gimple-iterator.h"
35 #include "tree-cfg.h"
36 #include "cfgloop.h"
37 #include "tree-eh.h"
38 #include "tree-ssa-live.h"
40 /* TODO:
41 1. Sinking store only using scalar promotion (IE without moving the RHS):
43 *q = p;
44 p = p + 1;
45 if (something)
46 *q = <not p>;
47 else
48 y = *q;
51 should become
52 sinktemp = p;
53 p = p + 1;
54 if (something)
55 *q = <not p>;
56 else
58 *q = sinktemp;
59 y = *q
61 Store copy propagation will take care of the store elimination above.
64 2. Sinking using Partial Dead Code Elimination. */
67 static struct
69 /* The number of statements sunk down the flowgraph by code sinking. */
70 int sunk;
72 /* The number of stores commoned and sunk down by store commoning. */
73 int commoned;
74 } sink_stats;
77 /* Given a PHI, and one of its arguments (DEF), find the edge for
78 that argument and return it. If the argument occurs twice in the PHI node,
79 we return NULL. */
81 static basic_block
82 find_bb_for_arg (gphi *phi, tree def)
84 size_t i;
85 bool foundone = false;
86 basic_block result = NULL;
87 for (i = 0; i < gimple_phi_num_args (phi); i++)
88 if (PHI_ARG_DEF (phi, i) == def)
90 if (foundone)
91 return NULL;
92 foundone = true;
93 result = gimple_phi_arg_edge (phi, i)->src;
95 return result;
98 /* When the first immediate use is in a statement, then return true if all
99 immediate uses in IMM are in the same statement.
100 We could also do the case where the first immediate use is in a phi node,
101 and all the other uses are in phis in the same basic block, but this
102 requires some expensive checking later (you have to make sure no def/vdef
103 in the statement occurs for multiple edges in the various phi nodes it's
104 used in, so that you only have one place you can sink it to. */
106 static bool
107 all_immediate_uses_same_place (def_operand_p def_p)
109 tree var = DEF_FROM_PTR (def_p);
110 imm_use_iterator imm_iter;
111 use_operand_p use_p;
113 gimple *firstuse = NULL;
114 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, var)
116 if (is_gimple_debug (USE_STMT (use_p)))
117 continue;
118 if (firstuse == NULL)
119 firstuse = USE_STMT (use_p);
120 else
121 if (firstuse != USE_STMT (use_p))
122 return false;
125 return true;
128 /* Find the nearest common dominator of all of the immediate uses in IMM. */
130 static basic_block
131 nearest_common_dominator_of_uses (def_operand_p def_p, bool *debug_stmts)
133 tree var = DEF_FROM_PTR (def_p);
134 auto_bitmap blocks;
135 basic_block commondom;
136 unsigned int j;
137 bitmap_iterator bi;
138 imm_use_iterator imm_iter;
139 use_operand_p use_p;
141 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, var)
143 gimple *usestmt = USE_STMT (use_p);
144 basic_block useblock;
146 if (gphi *phi = dyn_cast <gphi *> (usestmt))
148 int idx = PHI_ARG_INDEX_FROM_USE (use_p);
150 useblock = gimple_phi_arg_edge (phi, idx)->src;
152 else if (is_gimple_debug (usestmt))
154 *debug_stmts = true;
155 continue;
157 else
159 useblock = gimple_bb (usestmt);
162 /* Short circuit. Nothing dominates the entry block. */
163 if (useblock == ENTRY_BLOCK_PTR_FOR_FN (cfun))
164 return NULL;
166 bitmap_set_bit (blocks, useblock->index);
168 commondom = BASIC_BLOCK_FOR_FN (cfun, bitmap_first_set_bit (blocks));
169 EXECUTE_IF_SET_IN_BITMAP (blocks, 0, j, bi)
170 commondom = nearest_common_dominator (CDI_DOMINATORS, commondom,
171 BASIC_BLOCK_FOR_FN (cfun, j));
172 return commondom;
175 /* Return whether sinking STMT from EARLY_BB to BEST_BB should be avoided. */
177 static bool
178 do_not_sink (gimple *stmt, basic_block early_bb, basic_block best_bb)
180 /* Placing a statement before a setjmp-like function would be invalid
181 (it cannot be reevaluated when execution follows an abnormal edge).
182 If we selected a block with abnormal predecessors, just punt. */
183 if (bb_has_abnormal_pred (best_bb))
184 return true;
186 /* If the latch block is empty, don't make it non-empty by sinking
187 something into it. */
188 if (best_bb == early_bb->loop_father->latch
189 && empty_block_p (best_bb))
190 return true;
192 /* Avoid turning an unconditional read into a conditional one when we
193 still might want to perform vectorization. */
194 if (best_bb->loop_father == early_bb->loop_father
195 && loop_outer (best_bb->loop_father)
196 && !best_bb->loop_father->inner
197 && gimple_vuse (stmt)
198 && !gimple_vdef (stmt)
199 && flag_tree_loop_vectorize
200 && !(cfun->curr_properties & PROP_loop_opts_done)
201 && dominated_by_p (CDI_DOMINATORS, best_bb->loop_father->latch, early_bb)
202 && !dominated_by_p (CDI_DOMINATORS, best_bb->loop_father->latch, best_bb))
203 return true;
205 return false;
208 /* Given EARLY_BB and LATE_BB, two blocks in a path through the dominator
209 tree, return the best basic block between them (inclusive) to place
210 statements.
212 We want the most control dependent block in the shallowest loop nest.
214 If the resulting block is in a shallower loop nest, then use it. */
216 static basic_block
217 select_best_block (basic_block early_bb,
218 basic_block late_bb,
219 gimple *stmt)
221 /* First pick a block we do not disqualify. */
222 while (late_bb != early_bb
223 && do_not_sink (stmt, early_bb, late_bb))
224 late_bb = get_immediate_dominator (CDI_DOMINATORS, late_bb);
226 basic_block best_bb = late_bb;
227 basic_block temp_bb = late_bb;
228 while (temp_bb != early_bb)
230 /* Walk up the dominator tree, hopefully we'll find a shallower
231 loop nest. */
232 temp_bb = get_immediate_dominator (CDI_DOMINATORS, temp_bb);
234 /* Do not consider blocks we do not want to sink to. */
235 if (temp_bb != early_bb && do_not_sink (stmt, early_bb, temp_bb))
238 /* If we've moved into a lower loop nest, then that becomes
239 our best block. */
240 else if (bb_loop_depth (temp_bb) < bb_loop_depth (best_bb))
241 best_bb = temp_bb;
243 /* A higher loop nest is always worse. */
244 else if (bb_loop_depth (temp_bb) > bb_loop_depth (best_bb))
247 /* But sink the least distance, if the new candidate on the same
248 loop depth is post-dominated by the current best block pick
249 the new candidate. */
250 else if (dominated_by_p (CDI_POST_DOMINATORS, temp_bb, best_bb))
251 best_bb = temp_bb;
253 /* Avoid sinking across a conditional branching to exceptional
254 code. In practice this does not reduce the number of dynamic
255 executions of the sunk statement (this includes EH and
256 branches leading to abort for example). Treat this case as
257 post-dominating. */
258 else if (single_pred_p (best_bb)
259 && single_pred_edge (best_bb)->src == temp_bb
260 && (single_pred_edge (best_bb)->flags & EDGE_FALLTHRU
261 || (single_pred_edge (best_bb)->probability
262 >= profile_probability::always ())))
263 best_bb = temp_bb;
266 gcc_checking_assert (best_bb == early_bb
267 || (!do_not_sink (stmt, early_bb, best_bb)
268 && ((bb_loop_depth (best_bb)
269 < bb_loop_depth (early_bb))
270 || !dominated_by_p (CDI_POST_DOMINATORS,
271 early_bb, best_bb))));
273 return best_bb;
276 /* Given a statement (STMT) and the basic block it is currently in (FROMBB),
277 determine the location to sink the statement to, if any.
278 Returns true if there is such location; in that case, TOGSI points to the
279 statement before that STMT should be moved. */
281 static bool
282 statement_sink_location (gimple *stmt, basic_block frombb,
283 gimple_stmt_iterator *togsi, bool *zero_uses_p,
284 virtual_operand_live &vop_live)
286 gimple *use;
287 use_operand_p one_use = NULL_USE_OPERAND_P;
288 basic_block sinkbb;
289 use_operand_p use_p;
290 def_operand_p def_p;
291 ssa_op_iter iter;
292 imm_use_iterator imm_iter;
294 *zero_uses_p = false;
296 /* We only can sink assignments and const/pure calls that are guaranteed
297 to return exactly once. */
298 int cf;
299 if (!is_gimple_assign (stmt)
300 && (!is_gimple_call (stmt)
301 || !((cf = gimple_call_flags (stmt)) & (ECF_CONST|ECF_PURE))
302 || (cf & (ECF_LOOPING_CONST_OR_PURE|ECF_RETURNS_TWICE))))
303 return false;
305 /* We only can sink stmts with a single definition. */
306 def_p = single_ssa_def_operand (stmt, SSA_OP_ALL_DEFS);
307 if (def_p == NULL_DEF_OPERAND_P)
308 return false;
310 /* There are a few classes of things we can't or don't move, some because we
311 don't have code to handle it, some because it's not profitable and some
312 because it's not legal.
314 We can't sink things that may be global stores, at least not without
315 calculating a lot more information, because we may cause it to no longer
316 be seen by an external routine that needs it depending on where it gets
317 moved to.
319 We can't sink statements that end basic blocks without splitting the
320 incoming edge for the sink location to place it there.
322 We can't sink statements that have volatile operands.
324 We don't want to sink dead code, so anything with 0 immediate uses is not
325 sunk.
327 Don't sink BLKmode assignments if current function has any local explicit
328 register variables, as BLKmode assignments may involve memcpy or memset
329 calls or, on some targets, inline expansion thereof that sometimes need
330 to use specific hard registers.
333 if (stmt_ends_bb_p (stmt)
334 || gimple_has_side_effects (stmt)
335 || (cfun->has_local_explicit_reg_vars
336 && TYPE_MODE (TREE_TYPE (gimple_get_lhs (stmt))) == BLKmode))
337 return false;
339 /* Return if there are no immediate uses of this stmt. */
340 if (has_zero_uses (DEF_FROM_PTR (def_p)))
342 *zero_uses_p = true;
343 return false;
346 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (DEF_FROM_PTR (def_p)))
347 return false;
349 FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_ALL_USES)
351 tree use = USE_FROM_PTR (use_p);
352 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (use))
353 return false;
356 use = NULL;
358 /* If stmt is a store the one and only use needs to be the VOP
359 merging PHI node. */
360 if (virtual_operand_p (DEF_FROM_PTR (def_p)))
362 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, DEF_FROM_PTR (def_p))
364 gimple *use_stmt = USE_STMT (use_p);
366 /* A killing definition is not a use. */
367 if ((gimple_has_lhs (use_stmt)
368 && operand_equal_p (gimple_get_lhs (stmt),
369 gimple_get_lhs (use_stmt), 0))
370 || stmt_kills_ref_p (use_stmt, gimple_get_lhs (stmt)))
372 /* If use_stmt is or might be a nop assignment then USE_STMT
373 acts as a use as well as definition. */
374 if (stmt != use_stmt
375 && ref_maybe_used_by_stmt_p (use_stmt,
376 gimple_get_lhs (stmt)))
377 return false;
378 continue;
381 if (gimple_code (use_stmt) != GIMPLE_PHI)
382 return false;
384 if (use
385 && use != use_stmt)
386 return false;
388 use = use_stmt;
390 if (!use)
391 return false;
393 /* If all the immediate uses are not in the same place, find the nearest
394 common dominator of all the immediate uses. For PHI nodes, we have to
395 find the nearest common dominator of all of the predecessor blocks, since
396 that is where insertion would have to take place. */
397 else if (gimple_vuse (stmt)
398 || !all_immediate_uses_same_place (def_p))
400 bool debug_stmts = false;
401 basic_block commondom = nearest_common_dominator_of_uses (def_p,
402 &debug_stmts);
404 if (commondom == frombb)
405 return false;
407 /* If this is a load then do not sink past any stores. */
408 if (gimple_vuse (stmt))
410 /* Do not sink loads from hard registers. */
411 if (gimple_assign_single_p (stmt)
412 && VAR_P (gimple_assign_rhs1 (stmt))
413 && DECL_HARD_REGISTER (gimple_assign_rhs1 (stmt)))
414 return false;
416 /* When the live virtual operand at the intended sink location is
417 not the same as the one from the load walk up the dominator tree
418 for a new candidate location. */
419 while (commondom != frombb
420 && vop_live.get_live_in (commondom) != gimple_vuse (stmt))
421 commondom = get_immediate_dominator (CDI_DOMINATORS, commondom);
422 if (commondom == frombb)
423 return false;
426 /* Our common dominator has to be dominated by frombb in order to be a
427 trivially safe place to put this statement, since it has multiple
428 uses. */
429 if (!dominated_by_p (CDI_DOMINATORS, commondom, frombb))
430 return false;
432 commondom = select_best_block (frombb, commondom, stmt);
434 if (commondom == frombb)
435 return false;
437 *togsi = gsi_after_labels (commondom);
439 return true;
441 else
443 FOR_EACH_IMM_USE_FAST (one_use, imm_iter, DEF_FROM_PTR (def_p))
445 if (is_gimple_debug (USE_STMT (one_use)))
446 continue;
447 break;
449 use = USE_STMT (one_use);
451 if (gimple_code (use) != GIMPLE_PHI)
453 sinkbb = select_best_block (frombb, gimple_bb (use), stmt);
455 if (sinkbb == frombb)
456 return false;
458 *togsi = gsi_after_labels (sinkbb);
460 return true;
464 sinkbb = find_bb_for_arg (as_a <gphi *> (use), DEF_FROM_PTR (def_p));
466 /* This can happen if there are multiple uses in a PHI. */
467 if (!sinkbb)
468 return false;
470 basic_block bestbb = select_best_block (frombb, sinkbb, stmt);
471 if (bestbb == frombb
472 /* When we sink a store make sure there's not a path to any of
473 the possibly skipped killing defs as that wrecks the virtual
474 operand update, requiring inserting of a PHI node. */
475 || (gimple_vdef (stmt)
476 && bestbb != sinkbb
477 && !dominated_by_p (CDI_POST_DOMINATORS, bestbb, sinkbb)))
478 return false;
480 *togsi = gsi_after_labels (bestbb);
482 return true;
485 /* Very simplistic code to sink common stores from the predecessor through
486 our virtual PHI. We do this before sinking stmts from BB as it might
487 expose sinking opportunities of the merged stores.
488 Once we have partial dead code elimination through sth like SSU-PRE this
489 should be moved there. */
491 static unsigned
492 sink_common_stores_to_bb (basic_block bb)
494 unsigned todo = 0;
495 gphi *phi;
497 if (EDGE_COUNT (bb->preds) > 1
498 && (phi = get_virtual_phi (bb)))
500 /* Repeat until no more common stores are found. */
501 while (1)
503 gimple *first_store = NULL;
504 auto_vec <tree, 5> vdefs;
505 gimple_stmt_iterator gsi;
507 /* Search for common stores defined by all virtual PHI args.
508 ??? Common stores not present in all predecessors could
509 be handled by inserting a forwarder to sink to. Generally
510 this involves deciding which stores to do this for if
511 multiple common stores are present for different sets of
512 predecessors. See PR11832 for an interesting case. */
513 for (unsigned i = 0; i < gimple_phi_num_args (phi); ++i)
515 tree arg = gimple_phi_arg_def (phi, i);
516 gimple *def = SSA_NAME_DEF_STMT (arg);
517 if (! is_gimple_assign (def)
518 || stmt_can_throw_internal (cfun, def)
519 || (gimple_phi_arg_edge (phi, i)->flags & EDGE_ABNORMAL))
521 /* ??? We could handle some cascading with the def being
522 another PHI. We'd have to insert multiple PHIs for
523 the rhs then though (if they are not all equal). */
524 first_store = NULL;
525 break;
527 /* ??? Do not try to do anything fancy with aliasing, thus
528 do not sink across non-aliased loads (or even stores,
529 so different store order will make the sinking fail). */
530 bool all_uses_on_phi = true;
531 imm_use_iterator iter;
532 use_operand_p use_p;
533 FOR_EACH_IMM_USE_FAST (use_p, iter, arg)
534 if (USE_STMT (use_p) != phi)
536 all_uses_on_phi = false;
537 break;
539 if (! all_uses_on_phi)
541 first_store = NULL;
542 break;
544 /* Check all stores are to the same LHS. */
545 if (! first_store)
546 first_store = def;
547 /* ??? We could handle differing SSA uses in the LHS by inserting
548 PHIs for them. */
549 else if (! operand_equal_p (gimple_assign_lhs (first_store),
550 gimple_assign_lhs (def), 0)
551 || (gimple_clobber_p (first_store)
552 != gimple_clobber_p (def)))
554 first_store = NULL;
555 break;
557 vdefs.safe_push (arg);
559 if (! first_store)
560 break;
562 /* Check if we need a PHI node to merge the stored values. */
563 bool allsame = true;
564 if (!gimple_clobber_p (first_store))
565 for (unsigned i = 1; i < vdefs.length (); ++i)
567 gimple *def = SSA_NAME_DEF_STMT (vdefs[i]);
568 if (! operand_equal_p (gimple_assign_rhs1 (first_store),
569 gimple_assign_rhs1 (def), 0))
571 allsame = false;
572 break;
576 /* We cannot handle aggregate values if we need to merge them. */
577 tree type = TREE_TYPE (gimple_assign_lhs (first_store));
578 if (! allsame
579 && ! is_gimple_reg_type (type))
580 break;
582 if (dump_enabled_p ())
584 dump_printf_loc (MSG_OPTIMIZED_LOCATIONS,
585 first_store,
586 "sinking common stores %sto ",
587 allsame ? "with same value " : "");
588 dump_generic_expr (MSG_OPTIMIZED_LOCATIONS, TDF_SLIM,
589 gimple_assign_lhs (first_store));
590 dump_printf (MSG_OPTIMIZED_LOCATIONS, "\n");
593 /* Insert a PHI to merge differing stored values if necessary.
594 Note that in general inserting PHIs isn't a very good idea as
595 it makes the job of coalescing and register allocation harder.
596 Even common SSA uses on the rhs/lhs might extend their lifetime
597 across multiple edges by this code motion which makes
598 register allocation harder. */
599 tree from;
600 if (! allsame)
602 from = make_ssa_name (type);
603 gphi *newphi = create_phi_node (from, bb);
604 for (unsigned i = 0; i < vdefs.length (); ++i)
606 gimple *def = SSA_NAME_DEF_STMT (vdefs[i]);
607 add_phi_arg (newphi, gimple_assign_rhs1 (def),
608 EDGE_PRED (bb, i), UNKNOWN_LOCATION);
611 else
612 from = gimple_assign_rhs1 (first_store);
614 /* Remove all stores. */
615 for (unsigned i = 0; i < vdefs.length (); ++i)
616 TREE_VISITED (vdefs[i]) = 1;
617 for (unsigned i = 0; i < vdefs.length (); ++i)
618 /* If we have more than one use of a VDEF on the PHI make sure
619 we remove the defining stmt only once. */
620 if (TREE_VISITED (vdefs[i]))
622 TREE_VISITED (vdefs[i]) = 0;
623 gimple *def = SSA_NAME_DEF_STMT (vdefs[i]);
624 gsi = gsi_for_stmt (def);
625 unlink_stmt_vdef (def);
626 gsi_remove (&gsi, true);
627 release_defs (def);
630 /* Insert the first store at the beginning of the merge BB. */
631 gimple_set_vdef (first_store, gimple_phi_result (phi));
632 SSA_NAME_DEF_STMT (gimple_vdef (first_store)) = first_store;
633 gimple_phi_set_result (phi, make_ssa_name (gimple_vop (cfun)));
634 gimple_set_vuse (first_store, gimple_phi_result (phi));
635 gimple_assign_set_rhs1 (first_store, from);
636 /* ??? Should we reset first_stores location? */
637 gsi = gsi_after_labels (bb);
638 gsi_insert_before (&gsi, first_store, GSI_SAME_STMT);
639 sink_stats.commoned++;
641 todo |= TODO_cleanup_cfg;
644 /* We could now have empty predecessors that we could remove,
645 forming a proper CFG for further sinking. Note that even
646 CFG cleanup doesn't do this fully at the moment and it
647 doesn't preserve post-dominators in the process either.
648 The mergephi pass might do it though. gcc.dg/tree-ssa/ssa-sink-13.c
649 shows this nicely if you disable tail merging or (same effect)
650 make the stored values unequal. */
653 return todo;
656 /* Perform code sinking on BB */
658 static unsigned
659 sink_code_in_bb (basic_block bb, virtual_operand_live &vop_live)
661 gimple_stmt_iterator gsi;
662 edge_iterator ei;
663 edge e;
664 bool last = true;
665 unsigned todo = 0;
667 /* Sink common stores from the predecessor through our virtual PHI. */
668 todo |= sink_common_stores_to_bb (bb);
670 /* If this block doesn't dominate anything, there can't be any place to sink
671 the statements to. */
672 if (first_dom_son (CDI_DOMINATORS, bb) == NULL)
673 return todo;
675 /* We can't move things across abnormal edges, so don't try. */
676 FOR_EACH_EDGE (e, ei, bb->succs)
677 if (e->flags & EDGE_ABNORMAL)
678 return todo;
680 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi);)
682 gimple *stmt = gsi_stmt (gsi);
683 gimple_stmt_iterator togsi;
684 bool zero_uses_p;
686 if (!statement_sink_location (stmt, bb, &togsi, &zero_uses_p, vop_live))
688 gimple_stmt_iterator saved = gsi;
689 if (!gsi_end_p (gsi))
690 gsi_prev (&gsi);
691 /* If we face a dead stmt remove it as it possibly blocks
692 sinking of uses. */
693 if (zero_uses_p
694 && !gimple_vdef (stmt)
695 && (cfun->can_delete_dead_exceptions
696 || !stmt_could_throw_p (cfun, stmt)))
698 gsi_remove (&saved, true);
699 release_defs (stmt);
701 else
702 last = false;
703 continue;
705 if (dump_file)
707 fprintf (dump_file, "Sinking ");
708 print_gimple_stmt (dump_file, stmt, 0, TDF_VOPS);
709 fprintf (dump_file, " from bb %d to bb %d\n",
710 bb->index, (gsi_bb (togsi))->index);
713 /* Update virtual operands of statements in the path we
714 do not sink to. */
715 if (gimple_vdef (stmt))
717 imm_use_iterator iter;
718 use_operand_p use_p;
719 gimple *vuse_stmt;
721 FOR_EACH_IMM_USE_STMT (vuse_stmt, iter, gimple_vdef (stmt))
722 if (gimple_code (vuse_stmt) != GIMPLE_PHI
723 && !dominated_by_p (CDI_DOMINATORS, gimple_bb (vuse_stmt),
724 gsi_bb (togsi)))
725 FOR_EACH_IMM_USE_ON_STMT (use_p, iter)
726 SET_USE (use_p, gimple_vuse (stmt));
729 /* If this is the end of the basic block, we need to insert at the end
730 of the basic block. */
731 if (gsi_end_p (togsi))
732 gsi_move_to_bb_end (&gsi, gsi_bb (togsi));
733 else
734 gsi_move_before (&gsi, &togsi);
736 sink_stats.sunk++;
738 /* If we've just removed the last statement of the BB, the
739 gsi_end_p() test below would fail, but gsi_prev() would have
740 succeeded, and we want it to succeed. So we keep track of
741 whether we're at the last statement and pick up the new last
742 statement. */
743 if (last)
745 gsi = gsi_last_bb (bb);
746 continue;
749 last = false;
750 if (!gsi_end_p (gsi))
751 gsi_prev (&gsi);
755 return todo;
758 /* Perform code sinking.
759 This moves code down the flowgraph when we know it would be
760 profitable to do so, or it wouldn't increase the number of
761 executions of the statement.
763 IE given
765 a_1 = b + c;
766 if (<something>)
769 else
771 foo (&b, &c);
772 a_5 = b + c;
774 a_6 = PHI (a_5, a_1);
775 USE a_6.
777 we'll transform this into:
779 if (<something>)
781 a_1 = b + c;
783 else
785 foo (&b, &c);
786 a_5 = b + c;
788 a_6 = PHI (a_5, a_1);
789 USE a_6.
791 Note that this reduces the number of computations of a = b + c to 1
792 when we take the else edge, instead of 2.
794 namespace {
796 const pass_data pass_data_sink_code =
798 GIMPLE_PASS, /* type */
799 "sink", /* name */
800 OPTGROUP_NONE, /* optinfo_flags */
801 TV_TREE_SINK, /* tv_id */
802 /* PROP_no_crit_edges is ensured by running split_edges_for_insertion in
803 pass_data_sink_code::execute (). */
804 ( PROP_cfg | PROP_ssa ), /* properties_required */
805 0, /* properties_provided */
806 0, /* properties_destroyed */
807 0, /* todo_flags_start */
808 TODO_update_ssa, /* todo_flags_finish */
811 class pass_sink_code : public gimple_opt_pass
813 public:
814 pass_sink_code (gcc::context *ctxt)
815 : gimple_opt_pass (pass_data_sink_code, ctxt), unsplit_edges (false)
818 /* opt_pass methods: */
819 bool gate (function *) final override { return flag_tree_sink != 0; }
820 unsigned int execute (function *) final override;
821 opt_pass *clone (void) final override { return new pass_sink_code (m_ctxt); }
822 void set_pass_param (unsigned n, bool param) final override
824 gcc_assert (n == 0);
825 unsplit_edges = param;
828 private:
829 bool unsplit_edges;
830 }; // class pass_sink_code
832 unsigned int
833 pass_sink_code::execute (function *fun)
835 loop_optimizer_init (LOOPS_NORMAL);
836 split_edges_for_insertion ();
837 /* Arrange for the critical edge splitting to be undone if requested. */
838 unsigned todo = unsplit_edges ? TODO_cleanup_cfg : 0;
839 connect_infinite_loops_to_exit ();
840 mark_dfs_back_edges (fun);
841 memset (&sink_stats, 0, sizeof (sink_stats));
842 calculate_dominance_info (CDI_DOMINATORS);
843 calculate_dominance_info (CDI_POST_DOMINATORS);
845 virtual_operand_live vop_live;
847 int *rpo = XNEWVEC (int, n_basic_blocks_for_fn (cfun));
848 int n = inverted_rev_post_order_compute (fun, rpo);
849 for (int i = 0; i < n; ++i)
850 todo |= sink_code_in_bb (BASIC_BLOCK_FOR_FN (fun, rpo[i]), vop_live);
851 free (rpo);
853 statistics_counter_event (fun, "Sunk statements", sink_stats.sunk);
854 statistics_counter_event (fun, "Commoned stores", sink_stats.commoned);
855 free_dominance_info (CDI_POST_DOMINATORS);
856 remove_fake_exit_edges ();
857 loop_optimizer_finalize ();
859 return todo;
862 } // anon namespace
864 gimple_opt_pass *
865 make_pass_sink_code (gcc::context *ctxt)
867 return new pass_sink_code (ctxt);