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 unwinding instructions.
123 if (PredBB->getTerminator()->isExceptional())
126 succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
127 BasicBlock *OnlySucc = BB;
128 for (; SI != SE; ++SI)
129 if (*SI != OnlySucc) {
130 OnlySucc = nullptr; // There are multiple distinct successors!
134 // Can't merge if there are multiple successors.
135 if (!OnlySucc) return false;
137 // Can't merge if there is PHI loop.
138 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
139 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
140 for (Value *IncValue : PN->incoming_values())
147 // Begin by getting rid of unneeded PHIs.
148 if (isa<PHINode>(BB->front()))
149 FoldSingleEntryPHINodes(BB, AA, MemDep);
151 // Delete the unconditional branch from the predecessor...
152 PredBB->getInstList().pop_back();
154 // Make all PHI nodes that referred to BB now refer to Pred as their
156 BB->replaceAllUsesWith(PredBB);
158 // Move all definitions in the successor to the predecessor...
159 PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
161 // Inherit predecessors name if it exists.
162 if (!PredBB->hasName())
163 PredBB->takeName(BB);
165 // Finally, erase the old block and update dominator info.
167 if (DomTreeNode *DTN = DT->getNode(BB)) {
168 DomTreeNode *PredDTN = DT->getNode(PredBB);
169 SmallVector<DomTreeNode *, 8> Children(DTN->begin(), DTN->end());
170 for (SmallVectorImpl<DomTreeNode *>::iterator DI = Children.begin(),
173 DT->changeImmediateDominator(*DI, PredDTN);
182 MemDep->invalidateCachedPredecessors();
184 BB->eraseFromParent();
188 /// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
189 /// with a value, then remove and delete the original instruction.
191 void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
192 BasicBlock::iterator &BI, Value *V) {
193 Instruction &I = *BI;
194 // Replaces all of the uses of the instruction with uses of the value
195 I.replaceAllUsesWith(V);
197 // Make sure to propagate a name if there is one already.
198 if (I.hasName() && !V->hasName())
201 // Delete the unnecessary instruction now...
206 /// ReplaceInstWithInst - Replace the instruction specified by BI with the
207 /// instruction specified by I. The original instruction is deleted and BI is
208 /// updated to point to the new instruction.
210 void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
211 BasicBlock::iterator &BI, Instruction *I) {
212 assert(I->getParent() == nullptr &&
213 "ReplaceInstWithInst: Instruction already inserted into basic block!");
215 // Copy debug location to newly added instruction, if it wasn't already set
217 if (!I->getDebugLoc())
218 I->setDebugLoc(BI->getDebugLoc());
220 // Insert the new instruction into the basic block...
221 BasicBlock::iterator New = BIL.insert(BI, I);
223 // Replace all uses of the old instruction, and delete it.
224 ReplaceInstWithValue(BIL, BI, I);
226 // Move BI back to point to the newly inserted instruction
230 /// ReplaceInstWithInst - Replace the instruction specified by From with the
231 /// instruction specified by To.
233 void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
234 BasicBlock::iterator BI(From);
235 ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
238 /// SplitEdge - Split the edge connecting specified block. Pass P must
240 BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT,
242 unsigned SuccNum = GetSuccessorNumber(BB, Succ);
244 // If this is a critical edge, let SplitCriticalEdge do it.
245 TerminatorInst *LatchTerm = BB->getTerminator();
246 if (SplitCriticalEdge(LatchTerm, SuccNum, CriticalEdgeSplittingOptions(DT, LI)
247 .setPreserveLCSSA()))
248 return LatchTerm->getSuccessor(SuccNum);
250 // If the edge isn't critical, then BB has a single successor or Succ has a
251 // single pred. Split the block.
252 if (BasicBlock *SP = Succ->getSinglePredecessor()) {
253 // If the successor only has a single pred, split the top of the successor
255 assert(SP == BB && "CFG broken");
257 return SplitBlock(Succ, Succ->begin(), DT, LI);
260 // Otherwise, if BB has a single successor, split it at the bottom of the
262 assert(BB->getTerminator()->getNumSuccessors() == 1 &&
263 "Should have a single succ!");
264 return SplitBlock(BB, BB->getTerminator(), DT, LI);
268 llvm::SplitAllCriticalEdges(Function &F,
269 const CriticalEdgeSplittingOptions &Options) {
270 unsigned NumBroken = 0;
271 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
272 TerminatorInst *TI = I->getTerminator();
273 if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
274 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
275 if (SplitCriticalEdge(TI, i, Options))
281 /// SplitBlock - Split the specified block at the specified instruction - every
282 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
283 /// to a new block. The two blocks are joined by an unconditional branch and
284 /// the loop info is updated.
286 BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt,
287 DominatorTree *DT, LoopInfo *LI) {
288 BasicBlock::iterator SplitIt = SplitPt;
289 while (isa<PHINode>(SplitIt) || isa<LandingPadInst>(SplitIt))
291 BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
293 // The new block lives in whichever loop the old one did. This preserves
294 // LCSSA as well, because we force the split point to be after any PHI nodes.
296 if (Loop *L = LI->getLoopFor(Old))
297 L->addBasicBlockToLoop(New, *LI);
300 // Old dominates New. New node dominates all other nodes dominated by Old.
301 if (DomTreeNode *OldNode = DT->getNode(Old)) {
302 std::vector<DomTreeNode *> Children;
303 for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
305 Children.push_back(*I);
307 DomTreeNode *NewNode = DT->addNewBlock(New, Old);
308 for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
309 E = Children.end(); I != E; ++I)
310 DT->changeImmediateDominator(*I, NewNode);
316 /// UpdateAnalysisInformation - Update DominatorTree, LoopInfo, and LCCSA
317 /// analysis information.
318 static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
319 ArrayRef<BasicBlock *> Preds,
320 DominatorTree *DT, LoopInfo *LI,
321 bool PreserveLCSSA, bool &HasLoopExit) {
322 // Update dominator tree if available.
324 DT->splitBlock(NewBB);
326 // The rest of the logic is only relevant for updating the loop structures.
330 Loop *L = LI->getLoopFor(OldBB);
332 // If we need to preserve loop analyses, collect some information about how
333 // this split will affect loops.
334 bool IsLoopEntry = !!L;
335 bool SplitMakesNewLoopHeader = false;
336 for (ArrayRef<BasicBlock *>::iterator i = Preds.begin(), e = Preds.end();
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.
351 if (L->contains(Pred))
354 SplitMakesNewLoopHeader = true;
357 // Unless we have a loop for OldBB, nothing else to do here.
362 // Add the new block to the nearest enclosing loop (and not an adjacent
363 // loop). To find this, examine each of the predecessors and determine which
364 // loops enclose them, and select the most-nested loop which contains the
365 // loop containing the block being split.
366 Loop *InnermostPredLoop = nullptr;
367 for (ArrayRef<BasicBlock*>::iterator
368 i = Preds.begin(), e = Preds.end(); i != e; ++i) {
369 BasicBlock *Pred = *i;
370 if (Loop *PredLoop = LI->getLoopFor(Pred)) {
371 // Seek a loop which actually contains the block being split (to avoid
373 while (PredLoop && !PredLoop->contains(OldBB))
374 PredLoop = PredLoop->getParentLoop();
376 // Select the most-nested of these loops which contains the block.
377 if (PredLoop && PredLoop->contains(OldBB) &&
378 (!InnermostPredLoop ||
379 InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
380 InnermostPredLoop = PredLoop;
384 if (InnermostPredLoop)
385 InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
387 L->addBasicBlockToLoop(NewBB, *LI);
388 if (SplitMakesNewLoopHeader)
389 L->moveToHeader(NewBB);
393 /// UpdatePHINodes - Update the PHI nodes in OrigBB to include the values coming
394 /// from NewBB. This also updates AliasAnalysis, if available.
395 static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
396 ArrayRef<BasicBlock *> Preds, BranchInst *BI,
397 AliasAnalysis *AA, bool HasLoopExit) {
398 // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
399 SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
400 for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
401 PHINode *PN = cast<PHINode>(I++);
403 // Check to see if all of the values coming in are the same. If so, we
404 // don't need to create a new PHI node, unless it's needed for LCSSA.
405 Value *InVal = nullptr;
407 InVal = PN->getIncomingValueForBlock(Preds[0]);
408 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
409 if (!PredSet.count(PN->getIncomingBlock(i)))
412 InVal = PN->getIncomingValue(i);
413 else if (InVal != PN->getIncomingValue(i)) {
421 // If all incoming values for the new PHI would be the same, just don't
422 // make a new PHI. Instead, just remove the incoming values from the old
425 // NOTE! This loop walks backwards for a reason! First off, this minimizes
426 // the cost of removal if we end up removing a large number of values, and
427 // second off, this ensures that the indices for the incoming values
428 // aren't invalidated when we remove one.
429 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i)
430 if (PredSet.count(PN->getIncomingBlock(i)))
431 PN->removeIncomingValue(i, false);
433 // Add an incoming value to the PHI node in the loop for the preheader
435 PN->addIncoming(InVal, NewBB);
439 // If the values coming into the block are not the same, we need a new
441 // Create the new PHI node, insert it into NewBB at the end of the block
443 PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
445 AA->copyValue(PN, NewPHI);
447 // NOTE! This loop walks backwards for a reason! First off, this minimizes
448 // the cost of removal if we end up removing a large number of values, and
449 // second off, this ensures that the indices for the incoming values aren't
450 // invalidated when we remove one.
451 for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
452 BasicBlock *IncomingBB = PN->getIncomingBlock(i);
453 if (PredSet.count(IncomingBB)) {
454 Value *V = PN->removeIncomingValue(i, false);
455 NewPHI->addIncoming(V, IncomingBB);
459 PN->addIncoming(NewPHI, NewBB);
463 /// SplitBlockPredecessors - This method introduces at least one new basic block
464 /// into the function and moves some of the predecessors of BB to be
465 /// predecessors of the new block. The new predecessors are indicated by the
466 /// Preds array. The new block is given a suffix of 'Suffix'. Returns new basic
467 /// block to which predecessors from Preds are now pointing.
469 /// If BB is a landingpad block then additional basicblock might be introduced.
470 /// It will have suffix of 'Suffix'+".split_lp".
471 /// See SplitLandingPadPredecessors for more details on this case.
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, AliasAnalysis *AA,
481 DominatorTree *DT, LoopInfo *LI,
482 bool PreserveLCSSA) {
483 // For the landingpads we need to act a bit differently.
484 // Delegate this work to the SplitLandingPadPredecessors.
485 if (BB->isLandingPad()) {
486 SmallVector<BasicBlock*, 2> NewBBs;
487 std::string NewName = std::string(Suffix) + ".split-lp";
489 SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(),
490 NewBBs, AA, DT, LI, PreserveLCSSA);
494 // Create new basic block, insert right before the original block.
495 BasicBlock *NewBB = BasicBlock::Create(
496 BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB);
498 // The new block unconditionally branches to the old block.
499 BranchInst *BI = BranchInst::Create(BB, NewBB);
500 BI->setDebugLoc(BB->getFirstNonPHI()->getDebugLoc());
502 // Move the edges from Preds to point to NewBB instead of BB.
503 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
504 // This is slightly more strict than necessary; the minimum requirement
505 // is that there be no more than one indirectbr branching to BB. And
506 // all BlockAddress uses would need to be updated.
507 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
508 "Cannot split an edge from an IndirectBrInst");
509 Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
512 // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
513 // node becomes an incoming value for BB's phi node. However, if the Preds
514 // list is empty, we need to insert dummy entries into the PHI nodes in BB to
515 // account for the newly created predecessor.
516 if (Preds.size() == 0) {
517 // Insert dummy values as the incoming value.
518 for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
519 cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
523 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
524 bool HasLoopExit = false;
525 UpdateAnalysisInformation(BB, NewBB, Preds, DT, LI, PreserveLCSSA,
528 // Update the PHI nodes in BB with the values coming from NewBB.
529 UpdatePHINodes(BB, NewBB, Preds, BI, AA, HasLoopExit);
533 /// SplitLandingPadPredecessors - This method transforms the landing pad,
534 /// OrigBB, by introducing two new basic blocks into the function. One of those
535 /// new basic blocks gets the predecessors listed in Preds. The other basic
536 /// block gets the remaining predecessors of OrigBB. The landingpad instruction
537 /// OrigBB is clone into both of the new basic blocks. The new blocks are given
538 /// the suffixes 'Suffix1' and 'Suffix2', and are returned in the NewBBs vector.
540 /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
541 /// DominanceFrontier, LoopInfo, and LCCSA but no other analyses. In particular,
542 /// it does not preserve LoopSimplify (because it's complicated to handle the
543 /// case where one of the edges being split is an exit of a loop with other
546 void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
547 ArrayRef<BasicBlock *> Preds,
548 const char *Suffix1, const char *Suffix2,
549 SmallVectorImpl<BasicBlock *> &NewBBs,
550 AliasAnalysis *AA, DominatorTree *DT,
551 LoopInfo *LI, bool PreserveLCSSA) {
552 assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
554 // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
555 // it right before the original block.
556 BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
557 OrigBB->getName() + Suffix1,
558 OrigBB->getParent(), OrigBB);
559 NewBBs.push_back(NewBB1);
561 // The new block unconditionally branches to the old block.
562 BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
563 BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
565 // Move the edges from Preds to point to NewBB1 instead of OrigBB.
566 for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
567 // This is slightly more strict than necessary; the minimum requirement
568 // is that there be no more than one indirectbr branching to BB. And
569 // all BlockAddress uses would need to be updated.
570 assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
571 "Cannot split an edge from an IndirectBrInst");
572 Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
575 bool HasLoopExit = false;
576 UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DT, LI, PreserveLCSSA,
579 // Update the PHI nodes in OrigBB with the values coming from NewBB1.
580 UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, AA, HasLoopExit);
582 // Move the remaining edges from OrigBB to point to NewBB2.
583 SmallVector<BasicBlock*, 8> NewBB2Preds;
584 for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
586 BasicBlock *Pred = *i++;
587 if (Pred == NewBB1) continue;
588 assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
589 "Cannot split an edge from an IndirectBrInst");
590 NewBB2Preds.push_back(Pred);
591 e = pred_end(OrigBB);
594 BasicBlock *NewBB2 = nullptr;
595 if (!NewBB2Preds.empty()) {
596 // Create another basic block for the rest of OrigBB's predecessors.
597 NewBB2 = BasicBlock::Create(OrigBB->getContext(),
598 OrigBB->getName() + Suffix2,
599 OrigBB->getParent(), OrigBB);
600 NewBBs.push_back(NewBB2);
602 // The new block unconditionally branches to the old block.
603 BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
604 BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
606 // Move the remaining edges from OrigBB to point to NewBB2.
607 for (SmallVectorImpl<BasicBlock*>::iterator
608 i = NewBB2Preds.begin(), e = NewBB2Preds.end(); i != e; ++i)
609 (*i)->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
611 // Update DominatorTree, LoopInfo, and LCCSA analysis information.
613 UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DT, LI,
614 PreserveLCSSA, HasLoopExit);
616 // Update the PHI nodes in OrigBB with the values coming from NewBB2.
617 UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, AA, HasLoopExit);
620 LandingPadInst *LPad = OrigBB->getLandingPadInst();
621 Instruction *Clone1 = LPad->clone();
622 Clone1->setName(Twine("lpad") + Suffix1);
623 NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1);
626 Instruction *Clone2 = LPad->clone();
627 Clone2->setName(Twine("lpad") + Suffix2);
628 NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2);
630 // Create a PHI node for the two cloned landingpad instructions.
631 PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
632 PN->addIncoming(Clone1, NewBB1);
633 PN->addIncoming(Clone2, NewBB2);
634 LPad->replaceAllUsesWith(PN);
635 LPad->eraseFromParent();
637 // There is no second clone. Just replace the landing pad with the first
639 LPad->replaceAllUsesWith(Clone1);
640 LPad->eraseFromParent();
644 /// FoldReturnIntoUncondBranch - This method duplicates the specified return
645 /// instruction into a predecessor which ends in an unconditional branch. If
646 /// the return instruction returns a value defined by a PHI, propagate the
647 /// right value into the return. It returns the new return instruction in the
649 ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
651 Instruction *UncondBranch = Pred->getTerminator();
652 // Clone the return and add it to the end of the predecessor.
653 Instruction *NewRet = RI->clone();
654 Pred->getInstList().push_back(NewRet);
656 // If the return instruction returns a value, and if the value was a
657 // PHI node in "BB", propagate the right value into the return.
658 for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
661 Instruction *NewBC = nullptr;
662 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
663 // Return value might be bitcasted. Clone and insert it before the
664 // return instruction.
665 V = BCI->getOperand(0);
666 NewBC = BCI->clone();
667 Pred->getInstList().insert(NewRet, NewBC);
670 if (PHINode *PN = dyn_cast<PHINode>(V)) {
671 if (PN->getParent() == BB) {
673 NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
675 *i = PN->getIncomingValueForBlock(Pred);
680 // Update any PHI nodes in the returning block to realize that we no
681 // longer branch to them.
682 BB->removePredecessor(Pred);
683 UncondBranch->eraseFromParent();
684 return cast<ReturnInst>(NewRet);
687 /// SplitBlockAndInsertIfThen - Split the containing block at the
688 /// specified instruction - everything before and including SplitBefore stays
689 /// in the old basic block, and everything after SplitBefore is moved to a
690 /// new block. The two blocks are connected by a conditional branch
691 /// (with value of Cmp being the condition).
703 /// If Unreachable is true, then ThenBlock ends with
704 /// UnreachableInst, otherwise it branches to Tail.
705 /// Returns the NewBasicBlock's terminator.
707 TerminatorInst *llvm::SplitBlockAndInsertIfThen(Value *Cond,
708 Instruction *SplitBefore,
710 MDNode *BranchWeights,
712 BasicBlock *Head = SplitBefore->getParent();
713 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
714 TerminatorInst *HeadOldTerm = Head->getTerminator();
715 LLVMContext &C = Head->getContext();
716 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
717 TerminatorInst *CheckTerm;
719 CheckTerm = new UnreachableInst(C, ThenBlock);
721 CheckTerm = BranchInst::Create(Tail, ThenBlock);
722 CheckTerm->setDebugLoc(SplitBefore->getDebugLoc());
723 BranchInst *HeadNewTerm =
724 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cond);
725 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
726 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
729 if (DomTreeNode *OldNode = DT->getNode(Head)) {
730 std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
732 DomTreeNode *NewNode = DT->addNewBlock(Tail, Head);
733 for (auto Child : Children)
734 DT->changeImmediateDominator(Child, NewNode);
736 // Head dominates ThenBlock.
737 DT->addNewBlock(ThenBlock, Head);
744 /// SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen,
745 /// but also creates the ElseBlock.
758 void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
759 TerminatorInst **ThenTerm,
760 TerminatorInst **ElseTerm,
761 MDNode *BranchWeights) {
762 BasicBlock *Head = SplitBefore->getParent();
763 BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
764 TerminatorInst *HeadOldTerm = Head->getTerminator();
765 LLVMContext &C = Head->getContext();
766 BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
767 BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
768 *ThenTerm = BranchInst::Create(Tail, ThenBlock);
769 (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc());
770 *ElseTerm = BranchInst::Create(Tail, ElseBlock);
771 (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc());
772 BranchInst *HeadNewTerm =
773 BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond);
774 HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
775 ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
779 /// GetIfCondition - Given a basic block (BB) with two predecessors,
780 /// check to see if the merge at this block is due
781 /// to an "if condition". If so, return the boolean condition that determines
782 /// which entry into BB will be taken. Also, return by references the block
783 /// that will be entered from if the condition is true, and the block that will
784 /// be entered if the condition is false.
786 /// This does no checking to see if the true/false blocks have large or unsavory
787 /// instructions in them.
788 Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
789 BasicBlock *&IfFalse) {
790 PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
791 BasicBlock *Pred1 = nullptr;
792 BasicBlock *Pred2 = nullptr;
795 if (SomePHI->getNumIncomingValues() != 2)
797 Pred1 = SomePHI->getIncomingBlock(0);
798 Pred2 = SomePHI->getIncomingBlock(1);
800 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
801 if (PI == PE) // No predecessor
804 if (PI == PE) // Only one predecessor
807 if (PI != PE) // More than two predecessors
811 // We can only handle branches. Other control flow will be lowered to
812 // branches if possible anyway.
813 BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
814 BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
815 if (!Pred1Br || !Pred2Br)
818 // Eliminate code duplication by ensuring that Pred1Br is conditional if
820 if (Pred2Br->isConditional()) {
821 // If both branches are conditional, we don't have an "if statement". In
822 // reality, we could transform this case, but since the condition will be
823 // required anyway, we stand no chance of eliminating it, so the xform is
824 // probably not profitable.
825 if (Pred1Br->isConditional())
828 std::swap(Pred1, Pred2);
829 std::swap(Pred1Br, Pred2Br);
832 if (Pred1Br->isConditional()) {
833 // The only thing we have to watch out for here is to make sure that Pred2
834 // doesn't have incoming edges from other blocks. If it does, the condition
835 // doesn't dominate BB.
836 if (!Pred2->getSinglePredecessor())
839 // If we found a conditional branch predecessor, make sure that it branches
840 // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
841 if (Pred1Br->getSuccessor(0) == BB &&
842 Pred1Br->getSuccessor(1) == Pred2) {
845 } else if (Pred1Br->getSuccessor(0) == Pred2 &&
846 Pred1Br->getSuccessor(1) == BB) {
850 // We know that one arm of the conditional goes to BB, so the other must
851 // go somewhere unrelated, and this must not be an "if statement".
855 return Pred1Br->getCondition();
858 // Ok, if we got here, both predecessors end with an unconditional branch to
859 // BB. Don't panic! If both blocks only have a single (identical)
860 // predecessor, and THAT is a conditional branch, then we're all ok!
861 BasicBlock *CommonPred = Pred1->getSinglePredecessor();
862 if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
865 // Otherwise, if this is a conditional branch, then we can use it!
866 BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
867 if (!BI) return nullptr;
869 assert(BI->isConditional() && "Two successors but not conditional?");
870 if (BI->getSuccessor(0) == Pred1) {
877 return BI->getCondition();