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