LLVM  mainline
MachineBasicBlock.cpp
Go to the documentation of this file.
00001 //===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===//
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 // Collect the sequence of machine instructions for a basic block.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/CodeGen/MachineBasicBlock.h"
00015 #include "llvm/ADT/SmallPtrSet.h"
00016 #include "llvm/ADT/SmallString.h"
00017 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
00018 #include "llvm/CodeGen/LiveVariables.h"
00019 #include "llvm/CodeGen/MachineDominators.h"
00020 #include "llvm/CodeGen/MachineFunction.h"
00021 #include "llvm/CodeGen/MachineInstrBuilder.h"
00022 #include "llvm/CodeGen/MachineLoopInfo.h"
00023 #include "llvm/CodeGen/MachineRegisterInfo.h"
00024 #include "llvm/CodeGen/SlotIndexes.h"
00025 #include "llvm/IR/BasicBlock.h"
00026 #include "llvm/IR/DataLayout.h"
00027 #include "llvm/MC/MCAsmInfo.h"
00028 #include "llvm/MC/MCContext.h"
00029 #include "llvm/Support/Debug.h"
00030 #include "llvm/Support/raw_ostream.h"
00031 #include "llvm/Target/TargetInstrInfo.h"
00032 #include "llvm/Target/TargetMachine.h"
00033 #include "llvm/Target/TargetRegisterInfo.h"
00034 #include "llvm/Target/TargetSubtargetInfo.h"
00035 #include <algorithm>
00036 using namespace llvm;
00037 
00038 #define DEBUG_TYPE "codegen"
00039 
00040 MachineBasicBlock::MachineBasicBlock(MachineFunction &mf, const BasicBlock *bb)
00041   : BB(bb), Number(-1), xParent(&mf), Alignment(0), IsLandingPad(false),
00042     AddressTaken(false), CachedMCSymbol(nullptr) {
00043   Insts.Parent = this;
00044 }
00045 
00046 MachineBasicBlock::~MachineBasicBlock() {
00047 }
00048 
00049 /// getSymbol - Return the MCSymbol for this basic block.
00050 ///
00051 MCSymbol *MachineBasicBlock::getSymbol() const {
00052   if (!CachedMCSymbol) {
00053     const MachineFunction *MF = getParent();
00054     MCContext &Ctx = MF->getContext();
00055     const char *Prefix = Ctx.getAsmInfo()->getPrivateLabelPrefix();
00056     CachedMCSymbol = Ctx.getOrCreateSymbol(Twine(Prefix) + "BB" +
00057                                            Twine(MF->getFunctionNumber()) +
00058                                            "_" + Twine(getNumber()));
00059   }
00060 
00061   return CachedMCSymbol;
00062 }
00063 
00064 
00065 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
00066   MBB.print(OS);
00067   return OS;
00068 }
00069 
00070 /// addNodeToList (MBB) - When an MBB is added to an MF, we need to update the
00071 /// parent pointer of the MBB, the MBB numbering, and any instructions in the
00072 /// MBB to be on the right operand list for registers.
00073 ///
00074 /// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
00075 /// gets the next available unique MBB number. If it is removed from a
00076 /// MachineFunction, it goes back to being #-1.
00077 void ilist_traits<MachineBasicBlock>::addNodeToList(MachineBasicBlock *N) {
00078   MachineFunction &MF = *N->getParent();
00079   N->Number = MF.addToMBBNumbering(N);
00080 
00081   // Make sure the instructions have their operands in the reginfo lists.
00082   MachineRegisterInfo &RegInfo = MF.getRegInfo();
00083   for (MachineBasicBlock::instr_iterator
00084          I = N->instr_begin(), E = N->instr_end(); I != E; ++I)
00085     I->AddRegOperandsToUseLists(RegInfo);
00086 }
00087 
00088 void ilist_traits<MachineBasicBlock>::removeNodeFromList(MachineBasicBlock *N) {
00089   N->getParent()->removeFromMBBNumbering(N->Number);
00090   N->Number = -1;
00091 }
00092 
00093 
00094 /// addNodeToList (MI) - When we add an instruction to a basic block
00095 /// list, we update its parent pointer and add its operands from reg use/def
00096 /// lists if appropriate.
00097 void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
00098   assert(!N->getParent() && "machine instruction already in a basic block");
00099   N->setParent(Parent);
00100 
00101   // Add the instruction's register operands to their corresponding
00102   // use/def lists.
00103   MachineFunction *MF = Parent->getParent();
00104   N->AddRegOperandsToUseLists(MF->getRegInfo());
00105 }
00106 
00107 /// removeNodeFromList (MI) - When we remove an instruction from a basic block
00108 /// list, we update its parent pointer and remove its operands from reg use/def
00109 /// lists if appropriate.
00110 void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) {
00111   assert(N->getParent() && "machine instruction not in a basic block");
00112 
00113   // Remove from the use/def lists.
00114   if (MachineFunction *MF = N->getParent()->getParent())
00115     N->RemoveRegOperandsFromUseLists(MF->getRegInfo());
00116 
00117   N->setParent(nullptr);
00118 }
00119 
00120 /// transferNodesFromList (MI) - When moving a range of instructions from one
00121 /// MBB list to another, we need to update the parent pointers and the use/def
00122 /// lists.
00123 void ilist_traits<MachineInstr>::
00124 transferNodesFromList(ilist_traits<MachineInstr> &fromList,
00125                       ilist_iterator<MachineInstr> first,
00126                       ilist_iterator<MachineInstr> last) {
00127   assert(Parent->getParent() == fromList.Parent->getParent() &&
00128         "MachineInstr parent mismatch!");
00129 
00130   // Splice within the same MBB -> no change.
00131   if (Parent == fromList.Parent) return;
00132 
00133   // If splicing between two blocks within the same function, just update the
00134   // parent pointers.
00135   for (; first != last; ++first)
00136     first->setParent(Parent);
00137 }
00138 
00139 void ilist_traits<MachineInstr>::deleteNode(MachineInstr* MI) {
00140   assert(!MI->getParent() && "MI is still in a block!");
00141   Parent->getParent()->DeleteMachineInstr(MI);
00142 }
00143 
00144 MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
00145   instr_iterator I = instr_begin(), E = instr_end();
00146   while (I != E && I->isPHI())
00147     ++I;
00148   assert((I == E || !I->isInsideBundle()) &&
00149          "First non-phi MI cannot be inside a bundle!");
00150   return I;
00151 }
00152 
00153 MachineBasicBlock::iterator
00154 MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
00155   iterator E = end();
00156   while (I != E && (I->isPHI() || I->isPosition() || I->isDebugValue()))
00157     ++I;
00158   // FIXME: This needs to change if we wish to bundle labels / dbg_values
00159   // inside the bundle.
00160   assert((I == E || !I->isInsideBundle()) &&
00161          "First non-phi / non-label instruction is inside a bundle!");
00162   return I;
00163 }
00164 
00165 MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
00166   iterator B = begin(), E = end(), I = E;
00167   while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
00168     ; /*noop */
00169   while (I != E && !I->isTerminator())
00170     ++I;
00171   return I;
00172 }
00173 
00174 MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() {
00175   instr_iterator B = instr_begin(), E = instr_end(), I = E;
00176   while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
00177     ; /*noop */
00178   while (I != E && !I->isTerminator())
00179     ++I;
00180   return I;
00181 }
00182 
00183 MachineBasicBlock::iterator MachineBasicBlock::getFirstNonDebugInstr() {
00184   // Skip over begin-of-block dbg_value instructions.
00185   iterator I = begin(), E = end();
00186   while (I != E && I->isDebugValue())
00187     ++I;
00188   return I;
00189 }
00190 
00191 MachineBasicBlock::iterator MachineBasicBlock::getLastNonDebugInstr() {
00192   // Skip over end-of-block dbg_value instructions.
00193   instr_iterator B = instr_begin(), I = instr_end();
00194   while (I != B) {
00195     --I;
00196     // Return instruction that starts a bundle.
00197     if (I->isDebugValue() || I->isInsideBundle())
00198       continue;
00199     return I;
00200   }
00201   // The block is all debug values.
00202   return end();
00203 }
00204 
00205 const MachineBasicBlock *MachineBasicBlock::getLandingPadSuccessor() const {
00206   // A block with a landing pad successor only has one other successor.
00207   if (succ_size() > 2)
00208     return nullptr;
00209   for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I)
00210     if ((*I)->isLandingPad())
00211       return *I;
00212   return nullptr;
00213 }
00214 
00215 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00216 void MachineBasicBlock::dump() const {
00217   print(dbgs());
00218 }
00219 #endif
00220 
00221 StringRef MachineBasicBlock::getName() const {
00222   if (const BasicBlock *LBB = getBasicBlock())
00223     return LBB->getName();
00224   else
00225     return "(null)";
00226 }
00227 
00228 /// Return a hopefully unique identifier for this block.
00229 std::string MachineBasicBlock::getFullName() const {
00230   std::string Name;
00231   if (getParent())
00232     Name = (getParent()->getName() + ":").str();
00233   if (getBasicBlock())
00234     Name += getBasicBlock()->getName();
00235   else
00236     Name += ("BB" + Twine(getNumber())).str();
00237   return Name;
00238 }
00239 
00240 void MachineBasicBlock::print(raw_ostream &OS, SlotIndexes *Indexes) const {
00241   const MachineFunction *MF = getParent();
00242   if (!MF) {
00243     OS << "Can't print out MachineBasicBlock because parent MachineFunction"
00244        << " is null\n";
00245     return;
00246   }
00247 
00248   if (Indexes)
00249     OS << Indexes->getMBBStartIdx(this) << '\t';
00250 
00251   OS << "BB#" << getNumber() << ": ";
00252 
00253   const char *Comma = "";
00254   if (const BasicBlock *LBB = getBasicBlock()) {
00255     OS << Comma << "derived from LLVM BB ";
00256     LBB->printAsOperand(OS, /*PrintType=*/false);
00257     Comma = ", ";
00258   }
00259   if (isLandingPad()) { OS << Comma << "EH LANDING PAD"; Comma = ", "; }
00260   if (hasAddressTaken()) { OS << Comma << "ADDRESS TAKEN"; Comma = ", "; }
00261   if (Alignment)
00262     OS << Comma << "Align " << Alignment << " (" << (1u << Alignment)
00263        << " bytes)";
00264 
00265   OS << '\n';
00266 
00267   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
00268   if (!livein_empty()) {
00269     if (Indexes) OS << '\t';
00270     OS << "    Live Ins:";
00271     for (livein_iterator I = livein_begin(),E = livein_end(); I != E; ++I)
00272       OS << ' ' << PrintReg(*I, TRI);
00273     OS << '\n';
00274   }
00275   // Print the preds of this block according to the CFG.
00276   if (!pred_empty()) {
00277     if (Indexes) OS << '\t';
00278     OS << "    Predecessors according to CFG:";
00279     for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)
00280       OS << " BB#" << (*PI)->getNumber();
00281     OS << '\n';
00282   }
00283 
00284   for (const_instr_iterator I = instr_begin(); I != instr_end(); ++I) {
00285     if (Indexes) {
00286       if (Indexes->hasIndex(I))
00287         OS << Indexes->getInstructionIndex(I);
00288       OS << '\t';
00289     }
00290     OS << '\t';
00291     if (I->isInsideBundle())
00292       OS << "  * ";
00293     I->print(OS);
00294   }
00295 
00296   // Print the successors of this block according to the CFG.
00297   if (!succ_empty()) {
00298     if (Indexes) OS << '\t';
00299     OS << "    Successors according to CFG:";
00300     for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI) {
00301       OS << " BB#" << (*SI)->getNumber();
00302       if (!Weights.empty())
00303         OS << '(' << *getWeightIterator(SI) << ')';
00304     }
00305     OS << '\n';
00306   }
00307 }
00308 
00309 void MachineBasicBlock::printAsOperand(raw_ostream &OS, bool /*PrintType*/) const {
00310   OS << "BB#" << getNumber();
00311 }
00312 
00313 void MachineBasicBlock::removeLiveIn(unsigned Reg) {
00314   std::vector<unsigned>::iterator I =
00315     std::find(LiveIns.begin(), LiveIns.end(), Reg);
00316   if (I != LiveIns.end())
00317     LiveIns.erase(I);
00318 }
00319 
00320 bool MachineBasicBlock::isLiveIn(unsigned Reg) const {
00321   livein_iterator I = std::find(livein_begin(), livein_end(), Reg);
00322   return I != livein_end();
00323 }
00324 
00325 unsigned
00326 MachineBasicBlock::addLiveIn(unsigned PhysReg, const TargetRegisterClass *RC) {
00327   assert(getParent() && "MBB must be inserted in function");
00328   assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) && "Expected physreg");
00329   assert(RC && "Register class is required");
00330   assert((isLandingPad() || this == &getParent()->front()) &&
00331          "Only the entry block and landing pads can have physreg live ins");
00332 
00333   bool LiveIn = isLiveIn(PhysReg);
00334   iterator I = SkipPHIsAndLabels(begin()), E = end();
00335   MachineRegisterInfo &MRI = getParent()->getRegInfo();
00336   const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
00337 
00338   // Look for an existing copy.
00339   if (LiveIn)
00340     for (;I != E && I->isCopy(); ++I)
00341       if (I->getOperand(1).getReg() == PhysReg) {
00342         unsigned VirtReg = I->getOperand(0).getReg();
00343         if (!MRI.constrainRegClass(VirtReg, RC))
00344           llvm_unreachable("Incompatible live-in register class.");
00345         return VirtReg;
00346       }
00347 
00348   // No luck, create a virtual register.
00349   unsigned VirtReg = MRI.createVirtualRegister(RC);
00350   BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
00351     .addReg(PhysReg, RegState::Kill);
00352   if (!LiveIn)
00353     addLiveIn(PhysReg);
00354   return VirtReg;
00355 }
00356 
00357 void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
00358   getParent()->splice(NewAfter, this);
00359 }
00360 
00361 void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
00362   MachineFunction::iterator BBI = NewBefore;
00363   getParent()->splice(++BBI, this);
00364 }
00365 
00366 void MachineBasicBlock::updateTerminator() {
00367   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
00368   // A block with no successors has no concerns with fall-through edges.
00369   if (this->succ_empty()) return;
00370 
00371   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
00372   SmallVector<MachineOperand, 4> Cond;
00373   DebugLoc dl;  // FIXME: this is nowhere
00374   bool B = TII->AnalyzeBranch(*this, TBB, FBB, Cond);
00375   (void) B;
00376   assert(!B && "UpdateTerminators requires analyzable predecessors!");
00377   if (Cond.empty()) {
00378     if (TBB) {
00379       // The block has an unconditional branch. If its successor is now
00380       // its layout successor, delete the branch.
00381       if (isLayoutSuccessor(TBB))
00382         TII->RemoveBranch(*this);
00383     } else {
00384       // The block has an unconditional fallthrough. If its successor is not
00385       // its layout successor, insert a branch. First we have to locate the
00386       // only non-landing-pad successor, as that is the fallthrough block.
00387       for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
00388         if ((*SI)->isLandingPad())
00389           continue;
00390         assert(!TBB && "Found more than one non-landing-pad successor!");
00391         TBB = *SI;
00392       }
00393 
00394       // If there is no non-landing-pad successor, the block has no
00395       // fall-through edges to be concerned with.
00396       if (!TBB)
00397         return;
00398 
00399       // Finally update the unconditional successor to be reached via a branch
00400       // if it would not be reached by fallthrough.
00401       if (!isLayoutSuccessor(TBB))
00402         TII->InsertBranch(*this, TBB, nullptr, Cond, dl);
00403     }
00404   } else {
00405     if (FBB) {
00406       // The block has a non-fallthrough conditional branch. If one of its
00407       // successors is its layout successor, rewrite it to a fallthrough
00408       // conditional branch.
00409       if (isLayoutSuccessor(TBB)) {
00410         if (TII->ReverseBranchCondition(Cond))
00411           return;
00412         TII->RemoveBranch(*this);
00413         TII->InsertBranch(*this, FBB, nullptr, Cond, dl);
00414       } else if (isLayoutSuccessor(FBB)) {
00415         TII->RemoveBranch(*this);
00416         TII->InsertBranch(*this, TBB, nullptr, Cond, dl);
00417       }
00418     } else {
00419       // Walk through the successors and find the successor which is not
00420       // a landing pad and is not the conditional branch destination (in TBB)
00421       // as the fallthrough successor.
00422       MachineBasicBlock *FallthroughBB = nullptr;
00423       for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
00424         if ((*SI)->isLandingPad() || *SI == TBB)
00425           continue;
00426         assert(!FallthroughBB && "Found more than one fallthrough successor.");
00427         FallthroughBB = *SI;
00428       }
00429       if (!FallthroughBB && canFallThrough()) {
00430         // We fallthrough to the same basic block as the conditional jump
00431         // targets. Remove the conditional jump, leaving unconditional
00432         // fallthrough.
00433         // FIXME: This does not seem like a reasonable pattern to support, but it
00434         // has been seen in the wild coming out of degenerate ARM test cases.
00435         TII->RemoveBranch(*this);
00436 
00437         // Finally update the unconditional successor to be reached via a branch
00438         // if it would not be reached by fallthrough.
00439         if (!isLayoutSuccessor(TBB))
00440           TII->InsertBranch(*this, TBB, nullptr, Cond, dl);
00441         return;
00442       }
00443 
00444       // The block has a fallthrough conditional branch.
00445       if (isLayoutSuccessor(TBB)) {
00446         if (TII->ReverseBranchCondition(Cond)) {
00447           // We can't reverse the condition, add an unconditional branch.
00448           Cond.clear();
00449           TII->InsertBranch(*this, FallthroughBB, nullptr, Cond, dl);
00450           return;
00451         }
00452         TII->RemoveBranch(*this);
00453         TII->InsertBranch(*this, FallthroughBB, nullptr, Cond, dl);
00454       } else if (!isLayoutSuccessor(FallthroughBB)) {
00455         TII->RemoveBranch(*this);
00456         TII->InsertBranch(*this, TBB, FallthroughBB, Cond, dl);
00457       }
00458     }
00459   }
00460 }
00461 
00462 void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ, uint32_t weight) {
00463 
00464   // If we see non-zero value for the first time it means we actually use Weight
00465   // list, so we fill all Weights with 0's.
00466   if (weight != 0 && Weights.empty())
00467     Weights.resize(Successors.size());
00468 
00469   if (weight != 0 || !Weights.empty())
00470     Weights.push_back(weight);
00471 
00472    Successors.push_back(succ);
00473    succ->addPredecessor(this);
00474  }
00475 
00476 void MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) {
00477   succ->removePredecessor(this);
00478   succ_iterator I = std::find(Successors.begin(), Successors.end(), succ);
00479   assert(I != Successors.end() && "Not a current successor!");
00480 
00481   // If Weight list is empty it means we don't use it (disabled optimization).
00482   if (!Weights.empty()) {
00483     weight_iterator WI = getWeightIterator(I);
00484     Weights.erase(WI);
00485   }
00486 
00487   Successors.erase(I);
00488 }
00489 
00490 MachineBasicBlock::succ_iterator
00491 MachineBasicBlock::removeSuccessor(succ_iterator I) {
00492   assert(I != Successors.end() && "Not a current successor!");
00493 
00494   // If Weight list is empty it means we don't use it (disabled optimization).
00495   if (!Weights.empty()) {
00496     weight_iterator WI = getWeightIterator(I);
00497     Weights.erase(WI);
00498   }
00499 
00500   (*I)->removePredecessor(this);
00501   return Successors.erase(I);
00502 }
00503 
00504 void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
00505                                          MachineBasicBlock *New) {
00506   if (Old == New)
00507     return;
00508 
00509   succ_iterator E = succ_end();
00510   succ_iterator NewI = E;
00511   succ_iterator OldI = E;
00512   for (succ_iterator I = succ_begin(); I != E; ++I) {
00513     if (*I == Old) {
00514       OldI = I;
00515       if (NewI != E)
00516         break;
00517     }
00518     if (*I == New) {
00519       NewI = I;
00520       if (OldI != E)
00521         break;
00522     }
00523   }
00524   assert(OldI != E && "Old is not a successor of this block");
00525   Old->removePredecessor(this);
00526 
00527   // If New isn't already a successor, let it take Old's place.
00528   if (NewI == E) {
00529     New->addPredecessor(this);
00530     *OldI = New;
00531     return;
00532   }
00533 
00534   // New is already a successor.
00535   // Update its weight instead of adding a duplicate edge.
00536   if (!Weights.empty()) {
00537     weight_iterator OldWI = getWeightIterator(OldI);
00538     *getWeightIterator(NewI) += *OldWI;
00539     Weights.erase(OldWI);
00540   }
00541   Successors.erase(OldI);
00542 }
00543 
00544 void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) {
00545   Predecessors.push_back(pred);
00546 }
00547 
00548 void MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) {
00549   pred_iterator I = std::find(Predecessors.begin(), Predecessors.end(), pred);
00550   assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
00551   Predecessors.erase(I);
00552 }
00553 
00554 void MachineBasicBlock::transferSuccessors(MachineBasicBlock *fromMBB) {
00555   if (this == fromMBB)
00556     return;
00557 
00558   while (!fromMBB->succ_empty()) {
00559     MachineBasicBlock *Succ = *fromMBB->succ_begin();
00560     uint32_t Weight = 0;
00561 
00562     // If Weight list is empty it means we don't use it (disabled optimization).
00563     if (!fromMBB->Weights.empty())
00564       Weight = *fromMBB->Weights.begin();
00565 
00566     addSuccessor(Succ, Weight);
00567     fromMBB->removeSuccessor(Succ);
00568   }
00569 }
00570 
00571 void
00572 MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *fromMBB) {
00573   if (this == fromMBB)
00574     return;
00575 
00576   while (!fromMBB->succ_empty()) {
00577     MachineBasicBlock *Succ = *fromMBB->succ_begin();
00578     uint32_t Weight = 0;
00579     if (!fromMBB->Weights.empty())
00580       Weight = *fromMBB->Weights.begin();
00581     addSuccessor(Succ, Weight);
00582     fromMBB->removeSuccessor(Succ);
00583 
00584     // Fix up any PHI nodes in the successor.
00585     for (MachineBasicBlock::instr_iterator MI = Succ->instr_begin(),
00586            ME = Succ->instr_end(); MI != ME && MI->isPHI(); ++MI)
00587       for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) {
00588         MachineOperand &MO = MI->getOperand(i);
00589         if (MO.getMBB() == fromMBB)
00590           MO.setMBB(this);
00591       }
00592   }
00593 }
00594 
00595 bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
00596   return std::find(pred_begin(), pred_end(), MBB) != pred_end();
00597 }
00598 
00599 bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
00600   return std::find(succ_begin(), succ_end(), MBB) != succ_end();
00601 }
00602 
00603 bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
00604   MachineFunction::const_iterator I(this);
00605   return std::next(I) == MachineFunction::const_iterator(MBB);
00606 }
00607 
00608 bool MachineBasicBlock::canFallThrough() {
00609   MachineFunction::iterator Fallthrough = this;
00610   ++Fallthrough;
00611   // If FallthroughBlock is off the end of the function, it can't fall through.
00612   if (Fallthrough == getParent()->end())
00613     return false;
00614 
00615   // If FallthroughBlock isn't a successor, no fallthrough is possible.
00616   if (!isSuccessor(Fallthrough))
00617     return false;
00618 
00619   // Analyze the branches, if any, at the end of the block.
00620   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
00621   SmallVector<MachineOperand, 4> Cond;
00622   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
00623   if (TII->AnalyzeBranch(*this, TBB, FBB, Cond)) {
00624     // If we couldn't analyze the branch, examine the last instruction.
00625     // If the block doesn't end in a known control barrier, assume fallthrough
00626     // is possible. The isPredicated check is needed because this code can be
00627     // called during IfConversion, where an instruction which is normally a
00628     // Barrier is predicated and thus no longer an actual control barrier.
00629     return empty() || !back().isBarrier() || TII->isPredicated(&back());
00630   }
00631 
00632   // If there is no branch, control always falls through.
00633   if (!TBB) return true;
00634 
00635   // If there is some explicit branch to the fallthrough block, it can obviously
00636   // reach, even though the branch should get folded to fall through implicitly.
00637   if (MachineFunction::iterator(TBB) == Fallthrough ||
00638       MachineFunction::iterator(FBB) == Fallthrough)
00639     return true;
00640 
00641   // If it's an unconditional branch to some block not the fall through, it
00642   // doesn't fall through.
00643   if (Cond.empty()) return false;
00644 
00645   // Otherwise, if it is conditional and has no explicit false block, it falls
00646   // through.
00647   return FBB == nullptr;
00648 }
00649 
00650 MachineBasicBlock *
00651 MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ, Pass *P) {
00652   // Splitting the critical edge to a landing pad block is non-trivial. Don't do
00653   // it in this generic function.
00654   if (Succ->isLandingPad())
00655     return nullptr;
00656 
00657   MachineFunction *MF = getParent();
00658   DebugLoc dl;  // FIXME: this is nowhere
00659 
00660   // Performance might be harmed on HW that implements branching using exec mask
00661   // where both sides of the branches are always executed.
00662   if (MF->getTarget().requiresStructuredCFG())
00663     return nullptr;
00664 
00665   // We may need to update this's terminator, but we can't do that if
00666   // AnalyzeBranch fails. If this uses a jump table, we won't touch it.
00667   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
00668   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
00669   SmallVector<MachineOperand, 4> Cond;
00670   if (TII->AnalyzeBranch(*this, TBB, FBB, Cond))
00671     return nullptr;
00672 
00673   // Avoid bugpoint weirdness: A block may end with a conditional branch but
00674   // jumps to the same MBB is either case. We have duplicate CFG edges in that
00675   // case that we can't handle. Since this never happens in properly optimized
00676   // code, just skip those edges.
00677   if (TBB && TBB == FBB) {
00678     DEBUG(dbgs() << "Won't split critical edge after degenerate BB#"
00679                  << getNumber() << '\n');
00680     return nullptr;
00681   }
00682 
00683   MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
00684   MF->insert(std::next(MachineFunction::iterator(this)), NMBB);
00685   DEBUG(dbgs() << "Splitting critical edge:"
00686         " BB#" << getNumber()
00687         << " -- BB#" << NMBB->getNumber()
00688         << " -- BB#" << Succ->getNumber() << '\n');
00689 
00690   LiveIntervals *LIS = P->getAnalysisIfAvailable<LiveIntervals>();
00691   SlotIndexes *Indexes = P->getAnalysisIfAvailable<SlotIndexes>();
00692   if (LIS)
00693     LIS->insertMBBInMaps(NMBB);
00694   else if (Indexes)
00695     Indexes->insertMBBInMaps(NMBB);
00696 
00697   // On some targets like Mips, branches may kill virtual registers. Make sure
00698   // that LiveVariables is properly updated after updateTerminator replaces the
00699   // terminators.
00700   LiveVariables *LV = P->getAnalysisIfAvailable<LiveVariables>();
00701 
00702   // Collect a list of virtual registers killed by the terminators.
00703   SmallVector<unsigned, 4> KilledRegs;
00704   if (LV)
00705     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
00706          I != E; ++I) {
00707       MachineInstr *MI = I;
00708       for (MachineInstr::mop_iterator OI = MI->operands_begin(),
00709            OE = MI->operands_end(); OI != OE; ++OI) {
00710         if (!OI->isReg() || OI->getReg() == 0 ||
00711             !OI->isUse() || !OI->isKill() || OI->isUndef())
00712           continue;
00713         unsigned Reg = OI->getReg();
00714         if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
00715             LV->getVarInfo(Reg).removeKill(MI)) {
00716           KilledRegs.push_back(Reg);
00717           DEBUG(dbgs() << "Removing terminator kill: " << *MI);
00718           OI->setIsKill(false);
00719         }
00720       }
00721     }
00722 
00723   SmallVector<unsigned, 4> UsedRegs;
00724   if (LIS) {
00725     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
00726          I != E; ++I) {
00727       MachineInstr *MI = I;
00728 
00729       for (MachineInstr::mop_iterator OI = MI->operands_begin(),
00730            OE = MI->operands_end(); OI != OE; ++OI) {
00731         if (!OI->isReg() || OI->getReg() == 0)
00732           continue;
00733 
00734         unsigned Reg = OI->getReg();
00735         if (std::find(UsedRegs.begin(), UsedRegs.end(), Reg) == UsedRegs.end())
00736           UsedRegs.push_back(Reg);
00737       }
00738     }
00739   }
00740 
00741   ReplaceUsesOfBlockWith(Succ, NMBB);
00742 
00743   // If updateTerminator() removes instructions, we need to remove them from
00744   // SlotIndexes.
00745   SmallVector<MachineInstr*, 4> Terminators;
00746   if (Indexes) {
00747     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
00748          I != E; ++I)
00749       Terminators.push_back(I);
00750   }
00751 
00752   updateTerminator();
00753 
00754   if (Indexes) {
00755     SmallVector<MachineInstr*, 4> NewTerminators;
00756     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
00757          I != E; ++I)
00758       NewTerminators.push_back(I);
00759 
00760     for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(),
00761         E = Terminators.end(); I != E; ++I) {
00762       if (std::find(NewTerminators.begin(), NewTerminators.end(), *I) ==
00763           NewTerminators.end())
00764        Indexes->removeMachineInstrFromMaps(*I);
00765     }
00766   }
00767 
00768   // Insert unconditional "jump Succ" instruction in NMBB if necessary.
00769   NMBB->addSuccessor(Succ);
00770   if (!NMBB->isLayoutSuccessor(Succ)) {
00771     Cond.clear();
00772     MF->getSubtarget().getInstrInfo()->InsertBranch(*NMBB, Succ, nullptr, Cond,
00773                                                     dl);
00774 
00775     if (Indexes) {
00776       for (instr_iterator I = NMBB->instr_begin(), E = NMBB->instr_end();
00777            I != E; ++I) {
00778         // Some instructions may have been moved to NMBB by updateTerminator(),
00779         // so we first remove any instruction that already has an index.
00780         if (Indexes->hasIndex(I))
00781           Indexes->removeMachineInstrFromMaps(I);
00782         Indexes->insertMachineInstrInMaps(I);
00783       }
00784     }
00785   }
00786 
00787   // Fix PHI nodes in Succ so they refer to NMBB instead of this
00788   for (MachineBasicBlock::instr_iterator
00789          i = Succ->instr_begin(),e = Succ->instr_end();
00790        i != e && i->isPHI(); ++i)
00791     for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
00792       if (i->getOperand(ni+1).getMBB() == this)
00793         i->getOperand(ni+1).setMBB(NMBB);
00794 
00795   // Inherit live-ins from the successor
00796   for (MachineBasicBlock::livein_iterator I = Succ->livein_begin(),
00797          E = Succ->livein_end(); I != E; ++I)
00798     NMBB->addLiveIn(*I);
00799 
00800   // Update LiveVariables.
00801   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
00802   if (LV) {
00803     // Restore kills of virtual registers that were killed by the terminators.
00804     while (!KilledRegs.empty()) {
00805       unsigned Reg = KilledRegs.pop_back_val();
00806       for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
00807         if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
00808           continue;
00809         if (TargetRegisterInfo::isVirtualRegister(Reg))
00810           LV->getVarInfo(Reg).Kills.push_back(I);
00811         DEBUG(dbgs() << "Restored terminator kill: " << *I);
00812         break;
00813       }
00814     }
00815     // Update relevant live-through information.
00816     LV->addNewBlock(NMBB, this, Succ);
00817   }
00818 
00819   if (LIS) {
00820     // After splitting the edge and updating SlotIndexes, live intervals may be
00821     // in one of two situations, depending on whether this block was the last in
00822     // the function. If the original block was the last in the function, all live
00823     // intervals will end prior to the beginning of the new split block. If the
00824     // original block was not at the end of the function, all live intervals will
00825     // extend to the end of the new split block.
00826 
00827     bool isLastMBB =
00828       std::next(MachineFunction::iterator(NMBB)) == getParent()->end();
00829 
00830     SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
00831     SlotIndex PrevIndex = StartIndex.getPrevSlot();
00832     SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
00833 
00834     // Find the registers used from NMBB in PHIs in Succ.
00835     SmallSet<unsigned, 8> PHISrcRegs;
00836     for (MachineBasicBlock::instr_iterator
00837          I = Succ->instr_begin(), E = Succ->instr_end();
00838          I != E && I->isPHI(); ++I) {
00839       for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
00840         if (I->getOperand(ni+1).getMBB() == NMBB) {
00841           MachineOperand &MO = I->getOperand(ni);
00842           unsigned Reg = MO.getReg();
00843           PHISrcRegs.insert(Reg);
00844           if (MO.isUndef())
00845             continue;
00846 
00847           LiveInterval &LI = LIS->getInterval(Reg);
00848           VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
00849           assert(VNI && "PHI sources should be live out of their predecessors.");
00850           LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
00851         }
00852       }
00853     }
00854 
00855     MachineRegisterInfo *MRI = &getParent()->getRegInfo();
00856     for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
00857       unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
00858       if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
00859         continue;
00860 
00861       LiveInterval &LI = LIS->getInterval(Reg);
00862       if (!LI.liveAt(PrevIndex))
00863         continue;
00864 
00865       bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
00866       if (isLiveOut && isLastMBB) {
00867         VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
00868         assert(VNI && "LiveInterval should have VNInfo where it is live.");
00869         LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
00870       } else if (!isLiveOut && !isLastMBB) {
00871         LI.removeSegment(StartIndex, EndIndex);
00872       }
00873     }
00874 
00875     // Update all intervals for registers whose uses may have been modified by
00876     // updateTerminator().
00877     LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
00878   }
00879 
00880   if (MachineDominatorTree *MDT =
00881       P->getAnalysisIfAvailable<MachineDominatorTree>())
00882     MDT->recordSplitCriticalEdge(this, Succ, NMBB);
00883 
00884   if (MachineLoopInfo *MLI = P->getAnalysisIfAvailable<MachineLoopInfo>())
00885     if (MachineLoop *TIL = MLI->getLoopFor(this)) {
00886       // If one or the other blocks were not in a loop, the new block is not
00887       // either, and thus LI doesn't need to be updated.
00888       if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
00889         if (TIL == DestLoop) {
00890           // Both in the same loop, the NMBB joins loop.
00891           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
00892         } else if (TIL->contains(DestLoop)) {
00893           // Edge from an outer loop to an inner loop.  Add to the outer loop.
00894           TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
00895         } else if (DestLoop->contains(TIL)) {
00896           // Edge from an inner loop to an outer loop.  Add to the outer loop.
00897           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
00898         } else {
00899           // Edge from two loops with no containment relation.  Because these
00900           // are natural loops, we know that the destination block must be the
00901           // header of its loop (adding a branch into a loop elsewhere would
00902           // create an irreducible loop).
00903           assert(DestLoop->getHeader() == Succ &&
00904                  "Should not create irreducible loops!");
00905           if (MachineLoop *P = DestLoop->getParentLoop())
00906             P->addBasicBlockToLoop(NMBB, MLI->getBase());
00907         }
00908       }
00909     }
00910 
00911   return NMBB;
00912 }
00913 
00914 /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
00915 /// neighboring instructions so the bundle won't be broken by removing MI.
00916 static void unbundleSingleMI(MachineInstr *MI) {
00917   // Removing the first instruction in a bundle.
00918   if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
00919     MI->unbundleFromSucc();
00920   // Removing the last instruction in a bundle.
00921   if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
00922     MI->unbundleFromPred();
00923   // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
00924   // are already fine.
00925 }
00926 
00927 MachineBasicBlock::instr_iterator
00928 MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
00929   unbundleSingleMI(I);
00930   return Insts.erase(I);
00931 }
00932 
00933 MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
00934   unbundleSingleMI(MI);
00935   MI->clearFlag(MachineInstr::BundledPred);
00936   MI->clearFlag(MachineInstr::BundledSucc);
00937   return Insts.remove(MI);
00938 }
00939 
00940 MachineBasicBlock::instr_iterator
00941 MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
00942   assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
00943          "Cannot insert instruction with bundle flags");
00944   // Set the bundle flags when inserting inside a bundle.
00945   if (I != instr_end() && I->isBundledWithPred()) {
00946     MI->setFlag(MachineInstr::BundledPred);
00947     MI->setFlag(MachineInstr::BundledSucc);
00948   }
00949   return Insts.insert(I, MI);
00950 }
00951 
00952 /// removeFromParent - This method unlinks 'this' from the containing function,
00953 /// and returns it, but does not delete it.
00954 MachineBasicBlock *MachineBasicBlock::removeFromParent() {
00955   assert(getParent() && "Not embedded in a function!");
00956   getParent()->remove(this);
00957   return this;
00958 }
00959 
00960 
00961 /// eraseFromParent - This method unlinks 'this' from the containing function,
00962 /// and deletes it.
00963 void MachineBasicBlock::eraseFromParent() {
00964   assert(getParent() && "Not embedded in a function!");
00965   getParent()->erase(this);
00966 }
00967 
00968 
00969 /// ReplaceUsesOfBlockWith - Given a machine basic block that branched to
00970 /// 'Old', change the code and CFG so that it branches to 'New' instead.
00971 void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
00972                                                MachineBasicBlock *New) {
00973   assert(Old != New && "Cannot replace self with self!");
00974 
00975   MachineBasicBlock::instr_iterator I = instr_end();
00976   while (I != instr_begin()) {
00977     --I;
00978     if (!I->isTerminator()) break;
00979 
00980     // Scan the operands of this machine instruction, replacing any uses of Old
00981     // with New.
00982     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
00983       if (I->getOperand(i).isMBB() &&
00984           I->getOperand(i).getMBB() == Old)
00985         I->getOperand(i).setMBB(New);
00986   }
00987 
00988   // Update the successor information.
00989   replaceSuccessor(Old, New);
00990 }
00991 
00992 /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
00993 /// CFG to be inserted.  If we have proven that MBB can only branch to DestA and
00994 /// DestB, remove any other MBB successors from the CFG.  DestA and DestB can be
00995 /// null.
00996 ///
00997 /// Besides DestA and DestB, retain other edges leading to LandingPads
00998 /// (currently there can be only one; we don't check or require that here).
00999 /// Note it is possible that DestA and/or DestB are LandingPads.
01000 bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
01001                                              MachineBasicBlock *DestB,
01002                                              bool isCond) {
01003   // The values of DestA and DestB frequently come from a call to the
01004   // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial
01005   // values from there.
01006   //
01007   // 1. If both DestA and DestB are null, then the block ends with no branches
01008   //    (it falls through to its successor).
01009   // 2. If DestA is set, DestB is null, and isCond is false, then the block ends
01010   //    with only an unconditional branch.
01011   // 3. If DestA is set, DestB is null, and isCond is true, then the block ends
01012   //    with a conditional branch that falls through to a successor (DestB).
01013   // 4. If DestA and DestB is set and isCond is true, then the block ends with a
01014   //    conditional branch followed by an unconditional branch. DestA is the
01015   //    'true' destination and DestB is the 'false' destination.
01016 
01017   bool Changed = false;
01018 
01019   MachineFunction::iterator FallThru =
01020     std::next(MachineFunction::iterator(this));
01021 
01022   if (!DestA && !DestB) {
01023     // Block falls through to successor.
01024     DestA = FallThru;
01025     DestB = FallThru;
01026   } else if (DestA && !DestB) {
01027     if (isCond)
01028       // Block ends in conditional jump that falls through to successor.
01029       DestB = FallThru;
01030   } else {
01031     assert(DestA && DestB && isCond &&
01032            "CFG in a bad state. Cannot correct CFG edges");
01033   }
01034 
01035   // Remove superfluous edges. I.e., those which aren't destinations of this
01036   // basic block, duplicate edges, or landing pads.
01037   SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs;
01038   MachineBasicBlock::succ_iterator SI = succ_begin();
01039   while (SI != succ_end()) {
01040     const MachineBasicBlock *MBB = *SI;
01041     if (!SeenMBBs.insert(MBB).second ||
01042         (MBB != DestA && MBB != DestB && !MBB->isLandingPad())) {
01043       // This is a superfluous edge, remove it.
01044       SI = removeSuccessor(SI);
01045       Changed = true;
01046     } else {
01047       ++SI;
01048     }
01049   }
01050 
01051   return Changed;
01052 }
01053 
01054 /// findDebugLoc - find the next valid DebugLoc starting at MBBI, skipping
01055 /// any DBG_VALUE instructions.  Return UnknownLoc if there is none.
01056 DebugLoc
01057 MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
01058   DebugLoc DL;
01059   instr_iterator E = instr_end();
01060   if (MBBI == E)
01061     return DL;
01062 
01063   // Skip debug declarations, we don't want a DebugLoc from them.
01064   while (MBBI != E && MBBI->isDebugValue())
01065     MBBI++;
01066   if (MBBI != E)
01067     DL = MBBI->getDebugLoc();
01068   return DL;
01069 }
01070 
01071 /// getSuccWeight - Return weight of the edge from this block to MBB.
01072 ///
01073 uint32_t MachineBasicBlock::getSuccWeight(const_succ_iterator Succ) const {
01074   if (Weights.empty())
01075     return 0;
01076 
01077   return *getWeightIterator(Succ);
01078 }
01079 
01080 /// Set successor weight of a given iterator.
01081 void MachineBasicBlock::setSuccWeight(succ_iterator I, uint32_t weight) {
01082   if (Weights.empty())
01083     return;
01084   *getWeightIterator(I) = weight;
01085 }
01086 
01087 /// getWeightIterator - Return wight iterator corresonding to the I successor
01088 /// iterator
01089 MachineBasicBlock::weight_iterator MachineBasicBlock::
01090 getWeightIterator(MachineBasicBlock::succ_iterator I) {
01091   assert(Weights.size() == Successors.size() && "Async weight list!");
01092   size_t index = std::distance(Successors.begin(), I);
01093   assert(index < Weights.size() && "Not a current successor!");
01094   return Weights.begin() + index;
01095 }
01096 
01097 /// getWeightIterator - Return wight iterator corresonding to the I successor
01098 /// iterator
01099 MachineBasicBlock::const_weight_iterator MachineBasicBlock::
01100 getWeightIterator(MachineBasicBlock::const_succ_iterator I) const {
01101   assert(Weights.size() == Successors.size() && "Async weight list!");
01102   const size_t index = std::distance(Successors.begin(), I);
01103   assert(index < Weights.size() && "Not a current successor!");
01104   return Weights.begin() + index;
01105 }
01106 
01107 /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
01108 /// as of just before "MI".
01109 /// 
01110 /// Search is localised to a neighborhood of
01111 /// Neighborhood instructions before (searching for defs or kills) and N
01112 /// instructions after (searching just for defs) MI.
01113 MachineBasicBlock::LivenessQueryResult
01114 MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
01115                                            unsigned Reg, const_iterator Before,
01116                                            unsigned Neighborhood) const {
01117   unsigned N = Neighborhood;
01118 
01119   // Start by searching backwards from Before, looking for kills, reads or defs.
01120   const_iterator I(Before);
01121   // If this is the first insn in the block, don't search backwards.
01122   if (I != begin()) {
01123     do {
01124       --I;
01125 
01126       MachineOperandIteratorBase::PhysRegInfo Analysis =
01127         ConstMIOperands(I).analyzePhysReg(Reg, TRI);
01128 
01129       if (Analysis.Defines)
01130         // Outputs happen after inputs so they take precedence if both are
01131         // present.
01132         return Analysis.DefinesDead ? LQR_Dead : LQR_Live;
01133 
01134       if (Analysis.Kills || Analysis.Clobbers)
01135         // Register killed, so isn't live.
01136         return LQR_Dead;
01137 
01138       else if (Analysis.ReadsOverlap)
01139         // Defined or read without a previous kill - live.
01140         return Analysis.Reads ? LQR_Live : LQR_OverlappingLive;
01141 
01142     } while (I != begin() && --N > 0);
01143   }
01144 
01145   // Did we get to the start of the block?
01146   if (I == begin()) {
01147     // If so, the register's state is definitely defined by the live-in state.
01148     for (MCRegAliasIterator RAI(Reg, TRI, /*IncludeSelf=*/true);
01149          RAI.isValid(); ++RAI) {
01150       if (isLiveIn(*RAI))
01151         return (*RAI == Reg) ? LQR_Live : LQR_OverlappingLive;
01152     }
01153 
01154     return LQR_Dead;
01155   }
01156 
01157   N = Neighborhood;
01158 
01159   // Try searching forwards from Before, looking for reads or defs.
01160   I = const_iterator(Before);
01161   // If this is the last insn in the block, don't search forwards.
01162   if (I != end()) {
01163     for (++I; I != end() && N > 0; ++I, --N) {
01164       MachineOperandIteratorBase::PhysRegInfo Analysis =
01165         ConstMIOperands(I).analyzePhysReg(Reg, TRI);
01166 
01167       if (Analysis.ReadsOverlap)
01168         // Used, therefore must have been live.
01169         return (Analysis.Reads) ?
01170           LQR_Live : LQR_OverlappingLive;
01171 
01172       else if (Analysis.Clobbers || Analysis.Defines)
01173         // Defined (but not read) therefore cannot have been live.
01174         return LQR_Dead;
01175     }
01176   }
01177 
01178   // At this point we have no idea of the liveness of the register.
01179   return LQR_Unknown;
01180 }