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/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Target/TargetRegisterInfo.h"
34 #include "llvm/Target/TargetSubtargetInfo.h"
38 #define DEBUG_TYPE "codegen"
40 MachineBasicBlock::MachineBasicBlock(MachineFunction &mf, const BasicBlock *bb)
41 : BB(bb), Number(-1), xParent(&mf), Alignment(0), IsLandingPad(false),
42 AddressTaken(false), CachedMCSymbol(nullptr) {
46 MachineBasicBlock::~MachineBasicBlock() {
49 /// getSymbol - 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 /// addNodeToList (MBB) - When an MBB is added to an MF, we need to update the
71 /// parent pointer of the MBB, the MBB numbering, and any instructions in the
72 /// MBB to be on the right 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);
94 /// addNodeToList (MI) - When we add an instruction to a basic block
95 /// list, we update its parent pointer and add its operands from reg use/def
96 /// lists if appropriate.
97 void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
98 assert(!N->getParent() && "machine instruction already in a basic block");
101 // Add the instruction's register operands to their corresponding
103 MachineFunction *MF = Parent->getParent();
104 N->AddRegOperandsToUseLists(MF->getRegInfo());
107 /// removeNodeFromList (MI) - When we remove an instruction from a basic block
108 /// list, we update its parent pointer and remove its operands from reg use/def
109 /// lists if appropriate.
110 void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) {
111 assert(N->getParent() && "machine instruction not in a basic block");
113 // Remove from the use/def lists.
114 if (MachineFunction *MF = N->getParent()->getParent())
115 N->RemoveRegOperandsFromUseLists(MF->getRegInfo());
117 N->setParent(nullptr);
120 /// transferNodesFromList (MI) - When moving a range of instructions from one
121 /// MBB list to another, we need to update the parent pointers and the use/def
123 void ilist_traits<MachineInstr>::
124 transferNodesFromList(ilist_traits<MachineInstr> &fromList,
125 ilist_iterator<MachineInstr> first,
126 ilist_iterator<MachineInstr> last) {
127 assert(Parent->getParent() == fromList.Parent->getParent() &&
128 "MachineInstr parent mismatch!");
130 // Splice within the same MBB -> no change.
131 if (Parent == fromList.Parent) return;
133 // If splicing between two blocks within the same function, just update the
135 for (; first != last; ++first)
136 first->setParent(Parent);
139 void ilist_traits<MachineInstr>::deleteNode(MachineInstr* MI) {
140 assert(!MI->getParent() && "MI is still in a block!");
141 Parent->getParent()->DeleteMachineInstr(MI);
144 MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
145 instr_iterator I = instr_begin(), E = instr_end();
146 while (I != E && I->isPHI())
148 assert((I == E || !I->isInsideBundle()) &&
149 "First non-phi MI cannot be inside a bundle!");
153 MachineBasicBlock::iterator
154 MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
156 while (I != E && (I->isPHI() || I->isPosition() || I->isDebugValue()))
158 // FIXME: This needs to change if we wish to bundle labels / dbg_values
159 // inside the bundle.
160 assert((I == E || !I->isInsideBundle()) &&
161 "First non-phi / non-label instruction is inside a bundle!");
165 MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
166 iterator B = begin(), E = end(), I = E;
167 while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
169 while (I != E && !I->isTerminator())
174 MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() {
175 instr_iterator B = instr_begin(), E = instr_end(), I = E;
176 while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
178 while (I != E && !I->isTerminator())
183 MachineBasicBlock::iterator MachineBasicBlock::getLastNonDebugInstr() {
184 // Skip over end-of-block dbg_value instructions.
185 instr_iterator B = instr_begin(), I = instr_end();
188 // Return instruction that starts a bundle.
189 if (I->isDebugValue() || I->isInsideBundle())
193 // The block is all debug values.
197 const MachineBasicBlock *MachineBasicBlock::getLandingPadSuccessor() const {
198 // A block with a landing pad successor only has one other successor.
201 for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I)
202 if ((*I)->isLandingPad())
207 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
208 void MachineBasicBlock::dump() const {
213 StringRef MachineBasicBlock::getName() const {
214 if (const BasicBlock *LBB = getBasicBlock())
215 return LBB->getName();
220 /// Return a hopefully unique identifier for this block.
221 std::string MachineBasicBlock::getFullName() const {
224 Name = (getParent()->getName() + ":").str();
226 Name += getBasicBlock()->getName();
228 Name += ("BB" + Twine(getNumber())).str();
232 void MachineBasicBlock::print(raw_ostream &OS, SlotIndexes *Indexes) const {
233 const MachineFunction *MF = getParent();
235 OS << "Can't print out MachineBasicBlock because parent MachineFunction"
241 OS << Indexes->getMBBStartIdx(this) << '\t';
243 OS << "BB#" << getNumber() << ": ";
245 const char *Comma = "";
246 if (const BasicBlock *LBB = getBasicBlock()) {
247 OS << Comma << "derived from LLVM BB ";
248 LBB->printAsOperand(OS, /*PrintType=*/false);
251 if (isLandingPad()) { OS << Comma << "EH LANDING PAD"; Comma = ", "; }
252 if (hasAddressTaken()) { OS << Comma << "ADDRESS TAKEN"; Comma = ", "; }
254 OS << Comma << "Align " << Alignment << " (" << (1u << Alignment)
259 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
260 if (!livein_empty()) {
261 if (Indexes) OS << '\t';
263 for (livein_iterator I = livein_begin(),E = livein_end(); I != E; ++I)
264 OS << ' ' << PrintReg(*I, TRI);
267 // Print the preds of this block according to the CFG.
269 if (Indexes) OS << '\t';
270 OS << " Predecessors according to CFG:";
271 for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)
272 OS << " BB#" << (*PI)->getNumber();
276 for (const_instr_iterator I = instr_begin(); I != instr_end(); ++I) {
278 if (Indexes->hasIndex(I))
279 OS << Indexes->getInstructionIndex(I);
283 if (I->isInsideBundle())
288 // Print the successors of this block according to the CFG.
290 if (Indexes) OS << '\t';
291 OS << " Successors according to CFG:";
292 for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI) {
293 OS << " BB#" << (*SI)->getNumber();
294 if (!Weights.empty())
295 OS << '(' << *getWeightIterator(SI) << ')';
301 void MachineBasicBlock::printAsOperand(raw_ostream &OS, bool /*PrintType*/) const {
302 OS << "BB#" << getNumber();
305 void MachineBasicBlock::removeLiveIn(unsigned Reg) {
306 std::vector<unsigned>::iterator I =
307 std::find(LiveIns.begin(), LiveIns.end(), Reg);
308 if (I != LiveIns.end())
312 bool MachineBasicBlock::isLiveIn(unsigned Reg) const {
313 livein_iterator I = std::find(livein_begin(), livein_end(), Reg);
314 return I != livein_end();
318 MachineBasicBlock::addLiveIn(unsigned PhysReg, const TargetRegisterClass *RC) {
319 assert(getParent() && "MBB must be inserted in function");
320 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) && "Expected physreg");
321 assert(RC && "Register class is required");
322 assert((isLandingPad() || this == &getParent()->front()) &&
323 "Only the entry block and landing pads can have physreg live ins");
325 bool LiveIn = isLiveIn(PhysReg);
326 iterator I = SkipPHIsAndLabels(begin()), E = end();
327 MachineRegisterInfo &MRI = getParent()->getRegInfo();
328 const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
330 // Look for an existing copy.
332 for (;I != E && I->isCopy(); ++I)
333 if (I->getOperand(1).getReg() == PhysReg) {
334 unsigned VirtReg = I->getOperand(0).getReg();
335 if (!MRI.constrainRegClass(VirtReg, RC))
336 llvm_unreachable("Incompatible live-in register class.");
340 // No luck, create a virtual register.
341 unsigned VirtReg = MRI.createVirtualRegister(RC);
342 BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
343 .addReg(PhysReg, RegState::Kill);
349 void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
350 getParent()->splice(NewAfter, this);
353 void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
354 MachineFunction::iterator BBI = NewBefore;
355 getParent()->splice(++BBI, this);
358 void MachineBasicBlock::updateTerminator() {
359 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
360 // A block with no successors has no concerns with fall-through edges.
361 if (this->succ_empty()) return;
363 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
364 SmallVector<MachineOperand, 4> Cond;
365 DebugLoc dl; // FIXME: this is nowhere
366 bool B = TII->AnalyzeBranch(*this, TBB, FBB, Cond);
368 assert(!B && "UpdateTerminators requires analyzable predecessors!");
371 // The block has an unconditional branch. If its successor is now
372 // its layout successor, delete the branch.
373 if (isLayoutSuccessor(TBB))
374 TII->RemoveBranch(*this);
376 // The block has an unconditional fallthrough. If its successor is not
377 // its layout successor, insert a branch. First we have to locate the
378 // only non-landing-pad successor, as that is the fallthrough block.
379 for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
380 if ((*SI)->isLandingPad())
382 assert(!TBB && "Found more than one non-landing-pad successor!");
386 // If there is no non-landing-pad successor, the block has no
387 // fall-through edges to be concerned with.
391 // Finally update the unconditional successor to be reached via a branch
392 // if it would not be reached by fallthrough.
393 if (!isLayoutSuccessor(TBB))
394 TII->InsertBranch(*this, TBB, nullptr, Cond, dl);
398 // The block has a non-fallthrough conditional branch. If one of its
399 // successors is its layout successor, rewrite it to a fallthrough
400 // conditional branch.
401 if (isLayoutSuccessor(TBB)) {
402 if (TII->ReverseBranchCondition(Cond))
404 TII->RemoveBranch(*this);
405 TII->InsertBranch(*this, FBB, nullptr, Cond, dl);
406 } else if (isLayoutSuccessor(FBB)) {
407 TII->RemoveBranch(*this);
408 TII->InsertBranch(*this, TBB, nullptr, Cond, dl);
411 // Walk through the successors and find the successor which is not
412 // a landing pad and is not the conditional branch destination (in TBB)
413 // as the fallthrough successor.
414 MachineBasicBlock *FallthroughBB = nullptr;
415 for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
416 if ((*SI)->isLandingPad() || *SI == TBB)
418 assert(!FallthroughBB && "Found more than one fallthrough successor.");
421 if (!FallthroughBB && canFallThrough()) {
422 // We fallthrough to the same basic block as the conditional jump
423 // targets. Remove the conditional jump, leaving unconditional
425 // FIXME: This does not seem like a reasonable pattern to support, but it
426 // has been seen in the wild coming out of degenerate ARM test cases.
427 TII->RemoveBranch(*this);
429 // Finally update the unconditional successor to be reached via a branch
430 // if it would not be reached by fallthrough.
431 if (!isLayoutSuccessor(TBB))
432 TII->InsertBranch(*this, TBB, nullptr, Cond, dl);
436 // The block has a fallthrough conditional branch.
437 if (isLayoutSuccessor(TBB)) {
438 if (TII->ReverseBranchCondition(Cond)) {
439 // We can't reverse the condition, add an unconditional branch.
441 TII->InsertBranch(*this, FallthroughBB, nullptr, Cond, dl);
444 TII->RemoveBranch(*this);
445 TII->InsertBranch(*this, FallthroughBB, nullptr, Cond, dl);
446 } else if (!isLayoutSuccessor(FallthroughBB)) {
447 TII->RemoveBranch(*this);
448 TII->InsertBranch(*this, TBB, FallthroughBB, Cond, dl);
454 void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ, uint32_t weight) {
456 // If we see non-zero value for the first time it means we actually use Weight
457 // list, so we fill all Weights with 0's.
458 if (weight != 0 && Weights.empty())
459 Weights.resize(Successors.size());
461 if (weight != 0 || !Weights.empty())
462 Weights.push_back(weight);
464 Successors.push_back(succ);
465 succ->addPredecessor(this);
468 void MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) {
469 succ->removePredecessor(this);
470 succ_iterator I = std::find(Successors.begin(), Successors.end(), succ);
471 assert(I != Successors.end() && "Not a current successor!");
473 // If Weight list is empty it means we don't use it (disabled optimization).
474 if (!Weights.empty()) {
475 weight_iterator WI = getWeightIterator(I);
482 MachineBasicBlock::succ_iterator
483 MachineBasicBlock::removeSuccessor(succ_iterator I) {
484 assert(I != Successors.end() && "Not a current successor!");
486 // If Weight list is empty it means we don't use it (disabled optimization).
487 if (!Weights.empty()) {
488 weight_iterator WI = getWeightIterator(I);
492 (*I)->removePredecessor(this);
493 return Successors.erase(I);
496 void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
497 MachineBasicBlock *New) {
501 succ_iterator E = succ_end();
502 succ_iterator NewI = E;
503 succ_iterator OldI = E;
504 for (succ_iterator I = succ_begin(); I != E; ++I) {
516 assert(OldI != E && "Old is not a successor of this block");
517 Old->removePredecessor(this);
519 // If New isn't already a successor, let it take Old's place.
521 New->addPredecessor(this);
526 // New is already a successor.
527 // Update its weight instead of adding a duplicate edge.
528 if (!Weights.empty()) {
529 weight_iterator OldWI = getWeightIterator(OldI);
530 *getWeightIterator(NewI) += *OldWI;
531 Weights.erase(OldWI);
533 Successors.erase(OldI);
536 void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) {
537 Predecessors.push_back(pred);
540 void MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) {
541 pred_iterator I = std::find(Predecessors.begin(), Predecessors.end(), pred);
542 assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
543 Predecessors.erase(I);
546 void MachineBasicBlock::transferSuccessors(MachineBasicBlock *fromMBB) {
550 while (!fromMBB->succ_empty()) {
551 MachineBasicBlock *Succ = *fromMBB->succ_begin();
554 // If Weight list is empty it means we don't use it (disabled optimization).
555 if (!fromMBB->Weights.empty())
556 Weight = *fromMBB->Weights.begin();
558 addSuccessor(Succ, Weight);
559 fromMBB->removeSuccessor(Succ);
564 MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *fromMBB) {
568 while (!fromMBB->succ_empty()) {
569 MachineBasicBlock *Succ = *fromMBB->succ_begin();
571 if (!fromMBB->Weights.empty())
572 Weight = *fromMBB->Weights.begin();
573 addSuccessor(Succ, Weight);
574 fromMBB->removeSuccessor(Succ);
576 // Fix up any PHI nodes in the successor.
577 for (MachineBasicBlock::instr_iterator MI = Succ->instr_begin(),
578 ME = Succ->instr_end(); MI != ME && MI->isPHI(); ++MI)
579 for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) {
580 MachineOperand &MO = MI->getOperand(i);
581 if (MO.getMBB() == fromMBB)
587 bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
588 return std::find(pred_begin(), pred_end(), MBB) != pred_end();
591 bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
592 return std::find(succ_begin(), succ_end(), MBB) != succ_end();
595 bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
596 MachineFunction::const_iterator I(this);
597 return std::next(I) == MachineFunction::const_iterator(MBB);
600 bool MachineBasicBlock::canFallThrough() {
601 MachineFunction::iterator Fallthrough = this;
603 // If FallthroughBlock is off the end of the function, it can't fall through.
604 if (Fallthrough == getParent()->end())
607 // If FallthroughBlock isn't a successor, no fallthrough is possible.
608 if (!isSuccessor(Fallthrough))
611 // Analyze the branches, if any, at the end of the block.
612 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
613 SmallVector<MachineOperand, 4> Cond;
614 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
615 if (TII->AnalyzeBranch(*this, TBB, FBB, Cond)) {
616 // If we couldn't analyze the branch, examine the last instruction.
617 // If the block doesn't end in a known control barrier, assume fallthrough
618 // is possible. The isPredicated check is needed because this code can be
619 // called during IfConversion, where an instruction which is normally a
620 // Barrier is predicated and thus no longer an actual control barrier.
621 return empty() || !back().isBarrier() || TII->isPredicated(&back());
624 // If there is no branch, control always falls through.
625 if (!TBB) return true;
627 // If there is some explicit branch to the fallthrough block, it can obviously
628 // reach, even though the branch should get folded to fall through implicitly.
629 if (MachineFunction::iterator(TBB) == Fallthrough ||
630 MachineFunction::iterator(FBB) == Fallthrough)
633 // If it's an unconditional branch to some block not the fall through, it
634 // doesn't fall through.
635 if (Cond.empty()) return false;
637 // Otherwise, if it is conditional and has no explicit false block, it falls
639 return FBB == nullptr;
643 MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ, Pass *P) {
644 // Splitting the critical edge to a landing pad block is non-trivial. Don't do
645 // it in this generic function.
646 if (Succ->isLandingPad())
649 MachineFunction *MF = getParent();
650 DebugLoc dl; // FIXME: this is nowhere
652 // Performance might be harmed on HW that implements branching using exec mask
653 // where both sides of the branches are always executed.
654 if (MF->getTarget().requiresStructuredCFG())
657 // We may need to update this's terminator, but we can't do that if
658 // AnalyzeBranch fails. If this uses a jump table, we won't touch it.
659 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
660 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
661 SmallVector<MachineOperand, 4> Cond;
662 if (TII->AnalyzeBranch(*this, TBB, FBB, Cond))
665 // Avoid bugpoint weirdness: A block may end with a conditional branch but
666 // jumps to the same MBB is either case. We have duplicate CFG edges in that
667 // case that we can't handle. Since this never happens in properly optimized
668 // code, just skip those edges.
669 if (TBB && TBB == FBB) {
670 DEBUG(dbgs() << "Won't split critical edge after degenerate BB#"
671 << getNumber() << '\n');
675 MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
676 MF->insert(std::next(MachineFunction::iterator(this)), NMBB);
677 DEBUG(dbgs() << "Splitting critical edge:"
678 " BB#" << getNumber()
679 << " -- BB#" << NMBB->getNumber()
680 << " -- BB#" << Succ->getNumber() << '\n');
682 LiveIntervals *LIS = P->getAnalysisIfAvailable<LiveIntervals>();
683 SlotIndexes *Indexes = P->getAnalysisIfAvailable<SlotIndexes>();
685 LIS->insertMBBInMaps(NMBB);
687 Indexes->insertMBBInMaps(NMBB);
689 // On some targets like Mips, branches may kill virtual registers. Make sure
690 // that LiveVariables is properly updated after updateTerminator replaces the
692 LiveVariables *LV = P->getAnalysisIfAvailable<LiveVariables>();
694 // Collect a list of virtual registers killed by the terminators.
695 SmallVector<unsigned, 4> KilledRegs;
697 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
699 MachineInstr *MI = I;
700 for (MachineInstr::mop_iterator OI = MI->operands_begin(),
701 OE = MI->operands_end(); OI != OE; ++OI) {
702 if (!OI->isReg() || OI->getReg() == 0 ||
703 !OI->isUse() || !OI->isKill() || OI->isUndef())
705 unsigned Reg = OI->getReg();
706 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
707 LV->getVarInfo(Reg).removeKill(MI)) {
708 KilledRegs.push_back(Reg);
709 DEBUG(dbgs() << "Removing terminator kill: " << *MI);
710 OI->setIsKill(false);
715 SmallVector<unsigned, 4> UsedRegs;
717 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
719 MachineInstr *MI = I;
721 for (MachineInstr::mop_iterator OI = MI->operands_begin(),
722 OE = MI->operands_end(); OI != OE; ++OI) {
723 if (!OI->isReg() || OI->getReg() == 0)
726 unsigned Reg = OI->getReg();
727 if (std::find(UsedRegs.begin(), UsedRegs.end(), Reg) == UsedRegs.end())
728 UsedRegs.push_back(Reg);
733 ReplaceUsesOfBlockWith(Succ, NMBB);
735 // If updateTerminator() removes instructions, we need to remove them from
737 SmallVector<MachineInstr*, 4> Terminators;
739 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
741 Terminators.push_back(I);
747 SmallVector<MachineInstr*, 4> NewTerminators;
748 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
750 NewTerminators.push_back(I);
752 for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(),
753 E = Terminators.end(); I != E; ++I) {
754 if (std::find(NewTerminators.begin(), NewTerminators.end(), *I) ==
755 NewTerminators.end())
756 Indexes->removeMachineInstrFromMaps(*I);
760 // Insert unconditional "jump Succ" instruction in NMBB if necessary.
761 NMBB->addSuccessor(Succ);
762 if (!NMBB->isLayoutSuccessor(Succ)) {
764 MF->getSubtarget().getInstrInfo()->InsertBranch(*NMBB, Succ, nullptr, Cond,
768 for (instr_iterator I = NMBB->instr_begin(), E = NMBB->instr_end();
770 // Some instructions may have been moved to NMBB by updateTerminator(),
771 // so we first remove any instruction that already has an index.
772 if (Indexes->hasIndex(I))
773 Indexes->removeMachineInstrFromMaps(I);
774 Indexes->insertMachineInstrInMaps(I);
779 // Fix PHI nodes in Succ so they refer to NMBB instead of this
780 for (MachineBasicBlock::instr_iterator
781 i = Succ->instr_begin(),e = Succ->instr_end();
782 i != e && i->isPHI(); ++i)
783 for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
784 if (i->getOperand(ni+1).getMBB() == this)
785 i->getOperand(ni+1).setMBB(NMBB);
787 // Inherit live-ins from the successor
788 for (MachineBasicBlock::livein_iterator I = Succ->livein_begin(),
789 E = Succ->livein_end(); I != E; ++I)
792 // Update LiveVariables.
793 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
795 // Restore kills of virtual registers that were killed by the terminators.
796 while (!KilledRegs.empty()) {
797 unsigned Reg = KilledRegs.pop_back_val();
798 for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
799 if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
801 if (TargetRegisterInfo::isVirtualRegister(Reg))
802 LV->getVarInfo(Reg).Kills.push_back(I);
803 DEBUG(dbgs() << "Restored terminator kill: " << *I);
807 // Update relevant live-through information.
808 LV->addNewBlock(NMBB, this, Succ);
812 // After splitting the edge and updating SlotIndexes, live intervals may be
813 // in one of two situations, depending on whether this block was the last in
814 // the function. If the original block was the last in the function, all live
815 // intervals will end prior to the beginning of the new split block. If the
816 // original block was not at the end of the function, all live intervals will
817 // extend to the end of the new split block.
820 std::next(MachineFunction::iterator(NMBB)) == getParent()->end();
822 SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
823 SlotIndex PrevIndex = StartIndex.getPrevSlot();
824 SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
826 // Find the registers used from NMBB in PHIs in Succ.
827 SmallSet<unsigned, 8> PHISrcRegs;
828 for (MachineBasicBlock::instr_iterator
829 I = Succ->instr_begin(), E = Succ->instr_end();
830 I != E && I->isPHI(); ++I) {
831 for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
832 if (I->getOperand(ni+1).getMBB() == NMBB) {
833 MachineOperand &MO = I->getOperand(ni);
834 unsigned Reg = MO.getReg();
835 PHISrcRegs.insert(Reg);
839 LiveInterval &LI = LIS->getInterval(Reg);
840 VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
841 assert(VNI && "PHI sources should be live out of their predecessors.");
842 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
847 MachineRegisterInfo *MRI = &getParent()->getRegInfo();
848 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
849 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
850 if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
853 LiveInterval &LI = LIS->getInterval(Reg);
854 if (!LI.liveAt(PrevIndex))
857 bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
858 if (isLiveOut && isLastMBB) {
859 VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
860 assert(VNI && "LiveInterval should have VNInfo where it is live.");
861 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
862 } else if (!isLiveOut && !isLastMBB) {
863 LI.removeSegment(StartIndex, EndIndex);
867 // Update all intervals for registers whose uses may have been modified by
868 // updateTerminator().
869 LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
872 if (MachineDominatorTree *MDT =
873 P->getAnalysisIfAvailable<MachineDominatorTree>())
874 MDT->recordSplitCriticalEdge(this, Succ, NMBB);
876 if (MachineLoopInfo *MLI = P->getAnalysisIfAvailable<MachineLoopInfo>())
877 if (MachineLoop *TIL = MLI->getLoopFor(this)) {
878 // If one or the other blocks were not in a loop, the new block is not
879 // either, and thus LI doesn't need to be updated.
880 if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
881 if (TIL == DestLoop) {
882 // Both in the same loop, the NMBB joins loop.
883 DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
884 } else if (TIL->contains(DestLoop)) {
885 // Edge from an outer loop to an inner loop. Add to the outer loop.
886 TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
887 } else if (DestLoop->contains(TIL)) {
888 // Edge from an inner loop to an outer loop. Add to the outer loop.
889 DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
891 // Edge from two loops with no containment relation. Because these
892 // are natural loops, we know that the destination block must be the
893 // header of its loop (adding a branch into a loop elsewhere would
894 // create an irreducible loop).
895 assert(DestLoop->getHeader() == Succ &&
896 "Should not create irreducible loops!");
897 if (MachineLoop *P = DestLoop->getParentLoop())
898 P->addBasicBlockToLoop(NMBB, MLI->getBase());
906 /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
907 /// neighboring instructions so the bundle won't be broken by removing MI.
908 static void unbundleSingleMI(MachineInstr *MI) {
909 // Removing the first instruction in a bundle.
910 if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
911 MI->unbundleFromSucc();
912 // Removing the last instruction in a bundle.
913 if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
914 MI->unbundleFromPred();
915 // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
919 MachineBasicBlock::instr_iterator
920 MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
922 return Insts.erase(I);
925 MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
926 unbundleSingleMI(MI);
927 MI->clearFlag(MachineInstr::BundledPred);
928 MI->clearFlag(MachineInstr::BundledSucc);
929 return Insts.remove(MI);
932 MachineBasicBlock::instr_iterator
933 MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
934 assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
935 "Cannot insert instruction with bundle flags");
936 // Set the bundle flags when inserting inside a bundle.
937 if (I != instr_end() && I->isBundledWithPred()) {
938 MI->setFlag(MachineInstr::BundledPred);
939 MI->setFlag(MachineInstr::BundledSucc);
941 return Insts.insert(I, MI);
944 /// removeFromParent - This method unlinks 'this' from the containing function,
945 /// and returns it, but does not delete it.
946 MachineBasicBlock *MachineBasicBlock::removeFromParent() {
947 assert(getParent() && "Not embedded in a function!");
948 getParent()->remove(this);
953 /// eraseFromParent - This method unlinks 'this' from the containing function,
955 void MachineBasicBlock::eraseFromParent() {
956 assert(getParent() && "Not embedded in a function!");
957 getParent()->erase(this);
961 /// ReplaceUsesOfBlockWith - Given a machine basic block that branched to
962 /// 'Old', change the code and CFG so that it branches to 'New' instead.
963 void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
964 MachineBasicBlock *New) {
965 assert(Old != New && "Cannot replace self with self!");
967 MachineBasicBlock::instr_iterator I = instr_end();
968 while (I != instr_begin()) {
970 if (!I->isTerminator()) break;
972 // Scan the operands of this machine instruction, replacing any uses of Old
974 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
975 if (I->getOperand(i).isMBB() &&
976 I->getOperand(i).getMBB() == Old)
977 I->getOperand(i).setMBB(New);
980 // Update the successor information.
981 replaceSuccessor(Old, New);
984 /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
985 /// CFG to be inserted. If we have proven that MBB can only branch to DestA and
986 /// DestB, remove any other MBB successors from the CFG. DestA and DestB can be
989 /// Besides DestA and DestB, retain other edges leading to LandingPads
990 /// (currently there can be only one; we don't check or require that here).
991 /// Note it is possible that DestA and/or DestB are LandingPads.
992 bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
993 MachineBasicBlock *DestB,
995 // The values of DestA and DestB frequently come from a call to the
996 // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial
997 // values from there.
999 // 1. If both DestA and DestB are null, then the block ends with no branches
1000 // (it falls through to its successor).
1001 // 2. If DestA is set, DestB is null, and isCond is false, then the block ends
1002 // with only an unconditional branch.
1003 // 3. If DestA is set, DestB is null, and isCond is true, then the block ends
1004 // with a conditional branch that falls through to a successor (DestB).
1005 // 4. If DestA and DestB is set and isCond is true, then the block ends with a
1006 // conditional branch followed by an unconditional branch. DestA is the
1007 // 'true' destination and DestB is the 'false' destination.
1009 bool Changed = false;
1011 MachineFunction::iterator FallThru =
1012 std::next(MachineFunction::iterator(this));
1014 if (!DestA && !DestB) {
1015 // Block falls through to successor.
1018 } else if (DestA && !DestB) {
1020 // Block ends in conditional jump that falls through to successor.
1023 assert(DestA && DestB && isCond &&
1024 "CFG in a bad state. Cannot correct CFG edges");
1027 // Remove superfluous edges. I.e., those which aren't destinations of this
1028 // basic block, duplicate edges, or landing pads.
1029 SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs;
1030 MachineBasicBlock::succ_iterator SI = succ_begin();
1031 while (SI != succ_end()) {
1032 const MachineBasicBlock *MBB = *SI;
1033 if (!SeenMBBs.insert(MBB).second ||
1034 (MBB != DestA && MBB != DestB && !MBB->isLandingPad())) {
1035 // This is a superfluous edge, remove it.
1036 SI = removeSuccessor(SI);
1046 /// findDebugLoc - find the next valid DebugLoc starting at MBBI, skipping
1047 /// any DBG_VALUE instructions. Return UnknownLoc if there is none.
1049 MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
1051 instr_iterator E = instr_end();
1055 // Skip debug declarations, we don't want a DebugLoc from them.
1056 while (MBBI != E && MBBI->isDebugValue())
1059 DL = MBBI->getDebugLoc();
1063 /// getSuccWeight - Return weight of the edge from this block to MBB.
1065 uint32_t MachineBasicBlock::getSuccWeight(const_succ_iterator Succ) const {
1066 if (Weights.empty())
1069 return *getWeightIterator(Succ);
1072 /// Set successor weight of a given iterator.
1073 void MachineBasicBlock::setSuccWeight(succ_iterator I, uint32_t weight) {
1074 if (Weights.empty())
1076 *getWeightIterator(I) = weight;
1079 /// getWeightIterator - Return wight iterator corresonding to the I successor
1081 MachineBasicBlock::weight_iterator MachineBasicBlock::
1082 getWeightIterator(MachineBasicBlock::succ_iterator I) {
1083 assert(Weights.size() == Successors.size() && "Async weight list!");
1084 size_t index = std::distance(Successors.begin(), I);
1085 assert(index < Weights.size() && "Not a current successor!");
1086 return Weights.begin() + index;
1089 /// getWeightIterator - Return wight iterator corresonding to the I successor
1091 MachineBasicBlock::const_weight_iterator MachineBasicBlock::
1092 getWeightIterator(MachineBasicBlock::const_succ_iterator I) const {
1093 assert(Weights.size() == Successors.size() && "Async weight list!");
1094 const size_t index = std::distance(Successors.begin(), I);
1095 assert(index < Weights.size() && "Not a current successor!");
1096 return Weights.begin() + index;
1099 /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
1100 /// as of just before "MI".
1102 /// Search is localised to a neighborhood of
1103 /// Neighborhood instructions before (searching for defs or kills) and N
1104 /// instructions after (searching just for defs) MI.
1105 MachineBasicBlock::LivenessQueryResult
1106 MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
1107 unsigned Reg, const_iterator Before,
1108 unsigned Neighborhood) const {
1109 unsigned N = Neighborhood;
1111 // Start by searching backwards from Before, looking for kills, reads or defs.
1112 const_iterator I(Before);
1113 // If this is the first insn in the block, don't search backwards.
1118 MachineOperandIteratorBase::PhysRegInfo Analysis =
1119 ConstMIOperands(I).analyzePhysReg(Reg, TRI);
1121 if (Analysis.Defines)
1122 // Outputs happen after inputs so they take precedence if both are
1124 return Analysis.DefinesDead ? LQR_Dead : LQR_Live;
1126 if (Analysis.Kills || Analysis.Clobbers)
1127 // Register killed, so isn't live.
1130 else if (Analysis.ReadsOverlap)
1131 // Defined or read without a previous kill - live.
1132 return Analysis.Reads ? LQR_Live : LQR_OverlappingLive;
1134 } while (I != begin() && --N > 0);
1137 // Did we get to the start of the block?
1139 // If so, the register's state is definitely defined by the live-in state.
1140 for (MCRegAliasIterator RAI(Reg, TRI, /*IncludeSelf=*/true);
1141 RAI.isValid(); ++RAI) {
1143 return (*RAI == Reg) ? LQR_Live : LQR_OverlappingLive;
1151 // Try searching forwards from Before, looking for reads or defs.
1152 I = const_iterator(Before);
1153 // If this is the last insn in the block, don't search forwards.
1155 for (++I; I != end() && N > 0; ++I, --N) {
1156 MachineOperandIteratorBase::PhysRegInfo Analysis =
1157 ConstMIOperands(I).analyzePhysReg(Reg, TRI);
1159 if (Analysis.ReadsOverlap)
1160 // Used, therefore must have been live.
1161 return (Analysis.Reads) ?
1162 LQR_Live : LQR_OverlappingLive;
1164 else if (Analysis.Clobbers || Analysis.Defines)
1165 // Defined (but not read) therefore cannot have been live.
1170 // At this point we have no idea of the liveness of the register.