1 //===- BreakCriticalEdges.cpp - Critical Edge Elimination Pass ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // BreakCriticalEdges pass - Break all of the critical edges in the CFG by
11 // inserting a dummy basic block. This pass may be "required" by passes that
12 // cannot deal with critical edges. For this usage, the structure type is
13 // forward declared. This pass obviously invalidates the CFG, but can update
16 //===----------------------------------------------------------------------===//
18 #include "llvm/Transforms/Scalar.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Analysis/CFG.h"
23 #include "llvm/Analysis/LoopInfo.h"
24 #include "llvm/IR/CFG.h"
25 #include "llvm/IR/Dominators.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/Type.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
33 #define DEBUG_TYPE "break-crit-edges"
35 STATISTIC(NumBroken, "Number of blocks inserted");
38 struct BreakCriticalEdges : public FunctionPass {
39 static char ID; // Pass identification, replacement for typeid
40 BreakCriticalEdges() : FunctionPass(ID) {
41 initializeBreakCriticalEdgesPass(*PassRegistry::getPassRegistry());
44 bool runOnFunction(Function &F) override {
45 unsigned N = SplitAllCriticalEdges(F, this);
50 void getAnalysisUsage(AnalysisUsage &AU) const override {
51 AU.addPreserved<DominatorTreeWrapperPass>();
52 AU.addPreserved<LoopInfoWrapperPass>();
54 // No loop canonicalization guarantees are broken by this pass.
55 AU.addPreservedID(LoopSimplifyID);
60 char BreakCriticalEdges::ID = 0;
61 INITIALIZE_PASS(BreakCriticalEdges, "break-crit-edges",
62 "Break critical edges in CFG", false, false)
64 // Publicly exposed interface to pass...
65 char &llvm::BreakCriticalEdgesID = BreakCriticalEdges::ID;
66 FunctionPass *llvm::createBreakCriticalEdgesPass() {
67 return new BreakCriticalEdges();
70 //===----------------------------------------------------------------------===//
71 // Implementation of the external critical edge manipulation functions
72 //===----------------------------------------------------------------------===//
74 /// createPHIsForSplitLoopExit - When a loop exit edge is split, LCSSA form
75 /// may require new PHIs in the new exit block. This function inserts the
76 /// new PHIs, as needed. Preds is a list of preds inside the loop, SplitBB
77 /// is the new loop exit block, and DestBB is the old loop exit, now the
78 /// successor of SplitBB.
79 static void createPHIsForSplitLoopExit(ArrayRef<BasicBlock *> Preds,
82 // SplitBB shouldn't have anything non-trivial in it yet.
83 assert((SplitBB->getFirstNonPHI() == SplitBB->getTerminator() ||
84 SplitBB->isLandingPad()) && "SplitBB has non-PHI nodes!");
86 // For each PHI in the destination block.
87 for (BasicBlock::iterator I = DestBB->begin();
88 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
89 unsigned Idx = PN->getBasicBlockIndex(SplitBB);
90 Value *V = PN->getIncomingValue(Idx);
92 // If the input is a PHI which already satisfies LCSSA, don't create
94 if (const PHINode *VP = dyn_cast<PHINode>(V))
95 if (VP->getParent() == SplitBB)
98 // Otherwise a new PHI is needed. Create one and populate it.
100 PHINode::Create(PN->getType(), Preds.size(), "split",
101 SplitBB->isLandingPad() ?
102 SplitBB->begin() : SplitBB->getTerminator());
103 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
104 NewPN->addIncoming(V, Preds[i]);
106 // Update the original PHI.
107 PN->setIncomingValue(Idx, NewPN);
111 /// SplitCriticalEdge - If this edge is a critical edge, insert a new node to
112 /// split the critical edge. This will update DominatorTree information if it
113 /// is available, thus calling this pass will not invalidate either of them.
114 /// This returns the new block if the edge was split, null otherwise.
116 /// If MergeIdenticalEdges is true (not the default), *all* edges from TI to the
117 /// specified successor will be merged into the same critical edge block.
118 /// This is most commonly interesting with switch instructions, which may
119 /// have many edges to any one destination. This ensures that all edges to that
120 /// dest go to one block instead of each going to a different block, but isn't
121 /// the standard definition of a "critical edge".
123 /// It is invalid to call this function on a critical edge that starts at an
124 /// IndirectBrInst. Splitting these edges will almost always create an invalid
125 /// program because the address of the new block won't be the one that is jumped
128 BasicBlock *llvm::SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum,
129 Pass *P, bool MergeIdenticalEdges,
130 bool DontDeleteUselessPhis,
131 bool SplitLandingPads) {
132 if (!isCriticalEdge(TI, SuccNum, MergeIdenticalEdges)) return nullptr;
134 assert(!isa<IndirectBrInst>(TI) &&
135 "Cannot split critical edge from IndirectBrInst");
137 BasicBlock *TIBB = TI->getParent();
138 BasicBlock *DestBB = TI->getSuccessor(SuccNum);
140 // Splitting the critical edge to a landing pad block is non-trivial. Don't do
141 // it in this generic function.
142 if (DestBB->isLandingPad()) return nullptr;
144 // Create a new basic block, linking it into the CFG.
145 BasicBlock *NewBB = BasicBlock::Create(TI->getContext(),
146 TIBB->getName() + "." + DestBB->getName() + "_crit_edge");
147 // Create our unconditional branch.
148 BranchInst *NewBI = BranchInst::Create(DestBB, NewBB);
149 NewBI->setDebugLoc(TI->getDebugLoc());
151 // Branch to the new block, breaking the edge.
152 TI->setSuccessor(SuccNum, NewBB);
154 // Insert the block into the function... right after the block TI lives in.
155 Function &F = *TIBB->getParent();
156 Function::iterator FBBI = TIBB;
157 F.getBasicBlockList().insert(++FBBI, NewBB);
159 // If there are any PHI nodes in DestBB, we need to update them so that they
160 // merge incoming values from NewBB instead of from TIBB.
163 for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) {
164 // We no longer enter through TIBB, now we come in through NewBB.
165 // Revector exactly one entry in the PHI node that used to come from
166 // TIBB to come from NewBB.
167 PHINode *PN = cast<PHINode>(I);
169 // Reuse the previous value of BBIdx if it lines up. In cases where we
170 // have multiple phi nodes with *lots* of predecessors, this is a speed
171 // win because we don't have to scan the PHI looking for TIBB. This
172 // happens because the BB list of PHI nodes are usually in the same
174 if (PN->getIncomingBlock(BBIdx) != TIBB)
175 BBIdx = PN->getBasicBlockIndex(TIBB);
176 PN->setIncomingBlock(BBIdx, NewBB);
180 // If there are any other edges from TIBB to DestBB, update those to go
181 // through the split block, making those edges non-critical as well (and
182 // reducing the number of phi entries in the DestBB if relevant).
183 if (MergeIdenticalEdges) {
184 for (unsigned i = SuccNum+1, e = TI->getNumSuccessors(); i != e; ++i) {
185 if (TI->getSuccessor(i) != DestBB) continue;
187 // Remove an entry for TIBB from DestBB phi nodes.
188 DestBB->removePredecessor(TIBB, DontDeleteUselessPhis);
190 // We found another edge to DestBB, go to NewBB instead.
191 TI->setSuccessor(i, NewBB);
197 // If we don't have a pass object, we can't update anything...
198 if (!P) return NewBB;
201 auto *AA = P->getAnalysisIfAvailable<AliasAnalysis>();
202 DominatorTreeWrapperPass *DTWP =
203 P->getAnalysisIfAvailable<DominatorTreeWrapperPass>();
204 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
205 auto *LIWP = P->getAnalysisIfAvailable<LoopInfoWrapperPass>();
206 LoopInfo *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
207 bool PreserveLCSSA = P->mustPreserveAnalysisID(LCSSAID);
209 // If we have nothing to update, just return.
213 // Now update analysis information. Since the only predecessor of NewBB is
214 // the TIBB, TIBB clearly dominates NewBB. TIBB usually doesn't dominate
215 // anything, as there are other successors of DestBB. However, if all other
216 // predecessors of DestBB are already dominated by DestBB (e.g. DestBB is a
217 // loop header) then NewBB dominates DestBB.
218 SmallVector<BasicBlock*, 8> OtherPreds;
220 // If there is a PHI in the block, loop over predecessors with it, which is
221 // faster than iterating pred_begin/end.
222 if (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
223 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
224 if (PN->getIncomingBlock(i) != NewBB)
225 OtherPreds.push_back(PN->getIncomingBlock(i));
227 for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB);
231 OtherPreds.push_back(P);
235 bool NewBBDominatesDestBB = true;
237 // Should we update DominatorTree information?
239 DomTreeNode *TINode = DT->getNode(TIBB);
241 // The new block is not the immediate dominator for any other nodes, but
242 // TINode is the immediate dominator for the new node.
244 if (TINode) { // Don't break unreachable code!
245 DomTreeNode *NewBBNode = DT->addNewBlock(NewBB, TIBB);
246 DomTreeNode *DestBBNode = nullptr;
248 // If NewBBDominatesDestBB hasn't been computed yet, do so with DT.
249 if (!OtherPreds.empty()) {
250 DestBBNode = DT->getNode(DestBB);
251 while (!OtherPreds.empty() && NewBBDominatesDestBB) {
252 if (DomTreeNode *OPNode = DT->getNode(OtherPreds.back()))
253 NewBBDominatesDestBB = DT->dominates(DestBBNode, OPNode);
254 OtherPreds.pop_back();
259 // If NewBBDominatesDestBB, then NewBB dominates DestBB, otherwise it
260 // doesn't dominate anything.
261 if (NewBBDominatesDestBB) {
262 if (!DestBBNode) DestBBNode = DT->getNode(DestBB);
263 DT->changeImmediateDominator(DestBBNode, NewBBNode);
268 // Update LoopInfo if it is around.
270 if (Loop *TIL = LI->getLoopFor(TIBB)) {
271 // If one or the other blocks were not in a loop, the new block is not
272 // either, and thus LI doesn't need to be updated.
273 if (Loop *DestLoop = LI->getLoopFor(DestBB)) {
274 if (TIL == DestLoop) {
275 // Both in the same loop, the NewBB joins loop.
276 DestLoop->addBasicBlockToLoop(NewBB, *LI);
277 } else if (TIL->contains(DestLoop)) {
278 // Edge from an outer loop to an inner loop. Add to the outer loop.
279 TIL->addBasicBlockToLoop(NewBB, *LI);
280 } else if (DestLoop->contains(TIL)) {
281 // Edge from an inner loop to an outer loop. Add to the outer loop.
282 DestLoop->addBasicBlockToLoop(NewBB, *LI);
284 // Edge from two loops with no containment relation. Because these
285 // are natural loops, we know that the destination block must be the
286 // header of its loop (adding a branch into a loop elsewhere would
287 // create an irreducible loop).
288 assert(DestLoop->getHeader() == DestBB &&
289 "Should not create irreducible loops!");
290 if (Loop *P = DestLoop->getParentLoop())
291 P->addBasicBlockToLoop(NewBB, *LI);
295 // If TIBB is in a loop and DestBB is outside of that loop, we may need
296 // to update LoopSimplify form and LCSSA form.
297 if (!TIL->contains(DestBB)) {
298 assert(!TIL->contains(NewBB) &&
299 "Split point for loop exit is contained in loop!");
301 // Update LCSSA form in the newly created exit block.
303 createPHIsForSplitLoopExit(TIBB, NewBB, DestBB);
306 // The only that we can break LoopSimplify form by splitting a critical
307 // edge is if after the split there exists some edge from TIL to DestBB
308 // *and* the only edge into DestBB from outside of TIL is that of
309 // NewBB. If the first isn't true, then LoopSimplify still holds, NewBB
310 // is the new exit block and it has no non-loop predecessors. If the
311 // second isn't true, then DestBB was not in LoopSimplify form prior to
312 // the split as it had a non-loop predecessor. In both of these cases,
313 // the predecessor must be directly in TIL, not in a subloop, or again
314 // LoopSimplify doesn't hold.
315 SmallVector<BasicBlock *, 4> LoopPreds;
316 for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB); I != E;
320 continue; // The new block is known.
321 if (LI->getLoopFor(P) != TIL) {
322 // No need to re-simplify, it wasn't to start with.
326 LoopPreds.push_back(P);
328 if (!LoopPreds.empty()) {
329 assert(!DestBB->isLandingPad() &&
330 "We don't split edges to landing pads!");
331 BasicBlock *NewExitBB = SplitBlockPredecessors(
332 DestBB, LoopPreds, "split", AA, DT, LI, PreserveLCSSA);
334 createPHIsForSplitLoopExit(LoopPreds, NewExitBB, DestBB);