BasicBlockUtils.cpp 34 KB

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