BasicBlockUtils.cpp 29 KB

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