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