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 was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the BasicBlock class for the VMCore library.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/BasicBlock.h"
00015 #include "llvm/Constants.h"
00016 #include "llvm/Instructions.h"
00017 #include "llvm/Type.h"
00018 #include "llvm/Support/CFG.h"
00019 #include "llvm/Support/LeakDetector.h"
00020 #include "llvm/Support/Visibility.h"
00021 #include "SymbolTableListTraitsImpl.h"
00022 #include <algorithm>
00023 using namespace llvm;
00024 
00025 namespace {
00026   /// DummyInst - An instance of this class is used to mark the end of the
00027   /// instruction list.  This is not a real instruction.
00028   struct VISIBILITY_HIDDEN DummyInst : public Instruction {
00029     DummyInst() : Instruction(Type::VoidTy, OtherOpsEnd, 0, 0) {
00030       // This should not be garbage monitored.
00031       LeakDetector::removeGarbageObject(this);
00032     }
00033 
00034     virtual Instruction *clone() const {
00035       assert(0 && "Cannot clone EOL");abort();
00036       return 0;
00037     }
00038     virtual const char *getOpcodeName() const { return "*end-of-list-inst*"; }
00039 
00040     // Methods for support type inquiry through isa, cast, and dyn_cast...
00041     static inline bool classof(const DummyInst *) { return true; }
00042     static inline bool classof(const Instruction *I) {
00043       return I->getOpcode() == OtherOpsEnd;
00044     }
00045     static inline bool classof(const Value *V) {
00046       return isa<Instruction>(V) && classof(cast<Instruction>(V));
00047     }
00048   };
00049 }
00050 
00051 Instruction *ilist_traits<Instruction>::createSentinel() {
00052   return new DummyInst();
00053 }
00054 iplist<Instruction> &ilist_traits<Instruction>::getList(BasicBlock *BB) {
00055   return BB->getInstList();
00056 }
00057 
00058 // Explicit instantiation of SymbolTableListTraits since some of the methods
00059 // are not in the public header file...
00060 template class SymbolTableListTraits<Instruction, BasicBlock, Function>;
00061 
00062 
00063 BasicBlock::BasicBlock(const std::string &Name, Function *Parent,
00064                        BasicBlock *InsertBefore)
00065   : Value(Type::LabelTy, Value::BasicBlockVal, Name) {
00066   // Initialize the instlist...
00067   InstList.setItemParent(this);
00068 
00069   // Make sure that we get added to a function
00070   LeakDetector::addGarbageObject(this);
00071 
00072   if (InsertBefore) {
00073     assert(Parent &&
00074            "Cannot insert block before another block with no function!");
00075     Parent->getBasicBlockList().insert(InsertBefore, this);
00076   } else if (Parent) {
00077     Parent->getBasicBlockList().push_back(this);
00078   }
00079 }
00080 
00081 
00082 BasicBlock::~BasicBlock() {
00083   assert(getParent() == 0 && "BasicBlock still linked into the program!");
00084   dropAllReferences();
00085   InstList.clear();
00086 }
00087 
00088 void BasicBlock::setParent(Function *parent) {
00089   if (getParent())
00090     LeakDetector::addGarbageObject(this);
00091 
00092   InstList.setParent(parent);
00093 
00094   if (getParent())
00095     LeakDetector::removeGarbageObject(this);
00096 }
00097 
00098 void BasicBlock::removeFromParent() {
00099   getParent()->getBasicBlockList().remove(this);
00100 }
00101 
00102 void BasicBlock::eraseFromParent() {
00103   getParent()->getBasicBlockList().erase(this);
00104 }
00105 
00106 /// moveBefore - Unlink this instruction from its current function and
00107 /// insert it into the function that MovePos lives in, right before
00108 /// MovePos.
00109 void BasicBlock::moveBefore(BasicBlock *MovePos) {
00110   MovePos->getParent()->getBasicBlockList().splice(MovePos,
00111                        getParent()->getBasicBlockList(), this);
00112 }
00113 
00114 
00115 TerminatorInst *BasicBlock::getTerminator() {
00116   if (InstList.empty()) return 0;
00117   return dyn_cast<TerminatorInst>(&InstList.back());
00118 }
00119 
00120 const TerminatorInst *const BasicBlock::getTerminator() const {
00121   if (InstList.empty()) return 0;
00122   return dyn_cast<TerminatorInst>(&InstList.back());
00123 }
00124 
00125 Instruction* BasicBlock::getFirstNonPHI()
00126 {
00127     BasicBlock::iterator i = begin();
00128     // All valid basic blocks should have a terminator,
00129     // which is not a PHINode. If we have invalid basic
00130     // block we'll get assert when dereferencing past-the-end
00131     // iterator.
00132     while (isa<PHINode>(i)) ++i;
00133     return &*i;
00134 }
00135 
00136 void BasicBlock::dropAllReferences() {
00137   for(iterator I = begin(), E = end(); I != E; ++I)
00138     I->dropAllReferences();
00139 }
00140 
00141 /// getSinglePredecessor - If this basic block has a single predecessor block,
00142 /// return the block, otherwise return a null pointer.
00143 BasicBlock *BasicBlock::getSinglePredecessor() {
00144   pred_iterator PI = pred_begin(this), E = pred_end(this);
00145   if (PI == E) return 0;         // No preds.
00146   BasicBlock *ThePred = *PI;
00147   ++PI;
00148   return (PI == E) ? ThePred : 0 /*multiple preds*/;
00149 }
00150 
00151 /// removePredecessor - This method is used to notify a BasicBlock that the
00152 /// specified Predecessor of the block is no longer able to reach it.  This is
00153 /// actually not used to update the Predecessor list, but is actually used to
00154 /// update the PHI nodes that reside in the block.  Note that this should be
00155 /// called while the predecessor still refers to this block.
00156 ///
00157 void BasicBlock::removePredecessor(BasicBlock *Pred,
00158                                    bool DontDeleteUselessPHIs) {
00159   assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
00160           find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
00161          "removePredecessor: BB is not a predecessor!");
00162 
00163   if (InstList.empty()) return;
00164   PHINode *APN = dyn_cast<PHINode>(&front());
00165   if (!APN) return;   // Quick exit.
00166 
00167   // If there are exactly two predecessors, then we want to nuke the PHI nodes
00168   // altogether.  However, we cannot do this, if this in this case:
00169   //
00170   //  Loop:
00171   //    %x = phi [X, Loop]
00172   //    %x2 = add %x, 1         ;; This would become %x2 = add %x2, 1
00173   //    br Loop                 ;; %x2 does not dominate all uses
00174   //
00175   // This is because the PHI node input is actually taken from the predecessor
00176   // basic block.  The only case this can happen is with a self loop, so we
00177   // check for this case explicitly now.
00178   //
00179   unsigned max_idx = APN->getNumIncomingValues();
00180   assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
00181   if (max_idx == 2) {
00182     BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
00183 
00184     // Disable PHI elimination!
00185     if (this == Other) max_idx = 3;
00186   }
00187 
00188   // <= Two predecessors BEFORE I remove one?
00189   if (max_idx <= 2 && !DontDeleteUselessPHIs) {
00190     // Yup, loop through and nuke the PHI nodes
00191     while (PHINode *PN = dyn_cast<PHINode>(&front())) {
00192       // Remove the predecessor first.
00193       PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
00194 
00195       // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
00196       if (max_idx == 2) {
00197         if (PN->getOperand(0) != PN)
00198           PN->replaceAllUsesWith(PN->getOperand(0));
00199         else
00200           // We are left with an infinite loop with no entries: kill the PHI.
00201           PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
00202         getInstList().pop_front();    // Remove the PHI node
00203       }
00204 
00205       // If the PHI node already only had one entry, it got deleted by
00206       // removeIncomingValue.
00207     }
00208   } else {
00209     // Okay, now we know that we need to remove predecessor #pred_idx from all
00210     // PHI nodes.  Iterate over each PHI node fixing them up
00211     PHINode *PN;
00212     for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
00213       ++II;
00214       PN->removeIncomingValue(Pred, false);
00215       // If all incoming values to the Phi are the same, we can replace the Phi
00216       // with that value.
00217       Value* PNV = 0;
00218       if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue())) {
00219         PN->replaceAllUsesWith(PNV);
00220         PN->eraseFromParent();
00221       }
00222     }
00223   }
00224 }
00225 
00226 
00227 /// splitBasicBlock - This splits a basic block into two at the specified
00228 /// instruction.  Note that all instructions BEFORE the specified iterator stay
00229 /// as part of the original basic block, an unconditional branch is added to
00230 /// the new BB, and the rest of the instructions in the BB are moved to the new
00231 /// BB, including the old terminator.  This invalidates the iterator.
00232 ///
00233 /// Note that this only works on well formed basic blocks (must have a
00234 /// terminator), and 'I' must not be the end of instruction list (which would
00235 /// cause a degenerate basic block to be formed, having a terminator inside of
00236 /// the basic block).
00237 ///
00238 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const std::string &BBName) {
00239   assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
00240   assert(I != InstList.end() &&
00241          "Trying to get me to create degenerate basic block!");
00242 
00243   BasicBlock *New = new BasicBlock(BBName, getParent(), getNext());
00244 
00245   // Move all of the specified instructions from the original basic block into
00246   // the new basic block.
00247   New->getInstList().splice(New->end(), this->getInstList(), I, end());
00248 
00249   // Add a branch instruction to the newly formed basic block.
00250   new BranchInst(New, this);
00251 
00252   // Now we must loop through all of the successors of the New block (which
00253   // _were_ the successors of the 'this' block), and update any PHI nodes in
00254   // successors.  If there were PHI nodes in the successors, then they need to
00255   // know that incoming branches will be from New, not from Old.
00256   //
00257   for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
00258     // Loop over any phi nodes in the basic block, updating the BB field of
00259     // incoming values...
00260     BasicBlock *Successor = *I;
00261     PHINode *PN;
00262     for (BasicBlock::iterator II = Successor->begin();
00263          (PN = dyn_cast<PHINode>(II)); ++II) {
00264       int IDX = PN->getBasicBlockIndex(this);
00265       while (IDX != -1) {
00266         PN->setIncomingBlock((unsigned)IDX, New);
00267         IDX = PN->getBasicBlockIndex(this);
00268       }
00269     }
00270   }
00271   return New;
00272 }