9ff4858f0a4e0a574a1acdf93d07af81c54d5801
[oota-llvm.git] / lib / CodeGen / MachineBasicBlock.cpp
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/ADT/SmallString.h"
17 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
18 #include "llvm/CodeGen/LiveVariables.h"
19 #include "llvm/CodeGen/MachineDominators.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/SlotIndexes.h"
25 #include "llvm/IR/BasicBlock.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/ModuleSlotTracker.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCContext.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
41 MachineBasicBlock::MachineBasicBlock(MachineFunction &mf, const BasicBlock *bb)
42   : BB(bb), Number(-1), xParent(&mf), Alignment(0), IsLandingPad(false),
43     AddressTaken(false), CachedMCSymbol(nullptr) {
44   Insts.Parent = this;
45 }
46
47 MachineBasicBlock::~MachineBasicBlock() {
48 }
49
50 /// Return the MCSymbol for this basic block.
51 MCSymbol *MachineBasicBlock::getSymbol() const {
52   if (!CachedMCSymbol) {
53     const MachineFunction *MF = getParent();
54     MCContext &Ctx = MF->getContext();
55     const char *Prefix = Ctx.getAsmInfo()->getPrivateLabelPrefix();
56     CachedMCSymbol = Ctx.getOrCreateSymbol(Twine(Prefix) + "BB" +
57                                            Twine(MF->getFunctionNumber()) +
58                                            "_" + Twine(getNumber()));
59   }
60
61   return CachedMCSymbol;
62 }
63
64
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.
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
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.
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.
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>::
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
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
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
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
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
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
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
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
201 const MachineBasicBlock *MachineBasicBlock::getLandingPadSuccessor() const {
202   // A block with a landing pad successor only has one other successor.
203   if (succ_size() > 2)
204     return nullptr;
205   for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I)
206     if ((*I)->isLandingPad())
207       return *I;
208   return nullptr;
209 }
210
211 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
212 void MachineBasicBlock::dump() const {
213   print(dbgs());
214 }
215 #endif
216
217 StringRef MachineBasicBlock::getName() const {
218   if (const BasicBlock *LBB = getBasicBlock())
219     return LBB->getName();
220   else
221     return "(null)";
222 }
223
224 /// Return a hopefully unique identifier for this block.
225 std::string MachineBasicBlock::getFullName() const {
226   std::string Name;
227   if (getParent())
228     Name = (getParent()->getName() + ":").str();
229   if (getBasicBlock())
230     Name += getBasicBlock()->getName();
231   else
232     Name += ("BB" + Twine(getNumber())).str();
233   return Name;
234 }
235
236 void MachineBasicBlock::print(raw_ostream &OS, SlotIndexes *Indexes) const {
237   const MachineFunction *MF = getParent();
238   if (!MF) {
239     OS << "Can't print out MachineBasicBlock because parent MachineFunction"
240        << " is null\n";
241     return;
242   }
243   const Function *F = MF->getFunction();
244   const Module *M = F ? F->getParent() : nullptr;
245   ModuleSlotTracker MST(M);
246   print(OS, MST, Indexes);
247 }
248
249 void MachineBasicBlock::print(raw_ostream &OS, ModuleSlotTracker &MST,
250                               SlotIndexes *Indexes) const {
251   const MachineFunction *MF = getParent();
252   if (!MF) {
253     OS << "Can't print out MachineBasicBlock because parent MachineFunction"
254        << " is null\n";
255     return;
256   }
257
258   if (Indexes)
259     OS << Indexes->getMBBStartIdx(this) << '\t';
260
261   OS << "BB#" << getNumber() << ": ";
262
263   const char *Comma = "";
264   if (const BasicBlock *LBB = getBasicBlock()) {
265     OS << Comma << "derived from LLVM BB ";
266     LBB->printAsOperand(OS, /*PrintType=*/false, MST);
267     Comma = ", ";
268   }
269   if (isLandingPad()) { OS << Comma << "EH LANDING PAD"; Comma = ", "; }
270   if (hasAddressTaken()) { OS << Comma << "ADDRESS TAKEN"; Comma = ", "; }
271   if (Alignment)
272     OS << Comma << "Align " << Alignment << " (" << (1u << Alignment)
273        << " bytes)";
274
275   OS << '\n';
276
277   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
278   if (!livein_empty()) {
279     if (Indexes) OS << '\t';
280     OS << "    Live Ins:";
281     for (unsigned LI : make_range(livein_begin(), livein_end())) {
282       OS << ' ' << PrintReg(LI, TRI);
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 (const_instr_iterator I = instr_begin(); I != instr_end(); ++I) {
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 (!Weights.empty())
314         OS << '(' << *getWeightIterator(SI) << ')';
315     }
316     OS << '\n';
317   }
318 }
319
320 void MachineBasicBlock::printAsOperand(raw_ostream &OS,
321                                        bool /*PrintType*/) const {
322   OS << "BB#" << getNumber();
323 }
324
325 void MachineBasicBlock::removeLiveIn(unsigned Reg) {
326   std::vector<unsigned>::iterator I
327     = std::find(LiveIns.begin(), LiveIns.end(), Reg);
328   if (I != LiveIns.end())
329     LiveIns.erase(I);
330 }
331
332 bool MachineBasicBlock::isLiveIn(unsigned Reg) const {
333   livein_iterator I = std::find(livein_begin(), livein_end(), Reg);
334   return I != livein_end();
335 }
336
337 unsigned
338 MachineBasicBlock::addLiveIn(unsigned PhysReg, const TargetRegisterClass *RC) {
339   assert(getParent() && "MBB must be inserted in function");
340   assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) && "Expected physreg");
341   assert(RC && "Register class is required");
342   assert((isLandingPad() || this == &getParent()->front()) &&
343          "Only the entry block and landing pads can have physreg live ins");
344
345   bool LiveIn = isLiveIn(PhysReg);
346   iterator I = SkipPHIsAndLabels(begin()), E = end();
347   MachineRegisterInfo &MRI = getParent()->getRegInfo();
348   const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
349
350   // Look for an existing copy.
351   if (LiveIn)
352     for (;I != E && I->isCopy(); ++I)
353       if (I->getOperand(1).getReg() == PhysReg) {
354         unsigned VirtReg = I->getOperand(0).getReg();
355         if (!MRI.constrainRegClass(VirtReg, RC))
356           llvm_unreachable("Incompatible live-in register class.");
357         return VirtReg;
358       }
359
360   // No luck, create a virtual register.
361   unsigned VirtReg = MRI.createVirtualRegister(RC);
362   BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
363     .addReg(PhysReg, RegState::Kill);
364   if (!LiveIn)
365     addLiveIn(PhysReg);
366   return VirtReg;
367 }
368
369 void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
370   getParent()->splice(NewAfter, this);
371 }
372
373 void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
374   MachineFunction::iterator BBI = NewBefore;
375   getParent()->splice(++BBI, this);
376 }
377
378 void MachineBasicBlock::updateTerminator() {
379   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
380   // A block with no successors has no concerns with fall-through edges.
381   if (this->succ_empty()) return;
382
383   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
384   SmallVector<MachineOperand, 4> Cond;
385   DebugLoc dl;  // FIXME: this is nowhere
386   bool B = TII->AnalyzeBranch(*this, TBB, FBB, Cond);
387   (void) B;
388   assert(!B && "UpdateTerminators requires analyzable predecessors!");
389   if (Cond.empty()) {
390     if (TBB) {
391       // The block has an unconditional branch. If its successor is now
392       // its layout successor, delete the branch.
393       if (isLayoutSuccessor(TBB))
394         TII->RemoveBranch(*this);
395     } else {
396       // The block has an unconditional fallthrough. If its successor is not
397       // its layout successor, insert a branch. First we have to locate the
398       // only non-landing-pad successor, as that is the fallthrough block.
399       for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
400         if ((*SI)->isLandingPad())
401           continue;
402         assert(!TBB && "Found more than one non-landing-pad successor!");
403         TBB = *SI;
404       }
405
406       // If there is no non-landing-pad successor, the block has no
407       // fall-through edges to be concerned with.
408       if (!TBB)
409         return;
410
411       // Finally update the unconditional successor to be reached via a branch
412       // if it would not be reached by fallthrough.
413       if (!isLayoutSuccessor(TBB))
414         TII->InsertBranch(*this, TBB, nullptr, Cond, dl);
415     }
416   } else {
417     if (FBB) {
418       // The block has a non-fallthrough conditional branch. If one of its
419       // successors is its layout successor, rewrite it to a fallthrough
420       // conditional branch.
421       if (isLayoutSuccessor(TBB)) {
422         if (TII->ReverseBranchCondition(Cond))
423           return;
424         TII->RemoveBranch(*this);
425         TII->InsertBranch(*this, FBB, nullptr, Cond, dl);
426       } else if (isLayoutSuccessor(FBB)) {
427         TII->RemoveBranch(*this);
428         TII->InsertBranch(*this, TBB, nullptr, Cond, dl);
429       }
430     } else {
431       // Walk through the successors and find the successor which is not
432       // a landing pad and is not the conditional branch destination (in TBB)
433       // as the fallthrough successor.
434       MachineBasicBlock *FallthroughBB = nullptr;
435       for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
436         if ((*SI)->isLandingPad() || *SI == TBB)
437           continue;
438         assert(!FallthroughBB && "Found more than one fallthrough successor.");
439         FallthroughBB = *SI;
440       }
441       if (!FallthroughBB && canFallThrough()) {
442         // We fallthrough to the same basic block as the conditional jump
443         // targets. Remove the conditional jump, leaving unconditional
444         // fallthrough.
445         // FIXME: This does not seem like a reasonable pattern to support, but
446         // it has been seen in the wild coming out of degenerate ARM test cases.
447         TII->RemoveBranch(*this);
448
449         // Finally update the unconditional successor to be reached via a branch
450         // if it would not be reached by fallthrough.
451         if (!isLayoutSuccessor(TBB))
452           TII->InsertBranch(*this, TBB, nullptr, Cond, dl);
453         return;
454       }
455
456       // The block has a fallthrough conditional branch.
457       if (isLayoutSuccessor(TBB)) {
458         if (TII->ReverseBranchCondition(Cond)) {
459           // We can't reverse the condition, add an unconditional branch.
460           Cond.clear();
461           TII->InsertBranch(*this, FallthroughBB, nullptr, Cond, dl);
462           return;
463         }
464         TII->RemoveBranch(*this);
465         TII->InsertBranch(*this, FallthroughBB, nullptr, Cond, dl);
466       } else if (!isLayoutSuccessor(FallthroughBB)) {
467         TII->RemoveBranch(*this);
468         TII->InsertBranch(*this, TBB, FallthroughBB, Cond, dl);
469       }
470     }
471   }
472 }
473
474 void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ, uint32_t weight) {
475
476   // If we see non-zero value for the first time it means we actually use Weight
477   // list, so we fill all Weights with 0's.
478   if (weight != 0 && Weights.empty())
479     Weights.resize(Successors.size());
480
481   if (weight != 0 || !Weights.empty())
482     Weights.push_back(weight);
483
484   Successors.push_back(succ);
485   succ->addPredecessor(this);
486 }
487
488 void MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) {
489   succ->removePredecessor(this);
490   succ_iterator I = std::find(Successors.begin(), Successors.end(), succ);
491   assert(I != Successors.end() && "Not a current successor!");
492
493   // If Weight list is empty it means we don't use it (disabled optimization).
494   if (!Weights.empty()) {
495     weight_iterator WI = getWeightIterator(I);
496     Weights.erase(WI);
497   }
498
499   Successors.erase(I);
500 }
501
502 MachineBasicBlock::succ_iterator
503 MachineBasicBlock::removeSuccessor(succ_iterator I) {
504   assert(I != Successors.end() && "Not a current successor!");
505
506   // If Weight list is empty it means we don't use it (disabled optimization).
507   if (!Weights.empty()) {
508     weight_iterator WI = getWeightIterator(I);
509     Weights.erase(WI);
510   }
511
512   (*I)->removePredecessor(this);
513   return Successors.erase(I);
514 }
515
516 void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
517                                          MachineBasicBlock *New) {
518   if (Old == New)
519     return;
520
521   succ_iterator E = succ_end();
522   succ_iterator NewI = E;
523   succ_iterator OldI = E;
524   for (succ_iterator I = succ_begin(); I != E; ++I) {
525     if (*I == Old) {
526       OldI = I;
527       if (NewI != E)
528         break;
529     }
530     if (*I == New) {
531       NewI = I;
532       if (OldI != E)
533         break;
534     }
535   }
536   assert(OldI != E && "Old is not a successor of this block");
537   Old->removePredecessor(this);
538
539   // If New isn't already a successor, let it take Old's place.
540   if (NewI == E) {
541     New->addPredecessor(this);
542     *OldI = New;
543     return;
544   }
545
546   // New is already a successor.
547   // Update its weight instead of adding a duplicate edge.
548   if (!Weights.empty()) {
549     weight_iterator OldWI = getWeightIterator(OldI);
550     *getWeightIterator(NewI) += *OldWI;
551     Weights.erase(OldWI);
552   }
553   Successors.erase(OldI);
554 }
555
556 void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) {
557   Predecessors.push_back(pred);
558 }
559
560 void MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) {
561   pred_iterator I = std::find(Predecessors.begin(), Predecessors.end(), pred);
562   assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
563   Predecessors.erase(I);
564 }
565
566 void MachineBasicBlock::transferSuccessors(MachineBasicBlock *fromMBB) {
567   if (this == fromMBB)
568     return;
569
570   while (!fromMBB->succ_empty()) {
571     MachineBasicBlock *Succ = *fromMBB->succ_begin();
572     uint32_t Weight = 0;
573
574     // If Weight list is empty it means we don't use it (disabled optimization).
575     if (!fromMBB->Weights.empty())
576       Weight = *fromMBB->Weights.begin();
577
578     addSuccessor(Succ, Weight);
579     fromMBB->removeSuccessor(Succ);
580   }
581 }
582
583 void
584 MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *fromMBB) {
585   if (this == fromMBB)
586     return;
587
588   while (!fromMBB->succ_empty()) {
589     MachineBasicBlock *Succ = *fromMBB->succ_begin();
590     uint32_t Weight = 0;
591     if (!fromMBB->Weights.empty())
592       Weight = *fromMBB->Weights.begin();
593     addSuccessor(Succ, Weight);
594     fromMBB->removeSuccessor(Succ);
595
596     // Fix up any PHI nodes in the successor.
597     for (MachineBasicBlock::instr_iterator MI = Succ->instr_begin(),
598            ME = Succ->instr_end(); MI != ME && MI->isPHI(); ++MI)
599       for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) {
600         MachineOperand &MO = MI->getOperand(i);
601         if (MO.getMBB() == fromMBB)
602           MO.setMBB(this);
603       }
604   }
605 }
606
607 bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
608   return std::find(pred_begin(), pred_end(), MBB) != pred_end();
609 }
610
611 bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
612   return std::find(succ_begin(), succ_end(), MBB) != succ_end();
613 }
614
615 bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
616   MachineFunction::const_iterator I(this);
617   return std::next(I) == MachineFunction::const_iterator(MBB);
618 }
619
620 bool MachineBasicBlock::canFallThrough() {
621   MachineFunction::iterator Fallthrough = this;
622   ++Fallthrough;
623   // If FallthroughBlock is off the end of the function, it can't fall through.
624   if (Fallthrough == getParent()->end())
625     return false;
626
627   // If FallthroughBlock isn't a successor, no fallthrough is possible.
628   if (!isSuccessor(Fallthrough))
629     return false;
630
631   // Analyze the branches, if any, at the end of the block.
632   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
633   SmallVector<MachineOperand, 4> Cond;
634   const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
635   if (TII->AnalyzeBranch(*this, TBB, FBB, Cond)) {
636     // If we couldn't analyze the branch, examine the last instruction.
637     // If the block doesn't end in a known control barrier, assume fallthrough
638     // is possible. The isPredicated check is needed because this code can be
639     // called during IfConversion, where an instruction which is normally a
640     // Barrier is predicated and thus no longer an actual control barrier.
641     return empty() || !back().isBarrier() || TII->isPredicated(&back());
642   }
643
644   // If there is no branch, control always falls through.
645   if (!TBB) return true;
646
647   // If there is some explicit branch to the fallthrough block, it can obviously
648   // reach, even though the branch should get folded to fall through implicitly.
649   if (MachineFunction::iterator(TBB) == Fallthrough ||
650       MachineFunction::iterator(FBB) == Fallthrough)
651     return true;
652
653   // If it's an unconditional branch to some block not the fall through, it
654   // doesn't fall through.
655   if (Cond.empty()) return false;
656
657   // Otherwise, if it is conditional and has no explicit false block, it falls
658   // through.
659   return FBB == nullptr;
660 }
661
662 MachineBasicBlock *
663 MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ, Pass *P) {
664   // Splitting the critical edge to a landing pad block is non-trivial. Don't do
665   // it in this generic function.
666   if (Succ->isLandingPad())
667     return nullptr;
668
669   MachineFunction *MF = getParent();
670   DebugLoc dl;  // FIXME: this is nowhere
671
672   // Performance might be harmed on HW that implements branching using exec mask
673   // where both sides of the branches are always executed.
674   if (MF->getTarget().requiresStructuredCFG())
675     return nullptr;
676
677   // We may need to update this's terminator, but we can't do that if
678   // AnalyzeBranch fails. If this uses a jump table, we won't touch it.
679   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
680   MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
681   SmallVector<MachineOperand, 4> Cond;
682   if (TII->AnalyzeBranch(*this, TBB, FBB, Cond))
683     return nullptr;
684
685   // Avoid bugpoint weirdness: A block may end with a conditional branch but
686   // jumps to the same MBB is either case. We have duplicate CFG edges in that
687   // case that we can't handle. Since this never happens in properly optimized
688   // code, just skip those edges.
689   if (TBB && TBB == FBB) {
690     DEBUG(dbgs() << "Won't split critical edge after degenerate BB#"
691                  << getNumber() << '\n');
692     return nullptr;
693   }
694
695   MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
696   MF->insert(std::next(MachineFunction::iterator(this)), NMBB);
697   DEBUG(dbgs() << "Splitting critical edge:"
698         " BB#" << getNumber()
699         << " -- BB#" << NMBB->getNumber()
700         << " -- BB#" << Succ->getNumber() << '\n');
701
702   LiveIntervals *LIS = P->getAnalysisIfAvailable<LiveIntervals>();
703   SlotIndexes *Indexes = P->getAnalysisIfAvailable<SlotIndexes>();
704   if (LIS)
705     LIS->insertMBBInMaps(NMBB);
706   else if (Indexes)
707     Indexes->insertMBBInMaps(NMBB);
708
709   // On some targets like Mips, branches may kill virtual registers. Make sure
710   // that LiveVariables is properly updated after updateTerminator replaces the
711   // terminators.
712   LiveVariables *LV = P->getAnalysisIfAvailable<LiveVariables>();
713
714   // Collect a list of virtual registers killed by the terminators.
715   SmallVector<unsigned, 4> KilledRegs;
716   if (LV)
717     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
718          I != E; ++I) {
719       MachineInstr *MI = I;
720       for (MachineInstr::mop_iterator OI = MI->operands_begin(),
721            OE = MI->operands_end(); OI != OE; ++OI) {
722         if (!OI->isReg() || OI->getReg() == 0 ||
723             !OI->isUse() || !OI->isKill() || OI->isUndef())
724           continue;
725         unsigned Reg = OI->getReg();
726         if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
727             LV->getVarInfo(Reg).removeKill(MI)) {
728           KilledRegs.push_back(Reg);
729           DEBUG(dbgs() << "Removing terminator kill: " << *MI);
730           OI->setIsKill(false);
731         }
732       }
733     }
734
735   SmallVector<unsigned, 4> UsedRegs;
736   if (LIS) {
737     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
738          I != E; ++I) {
739       MachineInstr *MI = I;
740
741       for (MachineInstr::mop_iterator OI = MI->operands_begin(),
742            OE = MI->operands_end(); OI != OE; ++OI) {
743         if (!OI->isReg() || OI->getReg() == 0)
744           continue;
745
746         unsigned Reg = OI->getReg();
747         if (std::find(UsedRegs.begin(), UsedRegs.end(), Reg) == UsedRegs.end())
748           UsedRegs.push_back(Reg);
749       }
750     }
751   }
752
753   ReplaceUsesOfBlockWith(Succ, NMBB);
754
755   // If updateTerminator() removes instructions, we need to remove them from
756   // SlotIndexes.
757   SmallVector<MachineInstr*, 4> Terminators;
758   if (Indexes) {
759     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
760          I != E; ++I)
761       Terminators.push_back(I);
762   }
763
764   updateTerminator();
765
766   if (Indexes) {
767     SmallVector<MachineInstr*, 4> NewTerminators;
768     for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
769          I != E; ++I)
770       NewTerminators.push_back(I);
771
772     for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(),
773         E = Terminators.end(); I != E; ++I) {
774       if (std::find(NewTerminators.begin(), NewTerminators.end(), *I) ==
775           NewTerminators.end())
776        Indexes->removeMachineInstrFromMaps(*I);
777     }
778   }
779
780   // Insert unconditional "jump Succ" instruction in NMBB if necessary.
781   NMBB->addSuccessor(Succ);
782   if (!NMBB->isLayoutSuccessor(Succ)) {
783     Cond.clear();
784     MF->getSubtarget().getInstrInfo()->InsertBranch(*NMBB, Succ, nullptr, Cond,
785                                                     dl);
786
787     if (Indexes) {
788       for (instr_iterator I = NMBB->instr_begin(), E = NMBB->instr_end();
789            I != E; ++I) {
790         // Some instructions may have been moved to NMBB by updateTerminator(),
791         // so we first remove any instruction that already has an index.
792         if (Indexes->hasIndex(I))
793           Indexes->removeMachineInstrFromMaps(I);
794         Indexes->insertMachineInstrInMaps(I);
795       }
796     }
797   }
798
799   // Fix PHI nodes in Succ so they refer to NMBB instead of this
800   for (MachineBasicBlock::instr_iterator
801          i = Succ->instr_begin(),e = Succ->instr_end();
802        i != e && i->isPHI(); ++i)
803     for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
804       if (i->getOperand(ni+1).getMBB() == this)
805         i->getOperand(ni+1).setMBB(NMBB);
806
807   // Inherit live-ins from the successor
808   for (unsigned LI : Succ->liveins())
809     NMBB->addLiveIn(LI);
810
811   // Update LiveVariables.
812   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
813   if (LV) {
814     // Restore kills of virtual registers that were killed by the terminators.
815     while (!KilledRegs.empty()) {
816       unsigned Reg = KilledRegs.pop_back_val();
817       for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
818         if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
819           continue;
820         if (TargetRegisterInfo::isVirtualRegister(Reg))
821           LV->getVarInfo(Reg).Kills.push_back(I);
822         DEBUG(dbgs() << "Restored terminator kill: " << *I);
823         break;
824       }
825     }
826     // Update relevant live-through information.
827     LV->addNewBlock(NMBB, this, Succ);
828   }
829
830   if (LIS) {
831     // After splitting the edge and updating SlotIndexes, live intervals may be
832     // in one of two situations, depending on whether this block was the last in
833     // the function. If the original block was the last in the function, all
834     // live intervals will end prior to the beginning of the new split block. If
835     // the original block was not at the end of the function, all live intervals
836     // will extend to the end of the new split block.
837
838     bool isLastMBB =
839       std::next(MachineFunction::iterator(NMBB)) == getParent()->end();
840
841     SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
842     SlotIndex PrevIndex = StartIndex.getPrevSlot();
843     SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
844
845     // Find the registers used from NMBB in PHIs in Succ.
846     SmallSet<unsigned, 8> PHISrcRegs;
847     for (MachineBasicBlock::instr_iterator
848          I = Succ->instr_begin(), E = Succ->instr_end();
849          I != E && I->isPHI(); ++I) {
850       for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
851         if (I->getOperand(ni+1).getMBB() == NMBB) {
852           MachineOperand &MO = I->getOperand(ni);
853           unsigned Reg = MO.getReg();
854           PHISrcRegs.insert(Reg);
855           if (MO.isUndef())
856             continue;
857
858           LiveInterval &LI = LIS->getInterval(Reg);
859           VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
860           assert(VNI &&
861                  "PHI sources should be live out of their predecessors.");
862           LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
863         }
864       }
865     }
866
867     MachineRegisterInfo *MRI = &getParent()->getRegInfo();
868     for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
869       unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
870       if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
871         continue;
872
873       LiveInterval &LI = LIS->getInterval(Reg);
874       if (!LI.liveAt(PrevIndex))
875         continue;
876
877       bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
878       if (isLiveOut && isLastMBB) {
879         VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
880         assert(VNI && "LiveInterval should have VNInfo where it is live.");
881         LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
882       } else if (!isLiveOut && !isLastMBB) {
883         LI.removeSegment(StartIndex, EndIndex);
884       }
885     }
886
887     // Update all intervals for registers whose uses may have been modified by
888     // updateTerminator().
889     LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
890   }
891
892   if (MachineDominatorTree *MDT =
893       P->getAnalysisIfAvailable<MachineDominatorTree>())
894     MDT->recordSplitCriticalEdge(this, Succ, NMBB);
895
896   if (MachineLoopInfo *MLI = P->getAnalysisIfAvailable<MachineLoopInfo>())
897     if (MachineLoop *TIL = MLI->getLoopFor(this)) {
898       // If one or the other blocks were not in a loop, the new block is not
899       // either, and thus LI doesn't need to be updated.
900       if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
901         if (TIL == DestLoop) {
902           // Both in the same loop, the NMBB joins loop.
903           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
904         } else if (TIL->contains(DestLoop)) {
905           // Edge from an outer loop to an inner loop.  Add to the outer loop.
906           TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
907         } else if (DestLoop->contains(TIL)) {
908           // Edge from an inner loop to an outer loop.  Add to the outer loop.
909           DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
910         } else {
911           // Edge from two loops with no containment relation.  Because these
912           // are natural loops, we know that the destination block must be the
913           // header of its loop (adding a branch into a loop elsewhere would
914           // create an irreducible loop).
915           assert(DestLoop->getHeader() == Succ &&
916                  "Should not create irreducible loops!");
917           if (MachineLoop *P = DestLoop->getParentLoop())
918             P->addBasicBlockToLoop(NMBB, MLI->getBase());
919         }
920       }
921     }
922
923   return NMBB;
924 }
925
926 /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
927 /// neighboring instructions so the bundle won't be broken by removing MI.
928 static void unbundleSingleMI(MachineInstr *MI) {
929   // Removing the first instruction in a bundle.
930   if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
931     MI->unbundleFromSucc();
932   // Removing the last instruction in a bundle.
933   if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
934     MI->unbundleFromPred();
935   // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
936   // are already fine.
937 }
938
939 MachineBasicBlock::instr_iterator
940 MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
941   unbundleSingleMI(I);
942   return Insts.erase(I);
943 }
944
945 MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
946   unbundleSingleMI(MI);
947   MI->clearFlag(MachineInstr::BundledPred);
948   MI->clearFlag(MachineInstr::BundledSucc);
949   return Insts.remove(MI);
950 }
951
952 MachineBasicBlock::instr_iterator
953 MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
954   assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
955          "Cannot insert instruction with bundle flags");
956   // Set the bundle flags when inserting inside a bundle.
957   if (I != instr_end() && I->isBundledWithPred()) {
958     MI->setFlag(MachineInstr::BundledPred);
959     MI->setFlag(MachineInstr::BundledSucc);
960   }
961   return Insts.insert(I, MI);
962 }
963
964 /// This method unlinks 'this' from the containing function, and returns it, but
965 /// does not delete it.
966 MachineBasicBlock *MachineBasicBlock::removeFromParent() {
967   assert(getParent() && "Not embedded in a function!");
968   getParent()->remove(this);
969   return this;
970 }
971
972 /// This method unlinks 'this' from the containing function, and deletes it.
973 void MachineBasicBlock::eraseFromParent() {
974   assert(getParent() && "Not embedded in a function!");
975   getParent()->erase(this);
976 }
977
978 /// Given a machine basic block that branched to 'Old', change the code and CFG
979 /// so that it branches to 'New' instead.
980 void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
981                                                MachineBasicBlock *New) {
982   assert(Old != New && "Cannot replace self with self!");
983
984   MachineBasicBlock::instr_iterator I = instr_end();
985   while (I != instr_begin()) {
986     --I;
987     if (!I->isTerminator()) break;
988
989     // Scan the operands of this machine instruction, replacing any uses of Old
990     // with New.
991     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
992       if (I->getOperand(i).isMBB() &&
993           I->getOperand(i).getMBB() == Old)
994         I->getOperand(i).setMBB(New);
995   }
996
997   // Update the successor information.
998   replaceSuccessor(Old, New);
999 }
1000
1001 /// Various pieces of code can cause excess edges in the CFG to be inserted.  If
1002 /// we have proven that MBB can only branch to DestA and DestB, remove any other
1003 /// MBB successors from the CFG.  DestA and DestB can be null.
1004 ///
1005 /// Besides DestA and DestB, retain other edges leading to LandingPads
1006 /// (currently there can be only one; we don't check or require that here).
1007 /// Note it is possible that DestA and/or DestB are LandingPads.
1008 bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
1009                                              MachineBasicBlock *DestB,
1010                                              bool isCond) {
1011   // The values of DestA and DestB frequently come from a call to the
1012   // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial
1013   // values from there.
1014   //
1015   // 1. If both DestA and DestB are null, then the block ends with no branches
1016   //    (it falls through to its successor).
1017   // 2. If DestA is set, DestB is null, and isCond is false, then the block ends
1018   //    with only an unconditional branch.
1019   // 3. If DestA is set, DestB is null, and isCond is true, then the block ends
1020   //    with a conditional branch that falls through to a successor (DestB).
1021   // 4. If DestA and DestB is set and isCond is true, then the block ends with a
1022   //    conditional branch followed by an unconditional branch. DestA is the
1023   //    'true' destination and DestB is the 'false' destination.
1024
1025   bool Changed = false;
1026
1027   MachineFunction::iterator FallThru =
1028     std::next(MachineFunction::iterator(this));
1029
1030   if (!DestA && !DestB) {
1031     // Block falls through to successor.
1032     DestA = FallThru;
1033     DestB = FallThru;
1034   } else if (DestA && !DestB) {
1035     if (isCond)
1036       // Block ends in conditional jump that falls through to successor.
1037       DestB = FallThru;
1038   } else {
1039     assert(DestA && DestB && isCond &&
1040            "CFG in a bad state. Cannot correct CFG edges");
1041   }
1042
1043   // Remove superfluous edges. I.e., those which aren't destinations of this
1044   // basic block, duplicate edges, or landing pads.
1045   SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs;
1046   MachineBasicBlock::succ_iterator SI = succ_begin();
1047   while (SI != succ_end()) {
1048     const MachineBasicBlock *MBB = *SI;
1049     if (!SeenMBBs.insert(MBB).second ||
1050         (MBB != DestA && MBB != DestB && !MBB->isLandingPad())) {
1051       // This is a superfluous edge, remove it.
1052       SI = removeSuccessor(SI);
1053       Changed = true;
1054     } else {
1055       ++SI;
1056     }
1057   }
1058
1059   return Changed;
1060 }
1061
1062 /// Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE
1063 /// instructions.  Return UnknownLoc if there is none.
1064 DebugLoc
1065 MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
1066   DebugLoc DL;
1067   instr_iterator E = instr_end();
1068   if (MBBI == E)
1069     return DL;
1070
1071   // Skip debug declarations, we don't want a DebugLoc from them.
1072   while (MBBI != E && MBBI->isDebugValue())
1073     MBBI++;
1074   if (MBBI != E)
1075     DL = MBBI->getDebugLoc();
1076   return DL;
1077 }
1078
1079 /// Return weight of the edge from this block to MBB.
1080 uint32_t MachineBasicBlock::getSuccWeight(const_succ_iterator Succ) const {
1081   if (Weights.empty())
1082     return 0;
1083
1084   return *getWeightIterator(Succ);
1085 }
1086
1087 /// Set successor weight of a given iterator.
1088 void MachineBasicBlock::setSuccWeight(succ_iterator I, uint32_t weight) {
1089   if (Weights.empty())
1090     return;
1091   *getWeightIterator(I) = weight;
1092 }
1093
1094 /// Return wight iterator corresonding to the I successor iterator.
1095 MachineBasicBlock::weight_iterator MachineBasicBlock::
1096 getWeightIterator(MachineBasicBlock::succ_iterator I) {
1097   assert(Weights.size() == Successors.size() && "Async weight list!");
1098   size_t index = std::distance(Successors.begin(), I);
1099   assert(index < Weights.size() && "Not a current successor!");
1100   return Weights.begin() + index;
1101 }
1102
1103 /// Return wight iterator corresonding to the I successor iterator.
1104 MachineBasicBlock::const_weight_iterator MachineBasicBlock::
1105 getWeightIterator(MachineBasicBlock::const_succ_iterator I) const {
1106   assert(Weights.size() == Successors.size() && "Async weight list!");
1107   const size_t index = std::distance(Successors.begin(), I);
1108   assert(index < Weights.size() && "Not a current successor!");
1109   return Weights.begin() + index;
1110 }
1111
1112 /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
1113 /// as of just before "MI".
1114 /// 
1115 /// Search is localised to a neighborhood of
1116 /// Neighborhood instructions before (searching for defs or kills) and N
1117 /// instructions after (searching just for defs) MI.
1118 MachineBasicBlock::LivenessQueryResult
1119 MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
1120                                            unsigned Reg, const_iterator Before,
1121                                            unsigned Neighborhood) const {
1122   unsigned N = Neighborhood;
1123
1124   // Start by searching backwards from Before, looking for kills, reads or defs.
1125   const_iterator I(Before);
1126   // If this is the first insn in the block, don't search backwards.
1127   if (I != begin()) {
1128     do {
1129       --I;
1130
1131       MachineOperandIteratorBase::PhysRegInfo Analysis =
1132         ConstMIOperands(I).analyzePhysReg(Reg, TRI);
1133
1134       if (Analysis.Defines)
1135         // Outputs happen after inputs so they take precedence if both are
1136         // present.
1137         return Analysis.DefinesDead ? LQR_Dead : LQR_Live;
1138
1139       if (Analysis.Kills || Analysis.Clobbers)
1140         // Register killed, so isn't live.
1141         return LQR_Dead;
1142
1143       else if (Analysis.ReadsOverlap)
1144         // Defined or read without a previous kill - live.
1145         return Analysis.Reads ? LQR_Live : LQR_OverlappingLive;
1146
1147     } while (I != begin() && --N > 0);
1148   }
1149
1150   // Did we get to the start of the block?
1151   if (I == begin()) {
1152     // If so, the register's state is definitely defined by the live-in state.
1153     for (MCRegAliasIterator RAI(Reg, TRI, /*IncludeSelf=*/true);
1154          RAI.isValid(); ++RAI) {
1155       if (isLiveIn(*RAI))
1156         return (*RAI == Reg) ? LQR_Live : LQR_OverlappingLive;
1157     }
1158
1159     return LQR_Dead;
1160   }
1161
1162   N = Neighborhood;
1163
1164   // Try searching forwards from Before, looking for reads or defs.
1165   I = const_iterator(Before);
1166   // If this is the last insn in the block, don't search forwards.
1167   if (I != end()) {
1168     for (++I; I != end() && N > 0; ++I, --N) {
1169       MachineOperandIteratorBase::PhysRegInfo Analysis =
1170         ConstMIOperands(I).analyzePhysReg(Reg, TRI);
1171
1172       if (Analysis.ReadsOverlap)
1173         // Used, therefore must have been live.
1174         return (Analysis.Reads) ?
1175           LQR_Live : LQR_OverlappingLive;
1176
1177       else if (Analysis.Clobbers || Analysis.Defines)
1178         // Defined (but not read) therefore cannot have been live.
1179         return LQR_Dead;
1180     }
1181   }
1182
1183   // At this point we have no idea of the liveness of the register.
1184   return LQR_Unknown;
1185 }