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