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