[CodeGenPrepare] Use variables for reused values. NFC.
[oota-llvm.git] / lib / CodeGen / MachineBasicBlock.cpp
1 //===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Collect the sequence of machine instructions for a basic block.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/MachineBasicBlock.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
18 #include "llvm/CodeGen/LiveVariables.h"
19 #include "llvm/CodeGen/MachineDominators.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/SlotIndexes.h"
25 #include "llvm/IR/BasicBlock.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/LeakDetector.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetRegisterInfo.h"
35 #include "llvm/Target/TargetSubtargetInfo.h"
36 #include <algorithm>
37 using namespace llvm;
38
39 #define DEBUG_TYPE "codegen"
40
41 MachineBasicBlock::MachineBasicBlock(MachineFunction &mf, const BasicBlock *bb)
42   : BB(bb), Number(-1), xParent(&mf), Alignment(0), IsLandingPad(false),
43     AddressTaken(false), CachedMCSymbol(nullptr) {
44   Insts.Parent = this;
45 }
46
47 MachineBasicBlock::~MachineBasicBlock() {
48   LeakDetector::removeGarbageObject(this);
49 }
50
51 /// getSymbol - Return the MCSymbol for this basic block.
52 ///
53 MCSymbol *MachineBasicBlock::getSymbol() const {
54   if (!CachedMCSymbol) {
55     const MachineFunction *MF = getParent();
56     MCContext &Ctx = MF->getContext();
57     const char *Prefix = Ctx.getAsmInfo()->getPrivateLabelPrefix();
58     CachedMCSymbol = Ctx.GetOrCreateSymbol(Twine(Prefix) + "BB" +
59                                            Twine(MF->getFunctionNumber()) +
60                                            "_" + Twine(getNumber()));
61   }
62
63   return CachedMCSymbol;
64 }
65
66
67 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
68   MBB.print(OS);
69   return OS;
70 }
71
72 /// addNodeToList (MBB) - When an MBB is added to an MF, we need to update the
73 /// parent pointer of the MBB, the MBB numbering, and any instructions in the
74 /// MBB to be on the right operand list for registers.
75 ///
76 /// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
77 /// gets the next available unique MBB number. If it is removed from a
78 /// MachineFunction, it goes back to being #-1.
79 void ilist_traits<MachineBasicBlock>::addNodeToList(MachineBasicBlock *N) {
80   MachineFunction &MF = *N->getParent();
81   N->Number = MF.addToMBBNumbering(N);
82
83   // Make sure the instructions have their operands in the reginfo lists.
84   MachineRegisterInfo &RegInfo = MF.getRegInfo();
85   for (MachineBasicBlock::instr_iterator
86          I = N->instr_begin(), E = N->instr_end(); I != E; ++I)
87     I->AddRegOperandsToUseLists(RegInfo);
88
89   LeakDetector::removeGarbageObject(N);
90 }
91
92 void ilist_traits<MachineBasicBlock>::removeNodeFromList(MachineBasicBlock *N) {
93   N->getParent()->removeFromMBBNumbering(N->Number);
94   N->Number = -1;
95   LeakDetector::addGarbageObject(N);
96 }
97
98
99 /// addNodeToList (MI) - When we add an instruction to a basic block
100 /// list, we update its parent pointer and add its operands from reg use/def
101 /// lists if appropriate.
102 void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
103   assert(!N->getParent() && "machine instruction already in a basic block");
104   N->setParent(Parent);
105
106   // Add the instruction's register operands to their corresponding
107   // use/def lists.
108   MachineFunction *MF = Parent->getParent();
109   N->AddRegOperandsToUseLists(MF->getRegInfo());
110
111   LeakDetector::removeGarbageObject(N);
112 }
113
114 /// removeNodeFromList (MI) - When we remove an instruction from a basic block
115 /// list, we update its parent pointer and remove its operands from reg use/def
116 /// lists if appropriate.
117 void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) {
118   assert(N->getParent() && "machine instruction not in a basic block");
119
120   // Remove from the use/def lists.
121   if (MachineFunction *MF = N->getParent()->getParent())
122     N->RemoveRegOperandsFromUseLists(MF->getRegInfo());
123
124   N->setParent(nullptr);
125
126   LeakDetector::addGarbageObject(N);
127 }
128
129 /// transferNodesFromList (MI) - When moving a range of instructions from one
130 /// MBB list to another, we need to update the parent pointers and the use/def
131 /// lists.
132 void ilist_traits<MachineInstr>::
133 transferNodesFromList(ilist_traits<MachineInstr> &fromList,
134                       ilist_iterator<MachineInstr> first,
135                       ilist_iterator<MachineInstr> last) {
136   assert(Parent->getParent() == fromList.Parent->getParent() &&
137         "MachineInstr parent mismatch!");
138
139   // Splice within the same MBB -> no change.
140   if (Parent == fromList.Parent) return;
141
142   // If splicing between two blocks within the same function, just update the
143   // parent pointers.
144   for (; first != last; ++first)
145     first->setParent(Parent);
146 }
147
148 void ilist_traits<MachineInstr>::deleteNode(MachineInstr* MI) {
149   assert(!MI->getParent() && "MI is still in a block!");
150   Parent->getParent()->DeleteMachineInstr(MI);
151 }
152
153 MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
154   instr_iterator I = instr_begin(), E = instr_end();
155   while (I != E && I->isPHI())
156     ++I;
157   assert((I == E || !I->isInsideBundle()) &&
158          "First non-phi MI cannot be inside a bundle!");
159   return I;
160 }
161
162 MachineBasicBlock::iterator
163 MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
164   iterator E = end();
165   while (I != E && (I->isPHI() || I->isPosition() || I->isDebugValue()))
166     ++I;
167   // FIXME: This needs to change if we wish to bundle labels / dbg_values
168   // inside the bundle.
169   assert((I == E || !I->isInsideBundle()) &&
170          "First non-phi / non-label instruction is inside a bundle!");
171   return I;
172 }
173
174 MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
175   iterator B = begin(), E = end(), I = E;
176   while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
177     ; /*noop */
178   while (I != E && !I->isTerminator())
179     ++I;
180   return I;
181 }
182
183 MachineBasicBlock::const_iterator
184 MachineBasicBlock::getFirstTerminator() const {
185   const_iterator B = begin(), E = end(), I = E;
186   while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
187     ; /*noop */
188   while (I != E && !I->isTerminator())
189     ++I;
190   return I;
191 }
192
193 MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() {
194   instr_iterator B = instr_begin(), E = instr_end(), I = E;
195   while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
196     ; /*noop */
197   while (I != E && !I->isTerminator())
198     ++I;
199   return I;
200 }
201
202 MachineBasicBlock::iterator MachineBasicBlock::getLastNonDebugInstr() {
203   // Skip over end-of-block dbg_value instructions.
204   instr_iterator B = instr_begin(), I = instr_end();
205   while (I != B) {
206     --I;
207     // Return instruction that starts a bundle.
208     if (I->isDebugValue() || I->isInsideBundle())
209       continue;
210     return I;
211   }
212   // The block is all debug values.
213   return end();
214 }
215
216 MachineBasicBlock::const_iterator
217 MachineBasicBlock::getLastNonDebugInstr() const {
218   // Skip over end-of-block dbg_value instructions.
219   const_instr_iterator B = instr_begin(), I = instr_end();
220   while (I != B) {
221     --I;
222     // Return instruction that starts a bundle.
223     if (I->isDebugValue() || I->isInsideBundle())
224       continue;
225     return I;
226   }
227   // The block is all debug values.
228   return end();
229 }
230
231 const MachineBasicBlock *MachineBasicBlock::getLandingPadSuccessor() const {
232   // A block with a landing pad successor only has one other successor.
233   if (succ_size() > 2)
234     return nullptr;
235   for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I)
236     if ((*I)->isLandingPad())
237       return *I;
238   return nullptr;
239 }
240
241 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
242 void MachineBasicBlock::dump() const {
243   print(dbgs());
244 }
245 #endif
246
247 StringRef MachineBasicBlock::getName() const {
248   if (const BasicBlock *LBB = getBasicBlock())
249     return LBB->getName();
250   else
251     return "(null)";
252 }
253
254 /// Return a hopefully unique identifier for this block.
255 std::string MachineBasicBlock::getFullName() const {
256   std::string Name;
257   if (getParent())
258     Name = (getParent()->getName() + ":").str();
259   if (getBasicBlock())
260     Name += getBasicBlock()->getName();
261   else
262     Name += (Twine("BB") + Twine(getNumber())).str();
263   return Name;
264 }
265
266 void MachineBasicBlock::print(raw_ostream &OS, SlotIndexes *Indexes) const {
267   const MachineFunction *MF = getParent();
268   if (!MF) {
269     OS << "Can't print out MachineBasicBlock because parent MachineFunction"
270        << " is null\n";
271     return;
272   }
273
274   if (Indexes)
275     OS << Indexes->getMBBStartIdx(this) << '\t';
276
277   OS << "BB#" << getNumber() << ": ";
278
279   const char *Comma = "";
280   if (const BasicBlock *LBB = getBasicBlock()) {
281     OS << Comma << "derived from LLVM BB ";
282     LBB->printAsOperand(OS, /*PrintType=*/false);
283     Comma = ", ";
284   }
285   if (isLandingPad()) { OS << Comma << "EH LANDING PAD"; Comma = ", "; }
286   if (hasAddressTaken()) { OS << Comma << "ADDRESS TAKEN"; Comma = ", "; }
287   if (Alignment)
288     OS << Comma << "Align " << Alignment << " (" << (1u << Alignment)
289        << " bytes)";
290
291   OS << '\n';
292
293   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
294   if (!livein_empty()) {
295     if (Indexes) OS << '\t';
296     OS << "    Live Ins:";
297     for (livein_iterator I = livein_begin(),E = livein_end(); I != E; ++I)
298       OS << ' ' << PrintReg(*I, TRI);
299     OS << '\n';
300   }
301   // Print the preds of this block according to the CFG.
302   if (!pred_empty()) {
303     if (Indexes) OS << '\t';
304     OS << "    Predecessors according to CFG:";
305     for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)
306       OS << " BB#" << (*PI)->getNumber();
307     OS << '\n';
308   }
309
310   for (const_instr_iterator I = instr_begin(); I != instr_end(); ++I) {
311     if (Indexes) {
312       if (Indexes->hasIndex(I))
313         OS << Indexes->getInstructionIndex(I);
314       OS << '\t';
315     }
316     OS << '\t';
317     if (I->isInsideBundle())
318       OS << "  * ";
319     I->print(OS, &getParent()->getTarget());
320   }
321
322   // Print the successors of this block according to the CFG.
323   if (!succ_empty()) {
324     if (Indexes) OS << '\t';
325     OS << "    Successors according to CFG:";
326     for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI) {
327       OS << " BB#" << (*SI)->getNumber();
328       if (!Weights.empty())
329         OS << '(' << *getWeightIterator(SI) << ')';
330     }
331     OS << '\n';
332   }
333 }
334
335 void MachineBasicBlock::printAsOperand(raw_ostream &OS, bool /*PrintType*/) const {
336   OS << "BB#" << getNumber();
337 }
338
339 void MachineBasicBlock::removeLiveIn(unsigned Reg) {
340   std::vector<unsigned>::iterator I =
341     std::find(LiveIns.begin(), LiveIns.end(), Reg);
342   if (I != LiveIns.end())
343     LiveIns.erase(I);
344 }
345
346 bool MachineBasicBlock::isLiveIn(unsigned Reg) const {
347   livein_iterator I = std::find(livein_begin(), livein_end(), Reg);
348   return I != livein_end();
349 }
350
351 unsigned
352 MachineBasicBlock::addLiveIn(unsigned PhysReg, const TargetRegisterClass *RC) {
353   assert(getParent() && "MBB must be inserted in function");
354   assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) && "Expected physreg");
355   assert(RC && "Register class is required");
356   assert((isLandingPad() || this == &getParent()->front()) &&
357          "Only the entry block and landing pads can have physreg live ins");
358
359   bool LiveIn = isLiveIn(PhysReg);
360   iterator I = SkipPHIsAndLabels(begin()), E = end();
361   MachineRegisterInfo &MRI = getParent()->getRegInfo();
362   const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
363
364   // Look for an existing copy.
365   if (LiveIn)
366     for (;I != E && I->isCopy(); ++I)
367       if (I->getOperand(1).getReg() == PhysReg) {
368         unsigned VirtReg = I->getOperand(0).getReg();
369         if (!MRI.constrainRegClass(VirtReg, RC))
370           llvm_unreachable("Incompatible live-in register class.");
371         return VirtReg;
372       }
373
374   // No luck, create a virtual register.
375   unsigned VirtReg = MRI.createVirtualRegister(RC);
376   BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
377     .addReg(PhysReg, RegState::Kill);
378   if (!LiveIn)
379     addLiveIn(PhysReg);
380   return VirtReg;
381 }
382
383 void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
384   getParent()->splice(NewAfter, this);
385 }
386
387 void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
388   MachineFunction::iterator BBI = NewBefore;
389   getParent()->splice(++BBI, this);
390 }
391
392 void MachineBasicBlock::updateTerminator() {
393   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
394   // A block with no successors has no concerns with fall-through edges.
395   if (this->succ_empty()) return;
396
397   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
398   SmallVector<MachineOperand, 4> Cond;
399   DebugLoc dl;  // FIXME: this is nowhere
400   bool B = TII->AnalyzeBranch(*this, TBB, FBB, Cond);
401   (void) B;
402   assert(!B && "UpdateTerminators requires analyzable predecessors!");
403   if (Cond.empty()) {
404     if (TBB) {
405       // The block has an unconditional branch. If its successor is now
406       // its layout successor, delete the branch.
407       if (isLayoutSuccessor(TBB))
408         TII->RemoveBranch(*this);
409     } else {
410       // The block has an unconditional fallthrough. If its successor is not
411       // its layout successor, insert a branch. First we have to locate the
412       // only non-landing-pad successor, as that is the fallthrough block.
413       for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
414         if ((*SI)->isLandingPad())
415           continue;
416         assert(!TBB && "Found more than one non-landing-pad successor!");
417         TBB = *SI;
418       }
419
420       // If there is no non-landing-pad successor, the block has no
421       // fall-through edges to be concerned with.
422       if (!TBB)
423         return;
424
425       // Finally update the unconditional successor to be reached via a branch
426       // if it would not be reached by fallthrough.
427       if (!isLayoutSuccessor(TBB))
428         TII->InsertBranch(*this, TBB, nullptr, Cond, dl);
429     }
430   } else {
431     if (FBB) {
432       // The block has a non-fallthrough conditional branch. If one of its
433       // successors is its layout successor, rewrite it to a fallthrough
434       // conditional branch.
435       if (isLayoutSuccessor(TBB)) {
436         if (TII->ReverseBranchCondition(Cond))
437           return;
438         TII->RemoveBranch(*this);
439         TII->InsertBranch(*this, FBB, nullptr, Cond, dl);
440       } else if (isLayoutSuccessor(FBB)) {
441         TII->RemoveBranch(*this);
442         TII->InsertBranch(*this, TBB, nullptr, Cond, dl);
443       }
444     } else {
445       // Walk through the successors and find the successor which is not
446       // a landing pad and is not the conditional branch destination (in TBB)
447       // as the fallthrough successor.
448       MachineBasicBlock *FallthroughBB = nullptr;
449       for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
450         if ((*SI)->isLandingPad() || *SI == TBB)
451           continue;
452         assert(!FallthroughBB && "Found more than one fallthrough successor.");
453         FallthroughBB = *SI;
454       }
455       if (!FallthroughBB && canFallThrough()) {
456         // We fallthrough to the same basic block as the conditional jump
457         // targets. Remove the conditional jump, leaving unconditional
458         // fallthrough.
459         // FIXME: This does not seem like a reasonable pattern to support, but it
460         // has been seen in the wild coming out of degenerate ARM test cases.
461         TII->RemoveBranch(*this);
462
463         // Finally update the unconditional successor to be reached via a branch
464         // if it would not be reached by fallthrough.
465         if (!isLayoutSuccessor(TBB))
466           TII->InsertBranch(*this, TBB, nullptr, Cond, dl);
467         return;
468       }
469
470       // The block has a fallthrough conditional branch.
471       if (isLayoutSuccessor(TBB)) {
472         if (TII->ReverseBranchCondition(Cond)) {
473           // We can't reverse the condition, add an unconditional branch.
474           Cond.clear();
475           TII->InsertBranch(*this, FallthroughBB, nullptr, Cond, dl);
476           return;
477         }
478         TII->RemoveBranch(*this);
479         TII->InsertBranch(*this, FallthroughBB, nullptr, Cond, dl);
480       } else if (!isLayoutSuccessor(FallthroughBB)) {
481         TII->RemoveBranch(*this);
482         TII->InsertBranch(*this, TBB, FallthroughBB, Cond, dl);
483       }
484     }
485   }
486 }
487
488 void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ, uint32_t weight) {
489
490   // If we see non-zero value for the first time it means we actually use Weight
491   // list, so we fill all Weights with 0's.
492   if (weight != 0 && Weights.empty())
493     Weights.resize(Successors.size());
494
495   if (weight != 0 || !Weights.empty())
496     Weights.push_back(weight);
497
498    Successors.push_back(succ);
499    succ->addPredecessor(this);
500  }
501
502 void MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) {
503   succ->removePredecessor(this);
504   succ_iterator I = std::find(Successors.begin(), Successors.end(), succ);
505   assert(I != Successors.end() && "Not a current successor!");
506
507   // If Weight list is empty it means we don't use it (disabled optimization).
508   if (!Weights.empty()) {
509     weight_iterator WI = getWeightIterator(I);
510     Weights.erase(WI);
511   }
512
513   Successors.erase(I);
514 }
515
516 MachineBasicBlock::succ_iterator
517 MachineBasicBlock::removeSuccessor(succ_iterator I) {
518   assert(I != Successors.end() && "Not a current successor!");
519
520   // If Weight list is empty it means we don't use it (disabled optimization).
521   if (!Weights.empty()) {
522     weight_iterator WI = getWeightIterator(I);
523     Weights.erase(WI);
524   }
525
526   (*I)->removePredecessor(this);
527   return Successors.erase(I);
528 }
529
530 void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
531                                          MachineBasicBlock *New) {
532   if (Old == New)
533     return;
534
535   succ_iterator E = succ_end();
536   succ_iterator NewI = E;
537   succ_iterator OldI = E;
538   for (succ_iterator I = succ_begin(); I != E; ++I) {
539     if (*I == Old) {
540       OldI = I;
541       if (NewI != E)
542         break;
543     }
544     if (*I == New) {
545       NewI = I;
546       if (OldI != E)
547         break;
548     }
549   }
550   assert(OldI != E && "Old is not a successor of this block");
551   Old->removePredecessor(this);
552
553   // If New isn't already a successor, let it take Old's place.
554   if (NewI == E) {
555     New->addPredecessor(this);
556     *OldI = New;
557     return;
558   }
559
560   // New is already a successor.
561   // Update its weight instead of adding a duplicate edge.
562   if (!Weights.empty()) {
563     weight_iterator OldWI = getWeightIterator(OldI);
564     *getWeightIterator(NewI) += *OldWI;
565     Weights.erase(OldWI);
566   }
567   Successors.erase(OldI);
568 }
569
570 void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) {
571   Predecessors.push_back(pred);
572 }
573
574 void MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) {
575   pred_iterator I = std::find(Predecessors.begin(), Predecessors.end(), pred);
576   assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
577   Predecessors.erase(I);
578 }
579
580 void MachineBasicBlock::transferSuccessors(MachineBasicBlock *fromMBB) {
581   if (this == fromMBB)
582     return;
583
584   while (!fromMBB->succ_empty()) {
585     MachineBasicBlock *Succ = *fromMBB->succ_begin();
586     uint32_t Weight = 0;
587
588     // If Weight list is empty it means we don't use it (disabled optimization).
589     if (!fromMBB->Weights.empty())
590       Weight = *fromMBB->Weights.begin();
591
592     addSuccessor(Succ, Weight);
593     fromMBB->removeSuccessor(Succ);
594   }
595 }
596
597 void
598 MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *fromMBB) {
599   if (this == fromMBB)
600     return;
601
602   while (!fromMBB->succ_empty()) {
603     MachineBasicBlock *Succ = *fromMBB->succ_begin();
604     uint32_t Weight = 0;
605     if (!fromMBB->Weights.empty())
606       Weight = *fromMBB->Weights.begin();
607     addSuccessor(Succ, Weight);
608     fromMBB->removeSuccessor(Succ);
609
610     // Fix up any PHI nodes in the successor.
611     for (MachineBasicBlock::instr_iterator MI = Succ->instr_begin(),
612            ME = Succ->instr_end(); MI != ME && MI->isPHI(); ++MI)
613       for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) {
614         MachineOperand &MO = MI->getOperand(i);
615         if (MO.getMBB() == fromMBB)
616           MO.setMBB(this);
617       }
618   }
619 }
620
621 bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
622   return std::find(pred_begin(), pred_end(), MBB) != pred_end();
623 }
624
625 bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
626   return std::find(succ_begin(), succ_end(), MBB) != succ_end();
627 }
628
629 bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
630   MachineFunction::const_iterator I(this);
631   return std::next(I) == MachineFunction::const_iterator(MBB);
632 }
633
634 bool MachineBasicBlock::canFallThrough() {
635   MachineFunction::iterator Fallthrough = this;
636   ++Fallthrough;
637   // If FallthroughBlock is off the end of the function, it can't fall through.
638   if (Fallthrough == getParent()->end())
639     return false;
640
641   // If FallthroughBlock isn't a successor, no fallthrough is possible.
642   if (!isSuccessor(Fallthrough))
643     return false;
644
645   // Analyze the branches, if any, at the end of the block.
646   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
647   SmallVector<MachineOperand, 4> Cond;
648   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
649   if (TII->AnalyzeBranch(*this, TBB, FBB, Cond)) {
650     // If we couldn't analyze the branch, examine the last instruction.
651     // If the block doesn't end in a known control barrier, assume fallthrough
652     // is possible. The isPredicated check is needed because this code can be
653     // called during IfConversion, where an instruction which is normally a
654     // Barrier is predicated and thus no longer an actual control barrier.
655     return empty() || !back().isBarrier() || TII->isPredicated(&back());
656   }
657
658   // If there is no branch, control always falls through.
659   if (!TBB) return true;
660
661   // If there is some explicit branch to the fallthrough block, it can obviously
662   // reach, even though the branch should get folded to fall through implicitly.
663   if (MachineFunction::iterator(TBB) == Fallthrough ||
664       MachineFunction::iterator(FBB) == Fallthrough)
665     return true;
666
667   // If it's an unconditional branch to some block not the fall through, it
668   // doesn't fall through.
669   if (Cond.empty()) return false;
670
671   // Otherwise, if it is conditional and has no explicit false block, it falls
672   // through.
673   return FBB == nullptr;
674 }
675
676 MachineBasicBlock *
677 MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ, Pass *P) {
678   // Splitting the critical edge to a landing pad block is non-trivial. Don't do
679   // it in this generic function.
680   if (Succ->isLandingPad())
681     return nullptr;
682
683   MachineFunction *MF = getParent();
684   DebugLoc dl;  // FIXME: this is nowhere
685
686   // Performance might be harmed on HW that implements branching using exec mask
687   // where both sides of the branches are always executed.
688   if (MF->getTarget().requiresStructuredCFG())
689     return nullptr;
690
691   // We may need to update this's terminator, but we can't do that if
692   // AnalyzeBranch fails. If this uses a jump table, we won't touch it.
693   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
694   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
695   SmallVector<MachineOperand, 4> Cond;
696   if (TII->AnalyzeBranch(*this, TBB, FBB, Cond))
697     return nullptr;
698
699   // Avoid bugpoint weirdness: A block may end with a conditional branch but
700   // jumps to the same MBB is either case. We have duplicate CFG edges in that
701   // case that we can't handle. Since this never happens in properly optimized
702   // code, just skip those edges.
703   if (TBB && TBB == FBB) {
704     DEBUG(dbgs() << "Won't split critical edge after degenerate BB#"
705                  << getNumber() << '\n');
706     return nullptr;
707   }
708
709   MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
710   MF->insert(std::next(MachineFunction::iterator(this)), NMBB);
711   DEBUG(dbgs() << "Splitting critical edge:"
712         " BB#" << getNumber()
713         << " -- BB#" << NMBB->getNumber()
714         << " -- BB#" << Succ->getNumber() << '\n');
715
716   LiveIntervals *LIS = P->getAnalysisIfAvailable<LiveIntervals>();
717   SlotIndexes *Indexes = P->getAnalysisIfAvailable<SlotIndexes>();
718   if (LIS)
719     LIS->insertMBBInMaps(NMBB);
720   else if (Indexes)
721     Indexes->insertMBBInMaps(NMBB);
722
723   // On some targets like Mips, branches may kill virtual registers. Make sure
724   // that LiveVariables is properly updated after updateTerminator replaces the
725   // terminators.
726   LiveVariables *LV = P->getAnalysisIfAvailable<LiveVariables>();
727
728   // Collect a list of virtual registers killed by the terminators.
729   SmallVector<unsigned, 4> KilledRegs;
730   if (LV)
731     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
732          I != E; ++I) {
733       MachineInstr *MI = I;
734       for (MachineInstr::mop_iterator OI = MI->operands_begin(),
735            OE = MI->operands_end(); OI != OE; ++OI) {
736         if (!OI->isReg() || OI->getReg() == 0 ||
737             !OI->isUse() || !OI->isKill() || OI->isUndef())
738           continue;
739         unsigned Reg = OI->getReg();
740         if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
741             LV->getVarInfo(Reg).removeKill(MI)) {
742           KilledRegs.push_back(Reg);
743           DEBUG(dbgs() << "Removing terminator kill: " << *MI);
744           OI->setIsKill(false);
745         }
746       }
747     }
748
749   SmallVector<unsigned, 4> UsedRegs;
750   if (LIS) {
751     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
752          I != E; ++I) {
753       MachineInstr *MI = I;
754
755       for (MachineInstr::mop_iterator OI = MI->operands_begin(),
756            OE = MI->operands_end(); OI != OE; ++OI) {
757         if (!OI->isReg() || OI->getReg() == 0)
758           continue;
759
760         unsigned Reg = OI->getReg();
761         if (std::find(UsedRegs.begin(), UsedRegs.end(), Reg) == UsedRegs.end())
762           UsedRegs.push_back(Reg);
763       }
764     }
765   }
766
767   ReplaceUsesOfBlockWith(Succ, NMBB);
768
769   // If updateTerminator() removes instructions, we need to remove them from
770   // SlotIndexes.
771   SmallVector<MachineInstr*, 4> Terminators;
772   if (Indexes) {
773     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
774          I != E; ++I)
775       Terminators.push_back(I);
776   }
777
778   updateTerminator();
779
780   if (Indexes) {
781     SmallVector<MachineInstr*, 4> NewTerminators;
782     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
783          I != E; ++I)
784       NewTerminators.push_back(I);
785
786     for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(),
787         E = Terminators.end(); I != E; ++I) {
788       if (std::find(NewTerminators.begin(), NewTerminators.end(), *I) ==
789           NewTerminators.end())
790        Indexes->removeMachineInstrFromMaps(*I);
791     }
792   }
793
794   // Insert unconditional "jump Succ" instruction in NMBB if necessary.
795   NMBB->addSuccessor(Succ);
796   if (!NMBB->isLayoutSuccessor(Succ)) {
797     Cond.clear();
798     MF->getSubtarget().getInstrInfo()->InsertBranch(*NMBB, Succ, nullptr, Cond,
799                                                     dl);
800
801     if (Indexes) {
802       for (instr_iterator I = NMBB->instr_begin(), E = NMBB->instr_end();
803            I != E; ++I) {
804         // Some instructions may have been moved to NMBB by updateTerminator(),
805         // so we first remove any instruction that already has an index.
806         if (Indexes->hasIndex(I))
807           Indexes->removeMachineInstrFromMaps(I);
808         Indexes->insertMachineInstrInMaps(I);
809       }
810     }
811   }
812
813   // Fix PHI nodes in Succ so they refer to NMBB instead of this
814   for (MachineBasicBlock::instr_iterator
815          i = Succ->instr_begin(),e = Succ->instr_end();
816        i != e && i->isPHI(); ++i)
817     for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
818       if (i->getOperand(ni+1).getMBB() == this)
819         i->getOperand(ni+1).setMBB(NMBB);
820
821   // Inherit live-ins from the successor
822   for (MachineBasicBlock::livein_iterator I = Succ->livein_begin(),
823          E = Succ->livein_end(); I != E; ++I)
824     NMBB->addLiveIn(*I);
825
826   // Update LiveVariables.
827   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
828   if (LV) {
829     // Restore kills of virtual registers that were killed by the terminators.
830     while (!KilledRegs.empty()) {
831       unsigned Reg = KilledRegs.pop_back_val();
832       for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
833         if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
834           continue;
835         if (TargetRegisterInfo::isVirtualRegister(Reg))
836           LV->getVarInfo(Reg).Kills.push_back(I);
837         DEBUG(dbgs() << "Restored terminator kill: " << *I);
838         break;
839       }
840     }
841     // Update relevant live-through information.
842     LV->addNewBlock(NMBB, this, Succ);
843   }
844
845   if (LIS) {
846     // After splitting the edge and updating SlotIndexes, live intervals may be
847     // in one of two situations, depending on whether this block was the last in
848     // the function. If the original block was the last in the function, all live
849     // intervals will end prior to the beginning of the new split block. If the
850     // original block was not at the end of the function, all live intervals will
851     // extend to the end of the new split block.
852
853     bool isLastMBB =
854       std::next(MachineFunction::iterator(NMBB)) == getParent()->end();
855
856     SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
857     SlotIndex PrevIndex = StartIndex.getPrevSlot();
858     SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
859
860     // Find the registers used from NMBB in PHIs in Succ.
861     SmallSet<unsigned, 8> PHISrcRegs;
862     for (MachineBasicBlock::instr_iterator
863          I = Succ->instr_begin(), E = Succ->instr_end();
864          I != E && I->isPHI(); ++I) {
865       for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
866         if (I->getOperand(ni+1).getMBB() == NMBB) {
867           MachineOperand &MO = I->getOperand(ni);
868           unsigned Reg = MO.getReg();
869           PHISrcRegs.insert(Reg);
870           if (MO.isUndef())
871             continue;
872
873           LiveInterval &LI = LIS->getInterval(Reg);
874           VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
875           assert(VNI && "PHI sources should be live out of their predecessors.");
876           LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
877         }
878       }
879     }
880
881     MachineRegisterInfo *MRI = &getParent()->getRegInfo();
882     for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
883       unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
884       if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
885         continue;
886
887       LiveInterval &LI = LIS->getInterval(Reg);
888       if (!LI.liveAt(PrevIndex))
889         continue;
890
891       bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
892       if (isLiveOut && isLastMBB) {
893         VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
894         assert(VNI && "LiveInterval should have VNInfo where it is live.");
895         LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
896       } else if (!isLiveOut && !isLastMBB) {
897         LI.removeSegment(StartIndex, EndIndex);
898       }
899     }
900
901     // Update all intervals for registers whose uses may have been modified by
902     // updateTerminator().
903     LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
904   }
905
906   if (MachineDominatorTree *MDT =
907       P->getAnalysisIfAvailable<MachineDominatorTree>())
908     MDT->recordSplitCriticalEdge(this, Succ, NMBB);
909
910   if (MachineLoopInfo *MLI = P->getAnalysisIfAvailable<MachineLoopInfo>())
911     if (MachineLoop *TIL = MLI->getLoopFor(this)) {
912       // If one or the other blocks were not in a loop, the new block is not
913       // either, and thus LI doesn't need to be updated.
914       if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
915         if (TIL == DestLoop) {
916           // Both in the same loop, the NMBB joins loop.
917           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
918         } else if (TIL->contains(DestLoop)) {
919           // Edge from an outer loop to an inner loop.  Add to the outer loop.
920           TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
921         } else if (DestLoop->contains(TIL)) {
922           // Edge from an inner loop to an outer loop.  Add to the outer loop.
923           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
924         } else {
925           // Edge from two loops with no containment relation.  Because these
926           // are natural loops, we know that the destination block must be the
927           // header of its loop (adding a branch into a loop elsewhere would
928           // create an irreducible loop).
929           assert(DestLoop->getHeader() == Succ &&
930                  "Should not create irreducible loops!");
931           if (MachineLoop *P = DestLoop->getParentLoop())
932             P->addBasicBlockToLoop(NMBB, MLI->getBase());
933         }
934       }
935     }
936
937   return NMBB;
938 }
939
940 /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
941 /// neighboring instructions so the bundle won't be broken by removing MI.
942 static void unbundleSingleMI(MachineInstr *MI) {
943   // Removing the first instruction in a bundle.
944   if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
945     MI->unbundleFromSucc();
946   // Removing the last instruction in a bundle.
947   if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
948     MI->unbundleFromPred();
949   // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
950   // are already fine.
951 }
952
953 MachineBasicBlock::instr_iterator
954 MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
955   unbundleSingleMI(I);
956   return Insts.erase(I);
957 }
958
959 MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
960   unbundleSingleMI(MI);
961   MI->clearFlag(MachineInstr::BundledPred);
962   MI->clearFlag(MachineInstr::BundledSucc);
963   return Insts.remove(MI);
964 }
965
966 MachineBasicBlock::instr_iterator
967 MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
968   assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
969          "Cannot insert instruction with bundle flags");
970   // Set the bundle flags when inserting inside a bundle.
971   if (I != instr_end() && I->isBundledWithPred()) {
972     MI->setFlag(MachineInstr::BundledPred);
973     MI->setFlag(MachineInstr::BundledSucc);
974   }
975   return Insts.insert(I, MI);
976 }
977
978 /// removeFromParent - This method unlinks 'this' from the containing function,
979 /// and returns it, but does not delete it.
980 MachineBasicBlock *MachineBasicBlock::removeFromParent() {
981   assert(getParent() && "Not embedded in a function!");
982   getParent()->remove(this);
983   return this;
984 }
985
986
987 /// eraseFromParent - This method unlinks 'this' from the containing function,
988 /// and deletes it.
989 void MachineBasicBlock::eraseFromParent() {
990   assert(getParent() && "Not embedded in a function!");
991   getParent()->erase(this);
992 }
993
994
995 /// ReplaceUsesOfBlockWith - Given a machine basic block that branched to
996 /// 'Old', change the code and CFG so that it branches to 'New' instead.
997 void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
998                                                MachineBasicBlock *New) {
999   assert(Old != New && "Cannot replace self with self!");
1000
1001   MachineBasicBlock::instr_iterator I = instr_end();
1002   while (I != instr_begin()) {
1003     --I;
1004     if (!I->isTerminator()) break;
1005
1006     // Scan the operands of this machine instruction, replacing any uses of Old
1007     // with New.
1008     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1009       if (I->getOperand(i).isMBB() &&
1010           I->getOperand(i).getMBB() == Old)
1011         I->getOperand(i).setMBB(New);
1012   }
1013
1014   // Update the successor information.
1015   replaceSuccessor(Old, New);
1016 }
1017
1018 /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
1019 /// CFG to be inserted.  If we have proven that MBB can only branch to DestA and
1020 /// DestB, remove any other MBB successors from the CFG.  DestA and DestB can be
1021 /// null.
1022 ///
1023 /// Besides DestA and DestB, retain other edges leading to LandingPads
1024 /// (currently there can be only one; we don't check or require that here).
1025 /// Note it is possible that DestA and/or DestB are LandingPads.
1026 bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
1027                                              MachineBasicBlock *DestB,
1028                                              bool isCond) {
1029   // The values of DestA and DestB frequently come from a call to the
1030   // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial
1031   // values from there.
1032   //
1033   // 1. If both DestA and DestB are null, then the block ends with no branches
1034   //    (it falls through to its successor).
1035   // 2. If DestA is set, DestB is null, and isCond is false, then the block ends
1036   //    with only an unconditional branch.
1037   // 3. If DestA is set, DestB is null, and isCond is true, then the block ends
1038   //    with a conditional branch that falls through to a successor (DestB).
1039   // 4. If DestA and DestB is set and isCond is true, then the block ends with a
1040   //    conditional branch followed by an unconditional branch. DestA is the
1041   //    'true' destination and DestB is the 'false' destination.
1042
1043   bool Changed = false;
1044
1045   MachineFunction::iterator FallThru =
1046     std::next(MachineFunction::iterator(this));
1047
1048   if (!DestA && !DestB) {
1049     // Block falls through to successor.
1050     DestA = FallThru;
1051     DestB = FallThru;
1052   } else if (DestA && !DestB) {
1053     if (isCond)
1054       // Block ends in conditional jump that falls through to successor.
1055       DestB = FallThru;
1056   } else {
1057     assert(DestA && DestB && isCond &&
1058            "CFG in a bad state. Cannot correct CFG edges");
1059   }
1060
1061   // Remove superfluous edges. I.e., those which aren't destinations of this
1062   // basic block, duplicate edges, or landing pads.
1063   SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs;
1064   MachineBasicBlock::succ_iterator SI = succ_begin();
1065   while (SI != succ_end()) {
1066     const MachineBasicBlock *MBB = *SI;
1067     if (!SeenMBBs.insert(MBB).second ||
1068         (MBB != DestA && MBB != DestB && !MBB->isLandingPad())) {
1069       // This is a superfluous edge, remove it.
1070       SI = removeSuccessor(SI);
1071       Changed = true;
1072     } else {
1073       ++SI;
1074     }
1075   }
1076
1077   return Changed;
1078 }
1079
1080 /// findDebugLoc - find the next valid DebugLoc starting at MBBI, skipping
1081 /// any DBG_VALUE instructions.  Return UnknownLoc if there is none.
1082 DebugLoc
1083 MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
1084   DebugLoc DL;
1085   instr_iterator E = instr_end();
1086   if (MBBI == E)
1087     return DL;
1088
1089   // Skip debug declarations, we don't want a DebugLoc from them.
1090   while (MBBI != E && MBBI->isDebugValue())
1091     MBBI++;
1092   if (MBBI != E)
1093     DL = MBBI->getDebugLoc();
1094   return DL;
1095 }
1096
1097 /// getSuccWeight - Return weight of the edge from this block to MBB.
1098 ///
1099 uint32_t MachineBasicBlock::getSuccWeight(const_succ_iterator Succ) const {
1100   if (Weights.empty())
1101     return 0;
1102
1103   return *getWeightIterator(Succ);
1104 }
1105
1106 /// Set successor weight of a given iterator.
1107 void MachineBasicBlock::setSuccWeight(succ_iterator I, uint32_t weight) {
1108   if (Weights.empty())
1109     return;
1110   *getWeightIterator(I) = weight;
1111 }
1112
1113 /// getWeightIterator - Return wight iterator corresonding to the I successor
1114 /// iterator
1115 MachineBasicBlock::weight_iterator MachineBasicBlock::
1116 getWeightIterator(MachineBasicBlock::succ_iterator I) {
1117   assert(Weights.size() == Successors.size() && "Async weight list!");
1118   size_t index = std::distance(Successors.begin(), I);
1119   assert(index < Weights.size() && "Not a current successor!");
1120   return Weights.begin() + index;
1121 }
1122
1123 /// getWeightIterator - Return wight iterator corresonding to the I successor
1124 /// iterator
1125 MachineBasicBlock::const_weight_iterator MachineBasicBlock::
1126 getWeightIterator(MachineBasicBlock::const_succ_iterator I) const {
1127   assert(Weights.size() == Successors.size() && "Async weight list!");
1128   const size_t index = std::distance(Successors.begin(), I);
1129   assert(index < Weights.size() && "Not a current successor!");
1130   return Weights.begin() + index;
1131 }
1132
1133 /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
1134 /// as of just before "MI".
1135 /// 
1136 /// Search is localised to a neighborhood of
1137 /// Neighborhood instructions before (searching for defs or kills) and N
1138 /// instructions after (searching just for defs) MI.
1139 MachineBasicBlock::LivenessQueryResult
1140 MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
1141                                            unsigned Reg, MachineInstr *MI,
1142                                            unsigned Neighborhood) {
1143   unsigned N = Neighborhood;
1144   MachineBasicBlock *MBB = MI->getParent();
1145
1146   // Start by searching backwards from MI, looking for kills, reads or defs.
1147
1148   MachineBasicBlock::iterator I(MI);
1149   // If this is the first insn in the block, don't search backwards.
1150   if (I != MBB->begin()) {
1151     do {
1152       --I;
1153
1154       MachineOperandIteratorBase::PhysRegInfo Analysis =
1155         MIOperands(I).analyzePhysReg(Reg, TRI);
1156
1157       if (Analysis.Defines)
1158         // Outputs happen after inputs so they take precedence if both are
1159         // present.
1160         return Analysis.DefinesDead ? LQR_Dead : LQR_Live;
1161
1162       if (Analysis.Kills || Analysis.Clobbers)
1163         // Register killed, so isn't live.
1164         return LQR_Dead;
1165
1166       else if (Analysis.ReadsOverlap)
1167         // Defined or read without a previous kill - live.
1168         return Analysis.Reads ? LQR_Live : LQR_OverlappingLive;
1169
1170     } while (I != MBB->begin() && --N > 0);
1171   }
1172
1173   // Did we get to the start of the block?
1174   if (I == MBB->begin()) {
1175     // If so, the register's state is definitely defined by the live-in state.
1176     for (MCRegAliasIterator RAI(Reg, TRI, /*IncludeSelf=*/true);
1177          RAI.isValid(); ++RAI) {
1178       if (MBB->isLiveIn(*RAI))
1179         return (*RAI == Reg) ? LQR_Live : LQR_OverlappingLive;
1180     }
1181
1182     return LQR_Dead;
1183   }
1184
1185   N = Neighborhood;
1186
1187   // Try searching forwards from MI, looking for reads or defs.
1188   I = MachineBasicBlock::iterator(MI);
1189   // If this is the last insn in the block, don't search forwards.
1190   if (I != MBB->end()) {
1191     for (++I; I != MBB->end() && N > 0; ++I, --N) {
1192       MachineOperandIteratorBase::PhysRegInfo Analysis =
1193         MIOperands(I).analyzePhysReg(Reg, TRI);
1194
1195       if (Analysis.ReadsOverlap)
1196         // Used, therefore must have been live.
1197         return (Analysis.Reads) ?
1198           LQR_Live : LQR_OverlappingLive;
1199
1200       else if (Analysis.Clobbers || Analysis.Defines)
1201         // Defined (but not read) therefore cannot have been live.
1202         return LQR_Dead;
1203     }
1204   }
1205
1206   // At this point we have no idea of the liveness of the register.
1207   return LQR_Unknown;
1208 }