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