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