BasicBlock.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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->getBasicBlockList().insert(InsertBefore->getIterator(), this);
  54. else
  55. NewParent->getBasicBlockList().push_back(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()->getBasicBlockList().splice(
  116. MovePos->getIterator(), getParent()->getBasicBlockList(), getIterator());
  117. }
  118. void BasicBlock::moveAfter(BasicBlock *MovePos) {
  119. MovePos->getParent()->getBasicBlockList().splice(
  120. ++MovePos->getIterator(), getParent()->getBasicBlockList(),
  121. getIterator());
  122. }
  123. const Module *BasicBlock::getModule() const {
  124. return getParent()->getParent();
  125. }
  126. const Instruction *BasicBlock::getTerminator() const {
  127. if (InstList.empty() || !InstList.back().isTerminator())
  128. return nullptr;
  129. return &InstList.back();
  130. }
  131. const CallInst *BasicBlock::getTerminatingMustTailCall() const {
  132. if (InstList.empty())
  133. return nullptr;
  134. const ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back());
  135. if (!RI || RI == &InstList.front())
  136. return nullptr;
  137. const Instruction *Prev = RI->getPrevNode();
  138. if (!Prev)
  139. return nullptr;
  140. if (Value *RV = RI->getReturnValue()) {
  141. if (RV != Prev)
  142. return nullptr;
  143. // Look through the optional bitcast.
  144. if (auto *BI = dyn_cast<BitCastInst>(Prev)) {
  145. RV = BI->getOperand(0);
  146. Prev = BI->getPrevNode();
  147. if (!Prev || RV != Prev)
  148. return nullptr;
  149. }
  150. }
  151. if (auto *CI = dyn_cast<CallInst>(Prev)) {
  152. if (CI->isMustTailCall())
  153. return CI;
  154. }
  155. return nullptr;
  156. }
  157. const CallInst *BasicBlock::getTerminatingDeoptimizeCall() const {
  158. if (InstList.empty())
  159. return nullptr;
  160. auto *RI = dyn_cast<ReturnInst>(&InstList.back());
  161. if (!RI || RI == &InstList.front())
  162. return nullptr;
  163. if (auto *CI = dyn_cast_or_null<CallInst>(RI->getPrevNode()))
  164. if (Function *F = CI->getCalledFunction())
  165. if (F->getIntrinsicID() == Intrinsic::experimental_deoptimize)
  166. return CI;
  167. return nullptr;
  168. }
  169. const CallInst *BasicBlock::getPostdominatingDeoptimizeCall() const {
  170. const BasicBlock* BB = this;
  171. SmallPtrSet<const BasicBlock *, 8> Visited;
  172. Visited.insert(BB);
  173. while (auto *Succ = BB->getUniqueSuccessor()) {
  174. if (!Visited.insert(Succ).second)
  175. return nullptr;
  176. BB = Succ;
  177. }
  178. return BB->getTerminatingDeoptimizeCall();
  179. }
  180. const Instruction* BasicBlock::getFirstNonPHI() const {
  181. for (const Instruction &I : *this)
  182. if (!isa<PHINode>(I))
  183. return &I;
  184. return nullptr;
  185. }
  186. const Instruction *BasicBlock::getFirstNonPHIOrDbg(bool SkipPseudoOp) const {
  187. for (const Instruction &I : *this) {
  188. if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))
  189. continue;
  190. if (SkipPseudoOp && isa<PseudoProbeInst>(I))
  191. continue;
  192. return &I;
  193. }
  194. return nullptr;
  195. }
  196. const Instruction *
  197. BasicBlock::getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp) const {
  198. for (const Instruction &I : *this) {
  199. if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))
  200. continue;
  201. if (I.isLifetimeStartOrEnd())
  202. continue;
  203. if (SkipPseudoOp && isa<PseudoProbeInst>(I))
  204. continue;
  205. return &I;
  206. }
  207. return nullptr;
  208. }
  209. BasicBlock::const_iterator BasicBlock::getFirstInsertionPt() const {
  210. const Instruction *FirstNonPHI = getFirstNonPHI();
  211. if (!FirstNonPHI)
  212. return end();
  213. const_iterator InsertPt = FirstNonPHI->getIterator();
  214. if (InsertPt->isEHPad()) ++InsertPt;
  215. return InsertPt;
  216. }
  217. void BasicBlock::dropAllReferences() {
  218. for (Instruction &I : *this)
  219. I.dropAllReferences();
  220. }
  221. const BasicBlock *BasicBlock::getSinglePredecessor() const {
  222. const_pred_iterator PI = pred_begin(this), E = pred_end(this);
  223. if (PI == E) return nullptr; // No preds.
  224. const BasicBlock *ThePred = *PI;
  225. ++PI;
  226. return (PI == E) ? ThePred : nullptr /*multiple preds*/;
  227. }
  228. const BasicBlock *BasicBlock::getUniquePredecessor() const {
  229. const_pred_iterator PI = pred_begin(this), E = pred_end(this);
  230. if (PI == E) return nullptr; // No preds.
  231. const BasicBlock *PredBB = *PI;
  232. ++PI;
  233. for (;PI != E; ++PI) {
  234. if (*PI != PredBB)
  235. return nullptr;
  236. // The same predecessor appears multiple times in the predecessor list.
  237. // This is OK.
  238. }
  239. return PredBB;
  240. }
  241. bool BasicBlock::hasNPredecessors(unsigned N) const {
  242. return hasNItems(pred_begin(this), pred_end(this), N);
  243. }
  244. bool BasicBlock::hasNPredecessorsOrMore(unsigned N) const {
  245. return hasNItemsOrMore(pred_begin(this), pred_end(this), N);
  246. }
  247. const BasicBlock *BasicBlock::getSingleSuccessor() const {
  248. const_succ_iterator SI = succ_begin(this), E = succ_end(this);
  249. if (SI == E) return nullptr; // no successors
  250. const BasicBlock *TheSucc = *SI;
  251. ++SI;
  252. return (SI == E) ? TheSucc : nullptr /* multiple successors */;
  253. }
  254. const BasicBlock *BasicBlock::getUniqueSuccessor() const {
  255. const_succ_iterator SI = succ_begin(this), E = succ_end(this);
  256. if (SI == E) return nullptr; // No successors
  257. const BasicBlock *SuccBB = *SI;
  258. ++SI;
  259. for (;SI != E; ++SI) {
  260. if (*SI != SuccBB)
  261. return nullptr;
  262. // The same successor appears multiple times in the successor list.
  263. // This is OK.
  264. }
  265. return SuccBB;
  266. }
  267. iterator_range<BasicBlock::phi_iterator> BasicBlock::phis() {
  268. PHINode *P = empty() ? nullptr : dyn_cast<PHINode>(&*begin());
  269. return make_range<phi_iterator>(P, nullptr);
  270. }
  271. void BasicBlock::removePredecessor(BasicBlock *Pred,
  272. bool KeepOneInputPHIs) {
  273. // Use hasNUsesOrMore to bound the cost of this assertion for complex CFGs.
  274. assert((hasNUsesOrMore(16) || llvm::is_contained(predecessors(this), Pred)) &&
  275. "Pred is not a predecessor!");
  276. // Return early if there are no PHI nodes to update.
  277. if (empty() || !isa<PHINode>(begin()))
  278. return;
  279. unsigned NumPreds = cast<PHINode>(front()).getNumIncomingValues();
  280. for (PHINode &Phi : make_early_inc_range(phis())) {
  281. Phi.removeIncomingValue(Pred, !KeepOneInputPHIs);
  282. if (KeepOneInputPHIs)
  283. continue;
  284. // If we have a single predecessor, removeIncomingValue may have erased the
  285. // PHI node itself.
  286. if (NumPreds == 1)
  287. continue;
  288. // Try to replace the PHI node with a constant value.
  289. if (Value *PhiConstant = Phi.hasConstantValue()) {
  290. Phi.replaceAllUsesWith(PhiConstant);
  291. Phi.eraseFromParent();
  292. }
  293. }
  294. }
  295. bool BasicBlock::canSplitPredecessors() const {
  296. const Instruction *FirstNonPHI = getFirstNonPHI();
  297. if (isa<LandingPadInst>(FirstNonPHI))
  298. return true;
  299. // This is perhaps a little conservative because constructs like
  300. // CleanupBlockInst are pretty easy to split. However, SplitBlockPredecessors
  301. // cannot handle such things just yet.
  302. if (FirstNonPHI->isEHPad())
  303. return false;
  304. return true;
  305. }
  306. bool BasicBlock::isLegalToHoistInto() const {
  307. auto *Term = getTerminator();
  308. // No terminator means the block is under construction.
  309. if (!Term)
  310. return true;
  311. // If the block has no successors, there can be no instructions to hoist.
  312. assert(Term->getNumSuccessors() > 0);
  313. // Instructions should not be hoisted across exception handling boundaries.
  314. return !Term->isExceptionalTerminator();
  315. }
  316. bool BasicBlock::isEntryBlock() const {
  317. const Function *F = getParent();
  318. assert(F && "Block must have a parent function to use this API");
  319. return this == &F->getEntryBlock();
  320. }
  321. BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName,
  322. bool Before) {
  323. if (Before)
  324. return splitBasicBlockBefore(I, BBName);
  325. assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
  326. assert(I != InstList.end() &&
  327. "Trying to get me to create degenerate basic block!");
  328. BasicBlock *New = BasicBlock::Create(getContext(), BBName, getParent(),
  329. this->getNextNode());
  330. // Save DebugLoc of split point before invalidating iterator.
  331. DebugLoc Loc = I->getDebugLoc();
  332. // Move all of the specified instructions from the original basic block into
  333. // the new basic block.
  334. New->getInstList().splice(New->end(), this->getInstList(), I, end());
  335. // Add a branch instruction to the newly formed basic block.
  336. BranchInst *BI = BranchInst::Create(New, this);
  337. BI->setDebugLoc(Loc);
  338. // Now we must loop through all of the successors of the New block (which
  339. // _were_ the successors of the 'this' block), and update any PHI nodes in
  340. // successors. If there were PHI nodes in the successors, then they need to
  341. // know that incoming branches will be from New, not from Old (this).
  342. //
  343. New->replaceSuccessorsPhiUsesWith(this, New);
  344. return New;
  345. }
  346. BasicBlock *BasicBlock::splitBasicBlockBefore(iterator I, const Twine &BBName) {
  347. assert(getTerminator() &&
  348. "Can't use splitBasicBlockBefore on degenerate BB!");
  349. assert(I != InstList.end() &&
  350. "Trying to get me to create degenerate basic block!");
  351. assert((!isa<PHINode>(*I) || getSinglePredecessor()) &&
  352. "cannot split on multi incoming phis");
  353. BasicBlock *New = BasicBlock::Create(getContext(), BBName, getParent(), this);
  354. // Save DebugLoc of split point before invalidating iterator.
  355. DebugLoc Loc = I->getDebugLoc();
  356. // Move all of the specified instructions from the original basic block into
  357. // the new basic block.
  358. New->getInstList().splice(New->end(), this->getInstList(), begin(), I);
  359. // Loop through all of the predecessors of the 'this' block (which will be the
  360. // predecessors of the New block), replace the specified successor 'this'
  361. // block to point at the New block and update any PHI nodes in 'this' block.
  362. // If there were PHI nodes in 'this' block, the PHI nodes are updated
  363. // to reflect that the incoming branches will be from the New block and not
  364. // from predecessors of the 'this' block.
  365. for (BasicBlock *Pred : predecessors(this)) {
  366. Instruction *TI = Pred->getTerminator();
  367. TI->replaceSuccessorWith(this, New);
  368. this->replacePhiUsesWith(Pred, New);
  369. }
  370. // Add a branch instruction from "New" to "this" Block.
  371. BranchInst *BI = BranchInst::Create(this, New);
  372. BI->setDebugLoc(Loc);
  373. return New;
  374. }
  375. void BasicBlock::replacePhiUsesWith(BasicBlock *Old, BasicBlock *New) {
  376. // N.B. This might not be a complete BasicBlock, so don't assume
  377. // that it ends with a non-phi instruction.
  378. for (Instruction &I : *this) {
  379. PHINode *PN = dyn_cast<PHINode>(&I);
  380. if (!PN)
  381. break;
  382. PN->replaceIncomingBlockWith(Old, New);
  383. }
  384. }
  385. void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *Old,
  386. BasicBlock *New) {
  387. Instruction *TI = getTerminator();
  388. if (!TI)
  389. // Cope with being called on a BasicBlock that doesn't have a terminator
  390. // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.
  391. return;
  392. for (BasicBlock *Succ : successors(TI))
  393. Succ->replacePhiUsesWith(Old, New);
  394. }
  395. void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) {
  396. this->replaceSuccessorsPhiUsesWith(this, New);
  397. }
  398. bool BasicBlock::isLandingPad() const {
  399. return isa<LandingPadInst>(getFirstNonPHI());
  400. }
  401. const LandingPadInst *BasicBlock::getLandingPadInst() const {
  402. return dyn_cast<LandingPadInst>(getFirstNonPHI());
  403. }
  404. Optional<uint64_t> BasicBlock::getIrrLoopHeaderWeight() const {
  405. const Instruction *TI = getTerminator();
  406. if (MDNode *MDIrrLoopHeader =
  407. TI->getMetadata(LLVMContext::MD_irr_loop)) {
  408. MDString *MDName = cast<MDString>(MDIrrLoopHeader->getOperand(0));
  409. if (MDName->getString().equals("loop_header_weight")) {
  410. auto *CI = mdconst::extract<ConstantInt>(MDIrrLoopHeader->getOperand(1));
  411. return Optional<uint64_t>(CI->getValue().getZExtValue());
  412. }
  413. }
  414. return Optional<uint64_t>();
  415. }
  416. BasicBlock::iterator llvm::skipDebugIntrinsics(BasicBlock::iterator It) {
  417. while (isa<DbgInfoIntrinsic>(It))
  418. ++It;
  419. return It;
  420. }
  421. void BasicBlock::renumberInstructions() {
  422. unsigned Order = 0;
  423. for (Instruction &I : *this)
  424. I.Order = Order++;
  425. // Set the bit to indicate that the instruction order valid and cached.
  426. BasicBlockBits Bits = getBasicBlockBits();
  427. Bits.InstrOrderValid = true;
  428. setBasicBlockBits(Bits);
  429. NumInstrRenumberings++;
  430. }
  431. #ifndef NDEBUG
  432. /// In asserts builds, this checks the numbering. In non-asserts builds, it
  433. /// is defined as a no-op inline function in BasicBlock.h.
  434. void BasicBlock::validateInstrOrdering() const {
  435. if (!isInstrOrderValid())
  436. return;
  437. const Instruction *Prev = nullptr;
  438. for (const Instruction &I : *this) {
  439. assert((!Prev || Prev->comesBefore(&I)) &&
  440. "cached instruction ordering is incorrect");
  441. Prev = &I;
  442. }
  443. }
  444. #endif