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