BasicBlock.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. //===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
  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 file implements the BasicBlock class for the IR library.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/IR/BasicBlock.h"
  13. #include "SymbolTableListTraitsImpl.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/ADT/Statistic.h"
  16. #include "llvm/IR/CFG.h"
  17. #include "llvm/IR/Constants.h"
  18. #include "llvm/IR/Instructions.h"
  19. #include "llvm/IR/IntrinsicInst.h"
  20. #include "llvm/IR/LLVMContext.h"
  21. #include "llvm/IR/Type.h"
  22. using namespace llvm;
  23. #define DEBUG_TYPE "ir"
  24. STATISTIC(NumInstrRenumberings, "Number of renumberings across all blocks");
  25. ValueSymbolTable *BasicBlock::getValueSymbolTable() {
  26. if (Function *F = getParent())
  27. return F->getValueSymbolTable();
  28. return nullptr;
  29. }
  30. LLVMContext &BasicBlock::getContext() const {
  31. return getType()->getContext();
  32. }
  33. template <> void llvm::invalidateParentIListOrdering(BasicBlock *BB) {
  34. BB->invalidateOrders();
  35. }
  36. // Explicit instantiation of SymbolTableListTraits since some of the methods
  37. // are not in the public header file...
  38. template class llvm::SymbolTableListTraits<Instruction>;
  39. BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent,
  40. BasicBlock *InsertBefore)
  41. : Value(Type::getLabelTy(C), Value::BasicBlockVal), Parent(nullptr) {
  42. if (NewParent)
  43. insertInto(NewParent, InsertBefore);
  44. else
  45. assert(!InsertBefore &&
  46. "Cannot insert block before another block with no function!");
  47. setName(Name);
  48. }
  49. void BasicBlock::insertInto(Function *NewParent, BasicBlock *InsertBefore) {
  50. assert(NewParent && "Expected a parent");
  51. assert(!Parent && "Already has a parent");
  52. if (InsertBefore)
  53. NewParent->insert(InsertBefore->getIterator(), this);
  54. else
  55. NewParent->insert(NewParent->end(), this);
  56. }
  57. BasicBlock::~BasicBlock() {
  58. validateInstrOrdering();
  59. // If the address of the block is taken and it is being deleted (e.g. because
  60. // it is dead), this means that there is either a dangling constant expr
  61. // hanging off the block, or an undefined use of the block (source code
  62. // expecting the address of a label to keep the block alive even though there
  63. // is no indirect branch). Handle these cases by zapping the BlockAddress
  64. // nodes. There are no other possible uses at this point.
  65. if (hasAddressTaken()) {
  66. assert(!use_empty() && "There should be at least one blockaddress!");
  67. Constant *Replacement =
  68. ConstantInt::get(llvm::Type::getInt32Ty(getContext()), 1);
  69. while (!use_empty()) {
  70. BlockAddress *BA = cast<BlockAddress>(user_back());
  71. BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
  72. BA->getType()));
  73. BA->destroyConstant();
  74. }
  75. }
  76. assert(getParent() == nullptr && "BasicBlock still linked into the program!");
  77. dropAllReferences();
  78. InstList.clear();
  79. }
  80. void BasicBlock::setParent(Function *parent) {
  81. // Set Parent=parent, updating instruction symtab entries as appropriate.
  82. InstList.setSymTabObject(&Parent, parent);
  83. }
  84. iterator_range<filter_iterator<BasicBlock::const_iterator,
  85. std::function<bool(const Instruction &)>>>
  86. BasicBlock::instructionsWithoutDebug(bool SkipPseudoOp) const {
  87. std::function<bool(const Instruction &)> Fn = [=](const Instruction &I) {
  88. return !isa<DbgInfoIntrinsic>(I) &&
  89. !(SkipPseudoOp && isa<PseudoProbeInst>(I));
  90. };
  91. return make_filter_range(*this, Fn);
  92. }
  93. iterator_range<
  94. filter_iterator<BasicBlock::iterator, std::function<bool(Instruction &)>>>
  95. BasicBlock::instructionsWithoutDebug(bool SkipPseudoOp) {
  96. std::function<bool(Instruction &)> Fn = [=](Instruction &I) {
  97. return !isa<DbgInfoIntrinsic>(I) &&
  98. !(SkipPseudoOp && isa<PseudoProbeInst>(I));
  99. };
  100. return make_filter_range(*this, Fn);
  101. }
  102. filter_iterator<BasicBlock::const_iterator,
  103. std::function<bool(const Instruction &)>>::difference_type
  104. BasicBlock::sizeWithoutDebug() const {
  105. return std::distance(instructionsWithoutDebug().begin(),
  106. instructionsWithoutDebug().end());
  107. }
  108. void BasicBlock::removeFromParent() {
  109. getParent()->getBasicBlockList().remove(getIterator());
  110. }
  111. iplist<BasicBlock>::iterator BasicBlock::eraseFromParent() {
  112. return getParent()->getBasicBlockList().erase(getIterator());
  113. }
  114. void BasicBlock::moveBefore(BasicBlock *MovePos) {
  115. MovePos->getParent()->splice(MovePos->getIterator(), getParent(),
  116. getIterator());
  117. }
  118. void BasicBlock::moveAfter(BasicBlock *MovePos) {
  119. MovePos->getParent()->splice(++MovePos->getIterator(), getParent(),
  120. getIterator());
  121. }
  122. const Module *BasicBlock::getModule() const {
  123. return getParent()->getParent();
  124. }
  125. const CallInst *BasicBlock::getTerminatingMustTailCall() const {
  126. if (InstList.empty())
  127. return nullptr;
  128. const ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back());
  129. if (!RI || RI == &InstList.front())
  130. return nullptr;
  131. const Instruction *Prev = RI->getPrevNode();
  132. if (!Prev)
  133. return nullptr;
  134. if (Value *RV = RI->getReturnValue()) {
  135. if (RV != Prev)
  136. return nullptr;
  137. // Look through the optional bitcast.
  138. if (auto *BI = dyn_cast<BitCastInst>(Prev)) {
  139. RV = BI->getOperand(0);
  140. Prev = BI->getPrevNode();
  141. if (!Prev || RV != Prev)
  142. return nullptr;
  143. }
  144. }
  145. if (auto *CI = dyn_cast<CallInst>(Prev)) {
  146. if (CI->isMustTailCall())
  147. return CI;
  148. }
  149. return nullptr;
  150. }
  151. const CallInst *BasicBlock::getTerminatingDeoptimizeCall() const {
  152. if (InstList.empty())
  153. return nullptr;
  154. auto *RI = dyn_cast<ReturnInst>(&InstList.back());
  155. if (!RI || RI == &InstList.front())
  156. return nullptr;
  157. if (auto *CI = dyn_cast_or_null<CallInst>(RI->getPrevNode()))
  158. if (Function *F = CI->getCalledFunction())
  159. if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize)
  160. return CI;
  161. return nullptr;
  162. }
  163. const CallInst *BasicBlock::getPostdominatingDeoptimizeCall() const {
  164. const BasicBlock* BB = this;
  165. SmallPtrSet<const BasicBlock *, 8> Visited;
  166. Visited.insert(BB);
  167. while (auto *Succ = BB->getUniqueSuccessor()) {
  168. if (!Visited.insert(Succ).second)
  169. return nullptr;
  170. BB = Succ;
  171. }
  172. return BB->getTerminatingDeoptimizeCall();
  173. }
  174. const Instruction* BasicBlock::getFirstNonPHI() const {
  175. for (const Instruction &I : *this)
  176. if (!isa<PHINode>(I))
  177. return &I;
  178. return nullptr;
  179. }
  180. const Instruction *BasicBlock::getFirstNonPHIOrDbg(bool SkipPseudoOp) const {
  181. for (const Instruction &I : *this) {
  182. if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))
  183. continue;
  184. if (SkipPseudoOp && isa<PseudoProbeInst>(I))
  185. continue;
  186. return &I;
  187. }
  188. return nullptr;
  189. }
  190. const Instruction *
  191. BasicBlock::getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp) const {
  192. for (const Instruction &I : *this) {
  193. if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))
  194. continue;
  195. if (I.isLifetimeStartOrEnd())
  196. continue;
  197. if (SkipPseudoOp && isa<PseudoProbeInst>(I))
  198. continue;
  199. return &I;
  200. }
  201. return nullptr;
  202. }
  203. BasicBlock::const_iterator BasicBlock::getFirstInsertionPt() const {
  204. const Instruction *FirstNonPHI = getFirstNonPHI();
  205. if (!FirstNonPHI)
  206. return end();
  207. const_iterator InsertPt = FirstNonPHI->getIterator();
  208. if (InsertPt->isEHPad()) ++InsertPt;
  209. return InsertPt;
  210. }
  211. BasicBlock::const_iterator BasicBlock::getFirstNonPHIOrDbgOrAlloca() const {
  212. const Instruction *FirstNonPHI = getFirstNonPHI();
  213. if (!FirstNonPHI)
  214. return end();
  215. const_iterator InsertPt = FirstNonPHI->getIterator();
  216. if (InsertPt->isEHPad())
  217. ++InsertPt;
  218. if (isEntryBlock()) {
  219. const_iterator End = end();
  220. while (InsertPt != End &&
  221. (isa<AllocaInst>(*InsertPt) || isa<DbgInfoIntrinsic>(*InsertPt) ||
  222. isa<PseudoProbeInst>(*InsertPt))) {
  223. if (const AllocaInst *AI = dyn_cast<AllocaInst>(&*InsertPt)) {
  224. if (!AI->isStaticAlloca())
  225. break;
  226. }
  227. ++InsertPt;
  228. }
  229. }
  230. return InsertPt;
  231. }
  232. void BasicBlock::dropAllReferences() {
  233. for (Instruction &I : *this)
  234. I.dropAllReferences();
  235. }
  236. const BasicBlock *BasicBlock::getSinglePredecessor() const {
  237. const_pred_iterator PI = pred_begin(this), E = pred_end(this);
  238. if (PI == E) return nullptr; // No preds.
  239. const BasicBlock *ThePred = *PI;
  240. ++PI;
  241. return (PI == E) ? ThePred : nullptr /*multiple preds*/;
  242. }
  243. const BasicBlock *BasicBlock::getUniquePredecessor() const {
  244. const_pred_iterator PI = pred_begin(this), E = pred_end(this);
  245. if (PI == E) return nullptr; // No preds.
  246. const BasicBlock *PredBB = *PI;
  247. ++PI;
  248. for (;PI != E; ++PI) {
  249. if (*PI != PredBB)
  250. return nullptr;
  251. // The same predecessor appears multiple times in the predecessor list.
  252. // This is OK.
  253. }
  254. return PredBB;
  255. }
  256. bool BasicBlock::hasNPredecessors(unsigned N) const {
  257. return hasNItems(pred_begin(this), pred_end(this), N);
  258. }
  259. bool BasicBlock::hasNPredecessorsOrMore(unsigned N) const {
  260. return hasNItemsOrMore(pred_begin(this), pred_end(this), N);
  261. }
  262. const BasicBlock *BasicBlock::getSingleSuccessor() const {
  263. const_succ_iterator SI = succ_begin(this), E = succ_end(this);
  264. if (SI == E) return nullptr; // no successors
  265. const BasicBlock *TheSucc = *SI;
  266. ++SI;
  267. return (SI == E) ? TheSucc : nullptr /* multiple successors */;
  268. }
  269. const BasicBlock *BasicBlock::getUniqueSuccessor() const {
  270. const_succ_iterator SI = succ_begin(this), E = succ_end(this);
  271. if (SI == E) return nullptr; // No successors
  272. const BasicBlock *SuccBB = *SI;
  273. ++SI;
  274. for (;SI != E; ++SI) {
  275. if (*SI != SuccBB)
  276. return nullptr;
  277. // The same successor appears multiple times in the successor list.
  278. // This is OK.
  279. }
  280. return SuccBB;
  281. }
  282. iterator_range<BasicBlock::phi_iterator> BasicBlock::phis() {
  283. PHINode *P = empty() ? nullptr : dyn_cast<PHINode>(&*begin());
  284. return make_range<phi_iterator>(P, nullptr);
  285. }
  286. void BasicBlock::removePredecessor(BasicBlock *Pred,
  287. bool KeepOneInputPHIs) {
  288. // Use hasNUsesOrMore to bound the cost of this assertion for complex CFGs.
  289. assert((hasNUsesOrMore(16) || llvm::is_contained(predecessors(this), Pred)) &&
  290. "Pred is not a predecessor!");
  291. // Return early if there are no PHI nodes to update.
  292. if (empty() || !isa<PHINode>(begin()))
  293. return;
  294. unsigned NumPreds = cast<PHINode>(front()).getNumIncomingValues();
  295. for (PHINode &Phi : make_early_inc_range(phis())) {
  296. Phi.removeIncomingValue(Pred, !KeepOneInputPHIs);
  297. if (KeepOneInputPHIs)
  298. continue;
  299. // If we have a single predecessor, removeIncomingValue may have erased the
  300. // PHI node itself.
  301. if (NumPreds == 1)
  302. continue;
  303. // Try to replace the PHI node with a constant value.
  304. if (Value *PhiConstant = Phi.hasConstantValue()) {
  305. Phi.replaceAllUsesWith(PhiConstant);
  306. Phi.eraseFromParent();
  307. }
  308. }
  309. }
  310. bool BasicBlock::canSplitPredecessors() const {
  311. const Instruction *FirstNonPHI = getFirstNonPHI();
  312. if (isa<LandingPadInst>(FirstNonPHI))
  313. return true;
  314. // This is perhaps a little conservative because constructs like
  315. // CleanupBlockInst are pretty easy to split. However, SplitBlockPredecessors
  316. // cannot handle such things just yet.
  317. if (FirstNonPHI->isEHPad())
  318. return false;
  319. return true;
  320. }
  321. bool BasicBlock::isLegalToHoistInto() const {
  322. auto *Term = getTerminator();
  323. // No terminator means the block is under construction.
  324. if (!Term)
  325. return true;
  326. // If the block has no successors, there can be no instructions to hoist.
  327. assert(Term->getNumSuccessors() > 0);
  328. // Instructions should not be hoisted across exception handling boundaries.
  329. return !Term->isExceptionalTerminator();
  330. }
  331. bool BasicBlock::isEntryBlock() const {
  332. const Function *F = getParent();
  333. assert(F && "Block must have a parent function to use this API");
  334. return this == &F->getEntryBlock();
  335. }
  336. BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName,
  337. bool Before) {
  338. if (Before)
  339. return splitBasicBlockBefore(I, BBName);
  340. assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
  341. assert(I != InstList.end() &&
  342. "Trying to get me to create degenerate basic block!");
  343. BasicBlock *New = BasicBlock::Create(getContext(), BBName, getParent(),
  344. this->getNextNode());
  345. // Save DebugLoc of split point before invalidating iterator.
  346. DebugLoc Loc = I->getDebugLoc();
  347. // Move all of the specified instructions from the original basic block into
  348. // the new basic block.
  349. New->splice(New->end(), this, I, end());
  350. // Add a branch instruction to the newly formed basic block.
  351. BranchInst *BI = BranchInst::Create(New, this);
  352. BI->setDebugLoc(Loc);
  353. // Now we must loop through all of the successors of the New block (which
  354. // _were_ the successors of the 'this' block), and update any PHI nodes in
  355. // successors. If there were PHI nodes in the successors, then they need to
  356. // know that incoming branches will be from New, not from Old (this).
  357. //
  358. New->replaceSuccessorsPhiUsesWith(this, New);
  359. return New;
  360. }
  361. BasicBlock *BasicBlock::splitBasicBlockBefore(iterator I, const Twine &BBName) {
  362. assert(getTerminator() &&
  363. "Can't use splitBasicBlockBefore on degenerate BB!");
  364. assert(I != InstList.end() &&
  365. "Trying to get me to create degenerate basic block!");
  366. assert((!isa<PHINode>(*I) || getSinglePredecessor()) &&
  367. "cannot split on multi incoming phis");
  368. BasicBlock *New = BasicBlock::Create(getContext(), BBName, getParent(), this);
  369. // Save DebugLoc of split point before invalidating iterator.
  370. DebugLoc Loc = I->getDebugLoc();
  371. // Move all of the specified instructions from the original basic block into
  372. // the new basic block.
  373. New->splice(New->end(), this, begin(), I);
  374. // Loop through all of the predecessors of the 'this' block (which will be the
  375. // predecessors of the New block), replace the specified successor 'this'
  376. // block to point at the New block and update any PHI nodes in 'this' block.
  377. // If there were PHI nodes in 'this' block, the PHI nodes are updated
  378. // to reflect that the incoming branches will be from the New block and not
  379. // from predecessors of the 'this' block.
  380. // Save predecessors to separate vector before modifying them.
  381. SmallVector<BasicBlock *, 4> Predecessors;
  382. for (BasicBlock *Pred : predecessors(this))
  383. Predecessors.push_back(Pred);
  384. for (BasicBlock *Pred : Predecessors) {
  385. Instruction *TI = Pred->getTerminator();
  386. TI->replaceSuccessorWith(this, New);
  387. this->replacePhiUsesWith(Pred, New);
  388. }
  389. // Add a branch instruction from "New" to "this" Block.
  390. BranchInst *BI = BranchInst::Create(this, New);
  391. BI->setDebugLoc(Loc);
  392. return New;
  393. }
  394. void BasicBlock::splice(BasicBlock::iterator ToIt, BasicBlock *FromBB,
  395. BasicBlock::iterator FromBeginIt,
  396. BasicBlock::iterator FromEndIt) {
  397. #ifdef EXPENSIVE_CHECKS
  398. // Check that FromBeginIt is befor FromEndIt.
  399. auto FromBBEnd = FromBB->end();
  400. for (auto It = FromBeginIt; It != FromEndIt; ++It)
  401. assert(It != FromBBEnd && "FromBeginIt not before FromEndIt!");
  402. #endif // EXPENSIVE_CHECKS
  403. getInstList().splice(ToIt, FromBB->getInstList(), FromBeginIt, FromEndIt);
  404. }
  405. BasicBlock::iterator BasicBlock::erase(BasicBlock::iterator FromIt,
  406. BasicBlock::iterator ToIt) {
  407. return InstList.erase(FromIt, ToIt);
  408. }
  409. void BasicBlock::replacePhiUsesWith(BasicBlock *Old, BasicBlock *New) {
  410. // N.B. This might not be a complete BasicBlock, so don't assume
  411. // that it ends with a non-phi instruction.
  412. for (Instruction &I : *this) {
  413. PHINode *PN = dyn_cast<PHINode>(&I);
  414. if (!PN)
  415. break;
  416. PN->replaceIncomingBlockWith(Old, New);
  417. }
  418. }
  419. void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *Old,
  420. BasicBlock *New) {
  421. Instruction *TI = getTerminator();
  422. if (!TI)
  423. // Cope with being called on a BasicBlock that doesn't have a terminator
  424. // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.
  425. return;
  426. for (BasicBlock *Succ : successors(TI))
  427. Succ->replacePhiUsesWith(Old, New);
  428. }
  429. void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) {
  430. this->replaceSuccessorsPhiUsesWith(this, New);
  431. }
  432. bool BasicBlock::isLandingPad() const {
  433. return isa<LandingPadInst>(getFirstNonPHI());
  434. }
  435. const LandingPadInst *BasicBlock::getLandingPadInst() const {
  436. return dyn_cast<LandingPadInst>(getFirstNonPHI());
  437. }
  438. std::optional<uint64_t> BasicBlock::getIrrLoopHeaderWeight() const {
  439. const Instruction *TI = getTerminator();
  440. if (MDNode *MDIrrLoopHeader =
  441. TI->getMetadata(LLVMContext::MD_irr_loop)) {
  442. MDString *MDName = cast<MDString>(MDIrrLoopHeader->getOperand(0));
  443. if (MDName->getString().equals("loop_header_weight")) {
  444. auto *CI = mdconst::extract<ConstantInt>(MDIrrLoopHeader->getOperand(1));
  445. return std::optional<uint64_t>(CI->getValue().getZExtValue());
  446. }
  447. }
  448. return std::nullopt;
  449. }
  450. BasicBlock::iterator llvm::skipDebugIntrinsics(BasicBlock::iterator It) {
  451. while (isa<DbgInfoIntrinsic>(It))
  452. ++It;
  453. return It;
  454. }
  455. void BasicBlock::renumberInstructions() {
  456. unsigned Order = 0;
  457. for (Instruction &I : *this)
  458. I.Order = Order++;
  459. // Set the bit to indicate that the instruction order valid and cached.
  460. BasicBlockBits Bits = getBasicBlockBits();
  461. Bits.InstrOrderValid = true;
  462. setBasicBlockBits(Bits);
  463. NumInstrRenumberings++;
  464. }
  465. #ifndef NDEBUG
  466. /// In asserts builds, this checks the numbering. In non-asserts builds, it
  467. /// is defined as a no-op inline function in BasicBlock.h.
  468. void BasicBlock::validateInstrOrdering() const {
  469. if (!isInstrOrderValid())
  470. return;
  471. const Instruction *Prev = nullptr;
  472. for (const Instruction &I : *this) {
  473. assert((!Prev || Prev->comesBefore(&I)) &&
  474. "cached instruction ordering is incorrect");
  475. Prev = &I;
  476. }
  477. }
  478. #endif