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 (unsigned LI : make_range(livein_begin(), livein_end())) {
282 OS << ' ' << PrintReg(LI, TRI);
286 // Print the preds of this block according to the CFG.
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();
295 for (const_instr_iterator I = instr_begin(); I != instr_end(); ++I) {
297 if (Indexes->hasIndex(I))
298 OS << Indexes->getInstructionIndex(I);
302 if (I->isInsideBundle())
307 // Print the successors of this block according to the CFG.
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) << ')';
320 void MachineBasicBlock::printAsOperand(raw_ostream &OS,
321 bool /*PrintType*/) const {
322 OS << "BB#" << getNumber();
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())
332 bool MachineBasicBlock::isLiveIn(unsigned Reg) const {
333 livein_iterator I = std::find(livein_begin(), livein_end(), Reg);
334 return I != livein_end();
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");
345 bool LiveIn = isLiveIn(PhysReg);
346 iterator I = SkipPHIsAndLabels(begin()), E = end();
347 MachineRegisterInfo &MRI = getParent()->getRegInfo();
348 const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
350 // Look for an existing copy.
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.");
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);
369 void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
370 getParent()->splice(NewAfter, this);
373 void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
374 MachineFunction::iterator BBI = NewBefore;
375 getParent()->splice(++BBI, this);
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;
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);
388 assert(!B && "UpdateTerminators requires analyzable predecessors!");
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);
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())
402 assert(!TBB && "Found more than one non-landing-pad successor!");
406 // If there is no non-landing-pad successor, the block has no
407 // fall-through edges to be concerned with.
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);
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))
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);
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)
438 assert(!FallthroughBB && "Found more than one fallthrough successor.");
441 if (!FallthroughBB && canFallThrough()) {
442 // We fallthrough to the same basic block as the conditional jump
443 // targets. Remove the conditional jump, leaving unconditional
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);
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);
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.
461 TII->InsertBranch(*this, FallthroughBB, nullptr, Cond, dl);
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);
474 void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ, uint32_t weight) {
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());
481 if (weight != 0 || !Weights.empty())
482 Weights.push_back(weight);
484 Successors.push_back(succ);
485 succ->addPredecessor(this);
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!");
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);
502 MachineBasicBlock::succ_iterator
503 MachineBasicBlock::removeSuccessor(succ_iterator I) {
504 assert(I != Successors.end() && "Not a current successor!");
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);
512 (*I)->removePredecessor(this);
513 return Successors.erase(I);
516 void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
517 MachineBasicBlock *New) {
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) {
536 assert(OldI != E && "Old is not a successor of this block");
537 Old->removePredecessor(this);
539 // If New isn't already a successor, let it take Old's place.
541 New->addPredecessor(this);
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);
553 Successors.erase(OldI);
556 void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) {
557 Predecessors.push_back(pred);
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);
566 void MachineBasicBlock::transferSuccessors(MachineBasicBlock *fromMBB) {
570 while (!fromMBB->succ_empty()) {
571 MachineBasicBlock *Succ = *fromMBB->succ_begin();
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();
578 addSuccessor(Succ, Weight);
579 fromMBB->removeSuccessor(Succ);
584 MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *fromMBB) {
588 while (!fromMBB->succ_empty()) {
589 MachineBasicBlock *Succ = *fromMBB->succ_begin();
591 if (!fromMBB->Weights.empty())
592 Weight = *fromMBB->Weights.begin();
593 addSuccessor(Succ, Weight);
594 fromMBB->removeSuccessor(Succ);
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)
607 bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
608 return std::find(pred_begin(), pred_end(), MBB) != pred_end();
611 bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
612 return std::find(succ_begin(), succ_end(), MBB) != succ_end();
615 bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
616 MachineFunction::const_iterator I(this);
617 return std::next(I) == MachineFunction::const_iterator(MBB);
620 bool MachineBasicBlock::canFallThrough() {
621 MachineFunction::iterator Fallthrough = this;
623 // If FallthroughBlock is off the end of the function, it can't fall through.
624 if (Fallthrough == getParent()->end())
627 // If FallthroughBlock isn't a successor, no fallthrough is possible.
628 if (!isSuccessor(Fallthrough))
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());
644 // If there is no branch, control always falls through.
645 if (!TBB) return true;
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)
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;
657 // Otherwise, if it is conditional and has no explicit false block, it falls
659 return FBB == nullptr;
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())
669 MachineFunction *MF = getParent();
670 DebugLoc dl; // FIXME: this is nowhere
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())
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))
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');
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');
702 LiveIntervals *LIS = P->getAnalysisIfAvailable<LiveIntervals>();
703 SlotIndexes *Indexes = P->getAnalysisIfAvailable<SlotIndexes>();
705 LIS->insertMBBInMaps(NMBB);
707 Indexes->insertMBBInMaps(NMBB);
709 // On some targets like Mips, branches may kill virtual registers. Make sure
710 // that LiveVariables is properly updated after updateTerminator replaces the
712 LiveVariables *LV = P->getAnalysisIfAvailable<LiveVariables>();
714 // Collect a list of virtual registers killed by the terminators.
715 SmallVector<unsigned, 4> KilledRegs;
717 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
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())
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);
735 SmallVector<unsigned, 4> UsedRegs;
737 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
739 MachineInstr *MI = I;
741 for (MachineInstr::mop_iterator OI = MI->operands_begin(),
742 OE = MI->operands_end(); OI != OE; ++OI) {
743 if (!OI->isReg() || OI->getReg() == 0)
746 unsigned Reg = OI->getReg();
747 if (std::find(UsedRegs.begin(), UsedRegs.end(), Reg) == UsedRegs.end())
748 UsedRegs.push_back(Reg);
753 ReplaceUsesOfBlockWith(Succ, NMBB);
755 // If updateTerminator() removes instructions, we need to remove them from
757 SmallVector<MachineInstr*, 4> Terminators;
759 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
761 Terminators.push_back(I);
767 SmallVector<MachineInstr*, 4> NewTerminators;
768 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
770 NewTerminators.push_back(I);
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);
780 // Insert unconditional "jump Succ" instruction in NMBB if necessary.
781 NMBB->addSuccessor(Succ);
782 if (!NMBB->isLayoutSuccessor(Succ)) {
784 MF->getSubtarget().getInstrInfo()->InsertBranch(*NMBB, Succ, nullptr, Cond,
788 for (instr_iterator I = NMBB->instr_begin(), E = NMBB->instr_end();
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);
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);
807 // Inherit live-ins from the successor
808 for (unsigned LI : Succ->liveins())
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.