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