2
0

BasicBlockUtils.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  1. //===-- BasicBlockUtils.cpp - BasicBlock Utilities -------------------------==//
  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. // This family of functions perform manipulations on basic blocks, and
  11. // instructions contained within basic blocks.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  15. #include "llvm/Analysis/AliasAnalysis.h"
  16. #include "llvm/Analysis/CFG.h"
  17. #include "llvm/Analysis/LoopInfo.h"
  18. #include "llvm/Analysis/MemoryDependenceAnalysis.h"
  19. #include "llvm/IR/Constant.h"
  20. #include "llvm/IR/DataLayout.h"
  21. #include "llvm/IR/Dominators.h"
  22. #include "llvm/IR/Function.h"
  23. #include "llvm/IR/Instructions.h"
  24. #include "llvm/IR/IntrinsicInst.h"
  25. #include "llvm/IR/Type.h"
  26. #include "llvm/IR/ValueHandle.h"
  27. #include "llvm/Support/ErrorHandling.h"
  28. #include "llvm/Transforms/Scalar.h"
  29. #include "llvm/Transforms/Utils/Local.h"
  30. #include <algorithm>
  31. using namespace llvm;
  32. /// DeleteDeadBlock - Delete the specified block, which must have no
  33. /// predecessors.
  34. void llvm::DeleteDeadBlock(BasicBlock *BB) {
  35. assert((pred_begin(BB) == pred_end(BB) ||
  36. // Can delete self loop.
  37. BB->getSinglePredecessor() == BB) && "Block is not dead!");
  38. TerminatorInst *BBTerm = BB->getTerminator();
  39. // Loop through all of our successors and make sure they know that one
  40. // of their predecessors is going away.
  41. for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i)
  42. BBTerm->getSuccessor(i)->removePredecessor(BB);
  43. // Zap all the instructions in the block.
  44. while (!BB->empty()) {
  45. Instruction &I = BB->back();
  46. // If this instruction is used, replace uses with an arbitrary value.
  47. // Because control flow can't get here, we don't care what we replace the
  48. // value with. Note that since this block is unreachable, and all values
  49. // contained within it must dominate their uses, that all uses will
  50. // eventually be removed (they are themselves dead).
  51. if (!I.use_empty())
  52. I.replaceAllUsesWith(UndefValue::get(I.getType()));
  53. BB->getInstList().pop_back();
  54. }
  55. // Zap the block!
  56. BB->eraseFromParent();
  57. }
  58. /// FoldSingleEntryPHINodes - We know that BB has one predecessor. If there are
  59. /// any single-entry PHI nodes in it, fold them away. This handles the case
  60. /// when all entries to the PHI nodes in a block are guaranteed equal, such as
  61. /// when the block has exactly one predecessor.
  62. void llvm::FoldSingleEntryPHINodes(BasicBlock *BB, AliasAnalysis *AA,
  63. MemoryDependenceAnalysis *MemDep) {
  64. if (!isa<PHINode>(BB->begin())) return;
  65. while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
  66. if (PN->getIncomingValue(0) != PN)
  67. PN->replaceAllUsesWith(PN->getIncomingValue(0));
  68. else
  69. PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
  70. if (MemDep)
  71. MemDep->removeInstruction(PN); // Memdep updates AA itself.
  72. else if (AA && isa<PointerType>(PN->getType()))
  73. AA->deleteValue(PN);
  74. PN->eraseFromParent();
  75. }
  76. }
  77. /// DeleteDeadPHIs - Examine each PHI in the given block and delete it if it
  78. /// is dead. Also recursively delete any operands that become dead as
  79. /// a result. This includes tracing the def-use list from the PHI to see if
  80. /// it is ultimately unused or if it reaches an unused cycle.
  81. bool llvm::DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI) {
  82. // Recursively deleting a PHI may cause multiple PHIs to be deleted
  83. // or RAUW'd undef, so use an array of WeakVH for the PHIs to delete.
  84. SmallVector<WeakVH, 8> PHIs;
  85. for (BasicBlock::iterator I = BB->begin();
  86. PHINode *PN = dyn_cast<PHINode>(I); ++I)
  87. PHIs.push_back(PN);
  88. bool Changed = false;
  89. for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
  90. if (PHINode *PN = dyn_cast_or_null<PHINode>(PHIs[i].operator Value*()))
  91. Changed |= RecursivelyDeleteDeadPHINode(PN, TLI);
  92. return Changed;
  93. }
  94. /// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
  95. /// if possible. The return value indicates success or failure.
  96. bool llvm::MergeBlockIntoPredecessor(BasicBlock *BB, DominatorTree *DT,
  97. LoopInfo *LI, AliasAnalysis *AA,
  98. MemoryDependenceAnalysis *MemDep) {
  99. // Don't merge away blocks who have their address taken.
  100. if (BB->hasAddressTaken()) return false;
  101. // Can't merge if there are multiple predecessors, or no predecessors.
  102. BasicBlock *PredBB = BB->getUniquePredecessor();
  103. if (!PredBB) return false;
  104. // Don't break self-loops.
  105. if (PredBB == BB) return false;
  106. // Don't break invokes.
  107. if (isa<InvokeInst>(PredBB->getTerminator())) return false;
  108. succ_iterator SI(succ_begin(PredBB)), SE(succ_end(PredBB));
  109. BasicBlock *OnlySucc = BB;
  110. for (; SI != SE; ++SI)
  111. if (*SI != OnlySucc) {
  112. OnlySucc = nullptr; // There are multiple distinct successors!
  113. break;
  114. }
  115. // Can't merge if there are multiple successors.
  116. if (!OnlySucc) return false;
  117. // Can't merge if there is PHI loop.
  118. for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) {
  119. if (PHINode *PN = dyn_cast<PHINode>(BI)) {
  120. for (Value *IncValue : PN->incoming_values())
  121. if (IncValue == PN)
  122. return false;
  123. } else
  124. break;
  125. }
  126. // Begin by getting rid of unneeded PHIs.
  127. if (isa<PHINode>(BB->front()))
  128. FoldSingleEntryPHINodes(BB, AA, MemDep);
  129. // Delete the unconditional branch from the predecessor...
  130. PredBB->getInstList().pop_back();
  131. // Make all PHI nodes that referred to BB now refer to Pred as their
  132. // source...
  133. BB->replaceAllUsesWith(PredBB);
  134. // Move all definitions in the successor to the predecessor...
  135. PredBB->getInstList().splice(PredBB->end(), BB->getInstList());
  136. // Inherit predecessors name if it exists.
  137. if (!PredBB->hasName())
  138. PredBB->takeName(BB);
  139. // Finally, erase the old block and update dominator info.
  140. if (DT)
  141. if (DomTreeNode *DTN = DT->getNode(BB)) {
  142. DomTreeNode *PredDTN = DT->getNode(PredBB);
  143. SmallVector<DomTreeNode *, 8> Children(DTN->begin(), DTN->end());
  144. for (SmallVectorImpl<DomTreeNode *>::iterator DI = Children.begin(),
  145. DE = Children.end();
  146. DI != DE; ++DI)
  147. DT->changeImmediateDominator(*DI, PredDTN);
  148. DT->eraseNode(BB);
  149. }
  150. if (LI)
  151. LI->removeBlock(BB);
  152. if (MemDep)
  153. MemDep->invalidateCachedPredecessors();
  154. BB->eraseFromParent();
  155. return true;
  156. }
  157. /// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
  158. /// with a value, then remove and delete the original instruction.
  159. ///
  160. void llvm::ReplaceInstWithValue(BasicBlock::InstListType &BIL,
  161. BasicBlock::iterator &BI, Value *V) {
  162. Instruction &I = *BI;
  163. // Replaces all of the uses of the instruction with uses of the value
  164. I.replaceAllUsesWith(V);
  165. // Make sure to propagate a name if there is one already.
  166. if (I.hasName() && !V->hasName())
  167. V->takeName(&I);
  168. // Delete the unnecessary instruction now...
  169. BI = BIL.erase(BI);
  170. }
  171. /// ReplaceInstWithInst - Replace the instruction specified by BI with the
  172. /// instruction specified by I. The original instruction is deleted and BI is
  173. /// updated to point to the new instruction.
  174. ///
  175. void llvm::ReplaceInstWithInst(BasicBlock::InstListType &BIL,
  176. BasicBlock::iterator &BI, Instruction *I) {
  177. assert(I->getParent() == nullptr &&
  178. "ReplaceInstWithInst: Instruction already inserted into basic block!");
  179. // Copy debug location to newly added instruction, if it wasn't already set
  180. // by the caller.
  181. if (!I->getDebugLoc())
  182. I->setDebugLoc(BI->getDebugLoc());
  183. // Insert the new instruction into the basic block...
  184. BasicBlock::iterator New = BIL.insert(BI, I);
  185. // Replace all uses of the old instruction, and delete it.
  186. ReplaceInstWithValue(BIL, BI, I);
  187. // Move BI back to point to the newly inserted instruction
  188. BI = New;
  189. }
  190. /// ReplaceInstWithInst - Replace the instruction specified by From with the
  191. /// instruction specified by To.
  192. ///
  193. void llvm::ReplaceInstWithInst(Instruction *From, Instruction *To) {
  194. BasicBlock::iterator BI(From);
  195. ReplaceInstWithInst(From->getParent()->getInstList(), BI, To);
  196. }
  197. /// SplitEdge - Split the edge connecting specified block. Pass P must
  198. /// not be NULL.
  199. BasicBlock *llvm::SplitEdge(BasicBlock *BB, BasicBlock *Succ, DominatorTree *DT,
  200. LoopInfo *LI) {
  201. unsigned SuccNum = GetSuccessorNumber(BB, Succ);
  202. // If this is a critical edge, let SplitCriticalEdge do it.
  203. TerminatorInst *LatchTerm = BB->getTerminator();
  204. if (SplitCriticalEdge(LatchTerm, SuccNum, CriticalEdgeSplittingOptions(DT, LI)
  205. .setPreserveLCSSA()))
  206. return LatchTerm->getSuccessor(SuccNum);
  207. // If the edge isn't critical, then BB has a single successor or Succ has a
  208. // single pred. Split the block.
  209. if (BasicBlock *SP = Succ->getSinglePredecessor()) {
  210. // If the successor only has a single pred, split the top of the successor
  211. // block.
  212. assert(SP == BB && "CFG broken");
  213. SP = nullptr;
  214. return SplitBlock(Succ, Succ->begin(), DT, LI);
  215. }
  216. // Otherwise, if BB has a single successor, split it at the bottom of the
  217. // block.
  218. assert(BB->getTerminator()->getNumSuccessors() == 1 &&
  219. "Should have a single succ!");
  220. return SplitBlock(BB, BB->getTerminator(), DT, LI);
  221. }
  222. unsigned
  223. llvm::SplitAllCriticalEdges(Function &F,
  224. const CriticalEdgeSplittingOptions &Options) {
  225. unsigned NumBroken = 0;
  226. for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
  227. TerminatorInst *TI = I->getTerminator();
  228. if (TI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(TI))
  229. for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
  230. if (SplitCriticalEdge(TI, i, Options))
  231. ++NumBroken;
  232. }
  233. return NumBroken;
  234. }
  235. /// SplitBlock - Split the specified block at the specified instruction - every
  236. /// thing before SplitPt stays in Old and everything starting with SplitPt moves
  237. /// to a new block. The two blocks are joined by an unconditional branch and
  238. /// the loop info is updated.
  239. ///
  240. BasicBlock *llvm::SplitBlock(BasicBlock *Old, Instruction *SplitPt,
  241. DominatorTree *DT, LoopInfo *LI) {
  242. BasicBlock::iterator SplitIt = SplitPt;
  243. while (isa<PHINode>(SplitIt) || isa<LandingPadInst>(SplitIt))
  244. ++SplitIt;
  245. BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
  246. // The new block lives in whichever loop the old one did. This preserves
  247. // LCSSA as well, because we force the split point to be after any PHI nodes.
  248. if (LI)
  249. if (Loop *L = LI->getLoopFor(Old))
  250. L->addBasicBlockToLoop(New, *LI);
  251. if (DT)
  252. // Old dominates New. New node dominates all other nodes dominated by Old.
  253. if (DomTreeNode *OldNode = DT->getNode(Old)) {
  254. std::vector<DomTreeNode *> Children;
  255. for (DomTreeNode::iterator I = OldNode->begin(), E = OldNode->end();
  256. I != E; ++I)
  257. Children.push_back(*I);
  258. DomTreeNode *NewNode = DT->addNewBlock(New, Old);
  259. for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
  260. E = Children.end(); I != E; ++I)
  261. DT->changeImmediateDominator(*I, NewNode);
  262. }
  263. return New;
  264. }
  265. /// UpdateAnalysisInformation - Update DominatorTree, LoopInfo, and LCCSA
  266. /// analysis information.
  267. static void UpdateAnalysisInformation(BasicBlock *OldBB, BasicBlock *NewBB,
  268. ArrayRef<BasicBlock *> Preds,
  269. DominatorTree *DT, LoopInfo *LI,
  270. bool PreserveLCSSA, bool &HasLoopExit) {
  271. // Update dominator tree if available.
  272. if (DT)
  273. DT->splitBlock(NewBB);
  274. // The rest of the logic is only relevant for updating the loop structures.
  275. if (!LI)
  276. return;
  277. Loop *L = LI->getLoopFor(OldBB);
  278. // If we need to preserve loop analyses, collect some information about how
  279. // this split will affect loops.
  280. bool IsLoopEntry = !!L;
  281. bool SplitMakesNewLoopHeader = false;
  282. for (ArrayRef<BasicBlock *>::iterator i = Preds.begin(), e = Preds.end();
  283. i != e; ++i) {
  284. BasicBlock *Pred = *i;
  285. // If we need to preserve LCSSA, determine if any of the preds is a loop
  286. // exit.
  287. if (PreserveLCSSA)
  288. if (Loop *PL = LI->getLoopFor(Pred))
  289. if (!PL->contains(OldBB))
  290. HasLoopExit = true;
  291. // If we need to preserve LoopInfo, note whether any of the preds crosses
  292. // an interesting loop boundary.
  293. if (!L)
  294. continue;
  295. if (L->contains(Pred))
  296. IsLoopEntry = false;
  297. else
  298. SplitMakesNewLoopHeader = true;
  299. }
  300. // Unless we have a loop for OldBB, nothing else to do here.
  301. if (!L)
  302. return;
  303. if (IsLoopEntry) {
  304. // Add the new block to the nearest enclosing loop (and not an adjacent
  305. // loop). To find this, examine each of the predecessors and determine which
  306. // loops enclose them, and select the most-nested loop which contains the
  307. // loop containing the block being split.
  308. Loop *InnermostPredLoop = nullptr;
  309. for (ArrayRef<BasicBlock*>::iterator
  310. i = Preds.begin(), e = Preds.end(); i != e; ++i) {
  311. BasicBlock *Pred = *i;
  312. if (Loop *PredLoop = LI->getLoopFor(Pred)) {
  313. // Seek a loop which actually contains the block being split (to avoid
  314. // adjacent loops).
  315. while (PredLoop && !PredLoop->contains(OldBB))
  316. PredLoop = PredLoop->getParentLoop();
  317. // Select the most-nested of these loops which contains the block.
  318. if (PredLoop && PredLoop->contains(OldBB) &&
  319. (!InnermostPredLoop ||
  320. InnermostPredLoop->getLoopDepth() < PredLoop->getLoopDepth()))
  321. InnermostPredLoop = PredLoop;
  322. }
  323. }
  324. if (InnermostPredLoop)
  325. InnermostPredLoop->addBasicBlockToLoop(NewBB, *LI);
  326. } else {
  327. L->addBasicBlockToLoop(NewBB, *LI);
  328. if (SplitMakesNewLoopHeader)
  329. L->moveToHeader(NewBB);
  330. }
  331. }
  332. /// UpdatePHINodes - Update the PHI nodes in OrigBB to include the values coming
  333. /// from NewBB. This also updates AliasAnalysis, if available.
  334. static void UpdatePHINodes(BasicBlock *OrigBB, BasicBlock *NewBB,
  335. ArrayRef<BasicBlock *> Preds, BranchInst *BI,
  336. AliasAnalysis *AA, bool HasLoopExit) {
  337. // Otherwise, create a new PHI node in NewBB for each PHI node in OrigBB.
  338. SmallPtrSet<BasicBlock *, 16> PredSet(Preds.begin(), Preds.end());
  339. for (BasicBlock::iterator I = OrigBB->begin(); isa<PHINode>(I); ) {
  340. PHINode *PN = cast<PHINode>(I++);
  341. // Check to see if all of the values coming in are the same. If so, we
  342. // don't need to create a new PHI node, unless it's needed for LCSSA.
  343. Value *InVal = nullptr;
  344. if (!HasLoopExit) {
  345. InVal = PN->getIncomingValueForBlock(Preds[0]);
  346. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  347. if (!PredSet.count(PN->getIncomingBlock(i)))
  348. continue;
  349. if (!InVal)
  350. InVal = PN->getIncomingValue(i);
  351. else if (InVal != PN->getIncomingValue(i)) {
  352. InVal = nullptr;
  353. break;
  354. }
  355. }
  356. }
  357. if (InVal) {
  358. // If all incoming values for the new PHI would be the same, just don't
  359. // make a new PHI. Instead, just remove the incoming values from the old
  360. // PHI.
  361. // NOTE! This loop walks backwards for a reason! First off, this minimizes
  362. // the cost of removal if we end up removing a large number of values, and
  363. // second off, this ensures that the indices for the incoming values
  364. // aren't invalidated when we remove one.
  365. for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i)
  366. if (PredSet.count(PN->getIncomingBlock(i)))
  367. PN->removeIncomingValue(i, false);
  368. // Add an incoming value to the PHI node in the loop for the preheader
  369. // edge.
  370. PN->addIncoming(InVal, NewBB);
  371. continue;
  372. }
  373. // If the values coming into the block are not the same, we need a new
  374. // PHI.
  375. // Create the new PHI node, insert it into NewBB at the end of the block
  376. PHINode *NewPHI =
  377. PHINode::Create(PN->getType(), Preds.size(), PN->getName() + ".ph", BI);
  378. // NOTE! This loop walks backwards for a reason! First off, this minimizes
  379. // the cost of removal if we end up removing a large number of values, and
  380. // second off, this ensures that the indices for the incoming values aren't
  381. // invalidated when we remove one.
  382. for (int64_t i = PN->getNumIncomingValues() - 1; i >= 0; --i) {
  383. BasicBlock *IncomingBB = PN->getIncomingBlock(i);
  384. if (PredSet.count(IncomingBB)) {
  385. Value *V = PN->removeIncomingValue(i, false);
  386. NewPHI->addIncoming(V, IncomingBB);
  387. }
  388. }
  389. PN->addIncoming(NewPHI, NewBB);
  390. }
  391. }
  392. /// SplitBlockPredecessors - This method introduces at least one new basic block
  393. /// into the function and moves some of the predecessors of BB to be
  394. /// predecessors of the new block. The new predecessors are indicated by the
  395. /// Preds array. The new block is given a suffix of 'Suffix'. Returns new basic
  396. /// block to which predecessors from Preds are now pointing.
  397. ///
  398. /// If BB is a landingpad block then additional basicblock might be introduced.
  399. /// It will have suffix of 'Suffix'+".split_lp".
  400. /// See SplitLandingPadPredecessors for more details on this case.
  401. ///
  402. /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
  403. /// LoopInfo, and LCCSA but no other analyses. In particular, it does not
  404. /// preserve LoopSimplify (because it's complicated to handle the case where one
  405. /// of the edges being split is an exit of a loop with other exits).
  406. ///
  407. BasicBlock *llvm::SplitBlockPredecessors(BasicBlock *BB,
  408. ArrayRef<BasicBlock *> Preds,
  409. const char *Suffix, AliasAnalysis *AA,
  410. DominatorTree *DT, LoopInfo *LI,
  411. bool PreserveLCSSA) {
  412. // For the landingpads we need to act a bit differently.
  413. // Delegate this work to the SplitLandingPadPredecessors.
  414. if (BB->isLandingPad()) {
  415. SmallVector<BasicBlock*, 2> NewBBs;
  416. std::string NewName = std::string(Suffix) + ".split-lp";
  417. SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(),
  418. NewBBs, AA, DT, LI, PreserveLCSSA);
  419. return NewBBs[0];
  420. }
  421. // Create new basic block, insert right before the original block.
  422. BasicBlock *NewBB = BasicBlock::Create(
  423. BB->getContext(), BB->getName() + Suffix, BB->getParent(), BB);
  424. // The new block unconditionally branches to the old block.
  425. BranchInst *BI = BranchInst::Create(BB, NewBB);
  426. BI->setDebugLoc(BB->getFirstNonPHI()->getDebugLoc());
  427. // Move the edges from Preds to point to NewBB instead of BB.
  428. for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
  429. // This is slightly more strict than necessary; the minimum requirement
  430. // is that there be no more than one indirectbr branching to BB. And
  431. // all BlockAddress uses would need to be updated.
  432. assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
  433. "Cannot split an edge from an IndirectBrInst");
  434. Preds[i]->getTerminator()->replaceUsesOfWith(BB, NewBB);
  435. }
  436. // Insert a new PHI node into NewBB for every PHI node in BB and that new PHI
  437. // node becomes an incoming value for BB's phi node. However, if the Preds
  438. // list is empty, we need to insert dummy entries into the PHI nodes in BB to
  439. // account for the newly created predecessor.
  440. if (Preds.size() == 0) {
  441. // Insert dummy values as the incoming value.
  442. for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++I)
  443. cast<PHINode>(I)->addIncoming(UndefValue::get(I->getType()), NewBB);
  444. return NewBB;
  445. }
  446. // Update DominatorTree, LoopInfo, and LCCSA analysis information.
  447. bool HasLoopExit = false;
  448. UpdateAnalysisInformation(BB, NewBB, Preds, DT, LI, PreserveLCSSA,
  449. HasLoopExit);
  450. // Update the PHI nodes in BB with the values coming from NewBB.
  451. UpdatePHINodes(BB, NewBB, Preds, BI, AA, HasLoopExit);
  452. return NewBB;
  453. }
  454. /// SplitLandingPadPredecessors - This method transforms the landing pad,
  455. /// OrigBB, by introducing two new basic blocks into the function. One of those
  456. /// new basic blocks gets the predecessors listed in Preds. The other basic
  457. /// block gets the remaining predecessors of OrigBB. The landingpad instruction
  458. /// OrigBB is clone into both of the new basic blocks. The new blocks are given
  459. /// the suffixes 'Suffix1' and 'Suffix2', and are returned in the NewBBs vector.
  460. ///
  461. /// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
  462. /// DominanceFrontier, LoopInfo, and LCCSA but no other analyses. In particular,
  463. /// it does not preserve LoopSimplify (because it's complicated to handle the
  464. /// case where one of the edges being split is an exit of a loop with other
  465. /// exits).
  466. ///
  467. void llvm::SplitLandingPadPredecessors(BasicBlock *OrigBB,
  468. ArrayRef<BasicBlock *> Preds,
  469. const char *Suffix1, const char *Suffix2,
  470. SmallVectorImpl<BasicBlock *> &NewBBs,
  471. AliasAnalysis *AA, DominatorTree *DT,
  472. LoopInfo *LI, bool PreserveLCSSA) {
  473. assert(OrigBB->isLandingPad() && "Trying to split a non-landing pad!");
  474. // Create a new basic block for OrigBB's predecessors listed in Preds. Insert
  475. // it right before the original block.
  476. BasicBlock *NewBB1 = BasicBlock::Create(OrigBB->getContext(),
  477. OrigBB->getName() + Suffix1,
  478. OrigBB->getParent(), OrigBB);
  479. NewBBs.push_back(NewBB1);
  480. // The new block unconditionally branches to the old block.
  481. BranchInst *BI1 = BranchInst::Create(OrigBB, NewBB1);
  482. BI1->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
  483. // Move the edges from Preds to point to NewBB1 instead of OrigBB.
  484. for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
  485. // This is slightly more strict than necessary; the minimum requirement
  486. // is that there be no more than one indirectbr branching to BB. And
  487. // all BlockAddress uses would need to be updated.
  488. assert(!isa<IndirectBrInst>(Preds[i]->getTerminator()) &&
  489. "Cannot split an edge from an IndirectBrInst");
  490. Preds[i]->getTerminator()->replaceUsesOfWith(OrigBB, NewBB1);
  491. }
  492. bool HasLoopExit = false;
  493. UpdateAnalysisInformation(OrigBB, NewBB1, Preds, DT, LI, PreserveLCSSA,
  494. HasLoopExit);
  495. // Update the PHI nodes in OrigBB with the values coming from NewBB1.
  496. UpdatePHINodes(OrigBB, NewBB1, Preds, BI1, AA, HasLoopExit);
  497. // Move the remaining edges from OrigBB to point to NewBB2.
  498. SmallVector<BasicBlock*, 8> NewBB2Preds;
  499. for (pred_iterator i = pred_begin(OrigBB), e = pred_end(OrigBB);
  500. i != e; ) {
  501. BasicBlock *Pred = *i++;
  502. if (Pred == NewBB1) continue;
  503. assert(!isa<IndirectBrInst>(Pred->getTerminator()) &&
  504. "Cannot split an edge from an IndirectBrInst");
  505. NewBB2Preds.push_back(Pred);
  506. e = pred_end(OrigBB);
  507. }
  508. BasicBlock *NewBB2 = nullptr;
  509. if (!NewBB2Preds.empty()) {
  510. // Create another basic block for the rest of OrigBB's predecessors.
  511. NewBB2 = BasicBlock::Create(OrigBB->getContext(),
  512. OrigBB->getName() + Suffix2,
  513. OrigBB->getParent(), OrigBB);
  514. NewBBs.push_back(NewBB2);
  515. // The new block unconditionally branches to the old block.
  516. BranchInst *BI2 = BranchInst::Create(OrigBB, NewBB2);
  517. BI2->setDebugLoc(OrigBB->getFirstNonPHI()->getDebugLoc());
  518. // Move the remaining edges from OrigBB to point to NewBB2.
  519. for (SmallVectorImpl<BasicBlock*>::iterator
  520. i = NewBB2Preds.begin(), e = NewBB2Preds.end(); i != e; ++i)
  521. (*i)->getTerminator()->replaceUsesOfWith(OrigBB, NewBB2);
  522. // Update DominatorTree, LoopInfo, and LCCSA analysis information.
  523. HasLoopExit = false;
  524. UpdateAnalysisInformation(OrigBB, NewBB2, NewBB2Preds, DT, LI,
  525. PreserveLCSSA, HasLoopExit);
  526. // Update the PHI nodes in OrigBB with the values coming from NewBB2.
  527. UpdatePHINodes(OrigBB, NewBB2, NewBB2Preds, BI2, AA, HasLoopExit);
  528. }
  529. LandingPadInst *LPad = OrigBB->getLandingPadInst();
  530. Instruction *Clone1 = LPad->clone();
  531. Clone1->setName(Twine("lpad") + Suffix1);
  532. NewBB1->getInstList().insert(NewBB1->getFirstInsertionPt(), Clone1);
  533. if (NewBB2) {
  534. Instruction *Clone2 = LPad->clone();
  535. Clone2->setName(Twine("lpad") + Suffix2);
  536. NewBB2->getInstList().insert(NewBB2->getFirstInsertionPt(), Clone2);
  537. // Create a PHI node for the two cloned landingpad instructions.
  538. PHINode *PN = PHINode::Create(LPad->getType(), 2, "lpad.phi", LPad);
  539. PN->addIncoming(Clone1, NewBB1);
  540. PN->addIncoming(Clone2, NewBB2);
  541. LPad->replaceAllUsesWith(PN);
  542. LPad->eraseFromParent();
  543. } else {
  544. // There is no second clone. Just replace the landing pad with the first
  545. // clone.
  546. LPad->replaceAllUsesWith(Clone1);
  547. LPad->eraseFromParent();
  548. }
  549. }
  550. /// FoldReturnIntoUncondBranch - This method duplicates the specified return
  551. /// instruction into a predecessor which ends in an unconditional branch. If
  552. /// the return instruction returns a value defined by a PHI, propagate the
  553. /// right value into the return. It returns the new return instruction in the
  554. /// predecessor.
  555. ReturnInst *llvm::FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
  556. BasicBlock *Pred) {
  557. Instruction *UncondBranch = Pred->getTerminator();
  558. // Clone the return and add it to the end of the predecessor.
  559. Instruction *NewRet = RI->clone();
  560. Pred->getInstList().push_back(NewRet);
  561. // If the return instruction returns a value, and if the value was a
  562. // PHI node in "BB", propagate the right value into the return.
  563. for (User::op_iterator i = NewRet->op_begin(), e = NewRet->op_end();
  564. i != e; ++i) {
  565. Value *V = *i;
  566. Instruction *NewBC = nullptr;
  567. if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
  568. // Return value might be bitcasted. Clone and insert it before the
  569. // return instruction.
  570. V = BCI->getOperand(0);
  571. NewBC = BCI->clone();
  572. Pred->getInstList().insert(NewRet, NewBC);
  573. *i = NewBC;
  574. }
  575. if (PHINode *PN = dyn_cast<PHINode>(V)) {
  576. if (PN->getParent() == BB) {
  577. if (NewBC)
  578. NewBC->setOperand(0, PN->getIncomingValueForBlock(Pred));
  579. else
  580. *i = PN->getIncomingValueForBlock(Pred);
  581. }
  582. }
  583. }
  584. // Update any PHI nodes in the returning block to realize that we no
  585. // longer branch to them.
  586. BB->removePredecessor(Pred);
  587. UncondBranch->eraseFromParent();
  588. return cast<ReturnInst>(NewRet);
  589. }
  590. /// SplitBlockAndInsertIfThen - Split the containing block at the
  591. /// specified instruction - everything before and including SplitBefore stays
  592. /// in the old basic block, and everything after SplitBefore is moved to a
  593. /// new block. The two blocks are connected by a conditional branch
  594. /// (with value of Cmp being the condition).
  595. /// Before:
  596. /// Head
  597. /// SplitBefore
  598. /// Tail
  599. /// After:
  600. /// Head
  601. /// if (Cond)
  602. /// ThenBlock
  603. /// SplitBefore
  604. /// Tail
  605. ///
  606. /// If Unreachable is true, then ThenBlock ends with
  607. /// UnreachableInst, otherwise it branches to Tail.
  608. /// Returns the NewBasicBlock's terminator.
  609. TerminatorInst *llvm::SplitBlockAndInsertIfThen(Value *Cond,
  610. Instruction *SplitBefore,
  611. bool Unreachable,
  612. MDNode *BranchWeights,
  613. DominatorTree *DT) {
  614. BasicBlock *Head = SplitBefore->getParent();
  615. BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
  616. TerminatorInst *HeadOldTerm = Head->getTerminator();
  617. LLVMContext &C = Head->getContext();
  618. BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
  619. TerminatorInst *CheckTerm;
  620. if (Unreachable)
  621. CheckTerm = new UnreachableInst(C, ThenBlock);
  622. else
  623. CheckTerm = BranchInst::Create(Tail, ThenBlock);
  624. CheckTerm->setDebugLoc(SplitBefore->getDebugLoc());
  625. BranchInst *HeadNewTerm =
  626. BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/Tail, Cond);
  627. HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
  628. ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
  629. if (DT) {
  630. if (DomTreeNode *OldNode = DT->getNode(Head)) {
  631. std::vector<DomTreeNode *> Children(OldNode->begin(), OldNode->end());
  632. DomTreeNode *NewNode = DT->addNewBlock(Tail, Head);
  633. for (auto Child : Children)
  634. DT->changeImmediateDominator(Child, NewNode);
  635. // Head dominates ThenBlock.
  636. DT->addNewBlock(ThenBlock, Head);
  637. }
  638. }
  639. return CheckTerm;
  640. }
  641. /// SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen,
  642. /// but also creates the ElseBlock.
  643. /// Before:
  644. /// Head
  645. /// SplitBefore
  646. /// Tail
  647. /// After:
  648. /// Head
  649. /// if (Cond)
  650. /// ThenBlock
  651. /// else
  652. /// ElseBlock
  653. /// SplitBefore
  654. /// Tail
  655. void llvm::SplitBlockAndInsertIfThenElse(Value *Cond, Instruction *SplitBefore,
  656. TerminatorInst **ThenTerm,
  657. TerminatorInst **ElseTerm,
  658. MDNode *BranchWeights) {
  659. BasicBlock *Head = SplitBefore->getParent();
  660. BasicBlock *Tail = Head->splitBasicBlock(SplitBefore);
  661. TerminatorInst *HeadOldTerm = Head->getTerminator();
  662. LLVMContext &C = Head->getContext();
  663. BasicBlock *ThenBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
  664. BasicBlock *ElseBlock = BasicBlock::Create(C, "", Head->getParent(), Tail);
  665. *ThenTerm = BranchInst::Create(Tail, ThenBlock);
  666. (*ThenTerm)->setDebugLoc(SplitBefore->getDebugLoc());
  667. *ElseTerm = BranchInst::Create(Tail, ElseBlock);
  668. (*ElseTerm)->setDebugLoc(SplitBefore->getDebugLoc());
  669. BranchInst *HeadNewTerm =
  670. BranchInst::Create(/*ifTrue*/ThenBlock, /*ifFalse*/ElseBlock, Cond);
  671. HeadNewTerm->setMetadata(LLVMContext::MD_prof, BranchWeights);
  672. ReplaceInstWithInst(HeadOldTerm, HeadNewTerm);
  673. }
  674. /// GetIfCondition - Given a basic block (BB) with two predecessors,
  675. /// check to see if the merge at this block is due
  676. /// to an "if condition". If so, return the boolean condition that determines
  677. /// which entry into BB will be taken. Also, return by references the block
  678. /// that will be entered from if the condition is true, and the block that will
  679. /// be entered if the condition is false.
  680. ///
  681. /// This does no checking to see if the true/false blocks have large or unsavory
  682. /// instructions in them.
  683. Value *llvm::GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
  684. BasicBlock *&IfFalse) {
  685. PHINode *SomePHI = dyn_cast<PHINode>(BB->begin());
  686. BasicBlock *Pred1 = nullptr;
  687. BasicBlock *Pred2 = nullptr;
  688. if (SomePHI) {
  689. if (SomePHI->getNumIncomingValues() != 2)
  690. return nullptr;
  691. Pred1 = SomePHI->getIncomingBlock(0);
  692. Pred2 = SomePHI->getIncomingBlock(1);
  693. } else {
  694. pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
  695. if (PI == PE) // No predecessor
  696. return nullptr;
  697. Pred1 = *PI++;
  698. if (PI == PE) // Only one predecessor
  699. return nullptr;
  700. Pred2 = *PI++;
  701. if (PI != PE) // More than two predecessors
  702. return nullptr;
  703. }
  704. // We can only handle branches. Other control flow will be lowered to
  705. // branches if possible anyway.
  706. BranchInst *Pred1Br = dyn_cast<BranchInst>(Pred1->getTerminator());
  707. BranchInst *Pred2Br = dyn_cast<BranchInst>(Pred2->getTerminator());
  708. if (!Pred1Br || !Pred2Br)
  709. return nullptr;
  710. // Eliminate code duplication by ensuring that Pred1Br is conditional if
  711. // either are.
  712. if (Pred2Br->isConditional()) {
  713. // If both branches are conditional, we don't have an "if statement". In
  714. // reality, we could transform this case, but since the condition will be
  715. // required anyway, we stand no chance of eliminating it, so the xform is
  716. // probably not profitable.
  717. if (Pred1Br->isConditional())
  718. return nullptr;
  719. std::swap(Pred1, Pred2);
  720. std::swap(Pred1Br, Pred2Br);
  721. }
  722. if (Pred1Br->isConditional()) {
  723. // The only thing we have to watch out for here is to make sure that Pred2
  724. // doesn't have incoming edges from other blocks. If it does, the condition
  725. // doesn't dominate BB.
  726. if (!Pred2->getSinglePredecessor())
  727. return nullptr;
  728. // If we found a conditional branch predecessor, make sure that it branches
  729. // to BB and Pred2Br. If it doesn't, this isn't an "if statement".
  730. if (Pred1Br->getSuccessor(0) == BB &&
  731. Pred1Br->getSuccessor(1) == Pred2) {
  732. IfTrue = Pred1;
  733. IfFalse = Pred2;
  734. } else if (Pred1Br->getSuccessor(0) == Pred2 &&
  735. Pred1Br->getSuccessor(1) == BB) {
  736. IfTrue = Pred2;
  737. IfFalse = Pred1;
  738. } else {
  739. // We know that one arm of the conditional goes to BB, so the other must
  740. // go somewhere unrelated, and this must not be an "if statement".
  741. return nullptr;
  742. }
  743. return Pred1Br->getCondition();
  744. }
  745. // Ok, if we got here, both predecessors end with an unconditional branch to
  746. // BB. Don't panic! If both blocks only have a single (identical)
  747. // predecessor, and THAT is a conditional branch, then we're all ok!
  748. BasicBlock *CommonPred = Pred1->getSinglePredecessor();
  749. if (CommonPred == nullptr || CommonPred != Pred2->getSinglePredecessor())
  750. return nullptr;
  751. // Otherwise, if this is a conditional branch, then we can use it!
  752. BranchInst *BI = dyn_cast<BranchInst>(CommonPred->getTerminator());
  753. if (!BI) return nullptr;
  754. assert(BI->isConditional() && "Two successors but not conditional?");
  755. if (BI->getSuccessor(0) == Pred1) {
  756. IfTrue = Pred1;
  757. IfFalse = Pred2;
  758. } else {
  759. IfTrue = Pred2;
  760. IfFalse = Pred1;
  761. }
  762. return BI->getCondition();
  763. }