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 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
46 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
47 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
48 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
50 SplitAllCriticalEdges(F, CriticalEdgeSplittingOptions(DT, LI));
55 void getAnalysisUsage(AnalysisUsage &AU) const override {
56 AU.addPreserved<DominatorTreeWrapperPass>();
57 AU.addPreserved<LoopInfoWrapperPass>();
59 // No loop canonicalization guarantees are broken by this pass.
60 AU.addPreservedID(LoopSimplifyID);
65 char BreakCriticalEdges::ID = 0;
66 INITIALIZE_PASS(BreakCriticalEdges, "break-crit-edges",
67 "Break critical edges in CFG", false, false)
69 // Publicly exposed interface to pass...
70 char &llvm::BreakCriticalEdgesID = BreakCriticalEdges::ID;
71 FunctionPass *llvm::createBreakCriticalEdgesPass() {
72 return new BreakCriticalEdges();
75 //===----------------------------------------------------------------------===//
76 // Implementation of the external critical edge manipulation functions
77 //===----------------------------------------------------------------------===//
79 /// createPHIsForSplitLoopExit - When a loop exit edge is split, LCSSA form
80 /// may require new PHIs in the new exit block. This function inserts the
81 /// new PHIs, as needed. Preds is a list of preds inside the loop, SplitBB
82 /// is the new loop exit block, and DestBB is the old loop exit, now the
83 /// successor of SplitBB.
84 static void createPHIsForSplitLoopExit(ArrayRef<BasicBlock *> Preds,
87 // SplitBB shouldn't have anything non-trivial in it yet.
88 assert((SplitBB->getFirstNonPHI() == SplitBB->getTerminator() ||
89 SplitBB->isLandingPad()) && "SplitBB has non-PHI nodes!");
91 // For each PHI in the destination block.
92 for (BasicBlock::iterator I = DestBB->begin();
93 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
94 unsigned Idx = PN->getBasicBlockIndex(SplitBB);
95 Value *V = PN->getIncomingValue(Idx);
97 // If the input is a PHI which already satisfies LCSSA, don't create
99 if (const PHINode *VP = dyn_cast<PHINode>(V))
100 if (VP->getParent() == SplitBB)
103 // Otherwise a new PHI is needed. Create one and populate it.
104 PHINode *NewPN = PHINode::Create(
105 PN->getType(), Preds.size(), "split",
106 SplitBB->isLandingPad() ? &SplitBB->front() : SplitBB->getTerminator());
107 for (unsigned i = 0, e = Preds.size(); i != e; ++i)
108 NewPN->addIncoming(V, Preds[i]);
110 // Update the original PHI.
111 PN->setIncomingValue(Idx, NewPN);
115 /// SplitCriticalEdge - If this edge is a critical edge, insert a new node to
116 /// split the critical edge. This will update DominatorTree information if it
117 /// is available, thus calling this pass will not invalidate either of them.
118 /// This returns the new block if the edge was split, null otherwise.
120 /// If MergeIdenticalEdges is true (not the default), *all* edges from TI to the
121 /// specified successor will be merged into the same critical edge block.
122 /// This is most commonly interesting with switch instructions, which may
123 /// have many edges to any one destination. This ensures that all edges to that
124 /// dest go to one block instead of each going to a different block, but isn't
125 /// the standard definition of a "critical edge".
127 /// It is invalid to call this function on a critical edge that starts at an
128 /// IndirectBrInst. Splitting these edges will almost always create an invalid
129 /// program because the address of the new block won't be the one that is jumped
132 BasicBlock *llvm::SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum,
133 const CriticalEdgeSplittingOptions &Options) {
134 if (!isCriticalEdge(TI, SuccNum, Options.MergeIdenticalEdges))
137 assert(!isa<IndirectBrInst>(TI) &&
138 "Cannot split critical edge from IndirectBrInst");
140 BasicBlock *TIBB = TI->getParent();
141 BasicBlock *DestBB = TI->getSuccessor(SuccNum);
143 // Splitting the critical edge to a pad block is non-trivial. Don't do
144 // it in this generic function.
145 if (DestBB->isEHPad()) return nullptr;
147 // Create a new basic block, linking it into the CFG.
148 BasicBlock *NewBB = BasicBlock::Create(TI->getContext(),
149 TIBB->getName() + "." + DestBB->getName() + "_crit_edge");
150 // Create our unconditional branch.
151 BranchInst *NewBI = BranchInst::Create(DestBB, NewBB);
152 NewBI->setDebugLoc(TI->getDebugLoc());
154 // Branch to the new block, breaking the edge.
155 TI->setSuccessor(SuccNum, NewBB);
157 // Insert the block into the function... right after the block TI lives in.
158 Function &F = *TIBB->getParent();
159 Function::iterator FBBI = TIBB->getIterator();
160 F.getBasicBlockList().insert(++FBBI, NewBB);
162 // If there are any PHI nodes in DestBB, we need to update them so that they
163 // merge incoming values from NewBB instead of from TIBB.
166 for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) {
167 // We no longer enter through TIBB, now we come in through NewBB.
168 // Revector exactly one entry in the PHI node that used to come from
169 // TIBB to come from NewBB.
170 PHINode *PN = cast<PHINode>(I);
172 // Reuse the previous value of BBIdx if it lines up. In cases where we
173 // have multiple phi nodes with *lots* of predecessors, this is a speed
174 // win because we don't have to scan the PHI looking for TIBB. This
175 // happens because the BB list of PHI nodes are usually in the same
177 if (PN->getIncomingBlock(BBIdx) != TIBB)
178 BBIdx = PN->getBasicBlockIndex(TIBB);
179 PN->setIncomingBlock(BBIdx, NewBB);
183 // If there are any other edges from TIBB to DestBB, update those to go
184 // through the split block, making those edges non-critical as well (and
185 // reducing the number of phi entries in the DestBB if relevant).
186 if (Options.MergeIdenticalEdges) {
187 for (unsigned i = SuccNum+1, e = TI->getNumSuccessors(); i != e; ++i) {
188 if (TI->getSuccessor(i) != DestBB) continue;
190 // Remove an entry for TIBB from DestBB phi nodes.
191 DestBB->removePredecessor(TIBB, Options.DontDeleteUselessPHIs);
193 // We found another edge to DestBB, go to NewBB instead.
194 TI->setSuccessor(i, NewBB);
198 // If we have nothing to update, just return.
199 auto *DT = Options.DT;
200 auto *LI = Options.LI;
204 // Now update analysis information. Since the only predecessor of NewBB is
205 // the TIBB, TIBB clearly dominates NewBB. TIBB usually doesn't dominate
206 // anything, as there are other successors of DestBB. However, if all other
207 // predecessors of DestBB are already dominated by DestBB (e.g. DestBB is a
208 // loop header) then NewBB dominates DestBB.
209 SmallVector<BasicBlock*, 8> OtherPreds;
211 // If there is a PHI in the block, loop over predecessors with it, which is
212 // faster than iterating pred_begin/end.
213 if (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
214 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
215 if (PN->getIncomingBlock(i) != NewBB)
216 OtherPreds.push_back(PN->getIncomingBlock(i));
218 for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB);
222 OtherPreds.push_back(P);
226 bool NewBBDominatesDestBB = true;
228 // Should we update DominatorTree information?
230 DomTreeNode *TINode = DT->getNode(TIBB);
232 // The new block is not the immediate dominator for any other nodes, but
233 // TINode is the immediate dominator for the new node.
235 if (TINode) { // Don't break unreachable code!
236 DomTreeNode *NewBBNode = DT->addNewBlock(NewBB, TIBB);
237 DomTreeNode *DestBBNode = nullptr;
239 // If NewBBDominatesDestBB hasn't been computed yet, do so with DT.
240 if (!OtherPreds.empty()) {
241 DestBBNode = DT->getNode(DestBB);
242 while (!OtherPreds.empty() && NewBBDominatesDestBB) {
243 if (DomTreeNode *OPNode = DT->getNode(OtherPreds.back()))
244 NewBBDominatesDestBB = DT->dominates(DestBBNode, OPNode);
245 OtherPreds.pop_back();
250 // If NewBBDominatesDestBB, then NewBB dominates DestBB, otherwise it
251 // doesn't dominate anything.
252 if (NewBBDominatesDestBB) {
253 if (!DestBBNode) DestBBNode = DT->getNode(DestBB);
254 DT->changeImmediateDominator(DestBBNode, NewBBNode);
259 // Update LoopInfo if it is around.
261 if (Loop *TIL = LI->getLoopFor(TIBB)) {
262 // If one or the other blocks were not in a loop, the new block is not
263 // either, and thus LI doesn't need to be updated.
264 if (Loop *DestLoop = LI->getLoopFor(DestBB)) {
265 if (TIL == DestLoop) {
266 // Both in the same loop, the NewBB joins loop.
267 DestLoop->addBasicBlockToLoop(NewBB, *LI);
268 } else if (TIL->contains(DestLoop)) {
269 // Edge from an outer loop to an inner loop. Add to the outer loop.
270 TIL->addBasicBlockToLoop(NewBB, *LI);
271 } else if (DestLoop->contains(TIL)) {
272 // Edge from an inner loop to an outer loop. Add to the outer loop.
273 DestLoop->addBasicBlockToLoop(NewBB, *LI);
275 // Edge from two loops with no containment relation. Because these
276 // are natural loops, we know that the destination block must be the
277 // header of its loop (adding a branch into a loop elsewhere would
278 // create an irreducible loop).
279 assert(DestLoop->getHeader() == DestBB &&
280 "Should not create irreducible loops!");
281 if (Loop *P = DestLoop->getParentLoop())
282 P->addBasicBlockToLoop(NewBB, *LI);
286 // If TIBB is in a loop and DestBB is outside of that loop, we may need
287 // to update LoopSimplify form and LCSSA form.
288 if (!TIL->contains(DestBB)) {
289 assert(!TIL->contains(NewBB) &&
290 "Split point for loop exit is contained in loop!");
292 // Update LCSSA form in the newly created exit block.
293 if (Options.PreserveLCSSA) {
294 createPHIsForSplitLoopExit(TIBB, NewBB, DestBB);
297 // The only that we can break LoopSimplify form by splitting a critical
298 // edge is if after the split there exists some edge from TIL to DestBB
299 // *and* the only edge into DestBB from outside of TIL is that of
300 // NewBB. If the first isn't true, then LoopSimplify still holds, NewBB
301 // is the new exit block and it has no non-loop predecessors. If the
302 // second isn't true, then DestBB was not in LoopSimplify form prior to
303 // the split as it had a non-loop predecessor. In both of these cases,
304 // the predecessor must be directly in TIL, not in a subloop, or again
305 // LoopSimplify doesn't hold.
306 SmallVector<BasicBlock *, 4> LoopPreds;
307 for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB); I != E;
311 continue; // The new block is known.
312 if (LI->getLoopFor(P) != TIL) {
313 // No need to re-simplify, it wasn't to start with.
317 LoopPreds.push_back(P);
319 if (!LoopPreds.empty()) {
320 assert(!DestBB->isEHPad() && "We don't split edges to EH pads!");
321 BasicBlock *NewExitBB = SplitBlockPredecessors(
322 DestBB, LoopPreds, "split", DT, LI, Options.PreserveLCSSA);
323 if (Options.PreserveLCSSA)
324 createPHIsForSplitLoopExit(LoopPreds, NewExitBB, DestBB);