LLVM API Documentation

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