LLVM  3.7.0
BreakCriticalEdges.cpp
Go to the documentation of this file.
1 //===- BreakCriticalEdges.cpp - Critical Edge Elimination Pass ------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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
14 // dominator trees.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "llvm/Transforms/Scalar.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.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"
31 using namespace llvm;
32 
33 #define DEBUG_TYPE "break-crit-edges"
34 
35 STATISTIC(NumBroken, "Number of blocks inserted");
36 
37 namespace {
38  struct BreakCriticalEdges : public FunctionPass {
39  static char ID; // Pass identification, replacement for typeid
40  BreakCriticalEdges() : FunctionPass(ID) {
42  }
43 
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;
49  unsigned N =
51  NumBroken += N;
52  return N > 0;
53  }
54 
55  void getAnalysisUsage(AnalysisUsage &AU) const override {
58 
59  // No loop canonicalization guarantees are broken by this pass.
61  }
62  };
63 }
64 
65 char BreakCriticalEdges::ID = 0;
66 INITIALIZE_PASS(BreakCriticalEdges, "break-crit-edges",
67  "Break critical edges in CFG", false, false)
68 
69 // Publicly exposed interface to pass...
70 char &llvm::BreakCriticalEdgesID = BreakCriticalEdges::ID;
72  return new BreakCriticalEdges();
73 }
74 
75 //===----------------------------------------------------------------------===//
76 // Implementation of the external critical edge manipulation functions
77 //===----------------------------------------------------------------------===//
78 
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.
85  BasicBlock *SplitBB,
86  BasicBlock *DestBB) {
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!");
90 
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);
96 
97  // If the input is a PHI which already satisfies LCSSA, don't create
98  // a new one.
99  if (const PHINode *VP = dyn_cast<PHINode>(V))
100  if (VP->getParent() == SplitBB)
101  continue;
102 
103  // Otherwise a new PHI is needed. Create one and populate it.
104  PHINode *NewPN =
105  PHINode::Create(PN->getType(), Preds.size(), "split",
106  SplitBB->isLandingPad() ?
107  SplitBB->begin() : SplitBB->getTerminator());
108  for (unsigned i = 0, e = Preds.size(); i != e; ++i)
109  NewPN->addIncoming(V, Preds[i]);
110 
111  // Update the original PHI.
112  PN->setIncomingValue(Idx, NewPN);
113  }
114 }
115 
116 /// SplitCriticalEdge - If this edge is a critical edge, insert a new node to
117 /// split the critical edge. This will update DominatorTree information if it
118 /// is available, thus calling this pass will not invalidate either of them.
119 /// This returns the new block if the edge was split, null otherwise.
120 ///
121 /// If MergeIdenticalEdges is true (not the default), *all* edges from TI to the
122 /// specified successor will be merged into the same critical edge block.
123 /// This is most commonly interesting with switch instructions, which may
124 /// have many edges to any one destination. This ensures that all edges to that
125 /// dest go to one block instead of each going to a different block, but isn't
126 /// the standard definition of a "critical edge".
127 ///
128 /// It is invalid to call this function on a critical edge that starts at an
129 /// IndirectBrInst. Splitting these edges will almost always create an invalid
130 /// program because the address of the new block won't be the one that is jumped
131 /// to.
132 ///
134  const CriticalEdgeSplittingOptions &Options) {
135  if (!isCriticalEdge(TI, SuccNum, Options.MergeIdenticalEdges))
136  return nullptr;
137 
138  assert(!isa<IndirectBrInst>(TI) &&
139  "Cannot split critical edge from IndirectBrInst");
140 
141  BasicBlock *TIBB = TI->getParent();
142  BasicBlock *DestBB = TI->getSuccessor(SuccNum);
143 
144  // Splitting the critical edge to a landing pad block is non-trivial. Don't do
145  // it in this generic function.
146  if (DestBB->isLandingPad()) return nullptr;
147 
148  // Create a new basic block, linking it into the CFG.
150  TIBB->getName() + "." + DestBB->getName() + "_crit_edge");
151  // Create our unconditional branch.
152  BranchInst *NewBI = BranchInst::Create(DestBB, NewBB);
153  NewBI->setDebugLoc(TI->getDebugLoc());
154 
155  // Branch to the new block, breaking the edge.
156  TI->setSuccessor(SuccNum, NewBB);
157 
158  // Insert the block into the function... right after the block TI lives in.
159  Function &F = *TIBB->getParent();
160  Function::iterator FBBI = TIBB;
161  F.getBasicBlockList().insert(++FBBI, NewBB);
162 
163  // If there are any PHI nodes in DestBB, we need to update them so that they
164  // merge incoming values from NewBB instead of from TIBB.
165  {
166  unsigned BBIdx = 0;
167  for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) {
168  // We no longer enter through TIBB, now we come in through NewBB.
169  // Revector exactly one entry in the PHI node that used to come from
170  // TIBB to come from NewBB.
171  PHINode *PN = cast<PHINode>(I);
172 
173  // Reuse the previous value of BBIdx if it lines up. In cases where we
174  // have multiple phi nodes with *lots* of predecessors, this is a speed
175  // win because we don't have to scan the PHI looking for TIBB. This
176  // happens because the BB list of PHI nodes are usually in the same
177  // order.
178  if (PN->getIncomingBlock(BBIdx) != TIBB)
179  BBIdx = PN->getBasicBlockIndex(TIBB);
180  PN->setIncomingBlock(BBIdx, NewBB);
181  }
182  }
183 
184  // If there are any other edges from TIBB to DestBB, update those to go
185  // through the split block, making those edges non-critical as well (and
186  // reducing the number of phi entries in the DestBB if relevant).
187  if (Options.MergeIdenticalEdges) {
188  for (unsigned i = SuccNum+1, e = TI->getNumSuccessors(); i != e; ++i) {
189  if (TI->getSuccessor(i) != DestBB) continue;
190 
191  // Remove an entry for TIBB from DestBB phi nodes.
192  DestBB->removePredecessor(TIBB, Options.DontDeleteUselessPHIs);
193 
194  // We found another edge to DestBB, go to NewBB instead.
195  TI->setSuccessor(i, NewBB);
196  }
197  }
198 
199  // If we have nothing to update, just return.
200  auto *AA = Options.AA;
201  auto *DT = Options.DT;
202  auto *LI = Options.LI;
203  if (!DT && !LI)
204  return NewBB;
205 
206  // Now update analysis information. Since the only predecessor of NewBB is
207  // the TIBB, TIBB clearly dominates NewBB. TIBB usually doesn't dominate
208  // anything, as there are other successors of DestBB. However, if all other
209  // predecessors of DestBB are already dominated by DestBB (e.g. DestBB is a
210  // loop header) then NewBB dominates DestBB.
211  SmallVector<BasicBlock*, 8> OtherPreds;
212 
213  // If there is a PHI in the block, loop over predecessors with it, which is
214  // faster than iterating pred_begin/end.
215  if (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
216  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
217  if (PN->getIncomingBlock(i) != NewBB)
218  OtherPreds.push_back(PN->getIncomingBlock(i));
219  } else {
220  for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB);
221  I != E; ++I) {
222  BasicBlock *P = *I;
223  if (P != NewBB)
224  OtherPreds.push_back(P);
225  }
226  }
227 
228  bool NewBBDominatesDestBB = true;
229 
230  // Should we update DominatorTree information?
231  if (DT) {
232  DomTreeNode *TINode = DT->getNode(TIBB);
233 
234  // The new block is not the immediate dominator for any other nodes, but
235  // TINode is the immediate dominator for the new node.
236  //
237  if (TINode) { // Don't break unreachable code!
238  DomTreeNode *NewBBNode = DT->addNewBlock(NewBB, TIBB);
239  DomTreeNode *DestBBNode = nullptr;
240 
241  // If NewBBDominatesDestBB hasn't been computed yet, do so with DT.
242  if (!OtherPreds.empty()) {
243  DestBBNode = DT->getNode(DestBB);
244  while (!OtherPreds.empty() && NewBBDominatesDestBB) {
245  if (DomTreeNode *OPNode = DT->getNode(OtherPreds.back()))
246  NewBBDominatesDestBB = DT->dominates(DestBBNode, OPNode);
247  OtherPreds.pop_back();
248  }
249  OtherPreds.clear();
250  }
251 
252  // If NewBBDominatesDestBB, then NewBB dominates DestBB, otherwise it
253  // doesn't dominate anything.
254  if (NewBBDominatesDestBB) {
255  if (!DestBBNode) DestBBNode = DT->getNode(DestBB);
256  DT->changeImmediateDominator(DestBBNode, NewBBNode);
257  }
258  }
259  }
260 
261  // Update LoopInfo if it is around.
262  if (LI) {
263  if (Loop *TIL = LI->getLoopFor(TIBB)) {
264  // If one or the other blocks were not in a loop, the new block is not
265  // either, and thus LI doesn't need to be updated.
266  if (Loop *DestLoop = LI->getLoopFor(DestBB)) {
267  if (TIL == DestLoop) {
268  // Both in the same loop, the NewBB joins loop.
269  DestLoop->addBasicBlockToLoop(NewBB, *LI);
270  } else if (TIL->contains(DestLoop)) {
271  // Edge from an outer loop to an inner loop. Add to the outer loop.
272  TIL->addBasicBlockToLoop(NewBB, *LI);
273  } else if (DestLoop->contains(TIL)) {
274  // Edge from an inner loop to an outer loop. Add to the outer loop.
275  DestLoop->addBasicBlockToLoop(NewBB, *LI);
276  } else {
277  // Edge from two loops with no containment relation. Because these
278  // are natural loops, we know that the destination block must be the
279  // header of its loop (adding a branch into a loop elsewhere would
280  // create an irreducible loop).
281  assert(DestLoop->getHeader() == DestBB &&
282  "Should not create irreducible loops!");
283  if (Loop *P = DestLoop->getParentLoop())
284  P->addBasicBlockToLoop(NewBB, *LI);
285  }
286  }
287 
288  // If TIBB is in a loop and DestBB is outside of that loop, we may need
289  // to update LoopSimplify form and LCSSA form.
290  if (!TIL->contains(DestBB)) {
291  assert(!TIL->contains(NewBB) &&
292  "Split point for loop exit is contained in loop!");
293 
294  // Update LCSSA form in the newly created exit block.
295  if (Options.PreserveLCSSA) {
296  createPHIsForSplitLoopExit(TIBB, NewBB, DestBB);
297  }
298 
299  // The only that we can break LoopSimplify form by splitting a critical
300  // edge is if after the split there exists some edge from TIL to DestBB
301  // *and* the only edge into DestBB from outside of TIL is that of
302  // NewBB. If the first isn't true, then LoopSimplify still holds, NewBB
303  // is the new exit block and it has no non-loop predecessors. If the
304  // second isn't true, then DestBB was not in LoopSimplify form prior to
305  // the split as it had a non-loop predecessor. In both of these cases,
306  // the predecessor must be directly in TIL, not in a subloop, or again
307  // LoopSimplify doesn't hold.
309  for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB); I != E;
310  ++I) {
311  BasicBlock *P = *I;
312  if (P == NewBB)
313  continue; // The new block is known.
314  if (LI->getLoopFor(P) != TIL) {
315  // No need to re-simplify, it wasn't to start with.
316  LoopPreds.clear();
317  break;
318  }
319  LoopPreds.push_back(P);
320  }
321  if (!LoopPreds.empty()) {
322  assert(!DestBB->isLandingPad() &&
323  "We don't split edges to landing pads!");
324  BasicBlock *NewExitBB = SplitBlockPredecessors(
325  DestBB, LoopPreds, "split", AA, DT, LI, Options.PreserveLCSSA);
326  if (Options.PreserveLCSSA)
327  createPHIsForSplitLoopExit(LoopPreds, NewExitBB, DestBB);
328  }
329  }
330  }
331  }
332 
333  return NewBB;
334 }
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
void removePredecessor(BasicBlock *Pred, bool DontDeleteUselessPHIs=false)
Notify the BasicBlock that the predecessor Pred is no longer able to reach it.
Definition: BasicBlock.cpp:266
void addIncoming(Value *V, BasicBlock *BB)
addIncoming - Add an incoming value to the end of the PHI list
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
STATISTIC(NumFunctions,"Total number of functions")
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:111
F(f)
unsigned SplitAllCriticalEdges(Function &F, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
void initializeBreakCriticalEdgesPass(PassRegistry &)
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:188
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:231
Option class for critical edge splitting.
Instruction * getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
Definition: BasicBlock.cpp:165
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
Definition: SmallVector.h:57
Base class for the actual dominator tree node.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: ArrayRef.h:31
AnalysisUsage & addPreservedID(const void *ID)
void setSuccessor(unsigned idx, BasicBlock *B)
Update the specified successor to point at the provided block.
Definition: InstrTypes.h:67
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:134
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
Definition: InstrTypes.h:57
BasicBlock * SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
SplitCriticalEdge - If this edge is a critical edge, insert a new node to split the critical edge...
#define P(N)
Subclasses of this class are all able to terminate a basic block.
Definition: InstrTypes.h:35
LLVM Basic Block Representation.
Definition: BasicBlock.h:65
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
Definition: InstrTypes.h:62
BranchInst - Conditional or Unconditional Branch instruction.
char & BreakCriticalEdgesID
FunctionPass * createBreakCriticalEdgesPass()
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:114
const DebugLoc & getDebugLoc() const
getDebugLoc - Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:230
Represent the analysis usage information of a pass.
BasicBlock * getIncomingBlock(unsigned i) const
getIncomingBlock - Return incoming basic block number i.
iterator insert(iterator where, NodeTy *New)
Definition: ilist.h:412
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:294
Interval::pred_iterator pred_end(Interval *I)
Definition: Interval.h:117
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:103
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:519
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:56
char & LoopSimplifyID
const BasicBlockListType & getBasicBlockList() const
Definition: Function.h:436
void setIncomingBlock(unsigned i, BasicBlock *BB)
Value * getIncomingValue(unsigned i) const
getIncomingValue - Return incoming value number x
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:222
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
LLVM_ATTRIBUTE_UNUSED_RESULT std::enable_if< !is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:285
#define I(x, y, z)
Definition: MD5.cpp:54
#define N
TerminatorInst * getTerminator()
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:124
bool isLandingPad() const
Return true if this basic block is a landing pad.
Definition: BasicBlock.cpp:413
LLVM Value Representation.
Definition: Value.h:69
The legacy pass manager's analysis pass to compute loop information.
Definition: LoopInfo.h:737
BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, AliasAnalysis *AA=nullptr, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, bool PreserveLCSSA=false)
SplitBlockPredecessors - This method introduces at least one new basic block into the function and mo...
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:203
static void createPHIsForSplitLoopExit(ArrayRef< BasicBlock * > Preds, BasicBlock *SplitBB, BasicBlock *DestBB)
createPHIsForSplitLoopExit - When a loop exit edge is split, LCSSA form may require new PHIs in the n...
void setIncomingValue(unsigned i, Value *V)
int getBasicBlockIndex(const BasicBlock *BB) const
getBasicBlockIndex - Return the first index of the specified basic block in the value list for this P...
const BasicBlock * getParent() const
Definition: Instruction.h:72
bool isCriticalEdge(const TerminatorInst *TI, unsigned SuccNum, bool AllowIdenticalEdges=false)
Return true if the specified edge is a critical edge.
Definition: CFG.cpp:87