BasicBlock.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. //===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
  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 file implements the BasicBlock class for the IR library.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/IR/BasicBlock.h"
  14. #include "SymbolTableListTraitsImpl.h"
  15. #include "llvm/ADT/STLExtras.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. #include <algorithm>
  23. using namespace llvm;
  24. ValueSymbolTable *BasicBlock::getValueSymbolTable() {
  25. if (Function *F = getParent())
  26. return &F->getValueSymbolTable();
  27. return nullptr;
  28. }
  29. LLVMContext &BasicBlock::getContext() const {
  30. return getType()->getContext();
  31. }
  32. // Explicit instantiation of SymbolTableListTraits since some of the methods
  33. // are not in the public header file...
  34. template class llvm::SymbolTableListTraits<Instruction, BasicBlock>;
  35. BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent,
  36. BasicBlock *InsertBefore)
  37. : Value(Type::getLabelTy(C), Value::BasicBlockVal), Parent(nullptr) {
  38. // HLSL Change Begin
  39. // Do everything that can throw before inserting into the
  40. // linked list, which takes ownership of this object on success.
  41. setName(Name);
  42. // HLSL Change End
  43. if (NewParent)
  44. insertInto(NewParent, InsertBefore);
  45. else
  46. assert(!InsertBefore &&
  47. "Cannot insert block before another block with no function!");
  48. // setName(Name); // HLSL Change: moved above
  49. }
  50. void BasicBlock::insertInto(Function *NewParent, BasicBlock *InsertBefore) {
  51. assert(NewParent && "Expected a parent");
  52. assert(!Parent && "Already has a parent");
  53. if (InsertBefore)
  54. NewParent->getBasicBlockList().insert(InsertBefore, this);
  55. else
  56. NewParent->getBasicBlockList().push_back(this);
  57. }
  58. BasicBlock::~BasicBlock() {
  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. void BasicBlock::removeFromParent() {
  85. getParent()->getBasicBlockList().remove(this);
  86. }
  87. iplist<BasicBlock>::iterator BasicBlock::eraseFromParent() {
  88. return getParent()->getBasicBlockList().erase(this);
  89. }
  90. /// Unlink this basic block from its current function and
  91. /// insert it into the function that MovePos lives in, right before MovePos.
  92. void BasicBlock::moveBefore(BasicBlock *MovePos) {
  93. MovePos->getParent()->getBasicBlockList().splice(MovePos,
  94. getParent()->getBasicBlockList(), this);
  95. }
  96. /// Unlink this basic block from its current function and
  97. /// insert it into the function that MovePos lives in, right after MovePos.
  98. void BasicBlock::moveAfter(BasicBlock *MovePos) {
  99. Function::iterator I = MovePos;
  100. MovePos->getParent()->getBasicBlockList().splice(++I,
  101. getParent()->getBasicBlockList(), this);
  102. }
  103. const Module *BasicBlock::getModule() const {
  104. return getParent()->getParent();
  105. }
  106. Module *BasicBlock::getModule() {
  107. return getParent()->getParent();
  108. }
  109. TerminatorInst *BasicBlock::getTerminator() {
  110. if (InstList.empty()) return nullptr;
  111. return dyn_cast<TerminatorInst>(&InstList.back());
  112. }
  113. const TerminatorInst *BasicBlock::getTerminator() const {
  114. if (InstList.empty()) return nullptr;
  115. return dyn_cast<TerminatorInst>(&InstList.back());
  116. }
  117. CallInst *BasicBlock::getTerminatingMustTailCall() {
  118. if (InstList.empty())
  119. return nullptr;
  120. ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back());
  121. if (!RI || RI == &InstList.front())
  122. return nullptr;
  123. Instruction *Prev = RI->getPrevNode();
  124. if (!Prev)
  125. return nullptr;
  126. if (Value *RV = RI->getReturnValue()) {
  127. if (RV != Prev)
  128. return nullptr;
  129. // Look through the optional bitcast.
  130. if (auto *BI = dyn_cast<BitCastInst>(Prev)) {
  131. RV = BI->getOperand(0);
  132. Prev = BI->getPrevNode();
  133. if (!Prev || RV != Prev)
  134. return nullptr;
  135. }
  136. }
  137. if (auto *CI = dyn_cast<CallInst>(Prev)) {
  138. if (CI->isMustTailCall())
  139. return CI;
  140. }
  141. return nullptr;
  142. }
  143. // HLSL Change - begin
  144. size_t BasicBlock::compute_size_no_dbg() const {
  145. size_t ret = 0;
  146. for (auto it = InstList.begin(), E = InstList.end(); it != E; it++) {
  147. if (isa<DbgInfoIntrinsic>(&*it))
  148. continue;
  149. ret++;
  150. }
  151. return ret;
  152. }
  153. // HLSL Change - end
  154. Instruction* BasicBlock::getFirstNonPHI() {
  155. for (Instruction &I : *this)
  156. if (!isa<PHINode>(I))
  157. return &I;
  158. return nullptr;
  159. }
  160. Instruction* BasicBlock::getFirstNonPHIOrDbg() {
  161. for (Instruction &I : *this)
  162. if (!isa<PHINode>(I) && !isa<DbgInfoIntrinsic>(I))
  163. return &I;
  164. return nullptr;
  165. }
  166. Instruction* BasicBlock::getFirstNonPHIOrDbgOrLifetime() {
  167. for (Instruction &I : *this) {
  168. if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))
  169. continue;
  170. if (auto *II = dyn_cast<IntrinsicInst>(&I))
  171. if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
  172. II->getIntrinsicID() == Intrinsic::lifetime_end)
  173. continue;
  174. return &I;
  175. }
  176. return nullptr;
  177. }
  178. BasicBlock::iterator BasicBlock::getFirstInsertionPt() {
  179. Instruction *FirstNonPHI = getFirstNonPHI();
  180. if (!FirstNonPHI)
  181. return end();
  182. iterator InsertPt = FirstNonPHI;
  183. if (isa<LandingPadInst>(InsertPt)) ++InsertPt;
  184. return InsertPt;
  185. }
  186. void BasicBlock::dropAllReferences() {
  187. for(iterator I = begin(), E = end(); I != E; ++I)
  188. I->dropAllReferences();
  189. }
  190. /// If this basic block has a single predecessor block,
  191. /// return the block, otherwise return a null pointer.
  192. BasicBlock *BasicBlock::getSinglePredecessor() {
  193. pred_iterator PI = pred_begin(this), E = pred_end(this);
  194. if (PI == E) return nullptr; // No preds.
  195. BasicBlock *ThePred = *PI;
  196. ++PI;
  197. return (PI == E) ? ThePred : nullptr /*multiple preds*/;
  198. }
  199. /// If this basic block has a unique predecessor block,
  200. /// return the block, otherwise return a null pointer.
  201. /// Note that unique predecessor doesn't mean single edge, there can be
  202. /// multiple edges from the unique predecessor to this block (for example
  203. /// a switch statement with multiple cases having the same destination).
  204. BasicBlock *BasicBlock::getUniquePredecessor() {
  205. pred_iterator PI = pred_begin(this), E = pred_end(this);
  206. if (PI == E) return nullptr; // No preds.
  207. BasicBlock *PredBB = *PI;
  208. ++PI;
  209. for (;PI != E; ++PI) {
  210. if (*PI != PredBB)
  211. return nullptr;
  212. // The same predecessor appears multiple times in the predecessor list.
  213. // This is OK.
  214. }
  215. return PredBB;
  216. }
  217. BasicBlock *BasicBlock::getSingleSuccessor() {
  218. succ_iterator SI = succ_begin(this), E = succ_end(this);
  219. if (SI == E) return nullptr; // no successors
  220. BasicBlock *TheSucc = *SI;
  221. ++SI;
  222. return (SI == E) ? TheSucc : nullptr /* multiple successors */;
  223. }
  224. BasicBlock *BasicBlock::getUniqueSuccessor() {
  225. succ_iterator SI = succ_begin(this), E = succ_end(this);
  226. if (SI == E) return NULL; // No successors
  227. BasicBlock *SuccBB = *SI;
  228. ++SI;
  229. for (;SI != E; ++SI) {
  230. if (*SI != SuccBB)
  231. return NULL;
  232. // The same successor appears multiple times in the successor list.
  233. // This is OK.
  234. }
  235. return SuccBB;
  236. }
  237. /// This method is used to notify a BasicBlock that the
  238. /// specified Predecessor of the block is no longer able to reach it. This is
  239. /// actually not used to update the Predecessor list, but is actually used to
  240. /// update the PHI nodes that reside in the block. Note that this should be
  241. /// called while the predecessor still refers to this block.
  242. ///
  243. void BasicBlock::removePredecessor(BasicBlock *Pred,
  244. bool DontDeleteUselessPHIs) {
  245. assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
  246. find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
  247. "removePredecessor: BB is not a predecessor!");
  248. if (InstList.empty()) return;
  249. PHINode *APN = dyn_cast<PHINode>(&front());
  250. if (!APN) return; // Quick exit.
  251. // If there are exactly two predecessors, then we want to nuke the PHI nodes
  252. // altogether. However, we cannot do this, if this in this case:
  253. //
  254. // Loop:
  255. // %x = phi [X, Loop]
  256. // %x2 = add %x, 1 ;; This would become %x2 = add %x2, 1
  257. // br Loop ;; %x2 does not dominate all uses
  258. //
  259. // This is because the PHI node input is actually taken from the predecessor
  260. // basic block. The only case this can happen is with a self loop, so we
  261. // check for this case explicitly now.
  262. //
  263. unsigned max_idx = APN->getNumIncomingValues();
  264. assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
  265. if (max_idx == 2) {
  266. BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
  267. // Disable PHI elimination!
  268. if (this == Other) max_idx = 3;
  269. }
  270. // <= Two predecessors BEFORE I remove one?
  271. if (max_idx <= 2 && !DontDeleteUselessPHIs) {
  272. // Yup, loop through and nuke the PHI nodes
  273. while (PHINode *PN = dyn_cast<PHINode>(&front())) {
  274. // Remove the predecessor first.
  275. PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
  276. // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
  277. if (max_idx == 2) {
  278. if (PN->getIncomingValue(0) != PN)
  279. PN->replaceAllUsesWith(PN->getIncomingValue(0));
  280. else
  281. // We are left with an infinite loop with no entries: kill the PHI.
  282. PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
  283. getInstList().pop_front(); // Remove the PHI node
  284. }
  285. // If the PHI node already only had one entry, it got deleted by
  286. // removeIncomingValue.
  287. }
  288. } else {
  289. // Okay, now we know that we need to remove predecessor #pred_idx from all
  290. // PHI nodes. Iterate over each PHI node fixing them up
  291. PHINode *PN;
  292. for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
  293. ++II;
  294. PN->removeIncomingValue(Pred, false);
  295. // If all incoming values to the Phi are the same, we can replace the Phi
  296. // with that value.
  297. Value* PNV = nullptr;
  298. if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue()))
  299. if (PNV != PN) {
  300. PN->replaceAllUsesWith(PNV);
  301. PN->eraseFromParent();
  302. }
  303. }
  304. }
  305. }
  306. /// This splits a basic block into two at the specified
  307. /// instruction. Note that all instructions BEFORE the specified iterator stay
  308. /// as part of the original basic block, an unconditional branch is added to
  309. /// the new BB, and the rest of the instructions in the BB are moved to the new
  310. /// BB, including the old terminator. This invalidates the iterator.
  311. ///
  312. /// Note that this only works on well formed basic blocks (must have a
  313. /// terminator), and 'I' must not be the end of instruction list (which would
  314. /// cause a degenerate basic block to be formed, having a terminator inside of
  315. /// the basic block).
  316. ///
  317. BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName) {
  318. assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
  319. assert(I != InstList.end() &&
  320. "Trying to get me to create degenerate basic block!");
  321. BasicBlock *InsertBefore = std::next(Function::iterator(this))
  322. .getNodePtrUnchecked();
  323. BasicBlock *New = BasicBlock::Create(getContext(), BBName,
  324. getParent(), InsertBefore);
  325. // Save DebugLoc of split point before invalidating iterator.
  326. DebugLoc Loc = I->getDebugLoc();
  327. // Move all of the specified instructions from the original basic block into
  328. // the new basic block.
  329. New->getInstList().splice(New->end(), this->getInstList(), I, end());
  330. // Add a branch instruction to the newly formed basic block.
  331. BranchInst *BI = BranchInst::Create(New, this);
  332. BI->setDebugLoc(Loc);
  333. // Now we must loop through all of the successors of the New block (which
  334. // _were_ the successors of the 'this' block), and update any PHI nodes in
  335. // successors. If there were PHI nodes in the successors, then they need to
  336. // know that incoming branches will be from New, not from Old.
  337. //
  338. for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
  339. // Loop over any phi nodes in the basic block, updating the BB field of
  340. // incoming values...
  341. BasicBlock *Successor = *I;
  342. PHINode *PN;
  343. for (BasicBlock::iterator II = Successor->begin();
  344. (PN = dyn_cast<PHINode>(II)); ++II) {
  345. int IDX = PN->getBasicBlockIndex(this);
  346. while (IDX != -1) {
  347. PN->setIncomingBlock((unsigned)IDX, New);
  348. IDX = PN->getBasicBlockIndex(this);
  349. }
  350. }
  351. }
  352. return New;
  353. }
  354. void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) {
  355. TerminatorInst *TI = getTerminator();
  356. if (!TI)
  357. // Cope with being called on a BasicBlock that doesn't have a terminator
  358. // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.
  359. return;
  360. for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
  361. BasicBlock *Succ = TI->getSuccessor(i);
  362. // N.B. Succ might not be a complete BasicBlock, so don't assume
  363. // that it ends with a non-phi instruction.
  364. for (iterator II = Succ->begin(), IE = Succ->end(); II != IE; ++II) {
  365. PHINode *PN = dyn_cast<PHINode>(II);
  366. if (!PN)
  367. break;
  368. int i;
  369. while ((i = PN->getBasicBlockIndex(this)) >= 0)
  370. PN->setIncomingBlock(i, New);
  371. }
  372. }
  373. }
  374. /// Return true if this basic block is a landing pad. I.e., it's
  375. /// the destination of the 'unwind' edge of an invoke instruction.
  376. bool BasicBlock::isLandingPad() const {
  377. return isa<LandingPadInst>(getFirstNonPHI());
  378. }
  379. /// Return the landingpad instruction associated with the landing pad.
  380. LandingPadInst *BasicBlock::getLandingPadInst() {
  381. return dyn_cast<LandingPadInst>(getFirstNonPHI());
  382. }
  383. const LandingPadInst *BasicBlock::getLandingPadInst() const {
  384. return dyn_cast<LandingPadInst>(getFirstNonPHI());
  385. }