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