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