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