BasicBlockUtils.cpp 32 KB

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