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