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, AliasAnalysis *AA,
69 MemoryDependenceAnalysis *MemDep) {
70 if (!isa<PHINode>(BB->begin())) return;
72 while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
73 if (PN->getIncomingValue(0) != PN)
74 PN->replaceAllUsesWith(PN->getIncomingValue(0));
76 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
79 MemDep->removeInstruction(PN); // Memdep updates AA itself.
80 else if (AA && isa<PointerType>(PN->getType()))
83 PN->eraseFromParent();
88 /// DeleteDeadPHIs - Examine each PHI in the given block and delete it if it
89 /// is dead. Also recursively delete any operands that become dead as
90 /// a result. This includes tracing the def-use list from the PHI to see if
91 /// it is ultimately unused or if it reaches an unused cycle.
92 bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI) {
93 // Recursively deleting a PHI may cause multiple PHIs to be deleted
94 // or RAUW'd undef, so use an array of WeakVH for the PHIs to delete.
95 SmallVector<WeakVH, 8> PHIs;
96 for (BasicBlock::iterator I = BB->begin();
97 PHINode *PN = dyn_cast<PHINode>(I); ++I)
100 bool Changed = false;
101 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
102 if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
103 Changed |= RecursivelyDeleteDeadPHINode(PN, TLI);
108 /// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
109 /// if possible. The return value indicates success or failure.
110 bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, DominatorTree *DT,
111 LoopInfo *LI, AliasAnalysis *AA,
112 MemoryDependenceAnalysis *MemDep) {
113 // Don't merge away blocks who have their address taken.
114 if (BB->hasAddressTaken()) return false;
116 // Can't merge if there are multiple predecessors, or no predecessors.
117 BasicBlock *PredBB = BB->getUniquePredecessor();
118 if (!PredBB) return false;
120 // Don't break self-loops.
121 if (PredBB == BB) return false;
122 // Don't break invokes.
123 if (isa<InvokeInst>(PredBB->getTerminator())) return false;
125 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
126 BasicBlock *OnlySucc = BB;
127 for (; SI != SE; ++SI)
128 if (*SI != OnlySucc) {
129 OnlySucc = nullptr; // There are multiple distinct successors!
133 // Can't merge if there are multiple successors.
134 if (!OnlySucc) return false;
136 // Can't merge if there is PHI loop.
137 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
138 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
139 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
140 if (PN->getIncomingValue(i) == PN)
146 // Begin by getting rid of unneeded PHIs.
147 if (isa<PHINode>(BB->front()))
148 FoldSingleEntryPHINodes(BB, AA, MemDep);
150 // Delete the unconditional branch from the predecessor...
151 PredBB->getInstList().pop_back();
153 // Make all PHI nodes that referred to BB now refer to Pred as their
155 BB->replaceAllUsesWith(PredBB);
157 // Move all definitions in the successor to the predecessor...
158 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
160 // Inherit predecessors name if it exists.
161 if (!PredBB->hasName())
162 PredBB->takeName(BB);
164 // Finally, erase the old block and update dominator info.
166 if (DomTreeNode *DTN = DT->getNode(BB)) {
167 DomTreeNode *PredDTN = DT->getNode(PredBB);
168 SmallVector<DomTreeNode *, 8> Children(DTN->begin(), DTN->end());
169 for (SmallVectorImpl<DomTreeNode *>::iterator DI = Children.begin(),
172 DT->changeImmediateDominator(*DI, PredDTN);
181 MemDep->invalidateCachedPredecessors();
183 BB->eraseFromParent();
187 /// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
188 /// with a value, then remove and delete the original instruction.
190 void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
191 BasicBlock::iterator &BI, Value *V) {
192 Instruction &I = *BI;
193 // Replaces all of the uses of the instruction with uses of the value
194 I.replaceAllUsesWith(V);
196 // Make sure to propagate a name if there is one already.
197 if (I.hasName() && !V->hasName())
200 // Delete the unnecessary instruction now...
205 /// ReplaceInstWithInst - Replace the instruction specified by BI with the
206 /// instruction specified by I. The original instruction is deleted and BI is
207 /// updated to point to the new instruction.
209 void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
210 BasicBlock::iterator &BI, Instruction *I) {
211 assert(I->getParent() == nullptr &&
212 "ReplaceInstWithInst: Instruction already inserted into basic block!");
214 // Insert the new instruction into the basic block...
215 BasicBlock::iterator New = BIL.insert(BI, I);
217 // Replace all uses of the old instruction, and delete it.
218 ReplaceInstWithValue(BIL, BI, I);
220 // Move BI back to point to the newly inserted instruction
224 /// ReplaceInstWithInst - Replace the instruction specified by From with the
225 /// instruction specified by To.
227 void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
228 BasicBlock::iterator BI(From);
229 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
232 /// SplitEdge - Split the edge connecting specified block. Pass P must
234 BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, Pass *P) {
235 unsigned SuccNum = GetSuccessorNumber(BB, Succ);
237 // If this is a critical edge, let SplitCriticalEdge do it.
238 TerminatorInst *LatchTerm = BB->getTerminator();
239 if (SplitCriticalEdge(LatchTerm, SuccNum, P))
240 return LatchTerm->getSuccessor(SuccNum);
242 auto *DTWP = P->getAnalysisIfAvailable<DominatorTreeWrapperPass>();
243 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
244 auto *LIWP = P->getAnalysisIfAvailable<LoopInfoWrapperPass>();
245 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
247 // If the edge isn't critical, then BB has a single successor or Succ has a
248 // single pred. Split the block.
249 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
250 // If the successor only has a single pred, split the top of the successor
252 assert(SP == BB && "CFG broken");
254 return SplitBlock(Succ, Succ->begin(), DT, LI);
257 // Otherwise, if BB has a single successor, split it at the bottom of the
259 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
260 "Should have a single succ!");
261 return SplitBlock(BB, BB->getTerminator(), DT, LI);
264 unsigned llvm::SplitAllCriticalEdges(Function &F, Pass *P) {
265 unsigned NumBroken = 0;
266 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
267 TerminatorInst *TI = I->getTerminator();
268 if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
269 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
270 if (SplitCriticalEdge(TI, i, P))
276 /// SplitBlock - Split the specified block at the specified instruction - every
277 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
278 /// to a new block. The two blocks are joined by an unconditional branch and
279 /// the loop info is updated.
281 BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt,
282 DominatorTree *DT, LoopInfo *LI) {
283 BasicBlock::iterator SplitIt = SplitPt;
284 while (isa<PHINode>(SplitIt) || isa<LandingPadInst>(SplitIt))
286 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
288 // The new block lives in whichever loop the old one did. This preserves
289 // LCSSA as well, because we force the split point to be after any PHI nodes.
291 if (Loop *L = LI->getLoopFor(Old))
292 L->addBasicBlockToLoop(New, *LI);
295 // Old dominates New. New node dominates all other nodes dominated by Old.
296 if (DomTreeNode *OldNode = DT->getNode(Old)) {
297 std::vector<DomTreeNode *> Children;
298 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
300 Children.push_back(*I);
302 DomTreeNode *NewNode = DT->addNewBlock(New, Old);
303 for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
304 E = Children.end(); I != E; ++I)
305 DT->changeImmediateDominator(*I, NewNode);
311 /// UpdateAnalysisInformation - Update DominatorTree, LoopInfo, and LCCSA
312 /// analysis information.
313 static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
314 ArrayRef<BasicBlock *> Preds,
315 Pass *P, bool &HasLoopExit) {
318 auto *LIWP = P->getAnalysisIfAvailable<LoopInfoWrapperPass>();
319 LoopInfo *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
320 Loop *L = LI ? LI->getLoopFor(OldBB) : nullptr;
322 // If we need to preserve loop analyses, collect some information about how
323 // this split will affect loops.
324 bool IsLoopEntry = !!L;
325 bool SplitMakesNewLoopHeader = false;
327 bool PreserveLCSSA = P->mustPreserveAnalysisID(LCSSAID);
328 for (ArrayRef<BasicBlock*>::iterator
329 i = Preds.begin(), e = Preds.end(); i != e; ++i) {
330 BasicBlock *Pred = *i;
332 // If we need to preserve LCSSA, determine if any of the preds is a loop
335 if (Loop *PL = LI->getLoopFor(Pred))
336 if (!PL->contains(OldBB))
339 // If we need to preserve LoopInfo, note whether any of the preds crosses
340 // an interesting loop boundary.
342 if (L->contains(Pred))
345 SplitMakesNewLoopHeader = true;
349 // Update dominator tree if available.
350 if (DominatorTreeWrapperPass *DTWP =
351 P->getAnalysisIfAvailable<DominatorTreeWrapperPass>())
352 DTWP->getDomTree().splitBlock(NewBB);
357 // Add the new block to the nearest enclosing loop (and not an adjacent
358 // loop). To find this, examine each of the predecessors and determine which
359 // loops enclose them, and select the most-nested loop which contains the
360 // loop containing the block being split.
361 Loop *InnermostPredLoop = nullptr;
362 for (ArrayRef<BasicBlock*>::iterator
363 i = Preds.begin(), e = Preds.end(); i != e; ++i) {
364 BasicBlock *Pred = *i;
365 if (Loop *PredLoop = LI->getLoopFor(Pred)) {
366 // Seek a loop which actually contains the block being split (to avoid
368 while (PredLoop && !PredLoop->contains(OldBB))
369 PredLoop = PredLoop->getParentLoop();
371 // Select the most-nested of these loops which contains the block.
372 if (PredLoop && PredLoop->contains(OldBB) &&
373 (!InnermostPredLoop ||
374 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
375 InnermostPredLoop = PredLoop;
379 if (InnermostPredLoop)
380 InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
382 L->addBasicBlockToLoop(NewBB, *LI);
383 if (SplitMakesNewLoopHeader)
384 L->moveToHeader(NewBB);
388 /// UpdatePHINodes - Update the PHI nodes in OrigBB to include the values coming
389 /// from NewBB. This also updates AliasAnalysis, if available.
390 static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
391 ArrayRef<BasicBlock*> Preds, BranchInst *BI,
392 Pass *P, bool HasLoopExit) {
393 // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
394 AliasAnalysis *AA = P ? P->getAnalysisIfAvailable<AliasAnalysis>() : nullptr;
395 SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
396 for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
397 PHINode *PN = cast<PHINode>(I++);
399 // Check to see if all of the values coming in are the same. If so, we
400 // don't need to create a new PHI node, unless it's needed for LCSSA.
401 Value *InVal = nullptr;
403 InVal = PN->getIncomingValueForBlock(Preds[0]);
404 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
405 if (!PredSet.count(PN->getIncomingBlock(i)))
408 InVal = PN->getIncomingValue(i);
409 else if (InVal != PN->getIncomingValue(i)) {
417 // If all incoming values for the new PHI would be the same, just don't
418 // make a new PHI. Instead, just remove the incoming values from the old
421 // NOTE! This loop walks backwards for a reason! First off, this minimizes
422 // the cost of removal if we end up removing a large number of values, and
423 // second off, this ensures that the indices for the incoming values
424 // aren't invalidated when we remove one.
425 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i)
426 if (PredSet.count(PN->getIncomingBlock(i)))
427 PN->removeIncomingValue(i, false);
429 // Add an incoming value to the PHI node in the loop for the preheader
431 PN->addIncoming(InVal, NewBB);
435 // If the values coming into the block are not the same, we need a new
437 // Create the new PHI node, insert it into NewBB at the end of the block
439 PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
441 AA->copyValue(PN, NewPHI);
443 // NOTE! This loop walks backwards for a reason! First off, this minimizes
444 // the cost of removal if we end up removing a large number of values, and
445 // second off, this ensures that the indices for the incoming values aren't
446 // invalidated when we remove one.
447 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
448 BasicBlock *IncomingBB = PN->getIncomingBlock(i);
449 if (PredSet.count(IncomingBB)) {
450 Value *V = PN->removeIncomingValue(i, false);
451 NewPHI->addIncoming(V, IncomingBB);
455 PN->addIncoming(NewPHI, NewBB);
459 /// SplitBlockPredecessors - This method transforms BB by introducing a new
460 /// basic block into the function, and moving some of the predecessors of BB to
461 /// be predecessors of the new block. The new predecessors are indicated by the
462 /// Preds array, which has NumPreds elements in it. The new block is given a
463 /// suffix of 'Suffix'.
465 /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
466 /// LoopInfo, and LCCSA but no other analyses. In particular, it does not
467 /// preserve LoopSimplify (because it's complicated to handle the case where one
468 /// of the edges being split is an exit of a loop with other exits).
470 BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
471 ArrayRef<BasicBlock*> Preds,
472 const char *Suffix, Pass *P) {
473 // Create new basic block, insert right before the original block.
474 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), BB->getName()+Suffix,
475 BB->getParent(), BB);
477 // The new block unconditionally branches to the old block.
478 BranchInst *BI = BranchInst::Create(BB, NewBB);
480 // Move the edges from Preds to point to NewBB instead of BB.
481 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
482 // This is slightly more strict than necessary; the minimum requirement
483 // is that there be no more than one indirectbr branching to BB. And
484 // all BlockAddress uses would need to be updated.
485 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
486 "Cannot split an edge from an IndirectBrInst");
487 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
490 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
491 // node becomes an incoming value for BB's phi node. However, if the Preds
492 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
493 // account for the newly created predecessor.
494 if (Preds.size() == 0) {
495 // Insert dummy values as the incoming value.
496 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
497 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
501 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
502 bool HasLoopExit = false;
503 UpdateAnalysisInformation(BB, NewBB, Preds, P, HasLoopExit);
505 // Update the PHI nodes in BB with the values coming from NewBB.
506 UpdatePHINodes(BB, NewBB, Preds, BI, P, HasLoopExit);
510 /// SplitLandingPadPredecessors - This method transforms the landing pad,
511 /// OrigBB, by introducing two new basic blocks into the function. One of those
512 /// new basic blocks gets the predecessors listed in Preds. The other basic
513 /// block gets the remaining predecessors of OrigBB. The landingpad instruction
514 /// OrigBB is clone into both of the new basic blocks. The new blocks are given
515 /// the suffixes 'Suffix1' and 'Suffix2', and are returned in the NewBBs vector.
517 /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
518 /// DominanceFrontier, LoopInfo, and LCCSA but no other analyses. In particular,
519 /// it does not preserve LoopSimplify (because it's complicated to handle the
520 /// case where one of the edges being split is an exit of a loop with other
523 void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
524 ArrayRef<BasicBlock*> Preds,
525 const char *Suffix1, const char *Suffix2,
527 SmallVectorImpl<BasicBlock*> &NewBBs) {
528 assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
530 // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
531 // it right before the original block.
532 BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
533 OrigBB->getName() + Suffix1,
534 OrigBB->getParent(), OrigBB);
535 NewBBs.push_back(NewBB1);
537 // The new block unconditionally branches to the old block.
538 BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
540 // Move the edges from Preds to point to NewBB1 instead of OrigBB.
541 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
542 // This is slightly more strict than necessary; the minimum requirement
543 // is that there be no more than one indirectbr branching to BB. And
544 // all BlockAddress uses would need to be updated.
545 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
546 "Cannot split an edge from an IndirectBrInst");
547 Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
550 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
551 bool HasLoopExit = false;
552 UpdateAnalysisInformation(OrigBB, NewBB1, Preds, P, HasLoopExit);
554 // Update the PHI nodes in OrigBB with the values coming from NewBB1.
555 UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, P, HasLoopExit);
557 // Move the remaining edges from OrigBB to point to NewBB2.
558 SmallVector<BasicBlock*, 8> NewBB2Preds;
559 for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
561 BasicBlock *Pred = *i++;
562 if (Pred == NewBB1) continue;
563 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
564 "Cannot split an edge from an IndirectBrInst");
565 NewBB2Preds.push_back(Pred);
566 e = pred_end(OrigBB);
569 BasicBlock *NewBB2 = nullptr;
570 if (!NewBB2Preds.empty()) {
571 // Create another basic block for the rest of OrigBB's predecessors.
572 NewBB2 = BasicBlock::Create(OrigBB->getContext(),
573 OrigBB->getName() + Suffix2,
574 OrigBB->getParent(), OrigBB);
575 NewBBs.push_back(NewBB2);
577 // The new block unconditionally branches to the old block.
578 BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
580 // Move the remaining edges from OrigBB to point to NewBB2.
581 for (SmallVectorImpl<BasicBlock*>::iterator
582 i = NewBB2Preds.begin(), e = NewBB2Preds.end(); i != e; ++i)
583 (*i)->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
585 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
587 UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, P, HasLoopExit);
589 // Update the PHI nodes in OrigBB with the values coming from NewBB2.
590 UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, P, HasLoopExit);
593 LandingPadInst *LPad = OrigBB->getLandingPadInst();
594 Instruction *Clone1 = LPad->clone();
595 Clone1->setName(Twine("lpad") + Suffix1);
596 NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1);
599 Instruction *Clone2 = LPad->clone();
600 Clone2->setName(Twine("lpad") + Suffix2);
601 NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2);
603 // Create a PHI node for the two cloned landingpad instructions.
604 PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
605 PN->addIncoming(Clone1, NewBB1);
606 PN->addIncoming(Clone2, NewBB2);
607 LPad->replaceAllUsesWith(PN);
608 LPad->eraseFromParent();
610 // There is no second clone. Just replace the landing pad with the first
612 LPad->replaceAllUsesWith(Clone1);
613 LPad->eraseFromParent();
617 /// FoldReturnIntoUncondBranch - This method duplicates the specified return
618 /// instruction into a predecessor which ends in an unconditional branch. If
619 /// the return instruction returns a value defined by a PHI, propagate the
620 /// right value into the return. It returns the new return instruction in the
622 ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
624 Instruction *UncondBranch = Pred->getTerminator();
625 // Clone the return and add it to the end of the predecessor.
626 Instruction *NewRet = RI->clone();
627 Pred->getInstList().push_back(NewRet);
629 // If the return instruction returns a value, and if the value was a
630 // PHI node in "BB", propagate the right value into the return.
631 for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
634 Instruction *NewBC = nullptr;
635 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
636 // Return value might be bitcasted. Clone and insert it before the
637 // return instruction.
638 V = BCI->getOperand(0);
639 NewBC = BCI->clone();
640 Pred->getInstList().insert(NewRet, NewBC);
643 if (PHINode *PN = dyn_cast<PHINode>(V)) {
644 if (PN->getParent() == BB) {
646 NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
648 *i = PN->getIncomingValueForBlock(Pred);
653 // Update any PHI nodes in the returning block to realize that we no
654 // longer branch to them.
655 BB->removePredecessor(Pred);
656 UncondBranch->eraseFromParent();
657 return cast<ReturnInst>(NewRet);
660 /// SplitBlockAndInsertIfThen - Split the containing block at the
661 /// specified instruction - everything before and including SplitBefore stays
662 /// in the old basic block, and everything after SplitBefore is moved to a
663 /// new block. The two blocks are connected by a conditional branch
664 /// (with value of Cmp being the condition).
676 /// If Unreachable is true, then ThenBlock ends with
677 /// UnreachableInst, otherwise it branches to Tail.
678 /// Returns the NewBasicBlock's terminator.
680 TerminatorInst *llvm::SplitBlockAndInsertIfThen(Value *Cond,
681 Instruction *SplitBefore,
683 MDNode *BranchWeights,
685 BasicBlock *Head = SplitBefore->getParent();
686 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
687 TerminatorInst *HeadOldTerm = Head->getTerminator();
688 LLVMContext &C = Head->getContext();
689 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
690 TerminatorInst *CheckTerm;
692 CheckTerm = new UnreachableInst(C, ThenBlock);
694 CheckTerm = BranchInst::Create(Tail, ThenBlock);
695 CheckTerm->setDebugLoc(SplitBefore->getDebugLoc());
696 BranchInst *HeadNewTerm =
697 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cond);
698 HeadNewTerm->setDebugLoc(SplitBefore->getDebugLoc());
699 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
700 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
703 if (DomTreeNode *OldNode = DT->getNode(Head)) {
704 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
706 DomTreeNode *NewNode = DT->addNewBlock(Tail, Head);
707 for (auto Child : Children)
708 DT->changeImmediateDominator(Child, NewNode);
710 // Head dominates ThenBlock.
711 DT->addNewBlock(ThenBlock, Head);
718 /// SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen,
719 /// but also creates the ElseBlock.
732 void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
733 TerminatorInst **ThenTerm,
734 TerminatorInst **ElseTerm,
735 MDNode *BranchWeights) {
736 BasicBlock *Head = SplitBefore->getParent();
737 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
738 TerminatorInst *HeadOldTerm = Head->getTerminator();
739 LLVMContext &C = Head->getContext();
740 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
741 BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
742 *ThenTerm = BranchInst::Create(Tail, ThenBlock);
743 (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc());
744 *ElseTerm = BranchInst::Create(Tail, ElseBlock);
745 (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc());
746 BranchInst *HeadNewTerm =
747 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond);
748 HeadNewTerm->setDebugLoc(SplitBefore->getDebugLoc());
749 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
750 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
754 /// GetIfCondition - Given a basic block (BB) with two predecessors,
755 /// check to see if the merge at this block is due
756 /// to an "if condition". If so, return the boolean condition that determines
757 /// which entry into BB will be taken. Also, return by references the block
758 /// that will be entered from if the condition is true, and the block that will
759 /// be entered if the condition is false.
761 /// This does no checking to see if the true/false blocks have large or unsavory
762 /// instructions in them.
763 Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
764 BasicBlock *&IfFalse) {
765 PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
766 BasicBlock *Pred1 = nullptr;
767 BasicBlock *Pred2 = nullptr;
770 if (SomePHI->getNumIncomingValues() != 2)
772 Pred1 = SomePHI->getIncomingBlock(0);
773 Pred2 = SomePHI->getIncomingBlock(1);
775 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
776 if (PI == PE) // No predecessor
779 if (PI == PE) // Only one predecessor
782 if (PI != PE) // More than two predecessors
786 // We can only handle branches. Other control flow will be lowered to
787 // branches if possible anyway.
788 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
789 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
790 if (!Pred1Br || !Pred2Br)
793 // Eliminate code duplication by ensuring that Pred1Br is conditional if
795 if (Pred2Br->isConditional()) {
796 // If both branches are conditional, we don't have an "if statement". In
797 // reality, we could transform this case, but since the condition will be
798 // required anyway, we stand no chance of eliminating it, so the xform is
799 // probably not profitable.
800 if (Pred1Br->isConditional())
803 std::swap(Pred1, Pred2);
804 std::swap(Pred1Br, Pred2Br);
807 if (Pred1Br->isConditional()) {
808 // The only thing we have to watch out for here is to make sure that Pred2
809 // doesn't have incoming edges from other blocks. If it does, the condition
810 // doesn't dominate BB.
811 if (!Pred2->getSinglePredecessor())
814 // If we found a conditional branch predecessor, make sure that it branches
815 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
816 if (Pred1Br->getSuccessor(0) == BB &&
817 Pred1Br->getSuccessor(1) == Pred2) {
820 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
821 Pred1Br->getSuccessor(1) == BB) {
825 // We know that one arm of the conditional goes to BB, so the other must
826 // go somewhere unrelated, and this must not be an "if statement".
830 return Pred1Br->getCondition();
833 // Ok, if we got here, both predecessors end with an unconditional branch to
834 // BB. Don't panic! If both blocks only have a single (identical)
835 // predecessor, and THAT is a conditional branch, then we're all ok!
836 BasicBlock *CommonPred = Pred1->getSinglePredecessor();
837 if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
840 // Otherwise, if this is a conditional branch, then we can use it!
841 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
842 if (!BI) return nullptr;
844 assert(BI->isConditional() && "Two successors but not conditional?");
845 if (BI->getSuccessor(0) == Pred1) {
852 return BI->getCondition();