2015-09-25 Vladimir Makarov <vmakarov@redhat.com>
[official-gcc.git] / gcc / tree-cfgcleanup.c
blob40e14566ed1a3553bc7e8fa172f4e589246b8303
1 /* CFG cleanup for trees.
2 Copyright (C) 2001-2015 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 "cfghooks.h"
25 #include "tree.h"
26 #include "gimple.h"
27 #include "rtl.h"
28 #include "ssa.h"
29 #include "alias.h"
30 #include "fold-const.h"
31 #include "tm_p.h"
32 #include "cfganal.h"
33 #include "cfgcleanup.h"
34 #include "diagnostic-core.h"
35 #include "flags.h"
36 #include "langhooks.h"
37 #include "internal-fn.h"
38 #include "tree-eh.h"
39 #include "gimplify.h"
40 #include "gimple-iterator.h"
41 #include "tree-cfg.h"
42 #include "tree-ssa-loop-manip.h"
43 #include "insn-config.h"
44 #include "expmed.h"
45 #include "dojump.h"
46 #include "explow.h"
47 #include "calls.h"
48 #include "emit-rtl.h"
49 #include "varasm.h"
50 #include "stmt.h"
51 #include "expr.h"
52 #include "tree-dfa.h"
53 #include "tree-ssa.h"
54 #include "tree-pass.h"
55 #include "except.h"
56 #include "cfgloop.h"
57 #include "tree-ssa-propagate.h"
58 #include "tree-scalar-evolution.h"
60 /* The set of blocks in that at least one of the following changes happened:
61 -- the statement at the end of the block was changed
62 -- the block was newly created
63 -- the set of the predecessors of the block changed
64 -- the set of the successors of the block changed
65 ??? Maybe we could track these changes separately, since they determine
66 what cleanups it makes sense to try on the block. */
67 bitmap cfgcleanup_altered_bbs;
69 /* Remove any fallthru edge from EV. Return true if an edge was removed. */
71 static bool
72 remove_fallthru_edge (vec<edge, va_gc> *ev)
74 edge_iterator ei;
75 edge e;
77 FOR_EACH_EDGE (e, ei, ev)
78 if ((e->flags & EDGE_FALLTHRU) != 0)
80 if (e->flags & EDGE_COMPLEX)
81 e->flags &= ~EDGE_FALLTHRU;
82 else
83 remove_edge_and_dominated_blocks (e);
84 return true;
86 return false;
90 /* Disconnect an unreachable block in the control expression starting
91 at block BB. */
93 static bool
94 cleanup_control_expr_graph (basic_block bb, gimple_stmt_iterator gsi)
96 edge taken_edge;
97 bool retval = false;
98 gimple *stmt = gsi_stmt (gsi);
99 tree val;
101 if (!single_succ_p (bb))
103 edge e;
104 edge_iterator ei;
105 bool warned;
106 location_t loc;
108 fold_defer_overflow_warnings ();
109 loc = gimple_location (stmt);
110 switch (gimple_code (stmt))
112 case GIMPLE_COND:
113 val = fold_binary_loc (loc, gimple_cond_code (stmt),
114 boolean_type_node,
115 gimple_cond_lhs (stmt),
116 gimple_cond_rhs (stmt));
117 break;
119 case GIMPLE_SWITCH:
120 val = gimple_switch_index (as_a <gswitch *> (stmt));
121 break;
123 default:
124 val = NULL_TREE;
126 taken_edge = find_taken_edge (bb, val);
127 if (!taken_edge)
129 fold_undefer_and_ignore_overflow_warnings ();
130 return false;
133 /* Remove all the edges except the one that is always executed. */
134 warned = false;
135 for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
137 if (e != taken_edge)
139 if (!warned)
141 fold_undefer_overflow_warnings
142 (true, stmt, WARN_STRICT_OVERFLOW_CONDITIONAL);
143 warned = true;
146 taken_edge->probability += e->probability;
147 taken_edge->count += e->count;
148 remove_edge_and_dominated_blocks (e);
149 retval = true;
151 else
152 ei_next (&ei);
154 if (!warned)
155 fold_undefer_and_ignore_overflow_warnings ();
156 if (taken_edge->probability > REG_BR_PROB_BASE)
157 taken_edge->probability = REG_BR_PROB_BASE;
159 else
160 taken_edge = single_succ_edge (bb);
162 bitmap_set_bit (cfgcleanup_altered_bbs, bb->index);
163 gsi_remove (&gsi, true);
164 taken_edge->flags = EDGE_FALLTHRU;
166 return retval;
169 /* Cleanup the GF_CALL_CTRL_ALTERING flag according to
170 to updated gimple_call_flags. */
172 static void
173 cleanup_call_ctrl_altering_flag (gimple *bb_end)
175 if (!is_gimple_call (bb_end)
176 || !gimple_call_ctrl_altering_p (bb_end))
177 return;
179 int flags = gimple_call_flags (bb_end);
180 if (((flags & (ECF_CONST | ECF_PURE))
181 && !(flags & ECF_LOOPING_CONST_OR_PURE))
182 || (flags & ECF_LEAF))
183 gimple_call_set_ctrl_altering (bb_end, false);
186 /* Try to remove superfluous control structures in basic block BB. Returns
187 true if anything changes. */
189 static bool
190 cleanup_control_flow_bb (basic_block bb)
192 gimple_stmt_iterator gsi;
193 bool retval = false;
194 gimple *stmt;
196 /* If the last statement of the block could throw and now cannot,
197 we need to prune cfg. */
198 retval |= gimple_purge_dead_eh_edges (bb);
200 gsi = gsi_last_bb (bb);
201 if (gsi_end_p (gsi))
202 return retval;
204 stmt = gsi_stmt (gsi);
206 /* Try to cleanup ctrl altering flag for call which ends bb. */
207 cleanup_call_ctrl_altering_flag (stmt);
209 if (gimple_code (stmt) == GIMPLE_COND
210 || gimple_code (stmt) == GIMPLE_SWITCH)
211 retval |= cleanup_control_expr_graph (bb, gsi);
212 else if (gimple_code (stmt) == GIMPLE_GOTO
213 && TREE_CODE (gimple_goto_dest (stmt)) == ADDR_EXPR
214 && (TREE_CODE (TREE_OPERAND (gimple_goto_dest (stmt), 0))
215 == LABEL_DECL))
217 /* If we had a computed goto which has a compile-time determinable
218 destination, then we can eliminate the goto. */
219 edge e;
220 tree label;
221 edge_iterator ei;
222 basic_block target_block;
224 /* First look at all the outgoing edges. Delete any outgoing
225 edges which do not go to the right block. For the one
226 edge which goes to the right block, fix up its flags. */
227 label = TREE_OPERAND (gimple_goto_dest (stmt), 0);
228 target_block = label_to_block (label);
229 for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
231 if (e->dest != target_block)
232 remove_edge_and_dominated_blocks (e);
233 else
235 /* Turn off the EDGE_ABNORMAL flag. */
236 e->flags &= ~EDGE_ABNORMAL;
238 /* And set EDGE_FALLTHRU. */
239 e->flags |= EDGE_FALLTHRU;
240 ei_next (&ei);
244 bitmap_set_bit (cfgcleanup_altered_bbs, bb->index);
245 bitmap_set_bit (cfgcleanup_altered_bbs, target_block->index);
247 /* Remove the GOTO_EXPR as it is not needed. The CFG has all the
248 relevant information we need. */
249 gsi_remove (&gsi, true);
250 retval = true;
253 /* Check for indirect calls that have been turned into
254 noreturn calls. */
255 else if (is_gimple_call (stmt)
256 && gimple_call_noreturn_p (stmt)
257 && remove_fallthru_edge (bb->succs))
258 retval = true;
260 return retval;
263 /* Return true if basic block BB does nothing except pass control
264 flow to another block and that we can safely insert a label at
265 the start of the successor block.
267 As a precondition, we require that BB be not equal to
268 the entry block. */
270 static bool
271 tree_forwarder_block_p (basic_block bb, bool phi_wanted)
273 gimple_stmt_iterator gsi;
274 location_t locus;
276 /* BB must have a single outgoing edge. */
277 if (single_succ_p (bb) != 1
278 /* If PHI_WANTED is false, BB must not have any PHI nodes.
279 Otherwise, BB must have PHI nodes. */
280 || gimple_seq_empty_p (phi_nodes (bb)) == phi_wanted
281 /* BB may not be a predecessor of the exit block. */
282 || single_succ (bb) == EXIT_BLOCK_PTR_FOR_FN (cfun)
283 /* Nor should this be an infinite loop. */
284 || single_succ (bb) == bb
285 /* BB may not have an abnormal outgoing edge. */
286 || (single_succ_edge (bb)->flags & EDGE_ABNORMAL))
287 return false;
289 gcc_checking_assert (bb != ENTRY_BLOCK_PTR_FOR_FN (cfun));
291 locus = single_succ_edge (bb)->goto_locus;
293 /* There should not be an edge coming from entry, or an EH edge. */
295 edge_iterator ei;
296 edge e;
298 FOR_EACH_EDGE (e, ei, bb->preds)
299 if (e->src == ENTRY_BLOCK_PTR_FOR_FN (cfun) || (e->flags & EDGE_EH))
300 return false;
301 /* If goto_locus of any of the edges differs, prevent removing
302 the forwarder block for -O0. */
303 else if (optimize == 0 && e->goto_locus != locus)
304 return false;
307 /* Now walk through the statements backward. We can ignore labels,
308 anything else means this is not a forwarder block. */
309 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
311 gimple *stmt = gsi_stmt (gsi);
313 switch (gimple_code (stmt))
315 case GIMPLE_LABEL:
316 if (DECL_NONLOCAL (gimple_label_label (as_a <glabel *> (stmt))))
317 return false;
318 if (optimize == 0 && gimple_location (stmt) != locus)
319 return false;
320 break;
322 /* ??? For now, hope there's a corresponding debug
323 assignment at the destination. */
324 case GIMPLE_DEBUG:
325 break;
327 default:
328 return false;
332 if (current_loops)
334 basic_block dest;
335 /* Protect loop headers. */
336 if (bb->loop_father->header == bb)
337 return false;
339 dest = EDGE_SUCC (bb, 0)->dest;
340 /* Protect loop preheaders and latches if requested. */
341 if (dest->loop_father->header == dest)
343 if (bb->loop_father == dest->loop_father)
345 if (loops_state_satisfies_p (LOOPS_HAVE_SIMPLE_LATCHES))
346 return false;
347 /* If bb doesn't have a single predecessor we'd make this
348 loop have multiple latches. Don't do that if that
349 would in turn require disambiguating them. */
350 return (single_pred_p (bb)
351 || loops_state_satisfies_p
352 (LOOPS_MAY_HAVE_MULTIPLE_LATCHES));
354 else if (bb->loop_father == loop_outer (dest->loop_father))
355 return !loops_state_satisfies_p (LOOPS_HAVE_PREHEADERS);
356 /* Always preserve other edges into loop headers that are
357 not simple latches or preheaders. */
358 return false;
362 return true;
365 /* If all the PHI nodes in DEST have alternatives for E1 and E2 and
366 those alternatives are equal in each of the PHI nodes, then return
367 true, else return false. */
369 static bool
370 phi_alternatives_equal (basic_block dest, edge e1, edge e2)
372 int n1 = e1->dest_idx;
373 int n2 = e2->dest_idx;
374 gphi_iterator gsi;
376 for (gsi = gsi_start_phis (dest); !gsi_end_p (gsi); gsi_next (&gsi))
378 gphi *phi = gsi.phi ();
379 tree val1 = gimple_phi_arg_def (phi, n1);
380 tree val2 = gimple_phi_arg_def (phi, n2);
382 gcc_assert (val1 != NULL_TREE);
383 gcc_assert (val2 != NULL_TREE);
385 if (!operand_equal_for_phi_arg_p (val1, val2))
386 return false;
389 return true;
392 /* Removes forwarder block BB. Returns false if this failed. */
394 static bool
395 remove_forwarder_block (basic_block bb)
397 edge succ = single_succ_edge (bb), e, s;
398 basic_block dest = succ->dest;
399 gimple *label;
400 edge_iterator ei;
401 gimple_stmt_iterator gsi, gsi_to;
402 bool can_move_debug_stmts;
404 /* We check for infinite loops already in tree_forwarder_block_p.
405 However it may happen that the infinite loop is created
406 afterwards due to removal of forwarders. */
407 if (dest == bb)
408 return false;
410 /* If the destination block consists of a nonlocal label or is a
411 EH landing pad, do not merge it. */
412 label = first_stmt (dest);
413 if (label)
414 if (glabel *label_stmt = dyn_cast <glabel *> (label))
415 if (DECL_NONLOCAL (gimple_label_label (label_stmt))
416 || EH_LANDING_PAD_NR (gimple_label_label (label_stmt)) != 0)
417 return false;
419 /* If there is an abnormal edge to basic block BB, but not into
420 dest, problems might occur during removal of the phi node at out
421 of ssa due to overlapping live ranges of registers.
423 If there is an abnormal edge in DEST, the problems would occur
424 anyway since cleanup_dead_labels would then merge the labels for
425 two different eh regions, and rest of exception handling code
426 does not like it.
428 So if there is an abnormal edge to BB, proceed only if there is
429 no abnormal edge to DEST and there are no phi nodes in DEST. */
430 if (bb_has_abnormal_pred (bb)
431 && (bb_has_abnormal_pred (dest)
432 || !gimple_seq_empty_p (phi_nodes (dest))))
433 return false;
435 /* If there are phi nodes in DEST, and some of the blocks that are
436 predecessors of BB are also predecessors of DEST, check that the
437 phi node arguments match. */
438 if (!gimple_seq_empty_p (phi_nodes (dest)))
440 FOR_EACH_EDGE (e, ei, bb->preds)
442 s = find_edge (e->src, dest);
443 if (!s)
444 continue;
446 if (!phi_alternatives_equal (dest, succ, s))
447 return false;
451 can_move_debug_stmts = MAY_HAVE_DEBUG_STMTS && single_pred_p (dest);
453 basic_block pred = NULL;
454 if (single_pred_p (bb))
455 pred = single_pred (bb);
457 /* Redirect the edges. */
458 for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei)); )
460 bitmap_set_bit (cfgcleanup_altered_bbs, e->src->index);
462 if (e->flags & EDGE_ABNORMAL)
464 /* If there is an abnormal edge, redirect it anyway, and
465 move the labels to the new block to make it legal. */
466 s = redirect_edge_succ_nodup (e, dest);
468 else
469 s = redirect_edge_and_branch (e, dest);
471 if (s == e)
473 /* Create arguments for the phi nodes, since the edge was not
474 here before. */
475 for (gphi_iterator psi = gsi_start_phis (dest);
476 !gsi_end_p (psi);
477 gsi_next (&psi))
479 gphi *phi = psi.phi ();
480 source_location l = gimple_phi_arg_location_from_edge (phi, succ);
481 tree def = gimple_phi_arg_def (phi, succ->dest_idx);
482 add_phi_arg (phi, unshare_expr (def), s, l);
487 /* Move nonlocal labels and computed goto targets as well as user
488 defined labels and labels with an EH landing pad number to the
489 new block, so that the redirection of the abnormal edges works,
490 jump targets end up in a sane place and debug information for
491 labels is retained. */
492 gsi_to = gsi_start_bb (dest);
493 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); )
495 tree decl;
496 label = gsi_stmt (gsi);
497 if (is_gimple_debug (label))
498 break;
499 decl = gimple_label_label (as_a <glabel *> (label));
500 if (EH_LANDING_PAD_NR (decl) != 0
501 || DECL_NONLOCAL (decl)
502 || FORCED_LABEL (decl)
503 || !DECL_ARTIFICIAL (decl))
505 gsi_remove (&gsi, false);
506 gsi_insert_before (&gsi_to, label, GSI_SAME_STMT);
508 else
509 gsi_next (&gsi);
512 /* Move debug statements if the destination has a single predecessor. */
513 if (can_move_debug_stmts)
515 gsi_to = gsi_after_labels (dest);
516 for (gsi = gsi_after_labels (bb); !gsi_end_p (gsi); )
518 gimple *debug = gsi_stmt (gsi);
519 if (!is_gimple_debug (debug))
520 break;
521 gsi_remove (&gsi, false);
522 gsi_insert_before (&gsi_to, debug, GSI_SAME_STMT);
526 bitmap_set_bit (cfgcleanup_altered_bbs, dest->index);
528 /* Update the dominators. */
529 if (dom_info_available_p (CDI_DOMINATORS))
531 basic_block dom, dombb, domdest;
533 dombb = get_immediate_dominator (CDI_DOMINATORS, bb);
534 domdest = get_immediate_dominator (CDI_DOMINATORS, dest);
535 if (domdest == bb)
537 /* Shortcut to avoid calling (relatively expensive)
538 nearest_common_dominator unless necessary. */
539 dom = dombb;
541 else
542 dom = nearest_common_dominator (CDI_DOMINATORS, domdest, dombb);
544 set_immediate_dominator (CDI_DOMINATORS, dest, dom);
547 /* Adjust latch infomation of BB's parent loop as otherwise
548 the cfg hook has a hard time not to kill the loop. */
549 if (current_loops && bb->loop_father->latch == bb)
550 bb->loop_father->latch = pred;
552 /* And kill the forwarder block. */
553 delete_basic_block (bb);
555 return true;
558 /* STMT is a call that has been discovered noreturn. Split the
559 block to prepare fixing up the CFG and remove LHS.
560 Return true if cleanup-cfg needs to run. */
562 bool
563 fixup_noreturn_call (gimple *stmt)
565 basic_block bb = gimple_bb (stmt);
566 bool changed = false;
568 if (gimple_call_builtin_p (stmt, BUILT_IN_RETURN))
569 return false;
571 /* First split basic block if stmt is not last. */
572 if (stmt != gsi_stmt (gsi_last_bb (bb)))
574 if (stmt == gsi_stmt (gsi_last_nondebug_bb (bb)))
576 /* Don't split if there are only debug stmts
577 after stmt, that can result in -fcompare-debug
578 failures. Remove the debug stmts instead,
579 they should be all unreachable anyway. */
580 gimple_stmt_iterator gsi = gsi_for_stmt (stmt);
581 for (gsi_next (&gsi); !gsi_end_p (gsi); )
582 gsi_remove (&gsi, true);
584 else
586 split_block (bb, stmt);
587 changed = true;
591 /* If there is an LHS, remove it, but only if its type has fixed size.
592 The LHS will need to be recreated during RTL expansion and creating
593 temporaries of variable-sized types is not supported. */
594 tree lhs = gimple_call_lhs (stmt);
595 if (lhs && TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (lhs))) == INTEGER_CST)
597 gimple_call_set_lhs (stmt, NULL_TREE);
599 /* We need to fix up the SSA name to avoid checking errors. */
600 if (TREE_CODE (lhs) == SSA_NAME)
602 tree new_var = create_tmp_reg (TREE_TYPE (lhs));
603 SET_SSA_NAME_VAR_OR_IDENTIFIER (lhs, new_var);
604 SSA_NAME_DEF_STMT (lhs) = gimple_build_nop ();
605 set_ssa_default_def (cfun, new_var, lhs);
608 update_stmt (stmt);
611 /* Mark the call as altering control flow. */
612 if (!gimple_call_ctrl_altering_p (stmt))
614 gimple_call_set_ctrl_altering (stmt, true);
615 changed = true;
618 return changed;
622 /* Tries to cleanup cfg in basic block BB. Returns true if anything
623 changes. */
625 static bool
626 cleanup_tree_cfg_bb (basic_block bb)
628 bool retval = cleanup_control_flow_bb (bb);
630 if (tree_forwarder_block_p (bb, false)
631 && remove_forwarder_block (bb))
632 return true;
634 /* Merging the blocks may create new opportunities for folding
635 conditional branches (due to the elimination of single-valued PHI
636 nodes). */
637 if (single_succ_p (bb)
638 && can_merge_blocks_p (bb, single_succ (bb)))
640 /* If there is a merge opportunity with the predecessor
641 do nothing now but wait until we process the predecessor.
642 This happens when we visit BBs in a non-optimal order and
643 avoids quadratic behavior with adjusting stmts BB pointer. */
644 if (single_pred_p (bb)
645 && can_merge_blocks_p (single_pred (bb), bb))
647 else
649 merge_blocks (bb, single_succ (bb));
650 return true;
654 return retval;
657 /* Iterate the cfg cleanups, while anything changes. */
659 static bool
660 cleanup_tree_cfg_1 (void)
662 bool retval = false;
663 basic_block bb;
664 unsigned i, n;
666 /* Prepare the worklists of altered blocks. */
667 cfgcleanup_altered_bbs = BITMAP_ALLOC (NULL);
669 /* During forwarder block cleanup, we may redirect edges out of
670 SWITCH_EXPRs, which can get expensive. So we want to enable
671 recording of edge to CASE_LABEL_EXPR. */
672 start_recording_case_labels ();
674 /* Start by iterating over all basic blocks. We cannot use FOR_EACH_BB_FN,
675 since the basic blocks may get removed. */
676 n = last_basic_block_for_fn (cfun);
677 for (i = NUM_FIXED_BLOCKS; i < n; i++)
679 bb = BASIC_BLOCK_FOR_FN (cfun, i);
680 if (bb)
681 retval |= cleanup_tree_cfg_bb (bb);
684 /* Now process the altered blocks, as long as any are available. */
685 while (!bitmap_empty_p (cfgcleanup_altered_bbs))
687 i = bitmap_first_set_bit (cfgcleanup_altered_bbs);
688 bitmap_clear_bit (cfgcleanup_altered_bbs, i);
689 if (i < NUM_FIXED_BLOCKS)
690 continue;
692 bb = BASIC_BLOCK_FOR_FN (cfun, i);
693 if (!bb)
694 continue;
696 retval |= cleanup_tree_cfg_bb (bb);
699 end_recording_case_labels ();
700 BITMAP_FREE (cfgcleanup_altered_bbs);
701 return retval;
705 /* Remove unreachable blocks and other miscellaneous clean up work.
706 Return true if the flowgraph was modified, false otherwise. */
708 static bool
709 cleanup_tree_cfg_noloop (void)
711 bool changed;
713 timevar_push (TV_TREE_CLEANUP_CFG);
715 /* Iterate until there are no more cleanups left to do. If any
716 iteration changed the flowgraph, set CHANGED to true.
718 If dominance information is available, there cannot be any unreachable
719 blocks. */
720 if (!dom_info_available_p (CDI_DOMINATORS))
722 changed = delete_unreachable_blocks ();
723 calculate_dominance_info (CDI_DOMINATORS);
725 else
727 #ifdef ENABLE_CHECKING
728 verify_dominators (CDI_DOMINATORS);
729 #endif
730 changed = false;
733 changed |= cleanup_tree_cfg_1 ();
735 gcc_assert (dom_info_available_p (CDI_DOMINATORS));
736 compact_blocks ();
738 #ifdef ENABLE_CHECKING
739 verify_flow_info ();
740 #endif
742 timevar_pop (TV_TREE_CLEANUP_CFG);
744 if (changed && current_loops)
745 loops_state_set (LOOPS_NEED_FIXUP);
747 return changed;
750 /* Repairs loop structures. */
752 static void
753 repair_loop_structures (void)
755 bitmap changed_bbs;
756 unsigned n_new_loops;
758 calculate_dominance_info (CDI_DOMINATORS);
760 timevar_push (TV_REPAIR_LOOPS);
761 changed_bbs = BITMAP_ALLOC (NULL);
762 n_new_loops = fix_loop_structure (changed_bbs);
764 /* This usually does nothing. But sometimes parts of cfg that originally
765 were inside a loop get out of it due to edge removal (since they
766 become unreachable by back edges from latch). Also a former
767 irreducible loop can become reducible - in this case force a full
768 rewrite into loop-closed SSA form. */
769 if (loops_state_satisfies_p (LOOP_CLOSED_SSA))
770 rewrite_into_loop_closed_ssa (n_new_loops ? NULL : changed_bbs,
771 TODO_update_ssa);
773 BITMAP_FREE (changed_bbs);
775 #ifdef ENABLE_CHECKING
776 verify_loop_structure ();
777 #endif
778 scev_reset ();
780 timevar_pop (TV_REPAIR_LOOPS);
783 /* Cleanup cfg and repair loop structures. */
785 bool
786 cleanup_tree_cfg (void)
788 bool changed = cleanup_tree_cfg_noloop ();
790 if (current_loops != NULL
791 && loops_state_satisfies_p (LOOPS_NEED_FIXUP))
792 repair_loop_structures ();
794 return changed;
797 /* Tries to merge the PHI nodes at BB into those at BB's sole successor.
798 Returns true if successful. */
800 static bool
801 remove_forwarder_block_with_phi (basic_block bb)
803 edge succ = single_succ_edge (bb);
804 basic_block dest = succ->dest;
805 gimple *label;
806 basic_block dombb, domdest, dom;
808 /* We check for infinite loops already in tree_forwarder_block_p.
809 However it may happen that the infinite loop is created
810 afterwards due to removal of forwarders. */
811 if (dest == bb)
812 return false;
814 /* If the destination block consists of a nonlocal label, do not
815 merge it. */
816 label = first_stmt (dest);
817 if (label)
818 if (glabel *label_stmt = dyn_cast <glabel *> (label))
819 if (DECL_NONLOCAL (gimple_label_label (label_stmt)))
820 return false;
822 /* Record BB's single pred in case we need to update the father
823 loop's latch information later. */
824 basic_block pred = NULL;
825 if (single_pred_p (bb))
826 pred = single_pred (bb);
828 /* Redirect each incoming edge to BB to DEST. */
829 while (EDGE_COUNT (bb->preds) > 0)
831 edge e = EDGE_PRED (bb, 0), s;
832 gphi_iterator gsi;
834 s = find_edge (e->src, dest);
835 if (s)
837 /* We already have an edge S from E->src to DEST. If S and
838 E->dest's sole successor edge have the same PHI arguments
839 at DEST, redirect S to DEST. */
840 if (phi_alternatives_equal (dest, s, succ))
842 e = redirect_edge_and_branch (e, dest);
843 redirect_edge_var_map_clear (e);
844 continue;
847 /* PHI arguments are different. Create a forwarder block by
848 splitting E so that we can merge PHI arguments on E to
849 DEST. */
850 e = single_succ_edge (split_edge (e));
853 s = redirect_edge_and_branch (e, dest);
855 /* redirect_edge_and_branch must not create a new edge. */
856 gcc_assert (s == e);
858 /* Add to the PHI nodes at DEST each PHI argument removed at the
859 destination of E. */
860 for (gsi = gsi_start_phis (dest);
861 !gsi_end_p (gsi);
862 gsi_next (&gsi))
864 gphi *phi = gsi.phi ();
865 tree def = gimple_phi_arg_def (phi, succ->dest_idx);
866 source_location locus = gimple_phi_arg_location_from_edge (phi, succ);
868 if (TREE_CODE (def) == SSA_NAME)
870 /* If DEF is one of the results of PHI nodes removed during
871 redirection, replace it with the PHI argument that used
872 to be on E. */
873 vec<edge_var_map> *head = redirect_edge_var_map_vector (e);
874 size_t length = head ? head->length () : 0;
875 for (size_t i = 0; i < length; i++)
877 edge_var_map *vm = &(*head)[i];
878 tree old_arg = redirect_edge_var_map_result (vm);
879 tree new_arg = redirect_edge_var_map_def (vm);
881 if (def == old_arg)
883 def = new_arg;
884 locus = redirect_edge_var_map_location (vm);
885 break;
890 add_phi_arg (phi, def, s, locus);
893 redirect_edge_var_map_clear (e);
896 /* Update the dominators. */
897 dombb = get_immediate_dominator (CDI_DOMINATORS, bb);
898 domdest = get_immediate_dominator (CDI_DOMINATORS, dest);
899 if (domdest == bb)
901 /* Shortcut to avoid calling (relatively expensive)
902 nearest_common_dominator unless necessary. */
903 dom = dombb;
905 else
906 dom = nearest_common_dominator (CDI_DOMINATORS, domdest, dombb);
908 set_immediate_dominator (CDI_DOMINATORS, dest, dom);
910 /* Adjust latch infomation of BB's parent loop as otherwise
911 the cfg hook has a hard time not to kill the loop. */
912 if (current_loops && bb->loop_father->latch == bb)
913 bb->loop_father->latch = pred;
915 /* Remove BB since all of BB's incoming edges have been redirected
916 to DEST. */
917 delete_basic_block (bb);
919 return true;
922 /* This pass merges PHI nodes if one feeds into another. For example,
923 suppose we have the following:
925 goto <bb 9> (<L9>);
927 <L8>:;
928 tem_17 = foo ();
930 # tem_6 = PHI <tem_17(8), tem_23(7)>;
931 <L9>:;
933 # tem_3 = PHI <tem_6(9), tem_2(5)>;
934 <L10>:;
936 Then we merge the first PHI node into the second one like so:
938 goto <bb 9> (<L10>);
940 <L8>:;
941 tem_17 = foo ();
943 # tem_3 = PHI <tem_23(7), tem_2(5), tem_17(8)>;
944 <L10>:;
947 namespace {
949 const pass_data pass_data_merge_phi =
951 GIMPLE_PASS, /* type */
952 "mergephi", /* name */
953 OPTGROUP_NONE, /* optinfo_flags */
954 TV_TREE_MERGE_PHI, /* tv_id */
955 ( PROP_cfg | PROP_ssa ), /* properties_required */
956 0, /* properties_provided */
957 0, /* properties_destroyed */
958 0, /* todo_flags_start */
959 0, /* todo_flags_finish */
962 class pass_merge_phi : public gimple_opt_pass
964 public:
965 pass_merge_phi (gcc::context *ctxt)
966 : gimple_opt_pass (pass_data_merge_phi, ctxt)
969 /* opt_pass methods: */
970 opt_pass * clone () { return new pass_merge_phi (m_ctxt); }
971 virtual unsigned int execute (function *);
973 }; // class pass_merge_phi
975 unsigned int
976 pass_merge_phi::execute (function *fun)
978 basic_block *worklist = XNEWVEC (basic_block, n_basic_blocks_for_fn (fun));
979 basic_block *current = worklist;
980 basic_block bb;
982 calculate_dominance_info (CDI_DOMINATORS);
984 /* Find all PHI nodes that we may be able to merge. */
985 FOR_EACH_BB_FN (bb, fun)
987 basic_block dest;
989 /* Look for a forwarder block with PHI nodes. */
990 if (!tree_forwarder_block_p (bb, true))
991 continue;
993 dest = single_succ (bb);
995 /* We have to feed into another basic block with PHI
996 nodes. */
997 if (gimple_seq_empty_p (phi_nodes (dest))
998 /* We don't want to deal with a basic block with
999 abnormal edges. */
1000 || bb_has_abnormal_pred (bb))
1001 continue;
1003 if (!dominated_by_p (CDI_DOMINATORS, dest, bb))
1005 /* If BB does not dominate DEST, then the PHI nodes at
1006 DEST must be the only users of the results of the PHI
1007 nodes at BB. */
1008 *current++ = bb;
1010 else
1012 gphi_iterator gsi;
1013 unsigned int dest_idx = single_succ_edge (bb)->dest_idx;
1015 /* BB dominates DEST. There may be many users of the PHI
1016 nodes in BB. However, there is still a trivial case we
1017 can handle. If the result of every PHI in BB is used
1018 only by a PHI in DEST, then we can trivially merge the
1019 PHI nodes from BB into DEST. */
1020 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
1021 gsi_next (&gsi))
1023 gphi *phi = gsi.phi ();
1024 tree result = gimple_phi_result (phi);
1025 use_operand_p imm_use;
1026 gimple *use_stmt;
1028 /* If the PHI's result is never used, then we can just
1029 ignore it. */
1030 if (has_zero_uses (result))
1031 continue;
1033 /* Get the single use of the result of this PHI node. */
1034 if (!single_imm_use (result, &imm_use, &use_stmt)
1035 || gimple_code (use_stmt) != GIMPLE_PHI
1036 || gimple_bb (use_stmt) != dest
1037 || gimple_phi_arg_def (use_stmt, dest_idx) != result)
1038 break;
1041 /* If the loop above iterated through all the PHI nodes
1042 in BB, then we can merge the PHIs from BB into DEST. */
1043 if (gsi_end_p (gsi))
1044 *current++ = bb;
1048 /* Now let's drain WORKLIST. */
1049 bool changed = false;
1050 while (current != worklist)
1052 bb = *--current;
1053 changed |= remove_forwarder_block_with_phi (bb);
1055 free (worklist);
1057 /* Removing forwarder blocks can cause formerly irreducible loops
1058 to become reducible if we merged two entry blocks. */
1059 if (changed
1060 && current_loops)
1061 loops_state_set (LOOPS_NEED_FIXUP);
1063 return 0;
1066 } // anon namespace
1068 gimple_opt_pass *
1069 make_pass_merge_phi (gcc::context *ctxt)
1071 return new pass_merge_phi (ctxt);
1074 /* Pass: cleanup the CFG just before expanding trees to RTL.
1075 This is just a round of label cleanups and case node grouping
1076 because after the tree optimizers have run such cleanups may
1077 be necessary. */
1079 static unsigned int
1080 execute_cleanup_cfg_post_optimizing (void)
1082 unsigned int todo = execute_fixup_cfg ();
1083 if (cleanup_tree_cfg ())
1085 todo &= ~TODO_cleanup_cfg;
1086 todo |= TODO_update_ssa;
1088 maybe_remove_unreachable_handlers ();
1089 cleanup_dead_labels ();
1090 group_case_labels ();
1091 if ((flag_compare_debug_opt || flag_compare_debug)
1092 && flag_dump_final_insns)
1094 FILE *final_output = fopen (flag_dump_final_insns, "a");
1096 if (!final_output)
1098 error ("could not open final insn dump file %qs: %m",
1099 flag_dump_final_insns);
1100 flag_dump_final_insns = NULL;
1102 else
1104 int save_unnumbered = flag_dump_unnumbered;
1105 int save_noaddr = flag_dump_noaddr;
1107 flag_dump_noaddr = flag_dump_unnumbered = 1;
1108 fprintf (final_output, "\n");
1109 dump_enumerated_decls (final_output, dump_flags | TDF_NOUID);
1110 flag_dump_noaddr = save_noaddr;
1111 flag_dump_unnumbered = save_unnumbered;
1112 if (fclose (final_output))
1114 error ("could not close final insn dump file %qs: %m",
1115 flag_dump_final_insns);
1116 flag_dump_final_insns = NULL;
1120 return todo;
1123 namespace {
1125 const pass_data pass_data_cleanup_cfg_post_optimizing =
1127 GIMPLE_PASS, /* type */
1128 "optimized", /* name */
1129 OPTGROUP_NONE, /* optinfo_flags */
1130 TV_TREE_CLEANUP_CFG, /* tv_id */
1131 PROP_cfg, /* properties_required */
1132 0, /* properties_provided */
1133 0, /* properties_destroyed */
1134 0, /* todo_flags_start */
1135 TODO_remove_unused_locals, /* todo_flags_finish */
1138 class pass_cleanup_cfg_post_optimizing : public gimple_opt_pass
1140 public:
1141 pass_cleanup_cfg_post_optimizing (gcc::context *ctxt)
1142 : gimple_opt_pass (pass_data_cleanup_cfg_post_optimizing, ctxt)
1145 /* opt_pass methods: */
1146 virtual unsigned int execute (function *)
1148 return execute_cleanup_cfg_post_optimizing ();
1151 }; // class pass_cleanup_cfg_post_optimizing
1153 } // anon namespace
1155 gimple_opt_pass *
1156 make_pass_cleanup_cfg_post_optimizing (gcc::context *ctxt)
1158 return new pass_cleanup_cfg_post_optimizing (ctxt);