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