PR rtl-optimization/78355
[official-gcc.git] / gcc / tree-cfgcleanup.c
blobfe22ed309e4a6c7b029660e0b6bfc907fd62b175
1 /* CFG cleanup for trees.
2 Copyright (C) 2001-2016 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3, or (at your option)
9 any later version.
11 GCC is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
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 "rtl.h"
25 #include "tree.h"
26 #include "gimple.h"
27 #include "cfghooks.h"
28 #include "tree-pass.h"
29 #include "ssa.h"
30 #include "diagnostic-core.h"
31 #include "fold-const.h"
32 #include "cfganal.h"
33 #include "cfgcleanup.h"
34 #include "tree-eh.h"
35 #include "gimplify.h"
36 #include "gimple-iterator.h"
37 #include "tree-cfg.h"
38 #include "tree-ssa-loop-manip.h"
39 #include "tree-dfa.h"
40 #include "tree-ssa.h"
41 #include "cfgloop.h"
42 #include "tree-scalar-evolution.h"
43 #include "gimple-match.h"
44 #include "gimple-fold.h"
47 /* The set of blocks in that at least one of the following changes happened:
48 -- the statement at the end of the block was changed
49 -- the block was newly created
50 -- the set of the predecessors of the block changed
51 -- the set of the successors of the block changed
52 ??? Maybe we could track these changes separately, since they determine
53 what cleanups it makes sense to try on the block. */
54 bitmap cfgcleanup_altered_bbs;
56 /* Remove any fallthru edge from EV. Return true if an edge was removed. */
58 static bool
59 remove_fallthru_edge (vec<edge, va_gc> *ev)
61 edge_iterator ei;
62 edge e;
64 FOR_EACH_EDGE (e, ei, ev)
65 if ((e->flags & EDGE_FALLTHRU) != 0)
67 if (e->flags & EDGE_COMPLEX)
68 e->flags &= ~EDGE_FALLTHRU;
69 else
70 remove_edge_and_dominated_blocks (e);
71 return true;
73 return false;
77 /* Disconnect an unreachable block in the control expression starting
78 at block BB. */
80 static bool
81 cleanup_control_expr_graph (basic_block bb, gimple_stmt_iterator gsi,
82 bool first_p)
84 edge taken_edge;
85 bool retval = false;
86 gimple *stmt = gsi_stmt (gsi);
88 if (!single_succ_p (bb))
90 edge e;
91 edge_iterator ei;
92 bool warned;
93 tree val = NULL_TREE;
95 fold_defer_overflow_warnings ();
96 switch (gimple_code (stmt))
98 case GIMPLE_COND:
99 /* During a first iteration on the CFG only remove trivially
100 dead edges but mark other conditions for re-evaluation. */
101 if (first_p)
103 val = const_binop (gimple_cond_code (stmt), boolean_type_node,
104 gimple_cond_lhs (stmt),
105 gimple_cond_rhs (stmt));
106 if (! val)
107 bitmap_set_bit (cfgcleanup_altered_bbs, bb->index);
109 else
111 code_helper rcode;
112 tree ops[3] = {};
113 if (gimple_simplify (stmt, &rcode, ops, NULL, no_follow_ssa_edges,
114 no_follow_ssa_edges)
115 && rcode == INTEGER_CST)
116 val = ops[0];
118 break;
120 case GIMPLE_SWITCH:
121 val = gimple_switch_index (as_a <gswitch *> (stmt));
122 break;
124 default:
127 taken_edge = find_taken_edge (bb, val);
128 if (!taken_edge)
130 fold_undefer_and_ignore_overflow_warnings ();
131 return false;
134 /* Remove all the edges except the one that is always executed. */
135 warned = false;
136 for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
138 if (e != taken_edge)
140 if (!warned)
142 fold_undefer_overflow_warnings
143 (true, stmt, WARN_STRICT_OVERFLOW_CONDITIONAL);
144 warned = true;
147 taken_edge->probability += e->probability;
148 taken_edge->count += e->count;
149 remove_edge_and_dominated_blocks (e);
150 retval = true;
152 else
153 ei_next (&ei);
155 if (!warned)
156 fold_undefer_and_ignore_overflow_warnings ();
157 if (taken_edge->probability > REG_BR_PROB_BASE)
158 taken_edge->probability = REG_BR_PROB_BASE;
160 else
161 taken_edge = single_succ_edge (bb);
163 bitmap_set_bit (cfgcleanup_altered_bbs, bb->index);
164 gsi_remove (&gsi, true);
165 taken_edge->flags = EDGE_FALLTHRU;
167 return retval;
170 /* Cleanup the GF_CALL_CTRL_ALTERING flag according to
171 to updated gimple_call_flags. */
173 static void
174 cleanup_call_ctrl_altering_flag (gimple *bb_end)
176 if (!is_gimple_call (bb_end)
177 || !gimple_call_ctrl_altering_p (bb_end))
178 return;
180 int flags = gimple_call_flags (bb_end);
181 if (((flags & (ECF_CONST | ECF_PURE))
182 && !(flags & ECF_LOOPING_CONST_OR_PURE))
183 || (flags & ECF_LEAF))
184 gimple_call_set_ctrl_altering (bb_end, false);
187 /* Try to remove superfluous control structures in basic block BB. Returns
188 true if anything changes. */
190 static bool
191 cleanup_control_flow_bb (basic_block bb, bool first_p)
193 gimple_stmt_iterator gsi;
194 bool retval = false;
195 gimple *stmt;
197 /* If the last statement of the block could throw and now cannot,
198 we need to prune cfg. */
199 retval |= gimple_purge_dead_eh_edges (bb);
201 gsi = gsi_last_nondebug_bb (bb);
202 if (gsi_end_p (gsi))
203 return retval;
205 stmt = gsi_stmt (gsi);
207 /* Try to cleanup ctrl altering flag for call which ends bb. */
208 cleanup_call_ctrl_altering_flag (stmt);
210 if (gimple_code (stmt) == GIMPLE_COND
211 || gimple_code (stmt) == GIMPLE_SWITCH)
213 gcc_checking_assert (gsi_stmt (gsi_last_bb (bb)) == stmt);
214 retval |= cleanup_control_expr_graph (bb, gsi, first_p);
216 else if (gimple_code (stmt) == GIMPLE_GOTO
217 && TREE_CODE (gimple_goto_dest (stmt)) == ADDR_EXPR
218 && (TREE_CODE (TREE_OPERAND (gimple_goto_dest (stmt), 0))
219 == LABEL_DECL))
221 /* If we had a computed goto which has a compile-time determinable
222 destination, then we can eliminate the goto. */
223 edge e;
224 tree label;
225 edge_iterator ei;
226 basic_block target_block;
228 gcc_checking_assert (gsi_stmt (gsi_last_bb (bb)) == stmt);
229 /* First look at all the outgoing edges. Delete any outgoing
230 edges which do not go to the right block. For the one
231 edge which goes to the right block, fix up its flags. */
232 label = TREE_OPERAND (gimple_goto_dest (stmt), 0);
233 if (DECL_CONTEXT (label) != cfun->decl)
234 return retval;
235 target_block = label_to_block (label);
236 for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
238 if (e->dest != target_block)
239 remove_edge_and_dominated_blocks (e);
240 else
242 /* Turn off the EDGE_ABNORMAL flag. */
243 e->flags &= ~EDGE_ABNORMAL;
245 /* And set EDGE_FALLTHRU. */
246 e->flags |= EDGE_FALLTHRU;
247 ei_next (&ei);
251 bitmap_set_bit (cfgcleanup_altered_bbs, bb->index);
252 bitmap_set_bit (cfgcleanup_altered_bbs, target_block->index);
254 /* Remove the GOTO_EXPR as it is not needed. The CFG has all the
255 relevant information we need. */
256 gsi_remove (&gsi, true);
257 retval = true;
260 /* Check for indirect calls that have been turned into
261 noreturn calls. */
262 else if (is_gimple_call (stmt)
263 && gimple_call_noreturn_p (stmt))
265 /* If there are debug stmts after the noreturn call, remove them
266 now, they should be all unreachable anyway. */
267 for (gsi_next (&gsi); !gsi_end_p (gsi); )
268 gsi_remove (&gsi, true);
269 if (remove_fallthru_edge (bb->succs))
270 retval = true;
273 return retval;
276 /* Return true if basic block BB does nothing except pass control
277 flow to another block and that we can safely insert a label at
278 the start of the successor block.
280 As a precondition, we require that BB be not equal to
281 the entry block. */
283 static bool
284 tree_forwarder_block_p (basic_block bb, bool phi_wanted)
286 gimple_stmt_iterator gsi;
287 location_t locus;
289 /* BB must have a single outgoing edge. */
290 if (single_succ_p (bb) != 1
291 /* If PHI_WANTED is false, BB must not have any PHI nodes.
292 Otherwise, BB must have PHI nodes. */
293 || gimple_seq_empty_p (phi_nodes (bb)) == phi_wanted
294 /* BB may not be a predecessor of the exit block. */
295 || single_succ (bb) == EXIT_BLOCK_PTR_FOR_FN (cfun)
296 /* Nor should this be an infinite loop. */
297 || single_succ (bb) == bb
298 /* BB may not have an abnormal outgoing edge. */
299 || (single_succ_edge (bb)->flags & EDGE_ABNORMAL))
300 return false;
302 gcc_checking_assert (bb != ENTRY_BLOCK_PTR_FOR_FN (cfun));
304 locus = single_succ_edge (bb)->goto_locus;
306 /* There should not be an edge coming from entry, or an EH edge. */
308 edge_iterator ei;
309 edge e;
311 FOR_EACH_EDGE (e, ei, bb->preds)
312 if (e->src == ENTRY_BLOCK_PTR_FOR_FN (cfun) || (e->flags & EDGE_EH))
313 return false;
314 /* If goto_locus of any of the edges differs, prevent removing
315 the forwarder block for -O0. */
316 else if (optimize == 0 && e->goto_locus != locus)
317 return false;
320 /* Now walk through the statements backward. We can ignore labels,
321 anything else means this is not a forwarder block. */
322 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
324 gimple *stmt = gsi_stmt (gsi);
326 switch (gimple_code (stmt))
328 case GIMPLE_LABEL:
329 if (DECL_NONLOCAL (gimple_label_label (as_a <glabel *> (stmt))))
330 return false;
331 if (optimize == 0 && gimple_location (stmt) != locus)
332 return false;
333 break;
335 /* ??? For now, hope there's a corresponding debug
336 assignment at the destination. */
337 case GIMPLE_DEBUG:
338 break;
340 default:
341 return false;
345 if (current_loops)
347 basic_block dest;
348 /* Protect loop headers. */
349 if (bb_loop_header_p (bb))
350 return false;
352 dest = EDGE_SUCC (bb, 0)->dest;
353 /* Protect loop preheaders and latches if requested. */
354 if (dest->loop_father->header == dest)
356 if (bb->loop_father == dest->loop_father)
358 if (loops_state_satisfies_p (LOOPS_HAVE_SIMPLE_LATCHES))
359 return false;
360 /* If bb doesn't have a single predecessor we'd make this
361 loop have multiple latches. Don't do that if that
362 would in turn require disambiguating them. */
363 return (single_pred_p (bb)
364 || loops_state_satisfies_p
365 (LOOPS_MAY_HAVE_MULTIPLE_LATCHES));
367 else if (bb->loop_father == loop_outer (dest->loop_father))
368 return !loops_state_satisfies_p (LOOPS_HAVE_PREHEADERS);
369 /* Always preserve other edges into loop headers that are
370 not simple latches or preheaders. */
371 return false;
375 return true;
378 /* If all the PHI nodes in DEST have alternatives for E1 and E2 and
379 those alternatives are equal in each of the PHI nodes, then return
380 true, else return false. */
382 static bool
383 phi_alternatives_equal (basic_block dest, edge e1, edge e2)
385 int n1 = e1->dest_idx;
386 int n2 = e2->dest_idx;
387 gphi_iterator gsi;
389 for (gsi = gsi_start_phis (dest); !gsi_end_p (gsi); gsi_next (&gsi))
391 gphi *phi = gsi.phi ();
392 tree val1 = gimple_phi_arg_def (phi, n1);
393 tree val2 = gimple_phi_arg_def (phi, n2);
395 gcc_assert (val1 != NULL_TREE);
396 gcc_assert (val2 != NULL_TREE);
398 if (!operand_equal_for_phi_arg_p (val1, val2))
399 return false;
402 return true;
405 /* Removes forwarder block BB. Returns false if this failed. */
407 static bool
408 remove_forwarder_block (basic_block bb)
410 edge succ = single_succ_edge (bb), e, s;
411 basic_block dest = succ->dest;
412 gimple *label;
413 edge_iterator ei;
414 gimple_stmt_iterator gsi, gsi_to;
415 bool can_move_debug_stmts;
417 /* We check for infinite loops already in tree_forwarder_block_p.
418 However it may happen that the infinite loop is created
419 afterwards due to removal of forwarders. */
420 if (dest == bb)
421 return false;
423 /* If the destination block consists of a nonlocal label or is a
424 EH landing pad, do not merge it. */
425 label = first_stmt (dest);
426 if (label)
427 if (glabel *label_stmt = dyn_cast <glabel *> (label))
428 if (DECL_NONLOCAL (gimple_label_label (label_stmt))
429 || EH_LANDING_PAD_NR (gimple_label_label (label_stmt)) != 0)
430 return false;
432 /* If there is an abnormal edge to basic block BB, but not into
433 dest, problems might occur during removal of the phi node at out
434 of ssa due to overlapping live ranges of registers.
436 If there is an abnormal edge in DEST, the problems would occur
437 anyway since cleanup_dead_labels would then merge the labels for
438 two different eh regions, and rest of exception handling code
439 does not like it.
441 So if there is an abnormal edge to BB, proceed only if there is
442 no abnormal edge to DEST and there are no phi nodes in DEST. */
443 if (bb_has_abnormal_pred (bb)
444 && (bb_has_abnormal_pred (dest)
445 || !gimple_seq_empty_p (phi_nodes (dest))))
446 return false;
448 /* If there are phi nodes in DEST, and some of the blocks that are
449 predecessors of BB are also predecessors of DEST, check that the
450 phi node arguments match. */
451 if (!gimple_seq_empty_p (phi_nodes (dest)))
453 FOR_EACH_EDGE (e, ei, bb->preds)
455 s = find_edge (e->src, dest);
456 if (!s)
457 continue;
459 if (!phi_alternatives_equal (dest, succ, s))
460 return false;
464 can_move_debug_stmts = MAY_HAVE_DEBUG_STMTS && single_pred_p (dest);
466 basic_block pred = NULL;
467 if (single_pred_p (bb))
468 pred = single_pred (bb);
470 /* Redirect the edges. */
471 for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei)); )
473 bitmap_set_bit (cfgcleanup_altered_bbs, e->src->index);
475 if (e->flags & EDGE_ABNORMAL)
477 /* If there is an abnormal edge, redirect it anyway, and
478 move the labels to the new block to make it legal. */
479 s = redirect_edge_succ_nodup (e, dest);
481 else
482 s = redirect_edge_and_branch (e, dest);
484 if (s == e)
486 /* Create arguments for the phi nodes, since the edge was not
487 here before. */
488 for (gphi_iterator psi = gsi_start_phis (dest);
489 !gsi_end_p (psi);
490 gsi_next (&psi))
492 gphi *phi = psi.phi ();
493 source_location l = gimple_phi_arg_location_from_edge (phi, succ);
494 tree def = gimple_phi_arg_def (phi, succ->dest_idx);
495 add_phi_arg (phi, unshare_expr (def), s, l);
500 /* Move nonlocal labels and computed goto targets as well as user
501 defined labels and labels with an EH landing pad number to the
502 new block, so that the redirection of the abnormal edges works,
503 jump targets end up in a sane place and debug information for
504 labels is retained. */
505 gsi_to = gsi_start_bb (dest);
506 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); )
508 tree decl;
509 label = gsi_stmt (gsi);
510 if (is_gimple_debug (label))
511 break;
512 decl = gimple_label_label (as_a <glabel *> (label));
513 if (EH_LANDING_PAD_NR (decl) != 0
514 || DECL_NONLOCAL (decl)
515 || FORCED_LABEL (decl)
516 || !DECL_ARTIFICIAL (decl))
518 gsi_remove (&gsi, false);
519 gsi_insert_before (&gsi_to, label, GSI_SAME_STMT);
521 else
522 gsi_next (&gsi);
525 /* Move debug statements if the destination has a single predecessor. */
526 if (can_move_debug_stmts)
528 gsi_to = gsi_after_labels (dest);
529 for (gsi = gsi_after_labels (bb); !gsi_end_p (gsi); )
531 gimple *debug = gsi_stmt (gsi);
532 if (!is_gimple_debug (debug))
533 break;
534 gsi_remove (&gsi, false);
535 gsi_insert_before (&gsi_to, debug, GSI_SAME_STMT);
539 bitmap_set_bit (cfgcleanup_altered_bbs, dest->index);
541 /* Update the dominators. */
542 if (dom_info_available_p (CDI_DOMINATORS))
544 basic_block dom, dombb, domdest;
546 dombb = get_immediate_dominator (CDI_DOMINATORS, bb);
547 domdest = get_immediate_dominator (CDI_DOMINATORS, dest);
548 if (domdest == bb)
550 /* Shortcut to avoid calling (relatively expensive)
551 nearest_common_dominator unless necessary. */
552 dom = dombb;
554 else
555 dom = nearest_common_dominator (CDI_DOMINATORS, domdest, dombb);
557 set_immediate_dominator (CDI_DOMINATORS, dest, dom);
560 /* Adjust latch infomation of BB's parent loop as otherwise
561 the cfg hook has a hard time not to kill the loop. */
562 if (current_loops && bb->loop_father->latch == bb)
563 bb->loop_father->latch = pred;
565 /* And kill the forwarder block. */
566 delete_basic_block (bb);
568 return true;
571 /* STMT is a call that has been discovered noreturn. Split the
572 block to prepare fixing up the CFG and remove LHS.
573 Return true if cleanup-cfg needs to run. */
575 bool
576 fixup_noreturn_call (gimple *stmt)
578 basic_block bb = gimple_bb (stmt);
579 bool changed = false;
581 if (gimple_call_builtin_p (stmt, BUILT_IN_RETURN))
582 return false;
584 /* First split basic block if stmt is not last. */
585 if (stmt != gsi_stmt (gsi_last_bb (bb)))
587 if (stmt == gsi_stmt (gsi_last_nondebug_bb (bb)))
589 /* Don't split if there are only debug stmts
590 after stmt, that can result in -fcompare-debug
591 failures. Remove the debug stmts instead,
592 they should be all unreachable anyway. */
593 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
594 for (gsi_next (&gsi); !gsi_end_p (gsi); )
595 gsi_remove (&gsi, true);
597 else
599 split_block (bb, stmt);
600 changed = true;
604 /* If there is an LHS, remove it, but only if its type has fixed size.
605 The LHS will need to be recreated during RTL expansion and creating
606 temporaries of variable-sized types is not supported. Also don't
607 do this with TREE_ADDRESSABLE types, as assign_temp will abort.
608 Drop LHS regardless of TREE_ADDRESSABLE, if the function call
609 has been changed into a call that does not return a value, like
610 __builtin_unreachable or __cxa_pure_virtual. */
611 tree lhs = gimple_call_lhs (stmt);
612 if (lhs
613 && (should_remove_lhs_p (lhs)
614 || VOID_TYPE_P (TREE_TYPE (gimple_call_fntype (stmt)))))
616 gimple_call_set_lhs (stmt, NULL_TREE);
618 /* We need to fix up the SSA name to avoid checking errors. */
619 if (TREE_CODE (lhs) == SSA_NAME)
621 tree new_var = create_tmp_reg (TREE_TYPE (lhs));
622 SET_SSA_NAME_VAR_OR_IDENTIFIER (lhs, new_var);
623 SSA_NAME_DEF_STMT (lhs) = gimple_build_nop ();
624 set_ssa_default_def (cfun, new_var, lhs);
627 update_stmt (stmt);
630 /* Mark the call as altering control flow. */
631 if (!gimple_call_ctrl_altering_p (stmt))
633 gimple_call_set_ctrl_altering (stmt, true);
634 changed = true;
637 return changed;
641 /* Tries to cleanup cfg in basic block BB. Returns true if anything
642 changes. */
644 static bool
645 cleanup_tree_cfg_bb (basic_block bb)
647 if (tree_forwarder_block_p (bb, false)
648 && remove_forwarder_block (bb))
649 return true;
651 /* If there is a merge opportunity with the predecessor
652 do nothing now but wait until we process the predecessor.
653 This happens when we visit BBs in a non-optimal order and
654 avoids quadratic behavior with adjusting stmts BB pointer. */
655 if (single_pred_p (bb)
656 && can_merge_blocks_p (single_pred (bb), bb))
657 /* But make sure we _do_ visit it. When we remove unreachable paths
658 ending in a backedge we fail to mark the destinations predecessors
659 as changed. */
660 bitmap_set_bit (cfgcleanup_altered_bbs, single_pred (bb)->index);
662 /* Merging the blocks may create new opportunities for folding
663 conditional branches (due to the elimination of single-valued PHI
664 nodes). */
665 else if (single_succ_p (bb)
666 && can_merge_blocks_p (bb, single_succ (bb)))
668 merge_blocks (bb, single_succ (bb));
669 return true;
672 return false;
675 /* Iterate the cfg cleanups, while anything changes. */
677 static bool
678 cleanup_tree_cfg_1 (void)
680 bool retval = false;
681 basic_block bb;
682 unsigned i, n;
684 /* Prepare the worklists of altered blocks. */
685 cfgcleanup_altered_bbs = BITMAP_ALLOC (NULL);
687 /* During forwarder block cleanup, we may redirect edges out of
688 SWITCH_EXPRs, which can get expensive. So we want to enable
689 recording of edge to CASE_LABEL_EXPR. */
690 start_recording_case_labels ();
692 /* We cannot use FOR_EACH_BB_FN for the BB iterations below
693 since the basic blocks may get removed. */
695 /* Start by iterating over all basic blocks looking for edge removal
696 opportunities. Do this first because incoming SSA form may be
697 invalid and we want to avoid performing SSA related tasks such
698 as propgating out a PHI node during BB merging in that state. */
699 n = last_basic_block_for_fn (cfun);
700 for (i = NUM_FIXED_BLOCKS; i < n; i++)
702 bb = BASIC_BLOCK_FOR_FN (cfun, i);
703 if (bb)
704 retval |= cleanup_control_flow_bb (bb, true);
707 /* After doing the above SSA form should be valid (or an update SSA
708 should be required). */
710 /* Continue by iterating over all basic blocks looking for BB merging
711 opportunities. */
712 n = last_basic_block_for_fn (cfun);
713 for (i = NUM_FIXED_BLOCKS; i < n; i++)
715 bb = BASIC_BLOCK_FOR_FN (cfun, i);
716 if (bb)
717 retval |= cleanup_tree_cfg_bb (bb);
720 /* Now process the altered blocks, as long as any are available. */
721 while (!bitmap_empty_p (cfgcleanup_altered_bbs))
723 i = bitmap_first_set_bit (cfgcleanup_altered_bbs);
724 bitmap_clear_bit (cfgcleanup_altered_bbs, i);
725 if (i < NUM_FIXED_BLOCKS)
726 continue;
728 bb = BASIC_BLOCK_FOR_FN (cfun, i);
729 if (!bb)
730 continue;
732 retval |= cleanup_control_flow_bb (bb, false);
733 retval |= cleanup_tree_cfg_bb (bb);
736 end_recording_case_labels ();
737 BITMAP_FREE (cfgcleanup_altered_bbs);
738 return retval;
742 /* Remove unreachable blocks and other miscellaneous clean up work.
743 Return true if the flowgraph was modified, false otherwise. */
745 static bool
746 cleanup_tree_cfg_noloop (void)
748 bool changed;
750 timevar_push (TV_TREE_CLEANUP_CFG);
752 /* Iterate until there are no more cleanups left to do. If any
753 iteration changed the flowgraph, set CHANGED to true.
755 If dominance information is available, there cannot be any unreachable
756 blocks. */
757 if (!dom_info_available_p (CDI_DOMINATORS))
759 changed = delete_unreachable_blocks ();
760 calculate_dominance_info (CDI_DOMINATORS);
762 else
764 checking_verify_dominators (CDI_DOMINATORS);
765 changed = false;
768 changed |= cleanup_tree_cfg_1 ();
770 gcc_assert (dom_info_available_p (CDI_DOMINATORS));
771 compact_blocks ();
773 checking_verify_flow_info ();
775 timevar_pop (TV_TREE_CLEANUP_CFG);
777 if (changed && current_loops)
778 loops_state_set (LOOPS_NEED_FIXUP);
780 return changed;
783 /* Repairs loop structures. */
785 static void
786 repair_loop_structures (void)
788 bitmap changed_bbs;
789 unsigned n_new_loops;
791 calculate_dominance_info (CDI_DOMINATORS);
793 timevar_push (TV_REPAIR_LOOPS);
794 changed_bbs = BITMAP_ALLOC (NULL);
795 n_new_loops = fix_loop_structure (changed_bbs);
797 /* This usually does nothing. But sometimes parts of cfg that originally
798 were inside a loop get out of it due to edge removal (since they
799 become unreachable by back edges from latch). Also a former
800 irreducible loop can become reducible - in this case force a full
801 rewrite into loop-closed SSA form. */
802 if (loops_state_satisfies_p (LOOP_CLOSED_SSA))
803 rewrite_into_loop_closed_ssa (n_new_loops ? NULL : changed_bbs,
804 TODO_update_ssa);
806 BITMAP_FREE (changed_bbs);
808 checking_verify_loop_structure ();
809 scev_reset ();
811 timevar_pop (TV_REPAIR_LOOPS);
814 /* Cleanup cfg and repair loop structures. */
816 bool
817 cleanup_tree_cfg (void)
819 bool changed = cleanup_tree_cfg_noloop ();
821 if (current_loops != NULL
822 && loops_state_satisfies_p (LOOPS_NEED_FIXUP))
823 repair_loop_structures ();
825 return changed;
828 /* Tries to merge the PHI nodes at BB into those at BB's sole successor.
829 Returns true if successful. */
831 static bool
832 remove_forwarder_block_with_phi (basic_block bb)
834 edge succ = single_succ_edge (bb);
835 basic_block dest = succ->dest;
836 gimple *label;
837 basic_block dombb, domdest, dom;
839 /* We check for infinite loops already in tree_forwarder_block_p.
840 However it may happen that the infinite loop is created
841 afterwards due to removal of forwarders. */
842 if (dest == bb)
843 return false;
845 /* Removal of forwarders may expose new natural loops and thus
846 a block may turn into a loop header. */
847 if (current_loops && bb_loop_header_p (bb))
848 return false;
850 /* If the destination block consists of a nonlocal label, do not
851 merge it. */
852 label = first_stmt (dest);
853 if (label)
854 if (glabel *label_stmt = dyn_cast <glabel *> (label))
855 if (DECL_NONLOCAL (gimple_label_label (label_stmt)))
856 return false;
858 /* Record BB's single pred in case we need to update the father
859 loop's latch information later. */
860 basic_block pred = NULL;
861 if (single_pred_p (bb))
862 pred = single_pred (bb);
864 /* Redirect each incoming edge to BB to DEST. */
865 while (EDGE_COUNT (bb->preds) > 0)
867 edge e = EDGE_PRED (bb, 0), s;
868 gphi_iterator gsi;
870 s = find_edge (e->src, dest);
871 if (s)
873 /* We already have an edge S from E->src to DEST. If S and
874 E->dest's sole successor edge have the same PHI arguments
875 at DEST, redirect S to DEST. */
876 if (phi_alternatives_equal (dest, s, succ))
878 e = redirect_edge_and_branch (e, dest);
879 redirect_edge_var_map_clear (e);
880 continue;
883 /* PHI arguments are different. Create a forwarder block by
884 splitting E so that we can merge PHI arguments on E to
885 DEST. */
886 e = single_succ_edge (split_edge (e));
889 s = redirect_edge_and_branch (e, dest);
891 /* redirect_edge_and_branch must not create a new edge. */
892 gcc_assert (s == e);
894 /* Add to the PHI nodes at DEST each PHI argument removed at the
895 destination of E. */
896 for (gsi = gsi_start_phis (dest);
897 !gsi_end_p (gsi);
898 gsi_next (&gsi))
900 gphi *phi = gsi.phi ();
901 tree def = gimple_phi_arg_def (phi, succ->dest_idx);
902 source_location locus = gimple_phi_arg_location_from_edge (phi, succ);
904 if (TREE_CODE (def) == SSA_NAME)
906 /* If DEF is one of the results of PHI nodes removed during
907 redirection, replace it with the PHI argument that used
908 to be on E. */
909 vec<edge_var_map> *head = redirect_edge_var_map_vector (e);
910 size_t length = head ? head->length () : 0;
911 for (size_t i = 0; i < length; i++)
913 edge_var_map *vm = &(*head)[i];
914 tree old_arg = redirect_edge_var_map_result (vm);
915 tree new_arg = redirect_edge_var_map_def (vm);
917 if (def == old_arg)
919 def = new_arg;
920 locus = redirect_edge_var_map_location (vm);
921 break;
926 add_phi_arg (phi, def, s, locus);
929 redirect_edge_var_map_clear (e);
932 /* Update the dominators. */
933 dombb = get_immediate_dominator (CDI_DOMINATORS, bb);
934 domdest = get_immediate_dominator (CDI_DOMINATORS, dest);
935 if (domdest == bb)
937 /* Shortcut to avoid calling (relatively expensive)
938 nearest_common_dominator unless necessary. */
939 dom = dombb;
941 else
942 dom = nearest_common_dominator (CDI_DOMINATORS, domdest, dombb);
944 set_immediate_dominator (CDI_DOMINATORS, dest, dom);
946 /* Adjust latch infomation of BB's parent loop as otherwise
947 the cfg hook has a hard time not to kill the loop. */
948 if (current_loops && bb->loop_father->latch == bb)
949 bb->loop_father->latch = pred;
951 /* Remove BB since all of BB's incoming edges have been redirected
952 to DEST. */
953 delete_basic_block (bb);
955 return true;
958 /* This pass merges PHI nodes if one feeds into another. For example,
959 suppose we have the following:
961 goto <bb 9> (<L9>);
963 <L8>:;
964 tem_17 = foo ();
966 # tem_6 = PHI <tem_17(8), tem_23(7)>;
967 <L9>:;
969 # tem_3 = PHI <tem_6(9), tem_2(5)>;
970 <L10>:;
972 Then we merge the first PHI node into the second one like so:
974 goto <bb 9> (<L10>);
976 <L8>:;
977 tem_17 = foo ();
979 # tem_3 = PHI <tem_23(7), tem_2(5), tem_17(8)>;
980 <L10>:;
983 namespace {
985 const pass_data pass_data_merge_phi =
987 GIMPLE_PASS, /* type */
988 "mergephi", /* name */
989 OPTGROUP_NONE, /* optinfo_flags */
990 TV_TREE_MERGE_PHI, /* tv_id */
991 ( PROP_cfg | PROP_ssa ), /* properties_required */
992 0, /* properties_provided */
993 0, /* properties_destroyed */
994 0, /* todo_flags_start */
995 0, /* todo_flags_finish */
998 class pass_merge_phi : public gimple_opt_pass
1000 public:
1001 pass_merge_phi (gcc::context *ctxt)
1002 : gimple_opt_pass (pass_data_merge_phi, ctxt)
1005 /* opt_pass methods: */
1006 opt_pass * clone () { return new pass_merge_phi (m_ctxt); }
1007 virtual unsigned int execute (function *);
1009 }; // class pass_merge_phi
1011 unsigned int
1012 pass_merge_phi::execute (function *fun)
1014 basic_block *worklist = XNEWVEC (basic_block, n_basic_blocks_for_fn (fun));
1015 basic_block *current = worklist;
1016 basic_block bb;
1018 calculate_dominance_info (CDI_DOMINATORS);
1020 /* Find all PHI nodes that we may be able to merge. */
1021 FOR_EACH_BB_FN (bb, fun)
1023 basic_block dest;
1025 /* Look for a forwarder block with PHI nodes. */
1026 if (!tree_forwarder_block_p (bb, true))
1027 continue;
1029 dest = single_succ (bb);
1031 /* We have to feed into another basic block with PHI
1032 nodes. */
1033 if (gimple_seq_empty_p (phi_nodes (dest))
1034 /* We don't want to deal with a basic block with
1035 abnormal edges. */
1036 || bb_has_abnormal_pred (bb))
1037 continue;
1039 if (!dominated_by_p (CDI_DOMINATORS, dest, bb))
1041 /* If BB does not dominate DEST, then the PHI nodes at
1042 DEST must be the only users of the results of the PHI
1043 nodes at BB. */
1044 *current++ = bb;
1046 else
1048 gphi_iterator gsi;
1049 unsigned int dest_idx = single_succ_edge (bb)->dest_idx;
1051 /* BB dominates DEST. There may be many users of the PHI
1052 nodes in BB. However, there is still a trivial case we
1053 can handle. If the result of every PHI in BB is used
1054 only by a PHI in DEST, then we can trivially merge the
1055 PHI nodes from BB into DEST. */
1056 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
1057 gsi_next (&gsi))
1059 gphi *phi = gsi.phi ();
1060 tree result = gimple_phi_result (phi);
1061 use_operand_p imm_use;
1062 gimple *use_stmt;
1064 /* If the PHI's result is never used, then we can just
1065 ignore it. */
1066 if (has_zero_uses (result))
1067 continue;
1069 /* Get the single use of the result of this PHI node. */
1070 if (!single_imm_use (result, &imm_use, &use_stmt)
1071 || gimple_code (use_stmt) != GIMPLE_PHI
1072 || gimple_bb (use_stmt) != dest
1073 || gimple_phi_arg_def (use_stmt, dest_idx) != result)
1074 break;
1077 /* If the loop above iterated through all the PHI nodes
1078 in BB, then we can merge the PHIs from BB into DEST. */
1079 if (gsi_end_p (gsi))
1080 *current++ = bb;
1084 /* Now let's drain WORKLIST. */
1085 bool changed = false;
1086 while (current != worklist)
1088 bb = *--current;
1089 changed |= remove_forwarder_block_with_phi (bb);
1091 free (worklist);
1093 /* Removing forwarder blocks can cause formerly irreducible loops
1094 to become reducible if we merged two entry blocks. */
1095 if (changed
1096 && current_loops)
1097 loops_state_set (LOOPS_NEED_FIXUP);
1099 return 0;
1102 } // anon namespace
1104 gimple_opt_pass *
1105 make_pass_merge_phi (gcc::context *ctxt)
1107 return new pass_merge_phi (ctxt);
1110 /* Pass: cleanup the CFG just before expanding trees to RTL.
1111 This is just a round of label cleanups and case node grouping
1112 because after the tree optimizers have run such cleanups may
1113 be necessary. */
1115 static unsigned int
1116 execute_cleanup_cfg_post_optimizing (void)
1118 unsigned int todo = execute_fixup_cfg ();
1119 if (cleanup_tree_cfg ())
1121 todo &= ~TODO_cleanup_cfg;
1122 todo |= TODO_update_ssa;
1124 maybe_remove_unreachable_handlers ();
1125 cleanup_dead_labels ();
1126 group_case_labels ();
1127 if ((flag_compare_debug_opt || flag_compare_debug)
1128 && flag_dump_final_insns)
1130 FILE *final_output = fopen (flag_dump_final_insns, "a");
1132 if (!final_output)
1134 error ("could not open final insn dump file %qs: %m",
1135 flag_dump_final_insns);
1136 flag_dump_final_insns = NULL;
1138 else
1140 int save_unnumbered = flag_dump_unnumbered;
1141 int save_noaddr = flag_dump_noaddr;
1143 flag_dump_noaddr = flag_dump_unnumbered = 1;
1144 fprintf (final_output, "\n");
1145 dump_enumerated_decls (final_output, dump_flags | TDF_NOUID);
1146 flag_dump_noaddr = save_noaddr;
1147 flag_dump_unnumbered = save_unnumbered;
1148 if (fclose (final_output))
1150 error ("could not close final insn dump file %qs: %m",
1151 flag_dump_final_insns);
1152 flag_dump_final_insns = NULL;
1156 return todo;
1159 namespace {
1161 const pass_data pass_data_cleanup_cfg_post_optimizing =
1163 GIMPLE_PASS, /* type */
1164 "optimized", /* name */
1165 OPTGROUP_NONE, /* optinfo_flags */
1166 TV_TREE_CLEANUP_CFG, /* tv_id */
1167 PROP_cfg, /* properties_required */
1168 0, /* properties_provided */
1169 0, /* properties_destroyed */
1170 0, /* todo_flags_start */
1171 TODO_remove_unused_locals, /* todo_flags_finish */
1174 class pass_cleanup_cfg_post_optimizing : public gimple_opt_pass
1176 public:
1177 pass_cleanup_cfg_post_optimizing (gcc::context *ctxt)
1178 : gimple_opt_pass (pass_data_cleanup_cfg_post_optimizing, ctxt)
1181 /* opt_pass methods: */
1182 virtual unsigned int execute (function *)
1184 return execute_cleanup_cfg_post_optimizing ();
1187 }; // class pass_cleanup_cfg_post_optimizing
1189 } // anon namespace
1191 gimple_opt_pass *
1192 make_pass_cleanup_cfg_post_optimizing (gcc::context *ctxt)
1194 return new pass_cleanup_cfg_post_optimizing (ctxt);