1 //===---------- SplitKit.cpp - Toolkit for splitting live ranges ----------===//
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 // This file contains the SplitAnalysis class as well as mutator functions for
11 // live range splitting.
13 //===----------------------------------------------------------------------===//
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
18 #include "llvm/CodeGen/LiveRangeEdit.h"
19 #include "llvm/CodeGen/MachineDominators.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineLoopInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/VirtRegMap.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetMachine.h"
31 #define DEBUG_TYPE "regalloc"
33 STATISTIC(NumFinished, "Number of splits finished");
34 STATISTIC(NumSimple, "Number of splits that were simple");
35 STATISTIC(NumCopies, "Number of copies inserted for splitting");
36 STATISTIC(NumRemats, "Number of rematerialized defs for splitting");
37 STATISTIC(NumRepairs, "Number of invalid live ranges repaired");
39 //===----------------------------------------------------------------------===//
41 //===----------------------------------------------------------------------===//
43 SplitAnalysis::SplitAnalysis(const VirtRegMap &vrm, const LiveIntervals &lis,
44 const MachineLoopInfo &mli)
45 : MF(vrm.getMachineFunction()), VRM(vrm), LIS(lis), Loops(mli),
46 TII(*MF.getSubtarget().getInstrInfo()), CurLI(nullptr),
47 LastSplitPoint(MF.getNumBlockIDs()) {}
49 void SplitAnalysis::clear() {
52 ThroughBlocks.clear();
54 DidRepairRange = false;
57 SlotIndex SplitAnalysis::computeLastSplitPoint(unsigned Num) {
58 const MachineBasicBlock *MBB = MF.getBlockNumbered(Num);
59 // FIXME: Handle multiple EH pad successors.
60 const MachineBasicBlock *LPad = MBB->getLandingPadSuccessor();
61 std::pair<SlotIndex, SlotIndex> &LSP = LastSplitPoint[Num];
62 SlotIndex MBBEnd = LIS.getMBBEndIdx(MBB);
64 // Compute split points on the first call. The pair is independent of the
65 // current live interval.
66 if (!LSP.first.isValid()) {
67 MachineBasicBlock::const_iterator FirstTerm = MBB->getFirstTerminator();
68 if (FirstTerm == MBB->end())
71 LSP.first = LIS.getInstructionIndex(FirstTerm);
73 // If there is a landing pad successor, also find the call instruction.
76 // There may not be a call instruction (?) in which case we ignore LPad.
77 LSP.second = LSP.first;
78 for (MachineBasicBlock::const_iterator I = MBB->end(), E = MBB->begin();
82 LSP.second = LIS.getInstructionIndex(I);
88 // If CurLI is live into a landing pad successor, move the last split point
89 // back to the call that may throw.
90 if (!LPad || !LSP.second || !LIS.isLiveInToMBB(*CurLI, LPad))
93 // Find the value leaving MBB.
94 const VNInfo *VNI = CurLI->getVNInfoBefore(MBBEnd);
98 // If the value leaving MBB was defined after the call in MBB, it can't
99 // really be live-in to the landing pad. This can happen if the landing pad
100 // has a PHI, and this register is undef on the exceptional edge.
101 // <rdar://problem/10664933>
102 if (!SlotIndex::isEarlierInstr(VNI->def, LSP.second) && VNI->def < MBBEnd)
105 // Value is properly live-in to the landing pad.
106 // Only allow splits before the call.
110 MachineBasicBlock::iterator
111 SplitAnalysis::getLastSplitPointIter(MachineBasicBlock *MBB) {
112 SlotIndex LSP = getLastSplitPoint(MBB->getNumber());
113 if (LSP == LIS.getMBBEndIdx(MBB))
115 return LIS.getInstructionFromIndex(LSP);
118 /// analyzeUses - Count instructions, basic blocks, and loops using CurLI.
119 void SplitAnalysis::analyzeUses() {
120 assert(UseSlots.empty() && "Call clear first");
122 // First get all the defs from the interval values. This provides the correct
123 // slots for early clobbers.
124 for (const VNInfo *VNI : CurLI->valnos)
125 if (!VNI->isPHIDef() && !VNI->isUnused())
126 UseSlots.push_back(VNI->def);
128 // Get use slots form the use-def chain.
129 const MachineRegisterInfo &MRI = MF.getRegInfo();
130 for (MachineOperand &MO : MRI.use_nodbg_operands(CurLI->reg))
132 UseSlots.push_back(LIS.getInstructionIndex(MO.getParent()).getRegSlot());
134 array_pod_sort(UseSlots.begin(), UseSlots.end());
136 // Remove duplicates, keeping the smaller slot for each instruction.
137 // That is what we want for early clobbers.
138 UseSlots.erase(std::unique(UseSlots.begin(), UseSlots.end(),
139 SlotIndex::isSameInstr),
142 // Compute per-live block info.
143 if (!calcLiveBlockInfo()) {
144 // FIXME: calcLiveBlockInfo found inconsistencies in the live range.
145 // I am looking at you, RegisterCoalescer!
146 DidRepairRange = true;
148 DEBUG(dbgs() << "*** Fixing inconsistent live interval! ***\n");
149 const_cast<LiveIntervals&>(LIS)
150 .shrinkToUses(const_cast<LiveInterval*>(CurLI));
152 ThroughBlocks.clear();
153 bool fixed = calcLiveBlockInfo();
155 assert(fixed && "Couldn't fix broken live interval");
158 DEBUG(dbgs() << "Analyze counted "
159 << UseSlots.size() << " instrs in "
160 << UseBlocks.size() << " blocks, through "
161 << NumThroughBlocks << " blocks.\n");
164 /// calcLiveBlockInfo - Fill the LiveBlocks array with information about blocks
165 /// where CurLI is live.
166 bool SplitAnalysis::calcLiveBlockInfo() {
167 ThroughBlocks.resize(MF.getNumBlockIDs());
168 NumThroughBlocks = NumGapBlocks = 0;
172 LiveInterval::const_iterator LVI = CurLI->begin();
173 LiveInterval::const_iterator LVE = CurLI->end();
175 SmallVectorImpl<SlotIndex>::const_iterator UseI, UseE;
176 UseI = UseSlots.begin();
177 UseE = UseSlots.end();
179 // Loop over basic blocks where CurLI is live.
180 MachineFunction::iterator MFI = LIS.getMBBFromIndex(LVI->start);
184 SlotIndex Start, Stop;
185 std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
187 // If the block contains no uses, the range must be live through. At one
188 // point, RegisterCoalescer could create dangling ranges that ended
190 if (UseI == UseE || *UseI >= Stop) {
192 ThroughBlocks.set(BI.MBB->getNumber());
193 // The range shouldn't end mid-block if there are no uses. This shouldn't
198 // This block has uses. Find the first and last uses in the block.
199 BI.FirstInstr = *UseI;
200 assert(BI.FirstInstr >= Start);
202 while (UseI != UseE && *UseI < Stop);
203 BI.LastInstr = UseI[-1];
204 assert(BI.LastInstr < Stop);
206 // LVI is the first live segment overlapping MBB.
207 BI.LiveIn = LVI->start <= Start;
209 // When not live in, the first use should be a def.
211 assert(LVI->start == LVI->valno->def && "Dangling Segment start");
212 assert(LVI->start == BI.FirstInstr && "First instr should be a def");
213 BI.FirstDef = BI.FirstInstr;
216 // Look for gaps in the live range.
218 while (LVI->end < Stop) {
219 SlotIndex LastStop = LVI->end;
220 if (++LVI == LVE || LVI->start >= Stop) {
222 BI.LastInstr = LastStop;
226 if (LastStop < LVI->start) {
227 // There is a gap in the live range. Create duplicate entries for the
228 // live-in snippet and the live-out snippet.
231 // Push the Live-in part.
233 UseBlocks.push_back(BI);
234 UseBlocks.back().LastInstr = LastStop;
236 // Set up BI for the live-out part.
239 BI.FirstInstr = BI.FirstDef = LVI->start;
242 // A Segment that starts in the middle of the block must be a def.
243 assert(LVI->start == LVI->valno->def && "Dangling Segment start");
245 BI.FirstDef = LVI->start;
248 UseBlocks.push_back(BI);
250 // LVI is now at LVE or LVI->end >= Stop.
255 // Live segment ends exactly at Stop. Move to the next segment.
256 if (LVI->end == Stop && ++LVI == LVE)
259 // Pick the next basic block.
260 if (LVI->start < Stop)
263 MFI = LIS.getMBBFromIndex(LVI->start);
266 assert(getNumLiveBlocks() == countLiveBlocks(CurLI) && "Bad block count");
270 unsigned SplitAnalysis::countLiveBlocks(const LiveInterval *cli) const {
273 LiveInterval *li = const_cast<LiveInterval*>(cli);
274 LiveInterval::iterator LVI = li->begin();
275 LiveInterval::iterator LVE = li->end();
278 // Loop over basic blocks where li is live.
279 MachineFunction::const_iterator MFI = LIS.getMBBFromIndex(LVI->start);
280 SlotIndex Stop = LIS.getMBBEndIdx(MFI);
283 LVI = li->advanceTo(LVI, Stop);
288 Stop = LIS.getMBBEndIdx(MFI);
289 } while (Stop <= LVI->start);
293 bool SplitAnalysis::isOriginalEndpoint(SlotIndex Idx) const {
294 unsigned OrigReg = VRM.getOriginal(CurLI->reg);
295 const LiveInterval &Orig = LIS.getInterval(OrigReg);
296 assert(!Orig.empty() && "Splitting empty interval?");
297 LiveInterval::const_iterator I = Orig.find(Idx);
299 // Range containing Idx should begin at Idx.
300 if (I != Orig.end() && I->start <= Idx)
301 return I->start == Idx;
303 // Range does not contain Idx, previous must end at Idx.
304 return I != Orig.begin() && (--I)->end == Idx;
307 void SplitAnalysis::analyze(const LiveInterval *li) {
314 //===----------------------------------------------------------------------===//
316 //===----------------------------------------------------------------------===//
318 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
319 SplitEditor::SplitEditor(SplitAnalysis &sa, LiveIntervals &lis, VirtRegMap &vrm,
320 MachineDominatorTree &mdt,
321 MachineBlockFrequencyInfo &mbfi)
322 : SA(sa), LIS(lis), VRM(vrm), MRI(vrm.getMachineFunction().getRegInfo()),
323 MDT(mdt), TII(*vrm.getMachineFunction().getSubtarget().getInstrInfo()),
324 TRI(*vrm.getMachineFunction().getSubtarget().getRegisterInfo()),
325 MBFI(mbfi), Edit(nullptr), OpenIdx(0), SpillMode(SM_Partition),
326 RegAssign(Allocator) {}
328 void SplitEditor::reset(LiveRangeEdit &LRE, ComplementSpillMode SM) {
335 // Reset the LiveRangeCalc instances needed for this spill mode.
336 LRCalc[0].reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT,
337 &LIS.getVNInfoAllocator());
339 LRCalc[1].reset(&VRM.getMachineFunction(), LIS.getSlotIndexes(), &MDT,
340 &LIS.getVNInfoAllocator());
342 // We don't need an AliasAnalysis since we will only be performing
343 // cheap-as-a-copy remats anyway.
344 Edit->anyRematerializable(nullptr);
347 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
348 void SplitEditor::dump() const {
349 if (RegAssign.empty()) {
350 dbgs() << " empty\n";
354 for (RegAssignMap::const_iterator I = RegAssign.begin(); I.valid(); ++I)
355 dbgs() << " [" << I.start() << ';' << I.stop() << "):" << I.value();
360 VNInfo *SplitEditor::defValue(unsigned RegIdx,
361 const VNInfo *ParentVNI,
363 assert(ParentVNI && "Mapping NULL value");
364 assert(Idx.isValid() && "Invalid SlotIndex");
365 assert(Edit->getParent().getVNInfoAt(Idx) == ParentVNI && "Bad Parent VNI");
366 LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx));
368 // Create a new value.
369 VNInfo *VNI = LI->getNextValue(Idx, LIS.getVNInfoAllocator());
371 // Use insert for lookup, so we can add missing values with a second lookup.
372 std::pair<ValueMap::iterator, bool> InsP =
373 Values.insert(std::make_pair(std::make_pair(RegIdx, ParentVNI->id),
374 ValueForcePair(VNI, false)));
376 // This was the first time (RegIdx, ParentVNI) was mapped.
377 // Keep it as a simple def without any liveness.
381 // If the previous value was a simple mapping, add liveness for it now.
382 if (VNInfo *OldVNI = InsP.first->second.getPointer()) {
383 SlotIndex Def = OldVNI->def;
384 LI->addSegment(LiveInterval::Segment(Def, Def.getDeadSlot(), OldVNI));
385 // No longer a simple mapping. Switch to a complex, non-forced mapping.
386 InsP.first->second = ValueForcePair();
389 // This is a complex mapping, add liveness for VNI
390 SlotIndex Def = VNI->def;
391 LI->addSegment(LiveInterval::Segment(Def, Def.getDeadSlot(), VNI));
396 void SplitEditor::forceRecompute(unsigned RegIdx, const VNInfo *ParentVNI) {
397 assert(ParentVNI && "Mapping NULL value");
398 ValueForcePair &VFP = Values[std::make_pair(RegIdx, ParentVNI->id)];
399 VNInfo *VNI = VFP.getPointer();
401 // ParentVNI was either unmapped or already complex mapped. Either way, just
402 // set the force bit.
408 // This was previously a single mapping. Make sure the old def is represented
409 // by a trivial live range.
410 SlotIndex Def = VNI->def;
411 LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx));
412 LI->addSegment(LiveInterval::Segment(Def, Def.getDeadSlot(), VNI));
413 // Mark as complex mapped, forced.
414 VFP = ValueForcePair(nullptr, true);
417 VNInfo *SplitEditor::defFromParent(unsigned RegIdx,
420 MachineBasicBlock &MBB,
421 MachineBasicBlock::iterator I) {
422 MachineInstr *CopyMI = nullptr;
424 LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx));
426 // We may be trying to avoid interference that ends at a deleted instruction,
427 // so always begin RegIdx 0 early and all others late.
428 bool Late = RegIdx != 0;
430 // Attempt cheap-as-a-copy rematerialization.
431 LiveRangeEdit::Remat RM(ParentVNI);
432 if (Edit->canRematerializeAt(RM, UseIdx, true)) {
433 Def = Edit->rematerializeAt(MBB, I, LI->reg, RM, TRI, Late);
436 // Can't remat, just insert a copy from parent.
437 CopyMI = BuildMI(MBB, I, DebugLoc(), TII.get(TargetOpcode::COPY), LI->reg)
438 .addReg(Edit->getReg());
439 Def = LIS.getSlotIndexes()->insertMachineInstrInMaps(CopyMI, Late)
444 // Define the value in Reg.
445 return defValue(RegIdx, ParentVNI, Def);
448 /// Create a new virtual register and live interval.
449 unsigned SplitEditor::openIntv() {
450 // Create the complement as index 0.
452 Edit->createEmptyInterval();
454 // Create the open interval.
455 OpenIdx = Edit->size();
456 Edit->createEmptyInterval();
460 void SplitEditor::selectIntv(unsigned Idx) {
461 assert(Idx != 0 && "Cannot select the complement interval");
462 assert(Idx < Edit->size() && "Can only select previously opened interval");
463 DEBUG(dbgs() << " selectIntv " << OpenIdx << " -> " << Idx << '\n');
467 SlotIndex SplitEditor::enterIntvBefore(SlotIndex Idx) {
468 assert(OpenIdx && "openIntv not called before enterIntvBefore");
469 DEBUG(dbgs() << " enterIntvBefore " << Idx);
470 Idx = Idx.getBaseIndex();
471 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
473 DEBUG(dbgs() << ": not live\n");
476 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
477 MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
478 assert(MI && "enterIntvBefore called with invalid index");
480 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(), MI);
484 SlotIndex SplitEditor::enterIntvAfter(SlotIndex Idx) {
485 assert(OpenIdx && "openIntv not called before enterIntvAfter");
486 DEBUG(dbgs() << " enterIntvAfter " << Idx);
487 Idx = Idx.getBoundaryIndex();
488 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
490 DEBUG(dbgs() << ": not live\n");
493 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
494 MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
495 assert(MI && "enterIntvAfter called with invalid index");
497 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Idx, *MI->getParent(),
498 std::next(MachineBasicBlock::iterator(MI)));
502 SlotIndex SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
503 assert(OpenIdx && "openIntv not called before enterIntvAtEnd");
504 SlotIndex End = LIS.getMBBEndIdx(&MBB);
505 SlotIndex Last = End.getPrevSlot();
506 DEBUG(dbgs() << " enterIntvAtEnd BB#" << MBB.getNumber() << ", " << Last);
507 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Last);
509 DEBUG(dbgs() << ": not live\n");
512 DEBUG(dbgs() << ": valno " << ParentVNI->id);
513 VNInfo *VNI = defFromParent(OpenIdx, ParentVNI, Last, MBB,
514 SA.getLastSplitPointIter(&MBB));
515 RegAssign.insert(VNI->def, End, OpenIdx);
520 /// useIntv - indicate that all instructions in MBB should use OpenLI.
521 void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
522 useIntv(LIS.getMBBStartIdx(&MBB), LIS.getMBBEndIdx(&MBB));
525 void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
526 assert(OpenIdx && "openIntv not called before useIntv");
527 DEBUG(dbgs() << " useIntv [" << Start << ';' << End << "):");
528 RegAssign.insert(Start, End, OpenIdx);
532 SlotIndex SplitEditor::leaveIntvAfter(SlotIndex Idx) {
533 assert(OpenIdx && "openIntv not called before leaveIntvAfter");
534 DEBUG(dbgs() << " leaveIntvAfter " << Idx);
536 // The interval must be live beyond the instruction at Idx.
537 SlotIndex Boundary = Idx.getBoundaryIndex();
538 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Boundary);
540 DEBUG(dbgs() << ": not live\n");
541 return Boundary.getNextSlot();
543 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
544 MachineInstr *MI = LIS.getInstructionFromIndex(Boundary);
545 assert(MI && "No instruction at index");
547 // In spill mode, make live ranges as short as possible by inserting the copy
548 // before MI. This is only possible if that instruction doesn't redefine the
549 // value. The inserted COPY is not a kill, and we don't need to recompute
550 // the source live range. The spiller also won't try to hoist this copy.
551 if (SpillMode && !SlotIndex::isSameInstr(ParentVNI->def, Idx) &&
552 MI->readsVirtualRegister(Edit->getReg())) {
553 forceRecompute(0, ParentVNI);
554 defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI);
558 VNInfo *VNI = defFromParent(0, ParentVNI, Boundary, *MI->getParent(),
559 std::next(MachineBasicBlock::iterator(MI)));
563 SlotIndex SplitEditor::leaveIntvBefore(SlotIndex Idx) {
564 assert(OpenIdx && "openIntv not called before leaveIntvBefore");
565 DEBUG(dbgs() << " leaveIntvBefore " << Idx);
567 // The interval must be live into the instruction at Idx.
568 Idx = Idx.getBaseIndex();
569 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Idx);
571 DEBUG(dbgs() << ": not live\n");
572 return Idx.getNextSlot();
574 DEBUG(dbgs() << ": valno " << ParentVNI->id << '\n');
576 MachineInstr *MI = LIS.getInstructionFromIndex(Idx);
577 assert(MI && "No instruction at index");
578 VNInfo *VNI = defFromParent(0, ParentVNI, Idx, *MI->getParent(), MI);
582 SlotIndex SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
583 assert(OpenIdx && "openIntv not called before leaveIntvAtTop");
584 SlotIndex Start = LIS.getMBBStartIdx(&MBB);
585 DEBUG(dbgs() << " leaveIntvAtTop BB#" << MBB.getNumber() << ", " << Start);
587 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start);
589 DEBUG(dbgs() << ": not live\n");
593 VNInfo *VNI = defFromParent(0, ParentVNI, Start, MBB,
594 MBB.SkipPHIsAndLabels(MBB.begin()));
595 RegAssign.insert(Start, VNI->def, OpenIdx);
600 void SplitEditor::overlapIntv(SlotIndex Start, SlotIndex End) {
601 assert(OpenIdx && "openIntv not called before overlapIntv");
602 const VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(Start);
603 assert(ParentVNI == Edit->getParent().getVNInfoBefore(End) &&
604 "Parent changes value in extended range");
605 assert(LIS.getMBBFromIndex(Start) == LIS.getMBBFromIndex(End) &&
606 "Range cannot span basic blocks");
608 // The complement interval will be extended as needed by LRCalc.extend().
610 forceRecompute(0, ParentVNI);
611 DEBUG(dbgs() << " overlapIntv [" << Start << ';' << End << "):");
612 RegAssign.insert(Start, End, OpenIdx);
616 //===----------------------------------------------------------------------===//
618 //===----------------------------------------------------------------------===//
620 void SplitEditor::removeBackCopies(SmallVectorImpl<VNInfo*> &Copies) {
621 LiveInterval *LI = &LIS.getInterval(Edit->get(0));
622 DEBUG(dbgs() << "Removing " << Copies.size() << " back-copies.\n");
623 RegAssignMap::iterator AssignI;
624 AssignI.setMap(RegAssign);
626 for (unsigned i = 0, e = Copies.size(); i != e; ++i) {
627 SlotIndex Def = Copies[i]->def;
628 MachineInstr *MI = LIS.getInstructionFromIndex(Def);
629 assert(MI && "No instruction for back-copy");
631 MachineBasicBlock *MBB = MI->getParent();
632 MachineBasicBlock::iterator MBBI(MI);
634 do AtBegin = MBBI == MBB->begin();
635 while (!AtBegin && (--MBBI)->isDebugValue());
637 DEBUG(dbgs() << "Removing " << Def << '\t' << *MI);
638 LIS.removeVRegDefAt(*LI, Def);
639 LIS.RemoveMachineInstrFromMaps(MI);
640 MI->eraseFromParent();
642 // Adjust RegAssign if a register assignment is killed at Def. We want to
643 // avoid calculating the live range of the source register if possible.
644 AssignI.find(Def.getPrevSlot());
645 if (!AssignI.valid() || AssignI.start() >= Def)
647 // If MI doesn't kill the assigned register, just leave it.
648 if (AssignI.stop() != Def)
650 unsigned RegIdx = AssignI.value();
651 if (AtBegin || !MBBI->readsVirtualRegister(Edit->getReg())) {
652 DEBUG(dbgs() << " cannot find simple kill of RegIdx " << RegIdx << '\n');
653 forceRecompute(RegIdx, Edit->getParent().getVNInfoAt(Def));
655 SlotIndex Kill = LIS.getInstructionIndex(MBBI).getRegSlot();
656 DEBUG(dbgs() << " move kill to " << Kill << '\t' << *MBBI);
657 AssignI.setStop(Kill);
663 SplitEditor::findShallowDominator(MachineBasicBlock *MBB,
664 MachineBasicBlock *DefMBB) {
667 assert(MDT.dominates(DefMBB, MBB) && "MBB must be dominated by the def.");
669 const MachineLoopInfo &Loops = SA.Loops;
670 const MachineLoop *DefLoop = Loops.getLoopFor(DefMBB);
671 MachineDomTreeNode *DefDomNode = MDT[DefMBB];
673 // Best candidate so far.
674 MachineBasicBlock *BestMBB = MBB;
675 unsigned BestDepth = UINT_MAX;
678 const MachineLoop *Loop = Loops.getLoopFor(MBB);
680 // MBB isn't in a loop, it doesn't get any better. All dominators have a
681 // higher frequency by definition.
683 DEBUG(dbgs() << "Def in BB#" << DefMBB->getNumber() << " dominates BB#"
684 << MBB->getNumber() << " at depth 0\n");
688 // We'll never be able to exit the DefLoop.
689 if (Loop == DefLoop) {
690 DEBUG(dbgs() << "Def in BB#" << DefMBB->getNumber() << " dominates BB#"
691 << MBB->getNumber() << " in the same loop\n");
695 // Least busy dominator seen so far.
696 unsigned Depth = Loop->getLoopDepth();
697 if (Depth < BestDepth) {
700 DEBUG(dbgs() << "Def in BB#" << DefMBB->getNumber() << " dominates BB#"
701 << MBB->getNumber() << " at depth " << Depth << '\n');
704 // Leave loop by going to the immediate dominator of the loop header.
705 // This is a bigger stride than simply walking up the dominator tree.
706 MachineDomTreeNode *IDom = MDT[Loop->getHeader()]->getIDom();
708 // Too far up the dominator tree?
709 if (!IDom || !MDT.dominates(DefDomNode, IDom))
712 MBB = IDom->getBlock();
716 void SplitEditor::hoistCopiesForSize() {
717 // Get the complement interval, always RegIdx 0.
718 LiveInterval *LI = &LIS.getInterval(Edit->get(0));
719 LiveInterval *Parent = &Edit->getParent();
721 // Track the nearest common dominator for all back-copies for each ParentVNI,
722 // indexed by ParentVNI->id.
723 typedef std::pair<MachineBasicBlock*, SlotIndex> DomPair;
724 SmallVector<DomPair, 8> NearestDom(Parent->getNumValNums());
726 // Find the nearest common dominator for parent values with multiple
727 // back-copies. If a single back-copy dominates, put it in DomPair.second.
728 for (VNInfo *VNI : LI->valnos) {
731 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def);
732 assert(ParentVNI && "Parent not live at complement def");
734 // Don't hoist remats. The complement is probably going to disappear
735 // completely anyway.
736 if (Edit->didRematerialize(ParentVNI))
739 MachineBasicBlock *ValMBB = LIS.getMBBFromIndex(VNI->def);
740 DomPair &Dom = NearestDom[ParentVNI->id];
742 // Keep directly defined parent values. This is either a PHI or an
743 // instruction in the complement range. All other copies of ParentVNI
744 // should be eliminated.
745 if (VNI->def == ParentVNI->def) {
746 DEBUG(dbgs() << "Direct complement def at " << VNI->def << '\n');
747 Dom = DomPair(ValMBB, VNI->def);
750 // Skip the singly mapped values. There is nothing to gain from hoisting a
752 if (Values.lookup(std::make_pair(0, ParentVNI->id)).getPointer()) {
753 DEBUG(dbgs() << "Single complement def at " << VNI->def << '\n');
758 // First time we see ParentVNI. VNI dominates itself.
759 Dom = DomPair(ValMBB, VNI->def);
760 } else if (Dom.first == ValMBB) {
761 // Two defs in the same block. Pick the earlier def.
762 if (!Dom.second.isValid() || VNI->def < Dom.second)
763 Dom.second = VNI->def;
765 // Different basic blocks. Check if one dominates.
766 MachineBasicBlock *Near =
767 MDT.findNearestCommonDominator(Dom.first, ValMBB);
769 // Def ValMBB dominates.
770 Dom = DomPair(ValMBB, VNI->def);
771 else if (Near != Dom.first)
772 // None dominate. Hoist to common dominator, need new def.
773 Dom = DomPair(Near, SlotIndex());
776 DEBUG(dbgs() << "Multi-mapped complement " << VNI->id << '@' << VNI->def
777 << " for parent " << ParentVNI->id << '@' << ParentVNI->def
778 << " hoist to BB#" << Dom.first->getNumber() << ' '
779 << Dom.second << '\n');
782 // Insert the hoisted copies.
783 for (unsigned i = 0, e = Parent->getNumValNums(); i != e; ++i) {
784 DomPair &Dom = NearestDom[i];
785 if (!Dom.first || Dom.second.isValid())
787 // This value needs a hoisted copy inserted at the end of Dom.first.
788 VNInfo *ParentVNI = Parent->getValNumInfo(i);
789 MachineBasicBlock *DefMBB = LIS.getMBBFromIndex(ParentVNI->def);
790 // Get a less loopy dominator than Dom.first.
791 Dom.first = findShallowDominator(Dom.first, DefMBB);
792 SlotIndex Last = LIS.getMBBEndIdx(Dom.first).getPrevSlot();
794 defFromParent(0, ParentVNI, Last, *Dom.first,
795 SA.getLastSplitPointIter(Dom.first))->def;
798 // Remove redundant back-copies that are now known to be dominated by another
799 // def with the same value.
800 SmallVector<VNInfo*, 8> BackCopies;
801 for (VNInfo *VNI : LI->valnos) {
804 VNInfo *ParentVNI = Edit->getParent().getVNInfoAt(VNI->def);
805 const DomPair &Dom = NearestDom[ParentVNI->id];
806 if (!Dom.first || Dom.second == VNI->def)
808 BackCopies.push_back(VNI);
809 forceRecompute(0, ParentVNI);
811 removeBackCopies(BackCopies);
815 /// transferValues - Transfer all possible values to the new live ranges.
816 /// Values that were rematerialized are left alone, they need LRCalc.extend().
817 bool SplitEditor::transferValues() {
818 bool Skipped = false;
819 RegAssignMap::const_iterator AssignI = RegAssign.begin();
820 for (const LiveRange::Segment &S : Edit->getParent()) {
821 DEBUG(dbgs() << " blit " << S << ':');
822 VNInfo *ParentVNI = S.valno;
823 // RegAssign has holes where RegIdx 0 should be used.
824 SlotIndex Start = S.start;
825 AssignI.advanceTo(Start);
828 SlotIndex End = S.end;
829 if (!AssignI.valid()) {
831 } else if (AssignI.start() <= Start) {
832 RegIdx = AssignI.value();
833 if (AssignI.stop() < End) {
834 End = AssignI.stop();
839 End = std::min(End, AssignI.start());
842 // The interval [Start;End) is continuously mapped to RegIdx, ParentVNI.
843 DEBUG(dbgs() << " [" << Start << ';' << End << ")=" << RegIdx);
844 LiveRange &LR = LIS.getInterval(Edit->get(RegIdx));
846 // Check for a simply defined value that can be blitted directly.
847 ValueForcePair VFP = Values.lookup(std::make_pair(RegIdx, ParentVNI->id));
848 if (VNInfo *VNI = VFP.getPointer()) {
849 DEBUG(dbgs() << ':' << VNI->id);
850 LR.addSegment(LiveInterval::Segment(Start, End, VNI));
855 // Skip values with forced recomputation.
857 DEBUG(dbgs() << "(recalc)");
863 LiveRangeCalc &LRC = getLRCalc(RegIdx);
865 // This value has multiple defs in RegIdx, but it wasn't rematerialized,
866 // so the live range is accurate. Add live-in blocks in [Start;End) to the
868 MachineFunction::iterator MBB = LIS.getMBBFromIndex(Start);
869 SlotIndex BlockStart, BlockEnd;
870 std::tie(BlockStart, BlockEnd) = LIS.getSlotIndexes()->getMBBRange(MBB);
872 // The first block may be live-in, or it may have its own def.
873 if (Start != BlockStart) {
874 VNInfo *VNI = LR.extendInBlock(BlockStart, std::min(BlockEnd, End));
875 assert(VNI && "Missing def for complex mapped value");
876 DEBUG(dbgs() << ':' << VNI->id << "*BB#" << MBB->getNumber());
877 // MBB has its own def. Is it also live-out?
879 LRC.setLiveOutValue(MBB, VNI);
881 // Skip to the next block for live-in.
883 BlockStart = BlockEnd;
886 // Handle the live-in blocks covered by [Start;End).
887 assert(Start <= BlockStart && "Expected live-in block");
888 while (BlockStart < End) {
889 DEBUG(dbgs() << ">BB#" << MBB->getNumber());
890 BlockEnd = LIS.getMBBEndIdx(MBB);
891 if (BlockStart == ParentVNI->def) {
892 // This block has the def of a parent PHI, so it isn't live-in.
893 assert(ParentVNI->isPHIDef() && "Non-phi defined at block start?");
894 VNInfo *VNI = LR.extendInBlock(BlockStart, std::min(BlockEnd, End));
895 assert(VNI && "Missing def for complex mapped parent PHI");
897 LRC.setLiveOutValue(MBB, VNI); // Live-out as well.
899 // This block needs a live-in value. The last block covered may not
902 LRC.addLiveInBlock(LR, MDT[MBB], End);
904 // Live-through, and we don't know the value.
905 LRC.addLiveInBlock(LR, MDT[MBB]);
906 LRC.setLiveOutValue(MBB, nullptr);
909 BlockStart = BlockEnd;
913 } while (Start != S.end);
914 DEBUG(dbgs() << '\n');
917 LRCalc[0].calculateValues();
919 LRCalc[1].calculateValues();
924 void SplitEditor::extendPHIKillRanges() {
925 // Extend live ranges to be live-out for successor PHI values.
926 for (const VNInfo *PHIVNI : Edit->getParent().valnos) {
927 if (PHIVNI->isUnused() || !PHIVNI->isPHIDef())
929 unsigned RegIdx = RegAssign.lookup(PHIVNI->def);
930 LiveRange &LR = LIS.getInterval(Edit->get(RegIdx));
931 LiveRangeCalc &LRC = getLRCalc(RegIdx);
932 MachineBasicBlock *MBB = LIS.getMBBFromIndex(PHIVNI->def);
933 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
934 PE = MBB->pred_end(); PI != PE; ++PI) {
935 SlotIndex End = LIS.getMBBEndIdx(*PI);
936 SlotIndex LastUse = End.getPrevSlot();
937 // The predecessor may not have a live-out value. That is OK, like an
938 // undef PHI operand.
939 if (Edit->getParent().liveAt(LastUse)) {
940 assert(RegAssign.lookup(LastUse) == RegIdx &&
941 "Different register assignment in phi predecessor");
948 /// rewriteAssigned - Rewrite all uses of Edit->getReg().
949 void SplitEditor::rewriteAssigned(bool ExtendRanges) {
950 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Edit->getReg()),
951 RE = MRI.reg_end(); RI != RE;) {
952 MachineOperand &MO = *RI;
953 MachineInstr *MI = MO.getParent();
955 // LiveDebugVariables should have handled all DBG_VALUE instructions.
956 if (MI->isDebugValue()) {
957 DEBUG(dbgs() << "Zapping " << *MI);
962 // <undef> operands don't really read the register, so it doesn't matter
963 // which register we choose. When the use operand is tied to a def, we must
964 // use the same register as the def, so just do that always.
965 SlotIndex Idx = LIS.getInstructionIndex(MI);
966 if (MO.isDef() || MO.isUndef())
967 Idx = Idx.getRegSlot(MO.isEarlyClobber());
969 // Rewrite to the mapped register at Idx.
970 unsigned RegIdx = RegAssign.lookup(Idx);
971 LiveInterval *LI = &LIS.getInterval(Edit->get(RegIdx));
973 DEBUG(dbgs() << " rewr BB#" << MI->getParent()->getNumber() << '\t'
974 << Idx << ':' << RegIdx << '\t' << *MI);
976 // Extend liveness to Idx if the instruction reads reg.
977 if (!ExtendRanges || MO.isUndef())
980 // Skip instructions that don't read Reg.
982 if (!MO.getSubReg() && !MO.isEarlyClobber())
984 // We may wan't to extend a live range for a partial redef, or for a use
985 // tied to an early clobber.
986 Idx = Idx.getPrevSlot();
987 if (!Edit->getParent().liveAt(Idx))
990 Idx = Idx.getRegSlot(true);
992 getLRCalc(RegIdx).extend(*LI, Idx.getNextSlot());
996 void SplitEditor::deleteRematVictims() {
997 SmallVector<MachineInstr*, 8> Dead;
998 for (LiveRangeEdit::iterator I = Edit->begin(), E = Edit->end(); I != E; ++I){
999 LiveInterval *LI = &LIS.getInterval(*I);
1000 for (const LiveRange::Segment &S : LI->segments) {
1001 // Dead defs end at the dead slot.
1002 if (S.end != S.valno->def.getDeadSlot())
1004 MachineInstr *MI = LIS.getInstructionFromIndex(S.valno->def);
1005 assert(MI && "Missing instruction for dead def");
1006 MI->addRegisterDead(LI->reg, &TRI);
1008 if (!MI->allDefsAreDead())
1011 DEBUG(dbgs() << "All defs dead: " << *MI);
1019 Edit->eliminateDeadDefs(Dead);
1022 void SplitEditor::finish(SmallVectorImpl<unsigned> *LRMap) {
1025 // At this point, the live intervals in Edit contain VNInfos corresponding to
1026 // the inserted copies.
1028 // Add the original defs from the parent interval.
1029 for (const VNInfo *ParentVNI : Edit->getParent().valnos) {
1030 if (ParentVNI->isUnused())
1032 unsigned RegIdx = RegAssign.lookup(ParentVNI->def);
1033 defValue(RegIdx, ParentVNI, ParentVNI->def);
1035 // Force rematted values to be recomputed everywhere.
1036 // The new live ranges may be truncated.
1037 if (Edit->didRematerialize(ParentVNI))
1038 for (unsigned i = 0, e = Edit->size(); i != e; ++i)
1039 forceRecompute(i, ParentVNI);
1042 // Hoist back-copies to the complement interval when in spill mode.
1043 switch (SpillMode) {
1045 // Leave all back-copies as is.
1048 hoistCopiesForSize();
1051 llvm_unreachable("Spill mode 'speed' not implemented yet");
1054 // Transfer the simply mapped values, check if any are skipped.
1055 bool Skipped = transferValues();
1057 extendPHIKillRanges();
1061 // Rewrite virtual registers, possibly extending ranges.
1062 rewriteAssigned(Skipped);
1064 // Delete defs that were rematted everywhere.
1066 deleteRematVictims();
1068 // Get rid of unused values and set phi-kill flags.
1069 for (LiveRangeEdit::iterator I = Edit->begin(), E = Edit->end(); I != E; ++I) {
1070 LiveInterval &LI = LIS.getInterval(*I);
1071 LI.RenumberValues();
1074 // Provide a reverse mapping from original indices to Edit ranges.
1077 for (unsigned i = 0, e = Edit->size(); i != e; ++i)
1078 LRMap->push_back(i);
1081 // Now check if any registers were separated into multiple components.
1082 ConnectedVNInfoEqClasses ConEQ(LIS);
1083 for (unsigned i = 0, e = Edit->size(); i != e; ++i) {
1084 // Don't use iterators, they are invalidated by create() below.
1085 unsigned VReg = Edit->get(i);
1086 LiveInterval &LI = LIS.getInterval(VReg);
1087 SmallVector<LiveInterval*, 8> SplitLIs;
1088 LIS.splitSeparateComponents(LI, SplitLIs);
1089 unsigned Original = VRM.getOriginal(VReg);
1090 for (LiveInterval *SplitLI : SplitLIs)
1091 VRM.setIsSplitFromReg(SplitLI->reg, Original);
1093 // The new intervals all map back to i.
1095 LRMap->resize(Edit->size(), i);
1098 // Calculate spill weight and allocation hints for new intervals.
1099 Edit->calculateRegClassAndHint(VRM.getMachineFunction(), SA.Loops, MBFI);
1101 assert(!LRMap || LRMap->size() == Edit->size());
1105 //===----------------------------------------------------------------------===//
1106 // Single Block Splitting
1107 //===----------------------------------------------------------------------===//
1109 bool SplitAnalysis::shouldSplitSingleBlock(const BlockInfo &BI,
1110 bool SingleInstrs) const {
1111 // Always split for multiple instructions.
1112 if (!BI.isOneInstr())
1114 // Don't split for single instructions unless explicitly requested.
1117 // Splitting a live-through range always makes progress.
1118 if (BI.LiveIn && BI.LiveOut)
1120 // No point in isolating a copy. It has no register class constraints.
1121 if (LIS.getInstructionFromIndex(BI.FirstInstr)->isCopyLike())
1123 // Finally, don't isolate an end point that was created by earlier splits.
1124 return isOriginalEndpoint(BI.FirstInstr);
1127 void SplitEditor::splitSingleBlock(const SplitAnalysis::BlockInfo &BI) {
1129 SlotIndex LastSplitPoint = SA.getLastSplitPoint(BI.MBB->getNumber());
1130 SlotIndex SegStart = enterIntvBefore(std::min(BI.FirstInstr,
1132 if (!BI.LiveOut || BI.LastInstr < LastSplitPoint) {
1133 useIntv(SegStart, leaveIntvAfter(BI.LastInstr));
1135 // The last use is after the last valid split point.
1136 SlotIndex SegStop = leaveIntvBefore(LastSplitPoint);
1137 useIntv(SegStart, SegStop);
1138 overlapIntv(SegStop, BI.LastInstr);
1143 //===----------------------------------------------------------------------===//
1144 // Global Live Range Splitting Support
1145 //===----------------------------------------------------------------------===//
1147 // These methods support a method of global live range splitting that uses a
1148 // global algorithm to decide intervals for CFG edges. They will insert split
1149 // points and color intervals in basic blocks while avoiding interference.
1151 // Note that splitSingleBlock is also useful for blocks where both CFG edges
1152 // are on the stack.
1154 void SplitEditor::splitLiveThroughBlock(unsigned MBBNum,
1155 unsigned IntvIn, SlotIndex LeaveBefore,
1156 unsigned IntvOut, SlotIndex EnterAfter){
1157 SlotIndex Start, Stop;
1158 std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(MBBNum);
1160 DEBUG(dbgs() << "BB#" << MBBNum << " [" << Start << ';' << Stop
1161 << ") intf " << LeaveBefore << '-' << EnterAfter
1162 << ", live-through " << IntvIn << " -> " << IntvOut);
1164 assert((IntvIn || IntvOut) && "Use splitSingleBlock for isolated blocks");
1166 assert((!LeaveBefore || LeaveBefore < Stop) && "Interference after block");
1167 assert((!IntvIn || !LeaveBefore || LeaveBefore > Start) && "Impossible intf");
1168 assert((!EnterAfter || EnterAfter >= Start) && "Interference before block");
1170 MachineBasicBlock *MBB = VRM.getMachineFunction().getBlockNumbered(MBBNum);
1173 DEBUG(dbgs() << ", spill on entry.\n");
1175 // <<<<<<<<< Possible LeaveBefore interference.
1176 // |-----------| Live through.
1177 // -____________ Spill on entry.
1180 SlotIndex Idx = leaveIntvAtTop(*MBB);
1181 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
1187 DEBUG(dbgs() << ", reload on exit.\n");
1189 // >>>>>>> Possible EnterAfter interference.
1190 // |-----------| Live through.
1191 // ___________-- Reload on exit.
1193 selectIntv(IntvOut);
1194 SlotIndex Idx = enterIntvAtEnd(*MBB);
1195 assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
1200 if (IntvIn == IntvOut && !LeaveBefore && !EnterAfter) {
1201 DEBUG(dbgs() << ", straight through.\n");
1203 // |-----------| Live through.
1204 // ------------- Straight through, same intv, no interference.
1206 selectIntv(IntvOut);
1207 useIntv(Start, Stop);
1211 // We cannot legally insert splits after LSP.
1212 SlotIndex LSP = SA.getLastSplitPoint(MBBNum);
1213 assert((!IntvOut || !EnterAfter || EnterAfter < LSP) && "Impossible intf");
1215 if (IntvIn != IntvOut && (!LeaveBefore || !EnterAfter ||
1216 LeaveBefore.getBaseIndex() > EnterAfter.getBoundaryIndex())) {
1217 DEBUG(dbgs() << ", switch avoiding interference.\n");
1219 // >>>> <<<< Non-overlapping EnterAfter/LeaveBefore interference.
1220 // |-----------| Live through.
1221 // ------======= Switch intervals between interference.
1223 selectIntv(IntvOut);
1225 if (LeaveBefore && LeaveBefore < LSP) {
1226 Idx = enterIntvBefore(LeaveBefore);
1229 Idx = enterIntvAtEnd(*MBB);
1232 useIntv(Start, Idx);
1233 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
1234 assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
1238 DEBUG(dbgs() << ", create local intv for interference.\n");
1240 // >>><><><><<<< Overlapping EnterAfter/LeaveBefore interference.
1241 // |-----------| Live through.
1242 // ==---------== Switch intervals before/after interference.
1244 assert(LeaveBefore <= EnterAfter && "Missed case");
1246 selectIntv(IntvOut);
1247 SlotIndex Idx = enterIntvAfter(EnterAfter);
1249 assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
1252 Idx = leaveIntvBefore(LeaveBefore);
1253 useIntv(Start, Idx);
1254 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
1258 void SplitEditor::splitRegInBlock(const SplitAnalysis::BlockInfo &BI,
1259 unsigned IntvIn, SlotIndex LeaveBefore) {
1260 SlotIndex Start, Stop;
1261 std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
1263 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " [" << Start << ';' << Stop
1264 << "), uses " << BI.FirstInstr << '-' << BI.LastInstr
1265 << ", reg-in " << IntvIn << ", leave before " << LeaveBefore
1266 << (BI.LiveOut ? ", stack-out" : ", killed in block"));
1268 assert(IntvIn && "Must have register in");
1269 assert(BI.LiveIn && "Must be live-in");
1270 assert((!LeaveBefore || LeaveBefore > Start) && "Bad interference");
1272 if (!BI.LiveOut && (!LeaveBefore || LeaveBefore >= BI.LastInstr)) {
1273 DEBUG(dbgs() << " before interference.\n");
1275 // <<< Interference after kill.
1276 // |---o---x | Killed in block.
1277 // ========= Use IntvIn everywhere.
1280 useIntv(Start, BI.LastInstr);
1284 SlotIndex LSP = SA.getLastSplitPoint(BI.MBB->getNumber());
1286 if (!LeaveBefore || LeaveBefore > BI.LastInstr.getBoundaryIndex()) {
1288 // <<< Possible interference after last use.
1289 // |---o---o---| Live-out on stack.
1290 // =========____ Leave IntvIn after last use.
1292 // < Interference after last use.
1293 // |---o---o--o| Live-out on stack, late last use.
1294 // ============ Copy to stack after LSP, overlap IntvIn.
1295 // \_____ Stack interval is live-out.
1297 if (BI.LastInstr < LSP) {
1298 DEBUG(dbgs() << ", spill after last use before interference.\n");
1300 SlotIndex Idx = leaveIntvAfter(BI.LastInstr);
1301 useIntv(Start, Idx);
1302 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
1304 DEBUG(dbgs() << ", spill before last split point.\n");
1306 SlotIndex Idx = leaveIntvBefore(LSP);
1307 overlapIntv(Idx, BI.LastInstr);
1308 useIntv(Start, Idx);
1309 assert((!LeaveBefore || Idx <= LeaveBefore) && "Interference");
1314 // The interference is overlapping somewhere we wanted to use IntvIn. That
1315 // means we need to create a local interval that can be allocated a
1316 // different register.
1317 unsigned LocalIntv = openIntv();
1319 DEBUG(dbgs() << ", creating local interval " << LocalIntv << ".\n");
1321 if (!BI.LiveOut || BI.LastInstr < LSP) {
1323 // <<<<<<< Interference overlapping uses.
1324 // |---o---o---| Live-out on stack.
1325 // =====----____ Leave IntvIn before interference, then spill.
1327 SlotIndex To = leaveIntvAfter(BI.LastInstr);
1328 SlotIndex From = enterIntvBefore(LeaveBefore);
1331 useIntv(Start, From);
1332 assert((!LeaveBefore || From <= LeaveBefore) && "Interference");
1336 // <<<<<<< Interference overlapping uses.
1337 // |---o---o--o| Live-out on stack, late last use.
1338 // =====------- Copy to stack before LSP, overlap LocalIntv.
1339 // \_____ Stack interval is live-out.
1341 SlotIndex To = leaveIntvBefore(LSP);
1342 overlapIntv(To, BI.LastInstr);
1343 SlotIndex From = enterIntvBefore(std::min(To, LeaveBefore));
1346 useIntv(Start, From);
1347 assert((!LeaveBefore || From <= LeaveBefore) && "Interference");
1350 void SplitEditor::splitRegOutBlock(const SplitAnalysis::BlockInfo &BI,
1351 unsigned IntvOut, SlotIndex EnterAfter) {
1352 SlotIndex Start, Stop;
1353 std::tie(Start, Stop) = LIS.getSlotIndexes()->getMBBRange(BI.MBB);
1355 DEBUG(dbgs() << "BB#" << BI.MBB->getNumber() << " [" << Start << ';' << Stop
1356 << "), uses " << BI.FirstInstr << '-' << BI.LastInstr
1357 << ", reg-out " << IntvOut << ", enter after " << EnterAfter
1358 << (BI.LiveIn ? ", stack-in" : ", defined in block"));
1360 SlotIndex LSP = SA.getLastSplitPoint(BI.MBB->getNumber());
1362 assert(IntvOut && "Must have register out");
1363 assert(BI.LiveOut && "Must be live-out");
1364 assert((!EnterAfter || EnterAfter < LSP) && "Bad interference");
1366 if (!BI.LiveIn && (!EnterAfter || EnterAfter <= BI.FirstInstr)) {
1367 DEBUG(dbgs() << " after interference.\n");
1369 // >>>> Interference before def.
1370 // | o---o---| Defined in block.
1371 // ========= Use IntvOut everywhere.
1373 selectIntv(IntvOut);
1374 useIntv(BI.FirstInstr, Stop);
1378 if (!EnterAfter || EnterAfter < BI.FirstInstr.getBaseIndex()) {
1379 DEBUG(dbgs() << ", reload after interference.\n");
1381 // >>>> Interference before def.
1382 // |---o---o---| Live-through, stack-in.
1383 // ____========= Enter IntvOut before first use.
1385 selectIntv(IntvOut);
1386 SlotIndex Idx = enterIntvBefore(std::min(LSP, BI.FirstInstr));
1388 assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
1392 // The interference is overlapping somewhere we wanted to use IntvOut. That
1393 // means we need to create a local interval that can be allocated a
1394 // different register.
1395 DEBUG(dbgs() << ", interference overlaps uses.\n");
1397 // >>>>>>> Interference overlapping uses.
1398 // |---o---o---| Live-through, stack-in.
1399 // ____---====== Create local interval for interference range.
1401 selectIntv(IntvOut);
1402 SlotIndex Idx = enterIntvAfter(EnterAfter);
1404 assert((!EnterAfter || Idx >= EnterAfter) && "Interference");
1407 SlotIndex From = enterIntvBefore(std::min(Idx, BI.FirstInstr));