1 //===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Collect the sequence of machine instructions for a basic block.
12 //===----------------------------------------------------------------------===//
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"
39 #define DEBUG_TYPE "codegen"
41 MachineBasicBlock::MachineBasicBlock(MachineFunction &mf, const BasicBlock *bb)
42 : BB(bb), Number(-1), xParent(&mf), Alignment(0), IsLandingPad(false),
43 AddressTaken(false), CachedMCSymbol(nullptr) {
47 MachineBasicBlock::~MachineBasicBlock() {
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()));
61 return CachedMCSymbol;
65 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
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.
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);
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);
88 void ilist_traits<MachineBasicBlock>::removeNodeFromList(MachineBasicBlock *N) {
89 N->getParent()->removeFromMBBNumbering(N->Number);
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");
99 // Add the instruction's register operands to their corresponding
101 MachineFunction *MF = Parent->getParent();
102 N->AddRegOperandsToUseLists(MF->getRegInfo());
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");
110 // Remove from the use/def lists.
111 if (MachineFunction *MF = N->getParent()->getParent())
112 N->RemoveRegOperandsFromUseLists(MF->getRegInfo());
114 N->setParent(nullptr);
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!");
126 // Splice within the same MBB -> no change.
127 if (Parent == fromList.Parent) return;
129 // If splicing between two blocks within the same function, just update the
131 for (; first != last; ++first)
132 first->setParent(Parent);
135 void ilist_traits<MachineInstr>::deleteNode(MachineInstr* MI) {
136 assert(!MI->getParent() && "MI is still in a block!");
137 Parent->getParent()->DeleteMachineInstr(MI);
140 MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
141 instr_iterator I = instr_begin(), E = instr_end();
142 while (I != E && I->isPHI())
144 assert((I == E || !I->isInsideBundle()) &&
145 "First non-phi MI cannot be inside a bundle!");
149 MachineBasicBlock::iterator
150 MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
152 while (I != E && (I->isPHI() || I->isPosition() || I->isDebugValue()))
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!");
161 MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
162 iterator B = begin(), E = end(), I = E;
163 while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
165 while (I != E && !I->isTerminator())
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()))
174 while (I != E && !I->isTerminator())
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())
187 MachineBasicBlock::iterator MachineBasicBlock::getLastNonDebugInstr() {
188 // Skip over end-of-block dbg_value instructions.
189 instr_iterator B = instr_begin(), I = instr_end();
192 // Return instruction that starts a bundle.
193 if (I->isDebugValue() || I->isInsideBundle())
197 // The block is all debug values.
201 const MachineBasicBlock *MachineBasicBlock::getLandingPadSuccessor() const {
202 // A block with a landing pad successor only has one other successor.
205 for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I)
206 if ((*I)->isLandingPad())
211 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
212 void MachineBasicBlock::dump() const {
217 StringRef MachineBasicBlock::getName() const {
218 if (const BasicBlock *LBB = getBasicBlock())
219 return LBB->getName();
224 /// Return a hopefully unique identifier for this block.
225 std::string MachineBasicBlock::getFullName() const {
228 Name = (getParent()->getName() + ":").str();
230 Name += getBasicBlock()->getName();
232 Name += ("BB" + Twine(getNumber())).str();
236 void MachineBasicBlock::print(raw_ostream &OS, SlotIndexes *Indexes) const {
237 const MachineFunction *MF = getParent();
239 OS << "Can't print out MachineBasicBlock because parent MachineFunction"
243 const Function *F = MF->getFunction();
244 const Module *M = F ? F->getParent() : nullptr;
245 ModuleSlotTracker MST(M);
246 print(OS, MST, Indexes);
249 void MachineBasicBlock::print(raw_ostream &OS, ModuleSlotTracker &MST,
250 SlotIndexes *Indexes) const {
251 const MachineFunction *MF = getParent();
253 OS << "Can't print out MachineBasicBlock because parent MachineFunction"
259 OS << Indexes->getMBBStartIdx(this) << '\t';
261 OS << "BB#" << getNumber() << ": ";
263 const char *Comma = "";
264 if (const BasicBlock *LBB = getBasicBlock()) {
265 OS << Comma << "derived from LLVM BB ";
266 LBB->printAsOperand(OS, /*PrintType=*/false, MST);
269 if (isLandingPad()) { OS << Comma << "EH LANDING PAD"; Comma = ", "; }
270 if (hasAddressTaken()) { OS << Comma << "ADDRESS TAKEN"; Comma = ", "; }
272 OS << Comma << "Align " << Alignment << " (" << (1u << Alignment)
277 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
278 if (!livein_empty()) {
279 if (Indexes) OS << '\t';
281 for (livein_iterator I = livein_begin(),E = livein_end(); I != E; ++I)
282 OS << ' ' << PrintReg(*I, TRI);
285 // Print the preds of this block according to the CFG.
287 if (Indexes) OS << '\t';
288 OS << " Predecessors according to CFG:";
289 for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)
290 OS << " BB#" << (*PI)->getNumber();
294 for (const_instr_iterator I = instr_begin(); I != instr_end(); ++I) {
296 if (Indexes->hasIndex(I))
297 OS << Indexes->getInstructionIndex(I);
301 if (I->isInsideBundle())
306 // Print the successors of this block according to the CFG.
308 if (Indexes) OS << '\t';
309 OS << " Successors according to CFG:";
310 for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI) {
311 OS << " BB#" << (*SI)->getNumber();
312 if (!Weights.empty())
313 OS << '(' << *getWeightIterator(SI) << ')';
319 void MachineBasicBlock::printAsOperand(raw_ostream &OS,
320 bool /*PrintType*/) const {
321 OS << "BB#" << getNumber();
324 void MachineBasicBlock::removeLiveIn(unsigned Reg) {
325 std::vector<unsigned>::iterator I =
326 std::find(LiveIns.begin(), LiveIns.end(), Reg);
327 if (I != LiveIns.end())
331 bool MachineBasicBlock::isLiveIn(unsigned Reg) const {
332 livein_iterator I = std::find(livein_begin(), livein_end(), Reg);
333 return I != livein_end();
337 MachineBasicBlock::addLiveIn(unsigned PhysReg, const TargetRegisterClass *RC) {
338 assert(getParent() && "MBB must be inserted in function");
339 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) && "Expected physreg");
340 assert(RC && "Register class is required");
341 assert((isLandingPad() || this == &getParent()->front()) &&
342 "Only the entry block and landing pads can have physreg live ins");
344 bool LiveIn = isLiveIn(PhysReg);
345 iterator I = SkipPHIsAndLabels(begin()), E = end();
346 MachineRegisterInfo &MRI = getParent()->getRegInfo();
347 const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
349 // Look for an existing copy.
351 for (;I != E && I->isCopy(); ++I)
352 if (I->getOperand(1).getReg() == PhysReg) {
353 unsigned VirtReg = I->getOperand(0).getReg();
354 if (!MRI.constrainRegClass(VirtReg, RC))
355 llvm_unreachable("Incompatible live-in register class.");
359 // No luck, create a virtual register.
360 unsigned VirtReg = MRI.createVirtualRegister(RC);
361 BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
362 .addReg(PhysReg, RegState::Kill);
368 void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
369 getParent()->splice(NewAfter, this);
372 void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
373 MachineFunction::iterator BBI = NewBefore;
374 getParent()->splice(++BBI, this);
377 void MachineBasicBlock::updateTerminator() {
378 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
379 // A block with no successors has no concerns with fall-through edges.
380 if (this->succ_empty()) return;
382 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
383 SmallVector<MachineOperand, 4> Cond;
384 DebugLoc dl; // FIXME: this is nowhere
385 bool B = TII->AnalyzeBranch(*this, TBB, FBB, Cond);
387 assert(!B && "UpdateTerminators requires analyzable predecessors!");
390 // The block has an unconditional branch. If its successor is now
391 // its layout successor, delete the branch.
392 if (isLayoutSuccessor(TBB))
393 TII->RemoveBranch(*this);
395 // The block has an unconditional fallthrough. If its successor is not
396 // its layout successor, insert a branch. First we have to locate the
397 // only non-landing-pad successor, as that is the fallthrough block.
398 for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
399 if ((*SI)->isLandingPad())
401 assert(!TBB && "Found more than one non-landing-pad successor!");
405 // If there is no non-landing-pad successor, the block has no
406 // fall-through edges to be concerned with.
410 // Finally update the unconditional successor to be reached via a branch
411 // if it would not be reached by fallthrough.
412 if (!isLayoutSuccessor(TBB))
413 TII->InsertBranch(*this, TBB, nullptr, Cond, dl);
417 // The block has a non-fallthrough conditional branch. If one of its
418 // successors is its layout successor, rewrite it to a fallthrough
419 // conditional branch.
420 if (isLayoutSuccessor(TBB)) {
421 if (TII->ReverseBranchCondition(Cond))
423 TII->RemoveBranch(*this);
424 TII->InsertBranch(*this, FBB, nullptr, Cond, dl);
425 } else if (isLayoutSuccessor(FBB)) {
426 TII->RemoveBranch(*this);
427 TII->InsertBranch(*this, TBB, nullptr, Cond, dl);
430 // Walk through the successors and find the successor which is not
431 // a landing pad and is not the conditional branch destination (in TBB)
432 // as the fallthrough successor.
433 MachineBasicBlock *FallthroughBB = nullptr;
434 for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
435 if ((*SI)->isLandingPad() || *SI == TBB)
437 assert(!FallthroughBB && "Found more than one fallthrough successor.");
440 if (!FallthroughBB && canFallThrough()) {
441 // We fallthrough to the same basic block as the conditional jump
442 // targets. Remove the conditional jump, leaving unconditional
444 // FIXME: This does not seem like a reasonable pattern to support, but
445 // it has been seen in the wild coming out of degenerate ARM test cases.
446 TII->RemoveBranch(*this);
448 // Finally update the unconditional successor to be reached via a branch
449 // if it would not be reached by fallthrough.
450 if (!isLayoutSuccessor(TBB))
451 TII->InsertBranch(*this, TBB, nullptr, Cond, dl);
455 // The block has a fallthrough conditional branch.
456 if (isLayoutSuccessor(TBB)) {
457 if (TII->ReverseBranchCondition(Cond)) {
458 // We can't reverse the condition, add an unconditional branch.
460 TII->InsertBranch(*this, FallthroughBB, nullptr, Cond, dl);
463 TII->RemoveBranch(*this);
464 TII->InsertBranch(*this, FallthroughBB, nullptr, Cond, dl);
465 } else if (!isLayoutSuccessor(FallthroughBB)) {
466 TII->RemoveBranch(*this);
467 TII->InsertBranch(*this, TBB, FallthroughBB, Cond, dl);
473 void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ, uint32_t weight) {
475 // If we see non-zero value for the first time it means we actually use Weight
476 // list, so we fill all Weights with 0's.
477 if (weight != 0 && Weights.empty())
478 Weights.resize(Successors.size());
480 if (weight != 0 || !Weights.empty())
481 Weights.push_back(weight);
483 Successors.push_back(succ);
484 succ->addPredecessor(this);
487 void MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) {
488 succ->removePredecessor(this);
489 succ_iterator I = std::find(Successors.begin(), Successors.end(), succ);
490 assert(I != Successors.end() && "Not a current successor!");
492 // If Weight list is empty it means we don't use it (disabled optimization).
493 if (!Weights.empty()) {
494 weight_iterator WI = getWeightIterator(I);
501 MachineBasicBlock::succ_iterator
502 MachineBasicBlock::removeSuccessor(succ_iterator I) {
503 assert(I != Successors.end() && "Not a current successor!");
505 // If Weight list is empty it means we don't use it (disabled optimization).
506 if (!Weights.empty()) {
507 weight_iterator WI = getWeightIterator(I);
511 (*I)->removePredecessor(this);
512 return Successors.erase(I);
515 void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
516 MachineBasicBlock *New) {
520 succ_iterator E = succ_end();
521 succ_iterator NewI = E;
522 succ_iterator OldI = E;
523 for (succ_iterator I = succ_begin(); I != E; ++I) {
535 assert(OldI != E && "Old is not a successor of this block");
536 Old->removePredecessor(this);
538 // If New isn't already a successor, let it take Old's place.
540 New->addPredecessor(this);
545 // New is already a successor.
546 // Update its weight instead of adding a duplicate edge.
547 if (!Weights.empty()) {
548 weight_iterator OldWI = getWeightIterator(OldI);
549 *getWeightIterator(NewI) += *OldWI;
550 Weights.erase(OldWI);
552 Successors.erase(OldI);
555 void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) {
556 Predecessors.push_back(pred);
559 void MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) {
560 pred_iterator I = std::find(Predecessors.begin(), Predecessors.end(), pred);
561 assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
562 Predecessors.erase(I);
565 void MachineBasicBlock::transferSuccessors(MachineBasicBlock *fromMBB) {
569 while (!fromMBB->succ_empty()) {
570 MachineBasicBlock *Succ = *fromMBB->succ_begin();
573 // If Weight list is empty it means we don't use it (disabled optimization).
574 if (!fromMBB->Weights.empty())
575 Weight = *fromMBB->Weights.begin();
577 addSuccessor(Succ, Weight);
578 fromMBB->removeSuccessor(Succ);
583 MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *fromMBB) {
587 while (!fromMBB->succ_empty()) {
588 MachineBasicBlock *Succ = *fromMBB->succ_begin();
590 if (!fromMBB->Weights.empty())
591 Weight = *fromMBB->Weights.begin();
592 addSuccessor(Succ, Weight);
593 fromMBB->removeSuccessor(Succ);
595 // Fix up any PHI nodes in the successor.
596 for (MachineBasicBlock::instr_iterator MI = Succ->instr_begin(),
597 ME = Succ->instr_end(); MI != ME && MI->isPHI(); ++MI)
598 for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) {
599 MachineOperand &MO = MI->getOperand(i);
600 if (MO.getMBB() == fromMBB)
606 bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
607 return std::find(pred_begin(), pred_end(), MBB) != pred_end();
610 bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
611 return std::find(succ_begin(), succ_end(), MBB) != succ_end();
614 bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
615 MachineFunction::const_iterator I(this);
616 return std::next(I) == MachineFunction::const_iterator(MBB);
619 bool MachineBasicBlock::canFallThrough() {
620 MachineFunction::iterator Fallthrough = this;
622 // If FallthroughBlock is off the end of the function, it can't fall through.
623 if (Fallthrough == getParent()->end())
626 // If FallthroughBlock isn't a successor, no fallthrough is possible.
627 if (!isSuccessor(Fallthrough))
630 // Analyze the branches, if any, at the end of the block.
631 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
632 SmallVector<MachineOperand, 4> Cond;
633 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
634 if (TII->AnalyzeBranch(*this, TBB, FBB, Cond)) {
635 // If we couldn't analyze the branch, examine the last instruction.
636 // If the block doesn't end in a known control barrier, assume fallthrough
637 // is possible. The isPredicated check is needed because this code can be
638 // called during IfConversion, where an instruction which is normally a
639 // Barrier is predicated and thus no longer an actual control barrier.
640 return empty() || !back().isBarrier() || TII->isPredicated(&back());
643 // If there is no branch, control always falls through.
644 if (!TBB) return true;
646 // If there is some explicit branch to the fallthrough block, it can obviously
647 // reach, even though the branch should get folded to fall through implicitly.
648 if (MachineFunction::iterator(TBB) == Fallthrough ||
649 MachineFunction::iterator(FBB) == Fallthrough)
652 // If it's an unconditional branch to some block not the fall through, it
653 // doesn't fall through.
654 if (Cond.empty()) return false;
656 // Otherwise, if it is conditional and has no explicit false block, it falls
658 return FBB == nullptr;
662 MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ, Pass *P) {
663 // Splitting the critical edge to a landing pad block is non-trivial. Don't do
664 // it in this generic function.
665 if (Succ->isLandingPad())
668 MachineFunction *MF = getParent();
669 DebugLoc dl; // FIXME: this is nowhere
671 // Performance might be harmed on HW that implements branching using exec mask
672 // where both sides of the branches are always executed.
673 if (MF->getTarget().requiresStructuredCFG())
676 // We may need to update this's terminator, but we can't do that if
677 // AnalyzeBranch fails. If this uses a jump table, we won't touch it.
678 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
679 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
680 SmallVector<MachineOperand, 4> Cond;
681 if (TII->AnalyzeBranch(*this, TBB, FBB, Cond))
684 // Avoid bugpoint weirdness: A block may end with a conditional branch but
685 // jumps to the same MBB is either case. We have duplicate CFG edges in that
686 // case that we can't handle. Since this never happens in properly optimized
687 // code, just skip those edges.
688 if (TBB && TBB == FBB) {
689 DEBUG(dbgs() << "Won't split critical edge after degenerate BB#"
690 << getNumber() << '\n');
694 MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
695 MF->insert(std::next(MachineFunction::iterator(this)), NMBB);
696 DEBUG(dbgs() << "Splitting critical edge:"
697 " BB#" << getNumber()
698 << " -- BB#" << NMBB->getNumber()
699 << " -- BB#" << Succ->getNumber() << '\n');
701 LiveIntervals *LIS = P->getAnalysisIfAvailable<LiveIntervals>();
702 SlotIndexes *Indexes = P->getAnalysisIfAvailable<SlotIndexes>();
704 LIS->insertMBBInMaps(NMBB);
706 Indexes->insertMBBInMaps(NMBB);
708 // On some targets like Mips, branches may kill virtual registers. Make sure
709 // that LiveVariables is properly updated after updateTerminator replaces the
711 LiveVariables *LV = P->getAnalysisIfAvailable<LiveVariables>();
713 // Collect a list of virtual registers killed by the terminators.
714 SmallVector<unsigned, 4> KilledRegs;
716 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
718 MachineInstr *MI = I;
719 for (MachineInstr::mop_iterator OI = MI->operands_begin(),
720 OE = MI->operands_end(); OI != OE; ++OI) {
721 if (!OI->isReg() || OI->getReg() == 0 ||
722 !OI->isUse() || !OI->isKill() || OI->isUndef())
724 unsigned Reg = OI->getReg();
725 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
726 LV->getVarInfo(Reg).removeKill(MI)) {
727 KilledRegs.push_back(Reg);
728 DEBUG(dbgs() << "Removing terminator kill: " << *MI);
729 OI->setIsKill(false);
734 SmallVector<unsigned, 4> UsedRegs;
736 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
738 MachineInstr *MI = I;
740 for (MachineInstr::mop_iterator OI = MI->operands_begin(),
741 OE = MI->operands_end(); OI != OE; ++OI) {
742 if (!OI->isReg() || OI->getReg() == 0)
745 unsigned Reg = OI->getReg();
746 if (std::find(UsedRegs.begin(), UsedRegs.end(), Reg) == UsedRegs.end())
747 UsedRegs.push_back(Reg);
752 ReplaceUsesOfBlockWith(Succ, NMBB);
754 // If updateTerminator() removes instructions, we need to remove them from
756 SmallVector<MachineInstr*, 4> Terminators;
758 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
760 Terminators.push_back(I);
766 SmallVector<MachineInstr*, 4> NewTerminators;
767 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
769 NewTerminators.push_back(I);
771 for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(),
772 E = Terminators.end(); I != E; ++I) {
773 if (std::find(NewTerminators.begin(), NewTerminators.end(), *I) ==
774 NewTerminators.end())
775 Indexes->removeMachineInstrFromMaps(*I);
779 // Insert unconditional "jump Succ" instruction in NMBB if necessary.
780 NMBB->addSuccessor(Succ);
781 if (!NMBB->isLayoutSuccessor(Succ)) {
783 MF->getSubtarget().getInstrInfo()->InsertBranch(*NMBB, Succ, nullptr, Cond,
787 for (instr_iterator I = NMBB->instr_begin(), E = NMBB->instr_end();
789 // Some instructions may have been moved to NMBB by updateTerminator(),
790 // so we first remove any instruction that already has an index.
791 if (Indexes->hasIndex(I))
792 Indexes->removeMachineInstrFromMaps(I);
793 Indexes->insertMachineInstrInMaps(I);
798 // Fix PHI nodes in Succ so they refer to NMBB instead of this
799 for (MachineBasicBlock::instr_iterator
800 i = Succ->instr_begin(),e = Succ->instr_end();
801 i != e && i->isPHI(); ++i)
802 for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
803 if (i->getOperand(ni+1).getMBB() == this)
804 i->getOperand(ni+1).setMBB(NMBB);
806 // Inherit live-ins from the successor
807 for (MachineBasicBlock::livein_iterator I = Succ->livein_begin(),
808 E = Succ->livein_end(); I != E; ++I)
811 // Update LiveVariables.
812 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
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))
820 if (TargetRegisterInfo::isVirtualRegister(Reg))
821 LV->getVarInfo(Reg).Kills.push_back(I);
822 DEBUG(dbgs() << "Restored terminator kill: " << *I);
826 // Update relevant live-through information.
827 LV->addNewBlock(NMBB, this, Succ);
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.
839 std::next(MachineFunction::iterator(NMBB)) == getParent()->end();
841 SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
842 SlotIndex PrevIndex = StartIndex.getPrevSlot();
843 SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
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);
858 LiveInterval &LI = LIS->getInterval(Reg);
859 VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
861 "PHI sources should be live out of their predecessors.");
862 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
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))
873 LiveInterval &LI = LIS->getInterval(Reg);
874 if (!LI.liveAt(PrevIndex))
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);
887 // Update all intervals for registers whose uses may have been modified by
888 // updateTerminator().
889 LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
892 if (MachineDominatorTree *MDT =
893 P->getAnalysisIfAvailable<MachineDominatorTree>())
894 MDT->recordSplitCriticalEdge(this, Succ, NMBB);
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());
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());
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
939 MachineBasicBlock::instr_iterator
940 MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
942 return Insts.erase(I);
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);
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);
961 return Insts.insert(I, MI);
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);
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);
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!");
984 MachineBasicBlock::instr_iterator I = instr_end();
985 while (I != instr_begin()) {
987 if (!I->isTerminator()) break;
989 // Scan the operands of this machine instruction, replacing any uses of Old
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);
997 // Update the successor information.
998 replaceSuccessor(Old, New);
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.
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,
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.
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.
1025 bool Changed = false;
1027 MachineFunction::iterator FallThru =
1028 std::next(MachineFunction::iterator(this));
1030 if (!DestA && !DestB) {
1031 // Block falls through to successor.
1034 } else if (DestA && !DestB) {
1036 // Block ends in conditional jump that falls through to successor.
1039 assert(DestA && DestB && isCond &&
1040 "CFG in a bad state. Cannot correct CFG edges");
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);
1062 /// Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE
1063 /// instructions. Return UnknownLoc if there is none.
1065 MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
1067 instr_iterator E = instr_end();
1071 // Skip debug declarations, we don't want a DebugLoc from them.
1072 while (MBBI != E && MBBI->isDebugValue())
1075 DL = MBBI->getDebugLoc();
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())
1084 return *getWeightIterator(Succ);
1087 /// Set successor weight of a given iterator.
1088 void MachineBasicBlock::setSuccWeight(succ_iterator I, uint32_t weight) {
1089 if (Weights.empty())
1091 *getWeightIterator(I) = weight;
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;
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;
1112 /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
1113 /// as of just before "MI".
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;
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.
1131 MachineOperandIteratorBase::PhysRegInfo Analysis =
1132 ConstMIOperands(I).analyzePhysReg(Reg, TRI);
1134 if (Analysis.Defines)
1135 // Outputs happen after inputs so they take precedence if both are
1137 return Analysis.DefinesDead ? LQR_Dead : LQR_Live;
1139 if (Analysis.Kills || Analysis.Clobbers)
1140 // Register killed, so isn't live.
1143 else if (Analysis.ReadsOverlap)
1144 // Defined or read without a previous kill - live.
1145 return Analysis.Reads ? LQR_Live : LQR_OverlappingLive;
1147 } while (I != begin() && --N > 0);
1150 // Did we get to the start of the block?
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) {
1156 return (*RAI == Reg) ? LQR_Live : LQR_OverlappingLive;
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.
1168 for (++I; I != end() && N > 0; ++I, --N) {
1169 MachineOperandIteratorBase::PhysRegInfo Analysis =
1170 ConstMIOperands(I).analyzePhysReg(Reg, TRI);
1172 if (Analysis.ReadsOverlap)
1173 // Used, therefore must have been live.
1174 return (Analysis.Reads) ?
1175 LQR_Live : LQR_OverlappingLive;
1177 else if (Analysis.Clobbers || Analysis.Defines)
1178 // Defined (but not read) therefore cannot have been live.
1183 // At this point we have no idea of the liveness of the register.