LLVM  mainline
BasicBlock.cpp
Go to the documentation of this file.
00001 //===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the BasicBlock class for the IR library.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/IR/BasicBlock.h"
00015 #include "SymbolTableListTraitsImpl.h"
00016 #include "llvm/ADT/STLExtras.h"
00017 #include "llvm/IR/CFG.h"
00018 #include "llvm/IR/Constants.h"
00019 #include "llvm/IR/Instructions.h"
00020 #include "llvm/IR/IntrinsicInst.h"
00021 #include "llvm/IR/LLVMContext.h"
00022 #include "llvm/IR/Type.h"
00023 #include <algorithm>
00024 
00025 using namespace llvm;
00026 
00027 ValueSymbolTable *BasicBlock::getValueSymbolTable() {
00028   if (Function *F = getParent())
00029     return &F->getValueSymbolTable();
00030   return nullptr;
00031 }
00032 
00033 LLVMContext &BasicBlock::getContext() const {
00034   return getType()->getContext();
00035 }
00036 
00037 // Explicit instantiation of SymbolTableListTraits since some of the methods
00038 // are not in the public header file...
00039 template class llvm::SymbolTableListTraits<Instruction>;
00040 
00041 BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent,
00042                        BasicBlock *InsertBefore)
00043   : Value(Type::getLabelTy(C), Value::BasicBlockVal), Parent(nullptr) {
00044 
00045   if (NewParent)
00046     insertInto(NewParent, InsertBefore);
00047   else
00048     assert(!InsertBefore &&
00049            "Cannot insert block before another block with no function!");
00050 
00051   setName(Name);
00052 }
00053 
00054 void BasicBlock::insertInto(Function *NewParent, BasicBlock *InsertBefore) {
00055   assert(NewParent && "Expected a parent");
00056   assert(!Parent && "Already has a parent");
00057 
00058   if (InsertBefore)
00059     NewParent->getBasicBlockList().insert(InsertBefore->getIterator(), this);
00060   else
00061     NewParent->getBasicBlockList().push_back(this);
00062 }
00063 
00064 BasicBlock::~BasicBlock() {
00065   // If the address of the block is taken and it is being deleted (e.g. because
00066   // it is dead), this means that there is either a dangling constant expr
00067   // hanging off the block, or an undefined use of the block (source code
00068   // expecting the address of a label to keep the block alive even though there
00069   // is no indirect branch).  Handle these cases by zapping the BlockAddress
00070   // nodes.  There are no other possible uses at this point.
00071   if (hasAddressTaken()) {
00072     assert(!use_empty() && "There should be at least one blockaddress!");
00073     Constant *Replacement =
00074       ConstantInt::get(llvm::Type::getInt32Ty(getContext()), 1);
00075     while (!use_empty()) {
00076       BlockAddress *BA = cast<BlockAddress>(user_back());
00077       BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
00078                                                        BA->getType()));
00079       BA->destroyConstant();
00080     }
00081   }
00082 
00083   assert(getParent() == nullptr && "BasicBlock still linked into the program!");
00084   dropAllReferences();
00085   InstList.clear();
00086 }
00087 
00088 void BasicBlock::setParent(Function *parent) {
00089   // Set Parent=parent, updating instruction symtab entries as appropriate.
00090   InstList.setSymTabObject(&Parent, parent);
00091 }
00092 
00093 void BasicBlock::removeFromParent() {
00094   getParent()->getBasicBlockList().remove(getIterator());
00095 }
00096 
00097 iplist<BasicBlock>::iterator BasicBlock::eraseFromParent() {
00098   return getParent()->getBasicBlockList().erase(getIterator());
00099 }
00100 
00101 /// Unlink this basic block from its current function and
00102 /// insert it into the function that MovePos lives in, right before MovePos.
00103 void BasicBlock::moveBefore(BasicBlock *MovePos) {
00104   MovePos->getParent()->getBasicBlockList().splice(
00105       MovePos->getIterator(), getParent()->getBasicBlockList(), getIterator());
00106 }
00107 
00108 /// Unlink this basic block from its current function and
00109 /// insert it into the function that MovePos lives in, right after MovePos.
00110 void BasicBlock::moveAfter(BasicBlock *MovePos) {
00111   MovePos->getParent()->getBasicBlockList().splice(
00112       ++MovePos->getIterator(), getParent()->getBasicBlockList(),
00113       getIterator());
00114 }
00115 
00116 const Module *BasicBlock::getModule() const {
00117   return getParent()->getParent();
00118 }
00119 
00120 Module *BasicBlock::getModule() {
00121   return getParent()->getParent();
00122 }
00123 
00124 TerminatorInst *BasicBlock::getTerminator() {
00125   if (InstList.empty()) return nullptr;
00126   return dyn_cast<TerminatorInst>(&InstList.back());
00127 }
00128 
00129 const TerminatorInst *BasicBlock::getTerminator() const {
00130   if (InstList.empty()) return nullptr;
00131   return dyn_cast<TerminatorInst>(&InstList.back());
00132 }
00133 
00134 CallInst *BasicBlock::getTerminatingMustTailCall() {
00135   if (InstList.empty())
00136     return nullptr;
00137   ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back());
00138   if (!RI || RI == &InstList.front())
00139     return nullptr;
00140 
00141   Instruction *Prev = RI->getPrevNode();
00142   if (!Prev)
00143     return nullptr;
00144 
00145   if (Value *RV = RI->getReturnValue()) {
00146     if (RV != Prev)
00147       return nullptr;
00148 
00149     // Look through the optional bitcast.
00150     if (auto *BI = dyn_cast<BitCastInst>(Prev)) {
00151       RV = BI->getOperand(0);
00152       Prev = BI->getPrevNode();
00153       if (!Prev || RV != Prev)
00154         return nullptr;
00155     }
00156   }
00157 
00158   if (auto *CI = dyn_cast<CallInst>(Prev)) {
00159     if (CI->isMustTailCall())
00160       return CI;
00161   }
00162   return nullptr;
00163 }
00164 
00165 Instruction* BasicBlock::getFirstNonPHI() {
00166   for (Instruction &I : *this)
00167     if (!isa<PHINode>(I))
00168       return &I;
00169   return nullptr;
00170 }
00171 
00172 Instruction* BasicBlock::getFirstNonPHIOrDbg() {
00173   for (Instruction &I : *this)
00174     if (!isa<PHINode>(I) && !isa<DbgInfoIntrinsic>(I))
00175       return &I;
00176   return nullptr;
00177 }
00178 
00179 Instruction* BasicBlock::getFirstNonPHIOrDbgOrLifetime() {
00180   for (Instruction &I : *this) {
00181     if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))
00182       continue;
00183 
00184     if (auto *II = dyn_cast<IntrinsicInst>(&I))
00185       if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
00186           II->getIntrinsicID() == Intrinsic::lifetime_end)
00187         continue;
00188 
00189     return &I;
00190   }
00191   return nullptr;
00192 }
00193 
00194 BasicBlock::iterator BasicBlock::getFirstInsertionPt() {
00195   Instruction *FirstNonPHI = getFirstNonPHI();
00196   if (!FirstNonPHI)
00197     return end();
00198 
00199   iterator InsertPt = FirstNonPHI->getIterator();
00200   if (InsertPt->isEHPad()) ++InsertPt;
00201   return InsertPt;
00202 }
00203 
00204 void BasicBlock::dropAllReferences() {
00205   for(iterator I = begin(), E = end(); I != E; ++I)
00206     I->dropAllReferences();
00207 }
00208 
00209 /// If this basic block has a single predecessor block,
00210 /// return the block, otherwise return a null pointer.
00211 BasicBlock *BasicBlock::getSinglePredecessor() {
00212   pred_iterator PI = pred_begin(this), E = pred_end(this);
00213   if (PI == E) return nullptr;         // No preds.
00214   BasicBlock *ThePred = *PI;
00215   ++PI;
00216   return (PI == E) ? ThePred : nullptr /*multiple preds*/;
00217 }
00218 
00219 /// If this basic block has a unique predecessor block,
00220 /// return the block, otherwise return a null pointer.
00221 /// Note that unique predecessor doesn't mean single edge, there can be
00222 /// multiple edges from the unique predecessor to this block (for example
00223 /// a switch statement with multiple cases having the same destination).
00224 BasicBlock *BasicBlock::getUniquePredecessor() {
00225   pred_iterator PI = pred_begin(this), E = pred_end(this);
00226   if (PI == E) return nullptr; // No preds.
00227   BasicBlock *PredBB = *PI;
00228   ++PI;
00229   for (;PI != E; ++PI) {
00230     if (*PI != PredBB)
00231       return nullptr;
00232     // The same predecessor appears multiple times in the predecessor list.
00233     // This is OK.
00234   }
00235   return PredBB;
00236 }
00237 
00238 BasicBlock *BasicBlock::getSingleSuccessor() {
00239   succ_iterator SI = succ_begin(this), E = succ_end(this);
00240   if (SI == E) return nullptr; // no successors
00241   BasicBlock *TheSucc = *SI;
00242   ++SI;
00243   return (SI == E) ? TheSucc : nullptr /* multiple successors */;
00244 }
00245 
00246 BasicBlock *BasicBlock::getUniqueSuccessor() {
00247   succ_iterator SI = succ_begin(this), E = succ_end(this);
00248   if (SI == E) return nullptr; // No successors
00249   BasicBlock *SuccBB = *SI;
00250   ++SI;
00251   for (;SI != E; ++SI) {
00252     if (*SI != SuccBB)
00253       return nullptr;
00254     // The same successor appears multiple times in the successor list.
00255     // This is OK.
00256   }
00257   return SuccBB;
00258 }
00259 
00260 /// This method is used to notify a BasicBlock that the
00261 /// specified Predecessor of the block is no longer able to reach it.  This is
00262 /// actually not used to update the Predecessor list, but is actually used to
00263 /// update the PHI nodes that reside in the block.  Note that this should be
00264 /// called while the predecessor still refers to this block.
00265 ///
00266 void BasicBlock::removePredecessor(BasicBlock *Pred,
00267                                    bool DontDeleteUselessPHIs) {
00268   assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
00269           find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
00270          "removePredecessor: BB is not a predecessor!");
00271 
00272   if (InstList.empty()) return;
00273   PHINode *APN = dyn_cast<PHINode>(&front());
00274   if (!APN) return;   // Quick exit.
00275 
00276   // If there are exactly two predecessors, then we want to nuke the PHI nodes
00277   // altogether.  However, we cannot do this, if this in this case:
00278   //
00279   //  Loop:
00280   //    %x = phi [X, Loop]
00281   //    %x2 = add %x, 1         ;; This would become %x2 = add %x2, 1
00282   //    br Loop                 ;; %x2 does not dominate all uses
00283   //
00284   // This is because the PHI node input is actually taken from the predecessor
00285   // basic block.  The only case this can happen is with a self loop, so we
00286   // check for this case explicitly now.
00287   //
00288   unsigned max_idx = APN->getNumIncomingValues();
00289   assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
00290   if (max_idx == 2) {
00291     BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
00292 
00293     // Disable PHI elimination!
00294     if (this == Other) max_idx = 3;
00295   }
00296 
00297   // <= Two predecessors BEFORE I remove one?
00298   if (max_idx <= 2 && !DontDeleteUselessPHIs) {
00299     // Yup, loop through and nuke the PHI nodes
00300     while (PHINode *PN = dyn_cast<PHINode>(&front())) {
00301       // Remove the predecessor first.
00302       PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
00303 
00304       // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
00305       if (max_idx == 2) {
00306         if (PN->getIncomingValue(0) != PN)
00307           PN->replaceAllUsesWith(PN->getIncomingValue(0));
00308         else
00309           // We are left with an infinite loop with no entries: kill the PHI.
00310           PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
00311         getInstList().pop_front();    // Remove the PHI node
00312       }
00313 
00314       // If the PHI node already only had one entry, it got deleted by
00315       // removeIncomingValue.
00316     }
00317   } else {
00318     // Okay, now we know that we need to remove predecessor #pred_idx from all
00319     // PHI nodes.  Iterate over each PHI node fixing them up
00320     PHINode *PN;
00321     for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
00322       ++II;
00323       PN->removeIncomingValue(Pred, false);
00324       // If all incoming values to the Phi are the same, we can replace the Phi
00325       // with that value.
00326       Value* PNV = nullptr;
00327       if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue()))
00328         if (PNV != PN) {
00329           PN->replaceAllUsesWith(PNV);
00330           PN->eraseFromParent();
00331         }
00332     }
00333   }
00334 }
00335 
00336 bool BasicBlock::canSplitPredecessors() const {
00337   const Instruction *FirstNonPHI = getFirstNonPHI();
00338   if (isa<LandingPadInst>(FirstNonPHI))
00339     return true;
00340   // This is perhaps a little conservative because constructs like
00341   // CleanupBlockInst are pretty easy to split.  However, SplitBlockPredecessors
00342   // cannot handle such things just yet.
00343   if (FirstNonPHI->isEHPad())
00344     return false;
00345   return true;
00346 }
00347 
00348 /// This splits a basic block into two at the specified
00349 /// instruction.  Note that all instructions BEFORE the specified iterator stay
00350 /// as part of the original basic block, an unconditional branch is added to
00351 /// the new BB, and the rest of the instructions in the BB are moved to the new
00352 /// BB, including the old terminator.  This invalidates the iterator.
00353 ///
00354 /// Note that this only works on well formed basic blocks (must have a
00355 /// terminator), and 'I' must not be the end of instruction list (which would
00356 /// cause a degenerate basic block to be formed, having a terminator inside of
00357 /// the basic block).
00358 ///
00359 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName) {
00360   assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
00361   assert(I != InstList.end() &&
00362          "Trying to get me to create degenerate basic block!");
00363 
00364   BasicBlock *InsertBefore = std::next(Function::iterator(this))
00365                                .getNodePtrUnchecked();
00366   BasicBlock *New = BasicBlock::Create(getContext(), BBName,
00367                                        getParent(), InsertBefore);
00368 
00369   // Save DebugLoc of split point before invalidating iterator.
00370   DebugLoc Loc = I->getDebugLoc();
00371   // Move all of the specified instructions from the original basic block into
00372   // the new basic block.
00373   New->getInstList().splice(New->end(), this->getInstList(), I, end());
00374 
00375   // Add a branch instruction to the newly formed basic block.
00376   BranchInst *BI = BranchInst::Create(New, this);
00377   BI->setDebugLoc(Loc);
00378 
00379   // Now we must loop through all of the successors of the New block (which
00380   // _were_ the successors of the 'this' block), and update any PHI nodes in
00381   // successors.  If there were PHI nodes in the successors, then they need to
00382   // know that incoming branches will be from New, not from Old.
00383   //
00384   for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
00385     // Loop over any phi nodes in the basic block, updating the BB field of
00386     // incoming values...
00387     BasicBlock *Successor = *I;
00388     PHINode *PN;
00389     for (BasicBlock::iterator II = Successor->begin();
00390          (PN = dyn_cast<PHINode>(II)); ++II) {
00391       int IDX = PN->getBasicBlockIndex(this);
00392       while (IDX != -1) {
00393         PN->setIncomingBlock((unsigned)IDX, New);
00394         IDX = PN->getBasicBlockIndex(this);
00395       }
00396     }
00397   }
00398   return New;
00399 }
00400 
00401 void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) {
00402   TerminatorInst *TI = getTerminator();
00403   if (!TI)
00404     // Cope with being called on a BasicBlock that doesn't have a terminator
00405     // yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.
00406     return;
00407   for (BasicBlock *Succ : TI->successors()) {
00408     // N.B. Succ might not be a complete BasicBlock, so don't assume
00409     // that it ends with a non-phi instruction.
00410     for (iterator II = Succ->begin(), IE = Succ->end(); II != IE; ++II) {
00411       PHINode *PN = dyn_cast<PHINode>(II);
00412       if (!PN)
00413         break;
00414       int i;
00415       while ((i = PN->getBasicBlockIndex(this)) >= 0)
00416         PN->setIncomingBlock(i, New);
00417     }
00418   }
00419 }
00420 
00421 /// Return true if this basic block is a landing pad. I.e., it's
00422 /// the destination of the 'unwind' edge of an invoke instruction.
00423 bool BasicBlock::isLandingPad() const {
00424   return isa<LandingPadInst>(getFirstNonPHI());
00425 }
00426 
00427 /// Return the landingpad instruction associated with the landing pad.
00428 LandingPadInst *BasicBlock::getLandingPadInst() {
00429   return dyn_cast<LandingPadInst>(getFirstNonPHI());
00430 }
00431 const LandingPadInst *BasicBlock::getLandingPadInst() const {
00432   return dyn_cast<LandingPadInst>(getFirstNonPHI());
00433 }