1 //===-- BasicBlockUtils.cpp - BasicBlock Utilities -------------------------==//
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 // This family of functions perform manipulations on basic blocks, and
11 // instructions contained within basic blocks.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
16 #include "llvm/Analysis/AliasAnalysis.h"
17 #include "llvm/Analysis/CFG.h"
18 #include "llvm/Analysis/LoopInfo.h"
19 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
20 #include "llvm/IR/Constant.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Type.h"
27 #include "llvm/IR/ValueHandle.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Transforms/Scalar.h"
30 #include "llvm/Transforms/Utils/Local.h"
34 /// DeleteDeadBlock - Delete the specified block, which must have no
36 void llvm::DeleteDeadBlock(BasicBlock *BB) {
37 assert((pred_begin(BB) == pred_end(BB) ||
38 // Can delete self loop.
39 BB->getSinglePredecessor() == BB) && "Block is not dead!");
40 TerminatorInst *BBTerm = BB->getTerminator();
42 // Loop through all of our successors and make sure they know that one
43 // of their predecessors is going away.
44 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i)
45 BBTerm->getSuccessor(i)->removePredecessor(BB);
47 // Zap all the instructions in the block.
48 while (!BB->empty()) {
49 Instruction &I = BB->back();
50 // If this instruction is used, replace uses with an arbitrary value.
51 // Because control flow can't get here, we don't care what we replace the
52 // value with. Note that since this block is unreachable, and all values
53 // contained within it must dominate their uses, that all uses will
54 // eventually be removed (they are themselves dead).
56 I.replaceAllUsesWith(UndefValue::get(I.getType()));
57 BB->getInstList().pop_back();
61 BB->eraseFromParent();
64 /// FoldSingleEntryPHINodes - We know that BB has one predecessor. If there are
65 /// any single-entry PHI nodes in it, fold them away. This handles the case
66 /// when all entries to the PHI nodes in a block are guaranteed equal, such as
67 /// when the block has exactly one predecessor.
68 void llvm::FoldSingleEntryPHINodes(BasicBlock *BB, Pass *P) {
69 if (!isa<PHINode>(BB->begin())) return;
71 AliasAnalysis *AA = nullptr;
72 MemoryDependenceAnalysis *MemDep = nullptr;
74 AA = P->getAnalysisIfAvailable<AliasAnalysis>();
75 MemDep = P->getAnalysisIfAvailable<MemoryDependenceAnalysis>();
78 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
79 if (PN->getIncomingValue(0) != PN)
80 PN->replaceAllUsesWith(PN->getIncomingValue(0));
82 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
85 MemDep->removeInstruction(PN); // Memdep updates AA itself.
86 else if (AA && isa<PointerType>(PN->getType()))
89 PN->eraseFromParent();
94 /// DeleteDeadPHIs - Examine each PHI in the given block and delete it if it
95 /// is dead. Also recursively delete any operands that become dead as
96 /// a result. This includes tracing the def-use list from the PHI to see if
97 /// it is ultimately unused or if it reaches an unused cycle.
98 bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI) {
99 // Recursively deleting a PHI may cause multiple PHIs to be deleted
100 // or RAUW'd undef, so use an array of WeakVH for the PHIs to delete.
101 SmallVector<WeakVH, 8> PHIs;
102 for (BasicBlock::iterator I = BB->begin();
103 PHINode *PN = dyn_cast<PHINode>(I); ++I)
106 bool Changed = false;
107 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
108 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
109 Changed |= RecursivelyDeleteDeadPHINode(PN, TLI);
114 /// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
115 /// if possible. The return value indicates success or failure.
116 bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, Pass *P) {
117 // Don't merge away blocks who have their address taken.
118 if (BB->hasAddressTaken()) return false;
120 // Can't merge if there are multiple predecessors, or no predecessors.
121 BasicBlock *PredBB = BB->getUniquePredecessor();
122 if (!PredBB) return false;
124 // Don't break self-loops.
125 if (PredBB == BB) return false;
126 // Don't break invokes.
127 if (isa<InvokeInst>(PredBB->getTerminator())) return false;
129 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
130 BasicBlock *OnlySucc = BB;
131 for (; SI != SE; ++SI)
132 if (*SI != OnlySucc) {
133 OnlySucc = nullptr; // There are multiple distinct successors!
137 // Can't merge if there are multiple successors.
138 if (!OnlySucc) return false;
140 // Can't merge if there is PHI loop.
141 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
142 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
143 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
144 if (PN->getIncomingValue(i) == PN)
150 // Begin by getting rid of unneeded PHIs.
151 if (isa<PHINode>(BB->front()))
152 FoldSingleEntryPHINodes(BB, P);
154 // Delete the unconditional branch from the predecessor...
155 PredBB->getInstList().pop_back();
157 // Make all PHI nodes that referred to BB now refer to Pred as their
159 BB->replaceAllUsesWith(PredBB);
161 // Move all definitions in the successor to the predecessor...
162 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
164 // Inherit predecessors name if it exists.
165 if (!PredBB->hasName())
166 PredBB->takeName(BB);
168 // Finally, erase the old block and update dominator info.
170 if (DominatorTreeWrapperPass *DTWP =
171 P->getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
172 DominatorTree &DT = DTWP->getDomTree();
173 if (DomTreeNode *DTN = DT.getNode(BB)) {
174 DomTreeNode *PredDTN = DT.getNode(PredBB);
175 SmallVector<DomTreeNode*, 8> Children(DTN->begin(), DTN->end());
176 for (SmallVectorImpl<DomTreeNode *>::iterator DI = Children.begin(),
177 DE = Children.end(); DI != DE; ++DI)
178 DT.changeImmediateDominator(*DI, PredDTN);
183 if (auto *LIWP = P->getAnalysisIfAvailable<LoopInfoWrapperPass>())
184 LIWP->getLoopInfo().removeBlock(BB);
186 if (MemoryDependenceAnalysis *MD =
187 P->getAnalysisIfAvailable<MemoryDependenceAnalysis>())
188 MD->invalidateCachedPredecessors();
192 BB->eraseFromParent();
196 /// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
197 /// with a value, then remove and delete the original instruction.
199 void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
200 BasicBlock::iterator &BI, Value *V) {
201 Instruction &I = *BI;
202 // Replaces all of the uses of the instruction with uses of the value
203 I.replaceAllUsesWith(V);
205 // Make sure to propagate a name if there is one already.
206 if (I.hasName() && !V->hasName())
209 // Delete the unnecessary instruction now...
214 /// ReplaceInstWithInst - Replace the instruction specified by BI with the
215 /// instruction specified by I. The original instruction is deleted and BI is
216 /// updated to point to the new instruction.
218 void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
219 BasicBlock::iterator &BI, Instruction *I) {
220 assert(I->getParent() == nullptr &&
221 "ReplaceInstWithInst: Instruction already inserted into basic block!");
223 // Insert the new instruction into the basic block...
224 BasicBlock::iterator New = BIL.insert(BI, I);
226 // Replace all uses of the old instruction, and delete it.
227 ReplaceInstWithValue(BIL, BI, I);
229 // Move BI back to point to the newly inserted instruction
233 /// ReplaceInstWithInst - Replace the instruction specified by From with the
234 /// instruction specified by To.
236 void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
237 BasicBlock::iterator BI(From);
238 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
241 /// SplitEdge - Split the edge connecting specified block. Pass P must
243 BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
244 unsigned SuccNum = GetSuccessorNumber(BB, Succ);
246 // If this is a critical edge, let SplitCriticalEdge do it.
247 TerminatorInst *LatchTerm = BB->getTerminator();
248 if (SplitCriticalEdge(LatchTerm, SuccNum, P))
249 return LatchTerm->getSuccessor(SuccNum);
251 // If the edge isn't critical, then BB has a single successor or Succ has a
252 // single pred. Split the block.
253 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
254 // If the successor only has a single pred, split the top of the successor
256 assert(SP == BB && "CFG broken");
258 return SplitBlock(Succ, Succ->begin(), P);
261 // Otherwise, if BB has a single successor, split it at the bottom of the
263 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
264 "Should have a single succ!");
265 return SplitBlock(BB, BB->getTerminator(), P);
268 unsigned llvm::SplitAllCriticalEdges(Function &F, Pass *P) {
269 unsigned NumBroken = 0;
270 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
271 TerminatorInst *TI = I->getTerminator();
272 if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
273 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
274 if (SplitCriticalEdge(TI, i, P))
280 /// SplitBlock - Split the specified block at the specified instruction - every
281 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
282 /// to a new block. The two blocks are joined by an unconditional branch and
283 /// the loop info is updated.
285 BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P) {
286 BasicBlock::iterator SplitIt = SplitPt;
287 while (isa<PHINode>(SplitIt) || isa<LandingPadInst>(SplitIt))
289 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
291 // The new block lives in whichever loop the old one did. This preserves
292 // LCSSA as well, because we force the split point to be after any PHI nodes.
293 if (auto *LIWP = P->getAnalysisIfAvailable<LoopInfoWrapperPass>()) {
294 LoopInfo &LI = LIWP->getLoopInfo();
295 if (Loop *L = LI.getLoopFor(Old))
296 L->addBasicBlockToLoop(New, LI.getBase());
299 if (DominatorTreeWrapperPass *DTWP =
300 P->getAnalysisIfAvailable<DominatorTreeWrapperPass>()) {
301 DominatorTree &DT = DTWP->getDomTree();
302 // Old dominates New. New node dominates all other nodes dominated by Old.
303 if (DomTreeNode *OldNode = DT.getNode(Old)) {
304 std::vector<DomTreeNode *> Children;
305 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
307 Children.push_back(*I);
309 DomTreeNode *NewNode = DT.addNewBlock(New, Old);
310 for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
311 E = Children.end(); I != E; ++I)
312 DT.changeImmediateDominator(*I, NewNode);
319 /// UpdateAnalysisInformation - Update DominatorTree, LoopInfo, and LCCSA
320 /// analysis information.
321 static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
322 ArrayRef<BasicBlock *> Preds,
323 Pass *P, bool &HasLoopExit) {
326 auto *LIWP = P->getAnalysisIfAvailable<LoopInfoWrapperPass>();
327 LoopInfo *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
328 Loop *L = LI ? LI->getLoopFor(OldBB) : nullptr;
330 // If we need to preserve loop analyses, collect some information about how
331 // this split will affect loops.
332 bool IsLoopEntry = !!L;
333 bool SplitMakesNewLoopHeader = false;
335 bool PreserveLCSSA = P->mustPreserveAnalysisID(LCSSAID);
336 for (ArrayRef<BasicBlock*>::iterator
337 i = Preds.begin(), e = Preds.end(); i != e; ++i) {
338 BasicBlock *Pred = *i;
340 // If we need to preserve LCSSA, determine if any of the preds is a loop
343 if (Loop *PL = LI->getLoopFor(Pred))
344 if (!PL->contains(OldBB))
347 // If we need to preserve LoopInfo, note whether any of the preds crosses
348 // an interesting loop boundary.
350 if (L->contains(Pred))
353 SplitMakesNewLoopHeader = true;
357 // Update dominator tree if available.
358 if (DominatorTreeWrapperPass *DTWP =
359 P->getAnalysisIfAvailable<DominatorTreeWrapperPass>())
360 DTWP->getDomTree().splitBlock(NewBB);
365 // Add the new block to the nearest enclosing loop (and not an adjacent
366 // loop). To find this, examine each of the predecessors and determine which
367 // loops enclose them, and select the most-nested loop which contains the
368 // loop containing the block being split.
369 Loop *InnermostPredLoop = nullptr;
370 for (ArrayRef<BasicBlock*>::iterator
371 i = Preds.begin(), e = Preds.end(); i != e; ++i) {
372 BasicBlock *Pred = *i;
373 if (Loop *PredLoop = LI->getLoopFor(Pred)) {
374 // Seek a loop which actually contains the block being split (to avoid
376 while (PredLoop && !PredLoop->contains(OldBB))
377 PredLoop = PredLoop->getParentLoop();
379 // Select the most-nested of these loops which contains the block.
380 if (PredLoop && PredLoop->contains(OldBB) &&
381 (!InnermostPredLoop ||
382 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
383 InnermostPredLoop = PredLoop;
387 if (InnermostPredLoop)
388 InnermostPredLoop->addBasicBlockToLoop(NewBB, LI->getBase());
390 L->addBasicBlockToLoop(NewBB, LI->getBase());
391 if (SplitMakesNewLoopHeader)
392 L->moveToHeader(NewBB);
396 /// UpdatePHINodes - Update the PHI nodes in OrigBB to include the values coming
397 /// from NewBB. This also updates AliasAnalysis, if available.
398 static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
399 ArrayRef<BasicBlock*> Preds, BranchInst *BI,
400 Pass *P, bool HasLoopExit) {
401 // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
402 AliasAnalysis *AA = P ? P->getAnalysisIfAvailable<AliasAnalysis>() : nullptr;
403 SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
404 for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
405 PHINode *PN = cast<PHINode>(I++);
407 // Check to see if all of the values coming in are the same. If so, we
408 // don't need to create a new PHI node, unless it's needed for LCSSA.
409 Value *InVal = nullptr;
411 InVal = PN->getIncomingValueForBlock(Preds[0]);
412 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
413 if (!PredSet.count(PN->getIncomingBlock(i)))
416 InVal = PN->getIncomingValue(i);
417 else if (InVal != PN->getIncomingValue(i)) {
425 // If all incoming values for the new PHI would be the same, just don't
426 // make a new PHI. Instead, just remove the incoming values from the old
429 // NOTE! This loop walks backwards for a reason! First off, this minimizes
430 // the cost of removal if we end up removing a large number of values, and
431 // second off, this ensures that the indices for the incoming values
432 // aren't invalidated when we remove one.
433 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i)
434 if (PredSet.count(PN->getIncomingBlock(i)))
435 PN->removeIncomingValue(i, false);
437 // Add an incoming value to the PHI node in the loop for the preheader
439 PN->addIncoming(InVal, NewBB);
443 // If the values coming into the block are not the same, we need a new
445 // Create the new PHI node, insert it into NewBB at the end of the block
447 PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
449 AA->copyValue(PN, NewPHI);
451 // NOTE! This loop walks backwards for a reason! First off, this minimizes
452 // the cost of removal if we end up removing a large number of values, and
453 // second off, this ensures that the indices for the incoming values aren't
454 // invalidated when we remove one.
455 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
456 BasicBlock *IncomingBB = PN->getIncomingBlock(i);
457 if (PredSet.count(IncomingBB)) {
458 Value *V = PN->removeIncomingValue(i, false);
459 NewPHI->addIncoming(V, IncomingBB);
463 PN->addIncoming(NewPHI, NewBB);
467 /// SplitBlockPredecessors - This method transforms BB by introducing a new
468 /// basic block into the function, and moving some of the predecessors of BB to
469 /// be predecessors of the new block. The new predecessors are indicated by the
470 /// Preds array, which has NumPreds elements in it. The new block is given a
471 /// suffix of 'Suffix'.
473 /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
474 /// LoopInfo, and LCCSA but no other analyses. In particular, it does not
475 /// preserve LoopSimplify (because it's complicated to handle the case where one
476 /// of the edges being split is an exit of a loop with other exits).
478 BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
479 ArrayRef<BasicBlock*> Preds,
480 const char *Suffix, Pass *P) {
481 // Create new basic block, insert right before the original block.
482 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), BB->getName()+Suffix,
483 BB->getParent(), BB);
485 // The new block unconditionally branches to the old block.
486 BranchInst *BI = BranchInst::Create(BB, NewBB);
488 // Move the edges from Preds to point to NewBB instead of BB.
489 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
490 // This is slightly more strict than necessary; the minimum requirement
491 // is that there be no more than one indirectbr branching to BB. And
492 // all BlockAddress uses would need to be updated.
493 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
494 "Cannot split an edge from an IndirectBrInst");
495 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
498 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
499 // node becomes an incoming value for BB's phi node. However, if the Preds
500 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
501 // account for the newly created predecessor.
502 if (Preds.size() == 0) {
503 // Insert dummy values as the incoming value.
504 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
505 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
509 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
510 bool HasLoopExit = false;
511 UpdateAnalysisInformation(BB, NewBB, Preds, P, HasLoopExit);
513 // Update the PHI nodes in BB with the values coming from NewBB.
514 UpdatePHINodes(BB, NewBB, Preds, BI, P, HasLoopExit);
518 /// SplitLandingPadPredecessors - This method transforms the landing pad,
519 /// OrigBB, by introducing two new basic blocks into the function. One of those
520 /// new basic blocks gets the predecessors listed in Preds. The other basic
521 /// block gets the remaining predecessors of OrigBB. The landingpad instruction
522 /// OrigBB is clone into both of the new basic blocks. The new blocks are given
523 /// the suffixes 'Suffix1' and 'Suffix2', and are returned in the NewBBs vector.
525 /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
526 /// DominanceFrontier, LoopInfo, and LCCSA but no other analyses. In particular,
527 /// it does not preserve LoopSimplify (because it's complicated to handle the
528 /// case where one of the edges being split is an exit of a loop with other
531 void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
532 ArrayRef<BasicBlock*> Preds,
533 const char *Suffix1, const char *Suffix2,
535 SmallVectorImpl<BasicBlock*> &NewBBs) {
536 assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
538 // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
539 // it right before the original block.
540 BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
541 OrigBB->getName() + Suffix1,
542 OrigBB->getParent(), OrigBB);
543 NewBBs.push_back(NewBB1);
545 // The new block unconditionally branches to the old block.
546 BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
548 // Move the edges from Preds to point to NewBB1 instead of OrigBB.
549 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
550 // This is slightly more strict than necessary; the minimum requirement
551 // is that there be no more than one indirectbr branching to BB. And
552 // all BlockAddress uses would need to be updated.
553 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
554 "Cannot split an edge from an IndirectBrInst");
555 Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
558 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
559 bool HasLoopExit = false;
560 UpdateAnalysisInformation(OrigBB, NewBB1, Preds, P, HasLoopExit);
562 // Update the PHI nodes in OrigBB with the values coming from NewBB1.
563 UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, P, HasLoopExit);
565 // Move the remaining edges from OrigBB to point to NewBB2.
566 SmallVector<BasicBlock*, 8> NewBB2Preds;
567 for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
569 BasicBlock *Pred = *i++;
570 if (Pred == NewBB1) continue;
571 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
572 "Cannot split an edge from an IndirectBrInst");
573 NewBB2Preds.push_back(Pred);
574 e = pred_end(OrigBB);
577 BasicBlock *NewBB2 = nullptr;
578 if (!NewBB2Preds.empty()) {
579 // Create another basic block for the rest of OrigBB's predecessors.
580 NewBB2 = BasicBlock::Create(OrigBB->getContext(),
581 OrigBB->getName() + Suffix2,
582 OrigBB->getParent(), OrigBB);
583 NewBBs.push_back(NewBB2);
585 // The new block unconditionally branches to the old block.
586 BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
588 // Move the remaining edges from OrigBB to point to NewBB2.
589 for (SmallVectorImpl<BasicBlock*>::iterator
590 i = NewBB2Preds.begin(), e = NewBB2Preds.end(); i != e; ++i)
591 (*i)->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
593 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
595 UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, P, HasLoopExit);
597 // Update the PHI nodes in OrigBB with the values coming from NewBB2.
598 UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, P, HasLoopExit);
601 LandingPadInst *LPad = OrigBB->getLandingPadInst();
602 Instruction *Clone1 = LPad->clone();
603 Clone1->setName(Twine("lpad") + Suffix1);
604 NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1);
607 Instruction *Clone2 = LPad->clone();
608 Clone2->setName(Twine("lpad") + Suffix2);
609 NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2);
611 // Create a PHI node for the two cloned landingpad instructions.
612 PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
613 PN->addIncoming(Clone1, NewBB1);
614 PN->addIncoming(Clone2, NewBB2);
615 LPad->replaceAllUsesWith(PN);
616 LPad->eraseFromParent();
618 // There is no second clone. Just replace the landing pad with the first
620 LPad->replaceAllUsesWith(Clone1);
621 LPad->eraseFromParent();
625 /// FoldReturnIntoUncondBranch - This method duplicates the specified return
626 /// instruction into a predecessor which ends in an unconditional branch. If
627 /// the return instruction returns a value defined by a PHI, propagate the
628 /// right value into the return. It returns the new return instruction in the
630 ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
632 Instruction *UncondBranch = Pred->getTerminator();
633 // Clone the return and add it to the end of the predecessor.
634 Instruction *NewRet = RI->clone();
635 Pred->getInstList().push_back(NewRet);
637 // If the return instruction returns a value, and if the value was a
638 // PHI node in "BB", propagate the right value into the return.
639 for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
642 Instruction *NewBC = nullptr;
643 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
644 // Return value might be bitcasted. Clone and insert it before the
645 // return instruction.
646 V = BCI->getOperand(0);
647 NewBC = BCI->clone();
648 Pred->getInstList().insert(NewRet, NewBC);
651 if (PHINode *PN = dyn_cast<PHINode>(V)) {
652 if (PN->getParent() == BB) {
654 NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
656 *i = PN->getIncomingValueForBlock(Pred);
661 // Update any PHI nodes in the returning block to realize that we no
662 // longer branch to them.
663 BB->removePredecessor(Pred);
664 UncondBranch->eraseFromParent();
665 return cast<ReturnInst>(NewRet);
668 /// SplitBlockAndInsertIfThen - Split the containing block at the
669 /// specified instruction - everything before and including SplitBefore stays
670 /// in the old basic block, and everything after SplitBefore is moved to a
671 /// new block. The two blocks are connected by a conditional branch
672 /// (with value of Cmp being the condition).
684 /// If Unreachable is true, then ThenBlock ends with
685 /// UnreachableInst, otherwise it branches to Tail.
686 /// Returns the NewBasicBlock's terminator.
688 TerminatorInst *llvm::SplitBlockAndInsertIfThen(Value *Cond,
689 Instruction *SplitBefore,
691 MDNode *BranchWeights,
693 BasicBlock *Head = SplitBefore->getParent();
694 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
695 TerminatorInst *HeadOldTerm = Head->getTerminator();
696 LLVMContext &C = Head->getContext();
697 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
698 TerminatorInst *CheckTerm;
700 CheckTerm = new UnreachableInst(C, ThenBlock);
702 CheckTerm = BranchInst::Create(Tail, ThenBlock);
703 CheckTerm->setDebugLoc(SplitBefore->getDebugLoc());
704 BranchInst *HeadNewTerm =
705 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cond);
706 HeadNewTerm->setDebugLoc(SplitBefore->getDebugLoc());
707 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
708 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
711 if (DomTreeNode *OldNode = DT->getNode(Head)) {
712 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
714 DomTreeNode *NewNode = DT->addNewBlock(Tail, Head);
715 for (auto Child : Children)
716 DT->changeImmediateDominator(Child, NewNode);
718 // Head dominates ThenBlock.
719 DT->addNewBlock(ThenBlock, Head);
726 /// SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen,
727 /// but also creates the ElseBlock.
740 void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
741 TerminatorInst **ThenTerm,
742 TerminatorInst **ElseTerm,
743 MDNode *BranchWeights) {
744 BasicBlock *Head = SplitBefore->getParent();
745 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
746 TerminatorInst *HeadOldTerm = Head->getTerminator();
747 LLVMContext &C = Head->getContext();
748 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
749 BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
750 *ThenTerm = BranchInst::Create(Tail, ThenBlock);
751 (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc());
752 *ElseTerm = BranchInst::Create(Tail, ElseBlock);
753 (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc());
754 BranchInst *HeadNewTerm =
755 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond);
756 HeadNewTerm->setDebugLoc(SplitBefore->getDebugLoc());
757 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
758 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
762 /// GetIfCondition - Given a basic block (BB) with two predecessors,
763 /// check to see if the merge at this block is due
764 /// to an "if condition". If so, return the boolean condition that determines
765 /// which entry into BB will be taken. Also, return by references the block
766 /// that will be entered from if the condition is true, and the block that will
767 /// be entered if the condition is false.
769 /// This does no checking to see if the true/false blocks have large or unsavory
770 /// instructions in them.
771 Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
772 BasicBlock *&IfFalse) {
773 PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
774 BasicBlock *Pred1 = nullptr;
775 BasicBlock *Pred2 = nullptr;
778 if (SomePHI->getNumIncomingValues() != 2)
780 Pred1 = SomePHI->getIncomingBlock(0);
781 Pred2 = SomePHI->getIncomingBlock(1);
783 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
784 if (PI == PE) // No predecessor
787 if (PI == PE) // Only one predecessor
790 if (PI != PE) // More than two predecessors
794 // We can only handle branches. Other control flow will be lowered to
795 // branches if possible anyway.
796 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
797 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
798 if (!Pred1Br || !Pred2Br)
801 // Eliminate code duplication by ensuring that Pred1Br is conditional if
803 if (Pred2Br->isConditional()) {
804 // If both branches are conditional, we don't have an "if statement". In
805 // reality, we could transform this case, but since the condition will be
806 // required anyway, we stand no chance of eliminating it, so the xform is
807 // probably not profitable.
808 if (Pred1Br->isConditional())
811 std::swap(Pred1, Pred2);
812 std::swap(Pred1Br, Pred2Br);
815 if (Pred1Br->isConditional()) {
816 // The only thing we have to watch out for here is to make sure that Pred2
817 // doesn't have incoming edges from other blocks. If it does, the condition
818 // doesn't dominate BB.
819 if (!Pred2->getSinglePredecessor())
822 // If we found a conditional branch predecessor, make sure that it branches
823 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
824 if (Pred1Br->getSuccessor(0) == BB &&
825 Pred1Br->getSuccessor(1) == Pred2) {
828 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
829 Pred1Br->getSuccessor(1) == BB) {
833 // We know that one arm of the conditional goes to BB, so the other must
834 // go somewhere unrelated, and this must not be an "if statement".
838 return Pred1Br->getCondition();
841 // Ok, if we got here, both predecessors end with an unconditional branch to
842 // BB. Don't panic! If both blocks only have a single (identical)
843 // predecessor, and THAT is a conditional branch, then we're all ok!
844 BasicBlock *CommonPred = Pred1->getSinglePredecessor();
845 if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
848 // Otherwise, if this is a conditional branch, then we can use it!
849 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
850 if (!BI) return nullptr;
852 assert(BI->isConditional() && "Two successors but not conditional?");
853 if (BI->getSuccessor(0) == Pred1) {
860 return BI->getCondition();