1 //===- SplitKit.cpp - Toolkit for splitting live ranges -------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file contains the SplitAnalysis class as well as mutator functions for
10 // live range splitting.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/None.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/CodeGen/LiveRangeEdit.h"
20 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
21 #include "llvm/CodeGen/MachineDominators.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineLoopInfo.h"
25 #include "llvm/CodeGen/MachineOperand.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/TargetInstrInfo.h"
28 #include "llvm/CodeGen/TargetOpcodes.h"
29 #include "llvm/CodeGen/TargetRegisterInfo.h"
30 #include "llvm/CodeGen/TargetSubtargetInfo.h"
31 #include "llvm/CodeGen/VirtRegMap.h"
32 #include "llvm/Config/llvm-config.h"
33 #include "llvm/IR/DebugLoc.h"
34 #include "llvm/Support/Allocator.h"
35 #include "llvm/Support/BlockFrequency.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/raw_ostream.h"
47 #define DEBUG_TYPE "regalloc"
49 STATISTIC(NumFinished
, "Number of splits finished");
50 STATISTIC(NumSimple
, "Number of splits that were simple");
51 STATISTIC(NumCopies
, "Number of copies inserted for splitting");
52 STATISTIC(NumRemats
, "Number of rematerialized defs for splitting");
54 //===----------------------------------------------------------------------===//
55 // Last Insert Point Analysis
56 //===----------------------------------------------------------------------===//
58 InsertPointAnalysis::InsertPointAnalysis(const LiveIntervals
&lis
,
60 : LIS(lis
), LastInsertPoint(BBNum
) {}
63 InsertPointAnalysis::computeLastInsertPoint(const LiveInterval
&CurLI
,
64 const MachineBasicBlock
&MBB
) {
65 unsigned Num
= MBB
.getNumber();
66 std::pair
<SlotIndex
, SlotIndex
> &LIP
= LastInsertPoint
[Num
];
67 SlotIndex MBBEnd
= LIS
.getMBBEndIdx(&MBB
);
69 SmallVector
<const MachineBasicBlock
*, 1> ExceptionalSuccessors
;
70 bool EHPadSuccessor
= false;
71 for (const MachineBasicBlock
*SMBB
: MBB
.successors()) {
72 if (SMBB
->isEHPad()) {
73 ExceptionalSuccessors
.push_back(SMBB
);
74 EHPadSuccessor
= true;
75 } else if (SMBB
->isInlineAsmBrIndirectTarget())
76 ExceptionalSuccessors
.push_back(SMBB
);
79 // Compute insert points on the first call. The pair is independent of the
80 // current live interval.
81 if (!LIP
.first
.isValid()) {
82 MachineBasicBlock::const_iterator FirstTerm
= MBB
.getFirstTerminator();
83 if (FirstTerm
== MBB
.end())
86 LIP
.first
= LIS
.getInstructionIndex(*FirstTerm
);
88 // If there is a landing pad or inlineasm_br successor, also find the
89 // instruction. If there is no such instruction, we don't need to do
90 // anything special. We assume there cannot be multiple instructions that
91 // are Calls with EHPad successors or INLINEASM_BR in a block. Further, we
92 // assume that if there are any, they will be after any other call
93 // instructions in the block.
94 if (ExceptionalSuccessors
.empty())
96 for (const MachineInstr
&MI
: llvm::reverse(MBB
)) {
97 if ((EHPadSuccessor
&& MI
.isCall()) ||
98 MI
.getOpcode() == TargetOpcode::INLINEASM_BR
) {
99 LIP
.second
= LIS
.getInstructionIndex(MI
);
105 // If CurLI is live into a landing pad successor, move the last insert point
106 // back to the call that may throw.
110 if (none_of(ExceptionalSuccessors
, [&](const MachineBasicBlock
*EHPad
) {
111 return LIS
.isLiveInToMBB(CurLI
, EHPad
);
115 // Find the value leaving MBB.
116 const VNInfo
*VNI
= CurLI
.getVNInfoBefore(MBBEnd
);
120 // The def of statepoint instruction is a gc relocation and it should be alive
121 // in landing pad. So we cannot split interval after statepoint instruction.
122 if (SlotIndex::isSameInstr(VNI
->def
, LIP
.second
))
123 if (auto *I
= LIS
.getInstructionFromIndex(LIP
.second
))
124 if (I
->getOpcode() == TargetOpcode::STATEPOINT
)
127 // If the value leaving MBB was defined after the call in MBB, it can't
128 // really be live-in to the landing pad. This can happen if the landing pad
129 // has a PHI, and this register is undef on the exceptional edge.
130 // <rdar://problem/10664933>
131 if (!SlotIndex::isEarlierInstr(VNI
->def
, LIP
.second
) && VNI
->def
< MBBEnd
)
134 // Value is properly live-in to the landing pad.
135 // Only allow inserts before the call.
139 MachineBasicBlock::iterator
140 InsertPointAnalysis::getLastInsertPointIter(const LiveInterval
&CurLI
,
141 MachineBasicBlock
&MBB
) {
142 SlotIndex LIP
= getLastInsertPoint(CurLI
, MBB
);
143 if (LIP
== LIS
.getMBBEndIdx(&MBB
))
145 return LIS
.getInstructionFromIndex(LIP
);
148 //===----------------------------------------------------------------------===//
150 //===----------------------------------------------------------------------===//
152 SplitAnalysis::SplitAnalysis(const VirtRegMap
&vrm
, const LiveIntervals
&lis
,
153 const MachineLoopInfo
&mli
)
154 : MF(vrm
.getMachineFunction()), VRM(vrm
), LIS(lis
), Loops(mli
),
155 TII(*MF
.getSubtarget().getInstrInfo()), IPA(lis
, MF
.getNumBlockIDs()) {}
157 void SplitAnalysis::clear() {
160 ThroughBlocks
.clear();
164 /// analyzeUses - Count instructions, basic blocks, and loops using CurLI.
165 void SplitAnalysis::analyzeUses() {
166 assert(UseSlots
.empty() && "Call clear first");
168 // First get all the defs from the interval values. This provides the correct
169 // slots for early clobbers.
170 for (const VNInfo
*VNI
: CurLI
->valnos
)
171 if (!VNI
->isPHIDef() && !VNI
->isUnused())
172 UseSlots
.push_back(VNI
->def
);
174 // Get use slots form the use-def chain.
175 const MachineRegisterInfo
&MRI
= MF
.getRegInfo();
176 for (MachineOperand
&MO
: MRI
.use_nodbg_operands(CurLI
->reg()))
178 UseSlots
.push_back(LIS
.getInstructionIndex(*MO
.getParent()).getRegSlot());
180 array_pod_sort(UseSlots
.begin(), UseSlots
.end());
182 // Remove duplicates, keeping the smaller slot for each instruction.
183 // That is what we want for early clobbers.
184 UseSlots
.erase(std::unique(UseSlots
.begin(), UseSlots
.end(),
185 SlotIndex::isSameInstr
),
188 // Compute per-live block info.
191 LLVM_DEBUG(dbgs() << "Analyze counted " << UseSlots
.size() << " instrs in "
192 << UseBlocks
.size() << " blocks, through "
193 << NumThroughBlocks
<< " blocks.\n");
196 /// calcLiveBlockInfo - Fill the LiveBlocks array with information about blocks
197 /// where CurLI is live.
198 void SplitAnalysis::calcLiveBlockInfo() {
199 ThroughBlocks
.resize(MF
.getNumBlockIDs());
200 NumThroughBlocks
= NumGapBlocks
= 0;
204 LiveInterval::const_iterator LVI
= CurLI
->begin();
205 LiveInterval::const_iterator LVE
= CurLI
->end();
207 SmallVectorImpl
<SlotIndex
>::const_iterator UseI
, UseE
;
208 UseI
= UseSlots
.begin();
209 UseE
= UseSlots
.end();
211 // Loop over basic blocks where CurLI is live.
212 MachineFunction::iterator MFI
=
213 LIS
.getMBBFromIndex(LVI
->start
)->getIterator();
217 SlotIndex Start
, Stop
;
218 std::tie(Start
, Stop
) = LIS
.getSlotIndexes()->getMBBRange(BI
.MBB
);
220 // If the block contains no uses, the range must be live through. At one
221 // point, RegisterCoalescer could create dangling ranges that ended
223 if (UseI
== UseE
|| *UseI
>= Stop
) {
225 ThroughBlocks
.set(BI
.MBB
->getNumber());
226 // The range shouldn't end mid-block if there are no uses. This shouldn't
228 assert(LVI
->end
>= Stop
&& "range ends mid block with no uses");
230 // This block has uses. Find the first and last uses in the block.
231 BI
.FirstInstr
= *UseI
;
232 assert(BI
.FirstInstr
>= Start
);
234 while (UseI
!= UseE
&& *UseI
< Stop
);
235 BI
.LastInstr
= UseI
[-1];
236 assert(BI
.LastInstr
< Stop
);
238 // LVI is the first live segment overlapping MBB.
239 BI
.LiveIn
= LVI
->start
<= Start
;
241 // When not live in, the first use should be a def.
243 assert(LVI
->start
== LVI
->valno
->def
&& "Dangling Segment start");
244 assert(LVI
->start
== BI
.FirstInstr
&& "First instr should be a def");
245 BI
.FirstDef
= BI
.FirstInstr
;
248 // Look for gaps in the live range.
250 while (LVI
->end
< Stop
) {
251 SlotIndex LastStop
= LVI
->end
;
252 if (++LVI
== LVE
|| LVI
->start
>= Stop
) {
254 BI
.LastInstr
= LastStop
;
258 if (LastStop
< LVI
->start
) {
259 // There is a gap in the live range. Create duplicate entries for the
260 // live-in snippet and the live-out snippet.
263 // Push the Live-in part.
265 UseBlocks
.push_back(BI
);
266 UseBlocks
.back().LastInstr
= LastStop
;
268 // Set up BI for the live-out part.
271 BI
.FirstInstr
= BI
.FirstDef
= LVI
->start
;
274 // A Segment that starts in the middle of the block must be a def.
275 assert(LVI
->start
== LVI
->valno
->def
&& "Dangling Segment start");
277 BI
.FirstDef
= LVI
->start
;
280 UseBlocks
.push_back(BI
);
282 // LVI is now at LVE or LVI->end >= Stop.
287 // Live segment ends exactly at Stop. Move to the next segment.
288 if (LVI
->end
== Stop
&& ++LVI
== LVE
)
291 // Pick the next basic block.
292 if (LVI
->start
< Stop
)
295 MFI
= LIS
.getMBBFromIndex(LVI
->start
)->getIterator();
298 assert(getNumLiveBlocks() == countLiveBlocks(CurLI
) && "Bad block count");
301 unsigned SplitAnalysis::countLiveBlocks(const LiveInterval
*cli
) const {
304 LiveInterval
*li
= const_cast<LiveInterval
*>(cli
);
305 LiveInterval::iterator LVI
= li
->begin();
306 LiveInterval::iterator LVE
= li
->end();
309 // Loop over basic blocks where li is live.
310 MachineFunction::const_iterator MFI
=
311 LIS
.getMBBFromIndex(LVI
->start
)->getIterator();
312 SlotIndex Stop
= LIS
.getMBBEndIdx(&*MFI
);
315 LVI
= li
->advanceTo(LVI
, Stop
);
320 Stop
= LIS
.getMBBEndIdx(&*MFI
);
321 } while (Stop
<= LVI
->start
);
325 bool SplitAnalysis::isOriginalEndpoint(SlotIndex Idx
) const {
326 unsigned OrigReg
= VRM
.getOriginal(CurLI
->reg());
327 const LiveInterval
&Orig
= LIS
.getInterval(OrigReg
);
328 assert(!Orig
.empty() && "Splitting empty interval?");
329 LiveInterval::const_iterator I
= Orig
.find(Idx
);
331 // Range containing Idx should begin at Idx.
332 if (I
!= Orig
.end() && I
->start
<= Idx
)
333 return I
->start
== Idx
;
335 // Range does not contain Idx, previous must end at Idx.
336 return I
!= Orig
.begin() && (--I
)->end
== Idx
;
339 void SplitAnalysis::analyze(const LiveInterval
*li
) {
345 //===----------------------------------------------------------------------===//
347 //===----------------------------------------------------------------------===//
349 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
350 SplitEditor::SplitEditor(SplitAnalysis
&SA
, AliasAnalysis
&AA
,
351 LiveIntervals
&LIS
, VirtRegMap
&VRM
,
352 MachineDominatorTree
&MDT
,
353 MachineBlockFrequencyInfo
&MBFI
, VirtRegAuxInfo
&VRAI
)
354 : SA(SA
), AA(AA
), LIS(LIS
), VRM(VRM
),
355 MRI(VRM
.getMachineFunction().getRegInfo()), MDT(MDT
),
356 TII(*VRM
.getMachineFunction().getSubtarget().getInstrInfo()),
357 TRI(*VRM
.getMachineFunction().getSubtarget().getRegisterInfo()),
358 MBFI(MBFI
), VRAI(VRAI
), RegAssign(Allocator
) {}
360 void SplitEditor::reset(LiveRangeEdit
&LRE
, ComplementSpillMode SM
) {
367 // Reset the LiveIntervalCalc instances needed for this spill mode.
368 LICalc
[0].reset(&VRM
.getMachineFunction(), LIS
.getSlotIndexes(), &MDT
,
369 &LIS
.getVNInfoAllocator());
371 LICalc
[1].reset(&VRM
.getMachineFunction(), LIS
.getSlotIndexes(), &MDT
,
372 &LIS
.getVNInfoAllocator());
374 // We don't need an AliasAnalysis since we will only be performing
375 // cheap-as-a-copy remats anyway.
376 Edit
->anyRematerializable(nullptr);
379 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
380 LLVM_DUMP_METHOD
void SplitEditor::dump() const {
381 if (RegAssign
.empty()) {
382 dbgs() << " empty\n";
386 for (RegAssignMap::const_iterator I
= RegAssign
.begin(); I
.valid(); ++I
)
387 dbgs() << " [" << I
.start() << ';' << I
.stop() << "):" << I
.value();
392 /// Find a subrange corresponding to the exact lane mask @p LM in the live
393 /// interval @p LI. The interval @p LI is assumed to contain such a subrange.
394 /// This function is used to find corresponding subranges between the
395 /// original interval and the new intervals.
396 template <typename T
> auto &getSubrangeImpl(LaneBitmask LM
, T
&LI
) {
397 for (auto &S
: LI
.subranges())
398 if (S
.LaneMask
== LM
)
400 llvm_unreachable("SubRange for this mask not found");
403 LiveInterval::SubRange
&getSubRangeForMaskExact(LaneBitmask LM
,
405 return getSubrangeImpl(LM
, LI
);
408 const LiveInterval::SubRange
&getSubRangeForMaskExact(LaneBitmask LM
,
409 const LiveInterval
&LI
) {
410 return getSubrangeImpl(LM
, LI
);
413 /// Find a subrange corresponding to the lane mask @p LM, or a superset of it,
414 /// in the live interval @p LI. The interval @p LI is assumed to contain such
415 /// a subrange. This function is used to find corresponding subranges between
416 /// the original interval and the new intervals.
417 const LiveInterval::SubRange
&getSubRangeForMask(LaneBitmask LM
,
418 const LiveInterval
&LI
) {
419 for (const LiveInterval::SubRange
&S
: LI
.subranges())
420 if ((S
.LaneMask
& LM
) == LM
)
422 llvm_unreachable("SubRange for this mask not found");
425 void SplitEditor::addDeadDef(LiveInterval
&LI
, VNInfo
*VNI
, bool Original
) {
426 if (!LI
.hasSubRanges()) {
427 LI
.createDeadDef(VNI
);
431 SlotIndex Def
= VNI
->def
;
433 // If we are transferring a def from the original interval, make sure
434 // to only update the subranges for which the original subranges had
435 // a def at this location.
436 for (LiveInterval::SubRange
&S
: LI
.subranges()) {
437 auto &PS
= getSubRangeForMask(S
.LaneMask
, Edit
->getParent());
438 VNInfo
*PV
= PS
.getVNInfoAt(Def
);
439 if (PV
!= nullptr && PV
->def
== Def
)
440 S
.createDeadDef(Def
, LIS
.getVNInfoAllocator());
443 // This is a new def: either from rematerialization, or from an inserted
444 // copy. Since rematerialization can regenerate a definition of a sub-
445 // register, we need to check which subranges need to be updated.
446 const MachineInstr
*DefMI
= LIS
.getInstructionFromIndex(Def
);
447 assert(DefMI
!= nullptr);
449 for (const MachineOperand
&DefOp
: DefMI
->defs()) {
450 Register R
= DefOp
.getReg();
453 if (unsigned SR
= DefOp
.getSubReg())
454 LM
|= TRI
.getSubRegIndexLaneMask(SR
);
456 LM
= MRI
.getMaxLaneMaskForVReg(R
);
460 for (LiveInterval::SubRange
&S
: LI
.subranges())
461 if ((S
.LaneMask
& LM
).any())
462 S
.createDeadDef(Def
, LIS
.getVNInfoAllocator());
466 VNInfo
*SplitEditor::defValue(unsigned RegIdx
,
467 const VNInfo
*ParentVNI
,
470 assert(ParentVNI
&& "Mapping NULL value");
471 assert(Idx
.isValid() && "Invalid SlotIndex");
472 assert(Edit
->getParent().getVNInfoAt(Idx
) == ParentVNI
&& "Bad Parent VNI");
473 LiveInterval
*LI
= &LIS
.getInterval(Edit
->get(RegIdx
));
475 // Create a new value.
476 VNInfo
*VNI
= LI
->getNextValue(Idx
, LIS
.getVNInfoAllocator());
478 bool Force
= LI
->hasSubRanges();
479 ValueForcePair
FP(Force
? nullptr : VNI
, Force
);
480 // Use insert for lookup, so we can add missing values with a second lookup.
481 std::pair
<ValueMap::iterator
, bool> InsP
=
482 Values
.insert(std::make_pair(std::make_pair(RegIdx
, ParentVNI
->id
), FP
));
484 // This was the first time (RegIdx, ParentVNI) was mapped, and it is not
485 // forced. Keep it as a simple def without any liveness.
486 if (!Force
&& InsP
.second
)
489 // If the previous value was a simple mapping, add liveness for it now.
490 if (VNInfo
*OldVNI
= InsP
.first
->second
.getPointer()) {
491 addDeadDef(*LI
, OldVNI
, Original
);
493 // No longer a simple mapping. Switch to a complex mapping. If the
494 // interval has subranges, make it a forced mapping.
495 InsP
.first
->second
= ValueForcePair(nullptr, Force
);
498 // This is a complex mapping, add liveness for VNI
499 addDeadDef(*LI
, VNI
, Original
);
503 void SplitEditor::forceRecompute(unsigned RegIdx
, const VNInfo
&ParentVNI
) {
504 ValueForcePair
&VFP
= Values
[std::make_pair(RegIdx
, ParentVNI
.id
)];
505 VNInfo
*VNI
= VFP
.getPointer();
507 // ParentVNI was either unmapped or already complex mapped. Either way, just
508 // set the force bit.
514 // This was previously a single mapping. Make sure the old def is represented
515 // by a trivial live range.
516 addDeadDef(LIS
.getInterval(Edit
->get(RegIdx
)), VNI
, false);
518 // Mark as complex mapped, forced.
519 VFP
= ValueForcePair(nullptr, true);
522 SlotIndex
SplitEditor::buildSingleSubRegCopy(Register FromReg
, Register ToReg
,
523 MachineBasicBlock
&MBB
, MachineBasicBlock::iterator InsertBefore
,
524 unsigned SubIdx
, LiveInterval
&DestLI
, bool Late
, SlotIndex Def
) {
525 const MCInstrDesc
&Desc
= TII
.get(TargetOpcode::COPY
);
526 bool FirstCopy
= !Def
.isValid();
527 MachineInstr
*CopyMI
= BuildMI(MBB
, InsertBefore
, DebugLoc(), Desc
)
528 .addReg(ToReg
, RegState::Define
| getUndefRegState(FirstCopy
)
529 | getInternalReadRegState(!FirstCopy
), SubIdx
)
530 .addReg(FromReg
, 0, SubIdx
);
532 SlotIndexes
&Indexes
= *LIS
.getSlotIndexes();
534 Def
= Indexes
.insertMachineInstrInMaps(*CopyMI
, Late
).getRegSlot();
536 CopyMI
->bundleWithPred();
541 SlotIndex
SplitEditor::buildCopy(Register FromReg
, Register ToReg
,
542 LaneBitmask LaneMask
, MachineBasicBlock
&MBB
,
543 MachineBasicBlock::iterator InsertBefore
, bool Late
, unsigned RegIdx
) {
544 const MCInstrDesc
&Desc
= TII
.get(TargetOpcode::COPY
);
545 SlotIndexes
&Indexes
= *LIS
.getSlotIndexes();
546 if (LaneMask
.all() || LaneMask
== MRI
.getMaxLaneMaskForVReg(FromReg
)) {
547 // The full vreg is copied.
548 MachineInstr
*CopyMI
=
549 BuildMI(MBB
, InsertBefore
, DebugLoc(), Desc
, ToReg
).addReg(FromReg
);
550 return Indexes
.insertMachineInstrInMaps(*CopyMI
, Late
).getRegSlot();
553 // Only a subset of lanes needs to be copied. The following is a simple
554 // heuristic to construct a sequence of COPYs. We could add a target
555 // specific callback if this turns out to be suboptimal.
556 LiveInterval
&DestLI
= LIS
.getInterval(Edit
->get(RegIdx
));
558 // First pass: Try to find a perfectly matching subregister index. If none
559 // exists find the one covering the most lanemask bits.
560 const TargetRegisterClass
*RC
= MRI
.getRegClass(FromReg
);
561 assert(RC
== MRI
.getRegClass(ToReg
) && "Should have same reg class");
563 SmallVector
<unsigned, 8> SubIndexes
;
565 // Abort if we cannot possibly implement the COPY with the given indexes.
566 if (!TRI
.getCoveringSubRegIndexes(MRI
, RC
, LaneMask
, SubIndexes
))
567 report_fatal_error("Impossible to implement partial COPY");
570 for (unsigned BestIdx
: SubIndexes
) {
571 Def
= buildSingleSubRegCopy(FromReg
, ToReg
, MBB
, InsertBefore
, BestIdx
,
575 BumpPtrAllocator
&Allocator
= LIS
.getVNInfoAllocator();
576 DestLI
.refineSubRanges(
578 [Def
, &Allocator
](LiveInterval::SubRange
&SR
) {
579 SR
.createDeadDef(Def
, Allocator
);
586 VNInfo
*SplitEditor::defFromParent(unsigned RegIdx
, const VNInfo
*ParentVNI
,
587 SlotIndex UseIdx
, MachineBasicBlock
&MBB
,
588 MachineBasicBlock::iterator I
) {
590 LiveInterval
*LI
= &LIS
.getInterval(Edit
->get(RegIdx
));
592 // We may be trying to avoid interference that ends at a deleted instruction,
593 // so always begin RegIdx 0 early and all others late.
594 bool Late
= RegIdx
!= 0;
596 // Attempt cheap-as-a-copy rematerialization.
597 unsigned Original
= VRM
.getOriginal(Edit
->get(RegIdx
));
598 LiveInterval
&OrigLI
= LIS
.getInterval(Original
);
599 VNInfo
*OrigVNI
= OrigLI
.getVNInfoAt(UseIdx
);
601 Register Reg
= LI
->reg();
602 bool DidRemat
= false;
604 LiveRangeEdit::Remat
RM(ParentVNI
);
605 RM
.OrigMI
= LIS
.getInstructionFromIndex(OrigVNI
->def
);
606 if (Edit
->canRematerializeAt(RM
, OrigVNI
, UseIdx
, true)) {
607 Def
= Edit
->rematerializeAt(MBB
, I
, Reg
, RM
, TRI
, Late
);
613 LaneBitmask LaneMask
;
614 if (OrigLI
.hasSubRanges()) {
615 LaneMask
= LaneBitmask::getNone();
616 for (LiveInterval::SubRange
&S
: OrigLI
.subranges()) {
617 if (S
.liveAt(UseIdx
))
618 LaneMask
|= S
.LaneMask
;
621 LaneMask
= LaneBitmask::getAll();
624 if (LaneMask
.none()) {
625 const MCInstrDesc
&Desc
= TII
.get(TargetOpcode::IMPLICIT_DEF
);
626 MachineInstr
*ImplicitDef
= BuildMI(MBB
, I
, DebugLoc(), Desc
, Reg
);
627 SlotIndexes
&Indexes
= *LIS
.getSlotIndexes();
628 Def
= Indexes
.insertMachineInstrInMaps(*ImplicitDef
, Late
).getRegSlot();
631 Def
= buildCopy(Edit
->getReg(), Reg
, LaneMask
, MBB
, I
, Late
, RegIdx
);
635 // Define the value in Reg.
636 return defValue(RegIdx
, ParentVNI
, Def
, false);
639 /// Create a new virtual register and live interval.
640 unsigned SplitEditor::openIntv() {
641 // Create the complement as index 0.
643 Edit
->createEmptyInterval();
645 // Create the open interval.
646 OpenIdx
= Edit
->size();
647 Edit
->createEmptyInterval();
651 void SplitEditor::selectIntv(unsigned Idx
) {
652 assert(Idx
!= 0 && "Cannot select the complement interval");
653 assert(Idx
< Edit
->size() && "Can only select previously opened interval");
654 LLVM_DEBUG(dbgs() << " selectIntv " << OpenIdx
<< " -> " << Idx
<< '\n');
658 SlotIndex
SplitEditor::enterIntvBefore(SlotIndex Idx
) {
659 assert(OpenIdx
&& "openIntv not called before enterIntvBefore");
660 LLVM_DEBUG(dbgs() << " enterIntvBefore " << Idx
);
661 Idx
= Idx
.getBaseIndex();
662 VNInfo
*ParentVNI
= Edit
->getParent().getVNInfoAt(Idx
);
664 LLVM_DEBUG(dbgs() << ": not live\n");
667 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI
->id
<< '\n');
668 MachineInstr
*MI
= LIS
.getInstructionFromIndex(Idx
);
669 assert(MI
&& "enterIntvBefore called with invalid index");
671 VNInfo
*VNI
= defFromParent(OpenIdx
, ParentVNI
, Idx
, *MI
->getParent(), MI
);
675 SlotIndex
SplitEditor::enterIntvAfter(SlotIndex Idx
) {
676 assert(OpenIdx
&& "openIntv not called before enterIntvAfter");
677 LLVM_DEBUG(dbgs() << " enterIntvAfter " << Idx
);
678 Idx
= Idx
.getBoundaryIndex();
679 VNInfo
*ParentVNI
= Edit
->getParent().getVNInfoAt(Idx
);
681 LLVM_DEBUG(dbgs() << ": not live\n");
684 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI
->id
<< '\n');
685 MachineInstr
*MI
= LIS
.getInstructionFromIndex(Idx
);
686 assert(MI
&& "enterIntvAfter called with invalid index");
688 VNInfo
*VNI
= defFromParent(OpenIdx
, ParentVNI
, Idx
, *MI
->getParent(),
689 std::next(MachineBasicBlock::iterator(MI
)));
693 SlotIndex
SplitEditor::enterIntvAtEnd(MachineBasicBlock
&MBB
) {
694 assert(OpenIdx
&& "openIntv not called before enterIntvAtEnd");
695 SlotIndex End
= LIS
.getMBBEndIdx(&MBB
);
696 SlotIndex Last
= End
.getPrevSlot();
697 LLVM_DEBUG(dbgs() << " enterIntvAtEnd " << printMBBReference(MBB
) << ", "
699 VNInfo
*ParentVNI
= Edit
->getParent().getVNInfoAt(Last
);
701 LLVM_DEBUG(dbgs() << ": not live\n");
704 SlotIndex LSP
= SA
.getLastSplitPoint(&MBB
);
706 // It could be that the use after LSP is a def, and thus the ParentVNI
707 // just selected starts at that def. For this case to exist, the def
708 // must be part of a tied def/use pair (as otherwise we'd have split
709 // distinct live ranges into individual live intervals), and thus we
710 // can insert the def into the VNI of the use and the tied def/use
711 // pair can live in the resulting interval.
713 ParentVNI
= Edit
->getParent().getVNInfoAt(Last
);
715 // undef use --> undef tied def
716 LLVM_DEBUG(dbgs() << ": tied use not live\n");
721 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI
->id
);
722 VNInfo
*VNI
= defFromParent(OpenIdx
, ParentVNI
, Last
, MBB
,
723 SA
.getLastSplitPointIter(&MBB
));
724 RegAssign
.insert(VNI
->def
, End
, OpenIdx
);
729 /// useIntv - indicate that all instructions in MBB should use OpenLI.
730 void SplitEditor::useIntv(const MachineBasicBlock
&MBB
) {
731 useIntv(LIS
.getMBBStartIdx(&MBB
), LIS
.getMBBEndIdx(&MBB
));
734 void SplitEditor::useIntv(SlotIndex Start
, SlotIndex End
) {
735 assert(OpenIdx
&& "openIntv not called before useIntv");
736 LLVM_DEBUG(dbgs() << " useIntv [" << Start
<< ';' << End
<< "):");
737 RegAssign
.insert(Start
, End
, OpenIdx
);
741 SlotIndex
SplitEditor::leaveIntvAfter(SlotIndex Idx
) {
742 assert(OpenIdx
&& "openIntv not called before leaveIntvAfter");
743 LLVM_DEBUG(dbgs() << " leaveIntvAfter " << Idx
);
745 // The interval must be live beyond the instruction at Idx.
746 SlotIndex Boundary
= Idx
.getBoundaryIndex();
747 VNInfo
*ParentVNI
= Edit
->getParent().getVNInfoAt(Boundary
);
749 LLVM_DEBUG(dbgs() << ": not live\n");
750 return Boundary
.getNextSlot();
752 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI
->id
<< '\n');
753 MachineInstr
*MI
= LIS
.getInstructionFromIndex(Boundary
);
754 assert(MI
&& "No instruction at index");
756 // In spill mode, make live ranges as short as possible by inserting the copy
757 // before MI. This is only possible if that instruction doesn't redefine the
758 // value. The inserted COPY is not a kill, and we don't need to recompute
759 // the source live range. The spiller also won't try to hoist this copy.
760 if (SpillMode
&& !SlotIndex::isSameInstr(ParentVNI
->def
, Idx
) &&
761 MI
->readsVirtualRegister(Edit
->getReg())) {
762 forceRecompute(0, *ParentVNI
);
763 defFromParent(0, ParentVNI
, Idx
, *MI
->getParent(), MI
);
767 VNInfo
*VNI
= defFromParent(0, ParentVNI
, Boundary
, *MI
->getParent(),
768 std::next(MachineBasicBlock::iterator(MI
)));
772 SlotIndex
SplitEditor::leaveIntvBefore(SlotIndex Idx
) {
773 assert(OpenIdx
&& "openIntv not called before leaveIntvBefore");
774 LLVM_DEBUG(dbgs() << " leaveIntvBefore " << Idx
);
776 // The interval must be live into the instruction at Idx.
777 Idx
= Idx
.getBaseIndex();
778 VNInfo
*ParentVNI
= Edit
->getParent().getVNInfoAt(Idx
);
780 LLVM_DEBUG(dbgs() << ": not live\n");
781 return Idx
.getNextSlot();
783 LLVM_DEBUG(dbgs() << ": valno " << ParentVNI
->id
<< '\n');
785 MachineInstr
*MI
= LIS
.getInstructionFromIndex(Idx
);
786 assert(MI
&& "No instruction at index");
787 VNInfo
*VNI
= defFromParent(0, ParentVNI
, Idx
, *MI
->getParent(), MI
);
791 SlotIndex
SplitEditor::leaveIntvAtTop(MachineBasicBlock
&MBB
) {
792 assert(OpenIdx
&& "openIntv not called before leaveIntvAtTop");
793 SlotIndex Start
= LIS
.getMBBStartIdx(&MBB
);
794 LLVM_DEBUG(dbgs() << " leaveIntvAtTop " << printMBBReference(MBB
) << ", "
797 VNInfo
*ParentVNI
= Edit
->getParent().getVNInfoAt(Start
);
799 LLVM_DEBUG(dbgs() << ": not live\n");
803 VNInfo
*VNI
= defFromParent(0, ParentVNI
, Start
, MBB
,
804 MBB
.SkipPHIsLabelsAndDebug(MBB
.begin()));
805 RegAssign
.insert(Start
, VNI
->def
, OpenIdx
);
810 static bool hasTiedUseOf(MachineInstr
&MI
, unsigned Reg
) {
811 return any_of(MI
.defs(), [Reg
](const MachineOperand
&MO
) {
812 return MO
.isReg() && MO
.isTied() && MO
.getReg() == Reg
;
816 void SplitEditor::overlapIntv(SlotIndex Start
, SlotIndex End
) {
817 assert(OpenIdx
&& "openIntv not called before overlapIntv");
818 const VNInfo
*ParentVNI
= Edit
->getParent().getVNInfoAt(Start
);
819 assert(ParentVNI
== Edit
->getParent().getVNInfoBefore(End
) &&
820 "Parent changes value in extended range");
821 assert(LIS
.getMBBFromIndex(Start
) == LIS
.getMBBFromIndex(End
) &&
822 "Range cannot span basic blocks");
824 // The complement interval will be extended as needed by LICalc.extend().
826 forceRecompute(0, *ParentVNI
);
828 // If the last use is tied to a def, we can't mark it as live for the
829 // interval which includes only the use. That would cause the tied pair
830 // to end up in two different intervals.
831 if (auto *MI
= LIS
.getInstructionFromIndex(End
))
832 if (hasTiedUseOf(*MI
, Edit
->getReg())) {
833 LLVM_DEBUG(dbgs() << "skip overlap due to tied def at end\n");
837 LLVM_DEBUG(dbgs() << " overlapIntv [" << Start
<< ';' << End
<< "):");
838 RegAssign
.insert(Start
, End
, OpenIdx
);
842 //===----------------------------------------------------------------------===//
844 //===----------------------------------------------------------------------===//
846 void SplitEditor::removeBackCopies(SmallVectorImpl
<VNInfo
*> &Copies
) {
847 LiveInterval
*LI
= &LIS
.getInterval(Edit
->get(0));
848 LLVM_DEBUG(dbgs() << "Removing " << Copies
.size() << " back-copies.\n");
849 RegAssignMap::iterator AssignI
;
850 AssignI
.setMap(RegAssign
);
852 for (const VNInfo
*C
: Copies
) {
853 SlotIndex Def
= C
->def
;
854 MachineInstr
*MI
= LIS
.getInstructionFromIndex(Def
);
855 assert(MI
&& "No instruction for back-copy");
857 MachineBasicBlock
*MBB
= MI
->getParent();
858 MachineBasicBlock::iterator
MBBI(MI
);
860 do AtBegin
= MBBI
== MBB
->begin();
861 while (!AtBegin
&& (--MBBI
)->isDebugOrPseudoInstr());
863 LLVM_DEBUG(dbgs() << "Removing " << Def
<< '\t' << *MI
);
864 LIS
.removeVRegDefAt(*LI
, Def
);
865 LIS
.RemoveMachineInstrFromMaps(*MI
);
866 MI
->eraseFromParent();
868 // Adjust RegAssign if a register assignment is killed at Def. We want to
869 // avoid calculating the live range of the source register if possible.
870 AssignI
.find(Def
.getPrevSlot());
871 if (!AssignI
.valid() || AssignI
.start() >= Def
)
873 // If MI doesn't kill the assigned register, just leave it.
874 if (AssignI
.stop() != Def
)
876 unsigned RegIdx
= AssignI
.value();
877 // We could hoist back-copy right after another back-copy. As a result
878 // MMBI points to copy instruction which is actually dead now.
879 // We cannot set its stop to MBBI which will be the same as start and
880 // interval does not support that.
882 AtBegin
? SlotIndex() : LIS
.getInstructionIndex(*MBBI
).getRegSlot();
883 if (AtBegin
|| !MBBI
->readsVirtualRegister(Edit
->getReg()) ||
884 Kill
<= AssignI
.start()) {
885 LLVM_DEBUG(dbgs() << " cannot find simple kill of RegIdx " << RegIdx
887 forceRecompute(RegIdx
, *Edit
->getParent().getVNInfoAt(Def
));
889 LLVM_DEBUG(dbgs() << " move kill to " << Kill
<< '\t' << *MBBI
);
890 AssignI
.setStop(Kill
);
896 SplitEditor::findShallowDominator(MachineBasicBlock
*MBB
,
897 MachineBasicBlock
*DefMBB
) {
900 assert(MDT
.dominates(DefMBB
, MBB
) && "MBB must be dominated by the def.");
902 const MachineLoopInfo
&Loops
= SA
.Loops
;
903 const MachineLoop
*DefLoop
= Loops
.getLoopFor(DefMBB
);
904 MachineDomTreeNode
*DefDomNode
= MDT
[DefMBB
];
906 // Best candidate so far.
907 MachineBasicBlock
*BestMBB
= MBB
;
908 unsigned BestDepth
= std::numeric_limits
<unsigned>::max();
911 const MachineLoop
*Loop
= Loops
.getLoopFor(MBB
);
913 // MBB isn't in a loop, it doesn't get any better. All dominators have a
914 // higher frequency by definition.
916 LLVM_DEBUG(dbgs() << "Def in " << printMBBReference(*DefMBB
)
917 << " dominates " << printMBBReference(*MBB
)
922 // We'll never be able to exit the DefLoop.
923 if (Loop
== DefLoop
) {
924 LLVM_DEBUG(dbgs() << "Def in " << printMBBReference(*DefMBB
)
925 << " dominates " << printMBBReference(*MBB
)
926 << " in the same loop\n");
930 // Least busy dominator seen so far.
931 unsigned Depth
= Loop
->getLoopDepth();
932 if (Depth
< BestDepth
) {
935 LLVM_DEBUG(dbgs() << "Def in " << printMBBReference(*DefMBB
)
936 << " dominates " << printMBBReference(*MBB
)
937 << " at depth " << Depth
<< '\n');
940 // Leave loop by going to the immediate dominator of the loop header.
941 // This is a bigger stride than simply walking up the dominator tree.
942 MachineDomTreeNode
*IDom
= MDT
[Loop
->getHeader()]->getIDom();
944 // Too far up the dominator tree?
945 if (!IDom
|| !MDT
.dominates(DefDomNode
, IDom
))
948 MBB
= IDom
->getBlock();
952 void SplitEditor::computeRedundantBackCopies(
953 DenseSet
<unsigned> &NotToHoistSet
, SmallVectorImpl
<VNInfo
*> &BackCopies
) {
954 LiveInterval
*LI
= &LIS
.getInterval(Edit
->get(0));
955 const LiveInterval
*Parent
= &Edit
->getParent();
956 SmallVector
<SmallPtrSet
<VNInfo
*, 8>, 8> EqualVNs(Parent
->getNumValNums());
957 SmallPtrSet
<VNInfo
*, 8> DominatedVNIs
;
959 // Aggregate VNIs having the same value as ParentVNI.
960 for (VNInfo
*VNI
: LI
->valnos
) {
963 VNInfo
*ParentVNI
= Edit
->getParent().getVNInfoAt(VNI
->def
);
964 EqualVNs
[ParentVNI
->id
].insert(VNI
);
967 // For VNI aggregation of each ParentVNI, collect dominated, i.e.,
968 // redundant VNIs to BackCopies.
969 for (unsigned i
= 0, e
= Parent
->getNumValNums(); i
!= e
; ++i
) {
970 const VNInfo
*ParentVNI
= Parent
->getValNumInfo(i
);
971 if (!NotToHoistSet
.count(ParentVNI
->id
))
973 SmallPtrSetIterator
<VNInfo
*> It1
= EqualVNs
[ParentVNI
->id
].begin();
974 SmallPtrSetIterator
<VNInfo
*> It2
= It1
;
975 for (; It1
!= EqualVNs
[ParentVNI
->id
].end(); ++It1
) {
977 for (++It2
; It2
!= EqualVNs
[ParentVNI
->id
].end(); ++It2
) {
978 if (DominatedVNIs
.count(*It1
) || DominatedVNIs
.count(*It2
))
981 MachineBasicBlock
*MBB1
= LIS
.getMBBFromIndex((*It1
)->def
);
982 MachineBasicBlock
*MBB2
= LIS
.getMBBFromIndex((*It2
)->def
);
984 DominatedVNIs
.insert((*It1
)->def
< (*It2
)->def
? (*It2
) : (*It1
));
985 } else if (MDT
.dominates(MBB1
, MBB2
)) {
986 DominatedVNIs
.insert(*It2
);
987 } else if (MDT
.dominates(MBB2
, MBB1
)) {
988 DominatedVNIs
.insert(*It1
);
992 if (!DominatedVNIs
.empty()) {
993 forceRecompute(0, *ParentVNI
);
994 append_range(BackCopies
, DominatedVNIs
);
995 DominatedVNIs
.clear();
1000 /// For SM_Size mode, find a common dominator for all the back-copies for
1001 /// the same ParentVNI and hoist the backcopies to the dominator BB.
1002 /// For SM_Speed mode, if the common dominator is hot and it is not beneficial
1003 /// to do the hoisting, simply remove the dominated backcopies for the same
1005 void SplitEditor::hoistCopies() {
1006 // Get the complement interval, always RegIdx 0.
1007 LiveInterval
*LI
= &LIS
.getInterval(Edit
->get(0));
1008 const LiveInterval
*Parent
= &Edit
->getParent();
1010 // Track the nearest common dominator for all back-copies for each ParentVNI,
1011 // indexed by ParentVNI->id.
1012 using DomPair
= std::pair
<MachineBasicBlock
*, SlotIndex
>;
1013 SmallVector
<DomPair
, 8> NearestDom(Parent
->getNumValNums());
1014 // The total cost of all the back-copies for each ParentVNI.
1015 SmallVector
<BlockFrequency
, 8> Costs(Parent
->getNumValNums());
1016 // The ParentVNI->id set for which hoisting back-copies are not beneficial
1018 DenseSet
<unsigned> NotToHoistSet
;
1020 // Find the nearest common dominator for parent values with multiple
1021 // back-copies. If a single back-copy dominates, put it in DomPair.second.
1022 for (VNInfo
*VNI
: LI
->valnos
) {
1023 if (VNI
->isUnused())
1025 VNInfo
*ParentVNI
= Edit
->getParent().getVNInfoAt(VNI
->def
);
1026 assert(ParentVNI
&& "Parent not live at complement def");
1028 // Don't hoist remats. The complement is probably going to disappear
1029 // completely anyway.
1030 if (Edit
->didRematerialize(ParentVNI
))
1033 MachineBasicBlock
*ValMBB
= LIS
.getMBBFromIndex(VNI
->def
);
1035 DomPair
&Dom
= NearestDom
[ParentVNI
->id
];
1037 // Keep directly defined parent values. This is either a PHI or an
1038 // instruction in the complement range. All other copies of ParentVNI
1039 // should be eliminated.
1040 if (VNI
->def
== ParentVNI
->def
) {
1041 LLVM_DEBUG(dbgs() << "Direct complement def at " << VNI
->def
<< '\n');
1042 Dom
= DomPair(ValMBB
, VNI
->def
);
1045 // Skip the singly mapped values. There is nothing to gain from hoisting a
1046 // single back-copy.
1047 if (Values
.lookup(std::make_pair(0, ParentVNI
->id
)).getPointer()) {
1048 LLVM_DEBUG(dbgs() << "Single complement def at " << VNI
->def
<< '\n');
1053 // First time we see ParentVNI. VNI dominates itself.
1054 Dom
= DomPair(ValMBB
, VNI
->def
);
1055 } else if (Dom
.first
== ValMBB
) {
1056 // Two defs in the same block. Pick the earlier def.
1057 if (!Dom
.second
.isValid() || VNI
->def
< Dom
.second
)
1058 Dom
.second
= VNI
->def
;
1060 // Different basic blocks. Check if one dominates.
1061 MachineBasicBlock
*Near
=
1062 MDT
.findNearestCommonDominator(Dom
.first
, ValMBB
);
1064 // Def ValMBB dominates.
1065 Dom
= DomPair(ValMBB
, VNI
->def
);
1066 else if (Near
!= Dom
.first
)
1067 // None dominate. Hoist to common dominator, need new def.
1068 Dom
= DomPair(Near
, SlotIndex());
1069 Costs
[ParentVNI
->id
] += MBFI
.getBlockFreq(ValMBB
);
1072 LLVM_DEBUG(dbgs() << "Multi-mapped complement " << VNI
->id
<< '@'
1073 << VNI
->def
<< " for parent " << ParentVNI
->id
<< '@'
1074 << ParentVNI
->def
<< " hoist to "
1075 << printMBBReference(*Dom
.first
) << ' ' << Dom
.second
1079 // Insert the hoisted copies.
1080 for (unsigned i
= 0, e
= Parent
->getNumValNums(); i
!= e
; ++i
) {
1081 DomPair
&Dom
= NearestDom
[i
];
1082 if (!Dom
.first
|| Dom
.second
.isValid())
1084 // This value needs a hoisted copy inserted at the end of Dom.first.
1085 const VNInfo
*ParentVNI
= Parent
->getValNumInfo(i
);
1086 MachineBasicBlock
*DefMBB
= LIS
.getMBBFromIndex(ParentVNI
->def
);
1087 // Get a less loopy dominator than Dom.first.
1088 Dom
.first
= findShallowDominator(Dom
.first
, DefMBB
);
1089 if (SpillMode
== SM_Speed
&&
1090 MBFI
.getBlockFreq(Dom
.first
) > Costs
[ParentVNI
->id
]) {
1091 NotToHoistSet
.insert(ParentVNI
->id
);
1094 SlotIndex LSP
= SA
.getLastSplitPoint(Dom
.first
);
1095 if (LSP
<= ParentVNI
->def
) {
1096 NotToHoistSet
.insert(ParentVNI
->id
);
1099 Dom
.second
= defFromParent(0, ParentVNI
, LSP
, *Dom
.first
,
1100 SA
.getLastSplitPointIter(Dom
.first
))->def
;
1103 // Remove redundant back-copies that are now known to be dominated by another
1104 // def with the same value.
1105 SmallVector
<VNInfo
*, 8> BackCopies
;
1106 for (VNInfo
*VNI
: LI
->valnos
) {
1107 if (VNI
->isUnused())
1109 VNInfo
*ParentVNI
= Edit
->getParent().getVNInfoAt(VNI
->def
);
1110 const DomPair
&Dom
= NearestDom
[ParentVNI
->id
];
1111 if (!Dom
.first
|| Dom
.second
== VNI
->def
||
1112 NotToHoistSet
.count(ParentVNI
->id
))
1114 BackCopies
.push_back(VNI
);
1115 forceRecompute(0, *ParentVNI
);
1118 // If it is not beneficial to hoist all the BackCopies, simply remove
1119 // redundant BackCopies in speed mode.
1120 if (SpillMode
== SM_Speed
&& !NotToHoistSet
.empty())
1121 computeRedundantBackCopies(NotToHoistSet
, BackCopies
);
1123 removeBackCopies(BackCopies
);
1126 /// transferValues - Transfer all possible values to the new live ranges.
1127 /// Values that were rematerialized are left alone, they need LICalc.extend().
1128 bool SplitEditor::transferValues() {
1129 bool Skipped
= false;
1130 RegAssignMap::const_iterator AssignI
= RegAssign
.begin();
1131 for (const LiveRange::Segment
&S
: Edit
->getParent()) {
1132 LLVM_DEBUG(dbgs() << " blit " << S
<< ':');
1133 VNInfo
*ParentVNI
= S
.valno
;
1134 // RegAssign has holes where RegIdx 0 should be used.
1135 SlotIndex Start
= S
.start
;
1136 AssignI
.advanceTo(Start
);
1139 SlotIndex End
= S
.end
;
1140 if (!AssignI
.valid()) {
1142 } else if (AssignI
.start() <= Start
) {
1143 RegIdx
= AssignI
.value();
1144 if (AssignI
.stop() < End
) {
1145 End
= AssignI
.stop();
1150 End
= std::min(End
, AssignI
.start());
1153 // The interval [Start;End) is continuously mapped to RegIdx, ParentVNI.
1154 LLVM_DEBUG(dbgs() << " [" << Start
<< ';' << End
<< ")=" << RegIdx
<< '('
1155 << printReg(Edit
->get(RegIdx
)) << ')');
1156 LiveInterval
&LI
= LIS
.getInterval(Edit
->get(RegIdx
));
1158 // Check for a simply defined value that can be blitted directly.
1159 ValueForcePair VFP
= Values
.lookup(std::make_pair(RegIdx
, ParentVNI
->id
));
1160 if (VNInfo
*VNI
= VFP
.getPointer()) {
1161 LLVM_DEBUG(dbgs() << ':' << VNI
->id
);
1162 LI
.addSegment(LiveInterval::Segment(Start
, End
, VNI
));
1167 // Skip values with forced recomputation.
1169 LLVM_DEBUG(dbgs() << "(recalc)");
1175 LiveIntervalCalc
&LIC
= getLICalc(RegIdx
);
1177 // This value has multiple defs in RegIdx, but it wasn't rematerialized,
1178 // so the live range is accurate. Add live-in blocks in [Start;End) to the
1180 MachineFunction::iterator MBB
= LIS
.getMBBFromIndex(Start
)->getIterator();
1181 SlotIndex BlockStart
, BlockEnd
;
1182 std::tie(BlockStart
, BlockEnd
) = LIS
.getSlotIndexes()->getMBBRange(&*MBB
);
1184 // The first block may be live-in, or it may have its own def.
1185 if (Start
!= BlockStart
) {
1186 VNInfo
*VNI
= LI
.extendInBlock(BlockStart
, std::min(BlockEnd
, End
));
1187 assert(VNI
&& "Missing def for complex mapped value");
1188 LLVM_DEBUG(dbgs() << ':' << VNI
->id
<< "*" << printMBBReference(*MBB
));
1189 // MBB has its own def. Is it also live-out?
1190 if (BlockEnd
<= End
)
1191 LIC
.setLiveOutValue(&*MBB
, VNI
);
1193 // Skip to the next block for live-in.
1195 BlockStart
= BlockEnd
;
1198 // Handle the live-in blocks covered by [Start;End).
1199 assert(Start
<= BlockStart
&& "Expected live-in block");
1200 while (BlockStart
< End
) {
1201 LLVM_DEBUG(dbgs() << ">" << printMBBReference(*MBB
));
1202 BlockEnd
= LIS
.getMBBEndIdx(&*MBB
);
1203 if (BlockStart
== ParentVNI
->def
) {
1204 // This block has the def of a parent PHI, so it isn't live-in.
1205 assert(ParentVNI
->isPHIDef() && "Non-phi defined at block start?");
1206 VNInfo
*VNI
= LI
.extendInBlock(BlockStart
, std::min(BlockEnd
, End
));
1207 assert(VNI
&& "Missing def for complex mapped parent PHI");
1208 if (End
>= BlockEnd
)
1209 LIC
.setLiveOutValue(&*MBB
, VNI
); // Live-out as well.
1211 // This block needs a live-in value. The last block covered may not
1214 LIC
.addLiveInBlock(LI
, MDT
[&*MBB
], End
);
1216 // Live-through, and we don't know the value.
1217 LIC
.addLiveInBlock(LI
, MDT
[&*MBB
]);
1218 LIC
.setLiveOutValue(&*MBB
, nullptr);
1221 BlockStart
= BlockEnd
;
1225 } while (Start
!= S
.end
);
1226 LLVM_DEBUG(dbgs() << '\n');
1229 LICalc
[0].calculateValues();
1231 LICalc
[1].calculateValues();
1236 static bool removeDeadSegment(SlotIndex Def
, LiveRange
&LR
) {
1237 const LiveRange::Segment
*Seg
= LR
.getSegmentContaining(Def
);
1240 if (Seg
->end
!= Def
.getDeadSlot())
1242 // This is a dead PHI. Remove it.
1243 LR
.removeSegment(*Seg
, true);
1247 void SplitEditor::extendPHIRange(MachineBasicBlock
&B
, LiveIntervalCalc
&LIC
,
1248 LiveRange
&LR
, LaneBitmask LM
,
1249 ArrayRef
<SlotIndex
> Undefs
) {
1250 for (MachineBasicBlock
*P
: B
.predecessors()) {
1251 SlotIndex End
= LIS
.getMBBEndIdx(P
);
1252 SlotIndex LastUse
= End
.getPrevSlot();
1253 // The predecessor may not have a live-out value. That is OK, like an
1254 // undef PHI operand.
1255 const LiveInterval
&PLI
= Edit
->getParent();
1256 // Need the cast because the inputs to ?: would otherwise be deemed
1257 // "incompatible": SubRange vs LiveInterval.
1258 const LiveRange
&PSR
= !LM
.all() ? getSubRangeForMaskExact(LM
, PLI
)
1259 : static_cast<const LiveRange
&>(PLI
);
1260 if (PSR
.liveAt(LastUse
))
1261 LIC
.extend(LR
, End
, /*PhysReg=*/0, Undefs
);
1265 void SplitEditor::extendPHIKillRanges() {
1266 // Extend live ranges to be live-out for successor PHI values.
1268 // Visit each PHI def slot in the parent live interval. If the def is dead,
1269 // remove it. Otherwise, extend the live interval to reach the end indexes
1270 // of all predecessor blocks.
1272 const LiveInterval
&ParentLI
= Edit
->getParent();
1273 for (const VNInfo
*V
: ParentLI
.valnos
) {
1274 if (V
->isUnused() || !V
->isPHIDef())
1277 unsigned RegIdx
= RegAssign
.lookup(V
->def
);
1278 LiveInterval
&LI
= LIS
.getInterval(Edit
->get(RegIdx
));
1279 LiveIntervalCalc
&LIC
= getLICalc(RegIdx
);
1280 MachineBasicBlock
&B
= *LIS
.getMBBFromIndex(V
->def
);
1281 if (!removeDeadSegment(V
->def
, LI
))
1282 extendPHIRange(B
, LIC
, LI
, LaneBitmask::getAll(), /*Undefs=*/{});
1285 SmallVector
<SlotIndex
, 4> Undefs
;
1286 LiveIntervalCalc SubLIC
;
1288 for (const LiveInterval::SubRange
&PS
: ParentLI
.subranges()) {
1289 for (const VNInfo
*V
: PS
.valnos
) {
1290 if (V
->isUnused() || !V
->isPHIDef())
1292 unsigned RegIdx
= RegAssign
.lookup(V
->def
);
1293 LiveInterval
&LI
= LIS
.getInterval(Edit
->get(RegIdx
));
1294 LiveInterval::SubRange
&S
= getSubRangeForMaskExact(PS
.LaneMask
, LI
);
1295 if (removeDeadSegment(V
->def
, S
))
1298 MachineBasicBlock
&B
= *LIS
.getMBBFromIndex(V
->def
);
1299 SubLIC
.reset(&VRM
.getMachineFunction(), LIS
.getSlotIndexes(), &MDT
,
1300 &LIS
.getVNInfoAllocator());
1302 LI
.computeSubRangeUndefs(Undefs
, PS
.LaneMask
, MRI
, *LIS
.getSlotIndexes());
1303 extendPHIRange(B
, SubLIC
, S
, PS
.LaneMask
, Undefs
);
1308 /// rewriteAssigned - Rewrite all uses of Edit->getReg().
1309 void SplitEditor::rewriteAssigned(bool ExtendRanges
) {
1311 ExtPoint(const MachineOperand
&O
, unsigned R
, SlotIndex N
)
1312 : MO(O
), RegIdx(R
), Next(N
) {}
1319 SmallVector
<ExtPoint
,4> ExtPoints
;
1321 for (MachineOperand
&MO
:
1322 llvm::make_early_inc_range(MRI
.reg_operands(Edit
->getReg()))) {
1323 MachineInstr
*MI
= MO
.getParent();
1324 // LiveDebugVariables should have handled all DBG_VALUE instructions.
1325 if (MI
->isDebugValue()) {
1326 LLVM_DEBUG(dbgs() << "Zapping " << *MI
);
1331 // <undef> operands don't really read the register, so it doesn't matter
1332 // which register we choose. When the use operand is tied to a def, we must
1333 // use the same register as the def, so just do that always.
1334 SlotIndex Idx
= LIS
.getInstructionIndex(*MI
);
1335 if (MO
.isDef() || MO
.isUndef())
1336 Idx
= Idx
.getRegSlot(MO
.isEarlyClobber());
1338 // Rewrite to the mapped register at Idx.
1339 unsigned RegIdx
= RegAssign
.lookup(Idx
);
1340 LiveInterval
&LI
= LIS
.getInterval(Edit
->get(RegIdx
));
1341 MO
.setReg(LI
.reg());
1342 LLVM_DEBUG(dbgs() << " rewr " << printMBBReference(*MI
->getParent())
1343 << '\t' << Idx
<< ':' << RegIdx
<< '\t' << *MI
);
1345 // Extend liveness to Idx if the instruction reads reg.
1346 if (!ExtendRanges
|| MO
.isUndef())
1349 // Skip instructions that don't read Reg.
1351 if (!MO
.getSubReg() && !MO
.isEarlyClobber())
1353 // We may want to extend a live range for a partial redef, or for a use
1354 // tied to an early clobber.
1355 Idx
= Idx
.getPrevSlot();
1356 if (!Edit
->getParent().liveAt(Idx
))
1359 Idx
= Idx
.getRegSlot(true);
1361 SlotIndex Next
= Idx
.getNextSlot();
1362 if (LI
.hasSubRanges()) {
1363 // We have to delay extending subranges until we have seen all operands
1364 // defining the register. This is because a <def,read-undef> operand
1365 // will create an "undef" point, and we cannot extend any subranges
1366 // until all of them have been accounted for.
1368 ExtPoints
.push_back(ExtPoint(MO
, RegIdx
, Next
));
1370 LiveIntervalCalc
&LIC
= getLICalc(RegIdx
);
1371 LIC
.extend(LI
, Next
, 0, ArrayRef
<SlotIndex
>());
1375 for (ExtPoint
&EP
: ExtPoints
) {
1376 LiveInterval
&LI
= LIS
.getInterval(Edit
->get(EP
.RegIdx
));
1377 assert(LI
.hasSubRanges());
1379 LiveIntervalCalc SubLIC
;
1380 Register Reg
= EP
.MO
.getReg(), Sub
= EP
.MO
.getSubReg();
1381 LaneBitmask LM
= Sub
!= 0 ? TRI
.getSubRegIndexLaneMask(Sub
)
1382 : MRI
.getMaxLaneMaskForVReg(Reg
);
1383 for (LiveInterval::SubRange
&S
: LI
.subranges()) {
1384 if ((S
.LaneMask
& LM
).none())
1386 // The problem here can be that the new register may have been created
1387 // for a partially defined original register. For example:
1388 // %0:subreg_hireg<def,read-undef> = ...
1393 SubLIC
.reset(&VRM
.getMachineFunction(), LIS
.getSlotIndexes(), &MDT
,
1394 &LIS
.getVNInfoAllocator());
1395 SmallVector
<SlotIndex
, 4> Undefs
;
1396 LI
.computeSubRangeUndefs(Undefs
, S
.LaneMask
, MRI
, *LIS
.getSlotIndexes());
1397 SubLIC
.extend(S
, EP
.Next
, 0, Undefs
);
1401 for (Register R
: *Edit
) {
1402 LiveInterval
&LI
= LIS
.getInterval(R
);
1403 if (!LI
.hasSubRanges())
1406 LI
.removeEmptySubRanges();
1407 LIS
.constructMainRangeFromSubranges(LI
);
1411 void SplitEditor::deleteRematVictims() {
1412 SmallVector
<MachineInstr
*, 8> Dead
;
1413 for (const Register
&R
: *Edit
) {
1414 LiveInterval
*LI
= &LIS
.getInterval(R
);
1415 for (const LiveRange::Segment
&S
: LI
->segments
) {
1416 // Dead defs end at the dead slot.
1417 if (S
.end
!= S
.valno
->def
.getDeadSlot())
1419 if (S
.valno
->isPHIDef())
1421 MachineInstr
*MI
= LIS
.getInstructionFromIndex(S
.valno
->def
);
1422 assert(MI
&& "Missing instruction for dead def");
1423 MI
->addRegisterDead(LI
->reg(), &TRI
);
1425 if (!MI
->allDefsAreDead())
1428 LLVM_DEBUG(dbgs() << "All defs dead: " << *MI
);
1436 Edit
->eliminateDeadDefs(Dead
, None
, &AA
);
1439 void SplitEditor::forceRecomputeVNI(const VNInfo
&ParentVNI
) {
1440 // Fast-path for common case.
1441 if (!ParentVNI
.isPHIDef()) {
1442 for (unsigned I
= 0, E
= Edit
->size(); I
!= E
; ++I
)
1443 forceRecompute(I
, ParentVNI
);
1447 // Trace value through phis.
1448 SmallPtrSet
<const VNInfo
*, 8> Visited
; ///< whether VNI was/is in worklist.
1449 SmallVector
<const VNInfo
*, 4> WorkList
;
1450 Visited
.insert(&ParentVNI
);
1451 WorkList
.push_back(&ParentVNI
);
1453 const LiveInterval
&ParentLI
= Edit
->getParent();
1454 const SlotIndexes
&Indexes
= *LIS
.getSlotIndexes();
1456 const VNInfo
&VNI
= *WorkList
.back();
1457 WorkList
.pop_back();
1458 for (unsigned I
= 0, E
= Edit
->size(); I
!= E
; ++I
)
1459 forceRecompute(I
, VNI
);
1460 if (!VNI
.isPHIDef())
1463 MachineBasicBlock
&MBB
= *Indexes
.getMBBFromIndex(VNI
.def
);
1464 for (const MachineBasicBlock
*Pred
: MBB
.predecessors()) {
1465 SlotIndex PredEnd
= Indexes
.getMBBEndIdx(Pred
);
1466 VNInfo
*PredVNI
= ParentLI
.getVNInfoBefore(PredEnd
);
1467 assert(PredVNI
&& "Value available in PhiVNI predecessor");
1468 if (Visited
.insert(PredVNI
).second
)
1469 WorkList
.push_back(PredVNI
);
1471 } while(!WorkList
.empty());
1474 void SplitEditor::finish(SmallVectorImpl
<unsigned> *LRMap
) {
1477 // At this point, the live intervals in Edit contain VNInfos corresponding to
1478 // the inserted copies.
1480 // Add the original defs from the parent interval.
1481 for (const VNInfo
*ParentVNI
: Edit
->getParent().valnos
) {
1482 if (ParentVNI
->isUnused())
1484 unsigned RegIdx
= RegAssign
.lookup(ParentVNI
->def
);
1485 defValue(RegIdx
, ParentVNI
, ParentVNI
->def
, true);
1487 // Force rematted values to be recomputed everywhere.
1488 // The new live ranges may be truncated.
1489 if (Edit
->didRematerialize(ParentVNI
))
1490 forceRecomputeVNI(*ParentVNI
);
1493 // Hoist back-copies to the complement interval when in spill mode.
1494 switch (SpillMode
) {
1496 // Leave all back-copies as is.
1500 // hoistCopies will behave differently between size and speed.
1504 // Transfer the simply mapped values, check if any are skipped.
1505 bool Skipped
= transferValues();
1507 // Rewrite virtual registers, possibly extending ranges.
1508 rewriteAssigned(Skipped
);
1511 extendPHIKillRanges();
1515 // Delete defs that were rematted everywhere.
1517 deleteRematVictims();
1519 // Get rid of unused values and set phi-kill flags.
1520 for (Register Reg
: *Edit
) {
1521 LiveInterval
&LI
= LIS
.getInterval(Reg
);
1522 LI
.removeEmptySubRanges();
1523 LI
.RenumberValues();
1526 // Provide a reverse mapping from original indices to Edit ranges.
1528 auto Seq
= llvm::seq
<unsigned>(0, Edit
->size());
1529 LRMap
->assign(Seq
.begin(), Seq
.end());
1532 // Now check if any registers were separated into multiple components.
1533 ConnectedVNInfoEqClasses
ConEQ(LIS
);
1534 for (unsigned i
= 0, e
= Edit
->size(); i
!= e
; ++i
) {
1535 // Don't use iterators, they are invalidated by create() below.
1536 Register VReg
= Edit
->get(i
);
1537 LiveInterval
&LI
= LIS
.getInterval(VReg
);
1538 SmallVector
<LiveInterval
*, 8> SplitLIs
;
1539 LIS
.splitSeparateComponents(LI
, SplitLIs
);
1540 Register Original
= VRM
.getOriginal(VReg
);
1541 for (LiveInterval
*SplitLI
: SplitLIs
)
1542 VRM
.setIsSplitFromReg(SplitLI
->reg(), Original
);
1544 // The new intervals all map back to i.
1546 LRMap
->resize(Edit
->size(), i
);
1549 // Calculate spill weight and allocation hints for new intervals.
1550 Edit
->calculateRegClassAndHint(VRM
.getMachineFunction(), VRAI
);
1552 assert(!LRMap
|| LRMap
->size() == Edit
->size());
1555 //===----------------------------------------------------------------------===//
1556 // Single Block Splitting
1557 //===----------------------------------------------------------------------===//
1559 bool SplitAnalysis::shouldSplitSingleBlock(const BlockInfo
&BI
,
1560 bool SingleInstrs
) const {
1561 // Always split for multiple instructions.
1562 if (!BI
.isOneInstr())
1564 // Don't split for single instructions unless explicitly requested.
1567 // Splitting a live-through range always makes progress.
1568 if (BI
.LiveIn
&& BI
.LiveOut
)
1570 // No point in isolating a copy. It has no register class constraints.
1571 if (LIS
.getInstructionFromIndex(BI
.FirstInstr
)->isCopyLike())
1573 // Finally, don't isolate an end point that was created by earlier splits.
1574 return isOriginalEndpoint(BI
.FirstInstr
);
1577 void SplitEditor::splitSingleBlock(const SplitAnalysis::BlockInfo
&BI
) {
1579 SlotIndex LastSplitPoint
= SA
.getLastSplitPoint(BI
.MBB
);
1580 SlotIndex SegStart
= enterIntvBefore(std::min(BI
.FirstInstr
,
1582 if (!BI
.LiveOut
|| BI
.LastInstr
< LastSplitPoint
) {
1583 useIntv(SegStart
, leaveIntvAfter(BI
.LastInstr
));
1585 // The last use is after the last valid split point.
1586 SlotIndex SegStop
= leaveIntvBefore(LastSplitPoint
);
1587 useIntv(SegStart
, SegStop
);
1588 overlapIntv(SegStop
, BI
.LastInstr
);
1592 //===----------------------------------------------------------------------===//
1593 // Global Live Range Splitting Support
1594 //===----------------------------------------------------------------------===//
1596 // These methods support a method of global live range splitting that uses a
1597 // global algorithm to decide intervals for CFG edges. They will insert split
1598 // points and color intervals in basic blocks while avoiding interference.
1600 // Note that splitSingleBlock is also useful for blocks where both CFG edges
1601 // are on the stack.
1603 void SplitEditor::splitLiveThroughBlock(unsigned MBBNum
,
1604 unsigned IntvIn
, SlotIndex LeaveBefore
,
1605 unsigned IntvOut
, SlotIndex EnterAfter
){
1606 SlotIndex Start
, Stop
;
1607 std::tie(Start
, Stop
) = LIS
.getSlotIndexes()->getMBBRange(MBBNum
);
1609 LLVM_DEBUG(dbgs() << "%bb." << MBBNum
<< " [" << Start
<< ';' << Stop
1610 << ") intf " << LeaveBefore
<< '-' << EnterAfter
1611 << ", live-through " << IntvIn
<< " -> " << IntvOut
);
1613 assert((IntvIn
|| IntvOut
) && "Use splitSingleBlock for isolated blocks");
1615 assert((!LeaveBefore
|| LeaveBefore
< Stop
) && "Interference after block");
1616 assert((!IntvIn
|| !LeaveBefore
|| LeaveBefore
> Start
) && "Impossible intf");
1617 assert((!EnterAfter
|| EnterAfter
>= Start
) && "Interference before block");
1619 MachineBasicBlock
*MBB
= VRM
.getMachineFunction().getBlockNumbered(MBBNum
);
1622 LLVM_DEBUG(dbgs() << ", spill on entry.\n");
1624 // <<<<<<<<< Possible LeaveBefore interference.
1625 // |-----------| Live through.
1626 // -____________ Spill on entry.
1629 SlotIndex Idx
= leaveIntvAtTop(*MBB
);
1630 assert((!LeaveBefore
|| Idx
<= LeaveBefore
) && "Interference");
1636 LLVM_DEBUG(dbgs() << ", reload on exit.\n");
1638 // >>>>>>> Possible EnterAfter interference.
1639 // |-----------| Live through.
1640 // ___________-- Reload on exit.
1642 selectIntv(IntvOut
);
1643 SlotIndex Idx
= enterIntvAtEnd(*MBB
);
1644 assert((!EnterAfter
|| Idx
>= EnterAfter
) && "Interference");
1649 if (IntvIn
== IntvOut
&& !LeaveBefore
&& !EnterAfter
) {
1650 LLVM_DEBUG(dbgs() << ", straight through.\n");
1652 // |-----------| Live through.
1653 // ------------- Straight through, same intv, no interference.
1655 selectIntv(IntvOut
);
1656 useIntv(Start
, Stop
);
1660 // We cannot legally insert splits after LSP.
1661 SlotIndex LSP
= SA
.getLastSplitPoint(MBBNum
);
1662 assert((!IntvOut
|| !EnterAfter
|| EnterAfter
< LSP
) && "Impossible intf");
1664 if (IntvIn
!= IntvOut
&& (!LeaveBefore
|| !EnterAfter
||
1665 LeaveBefore
.getBaseIndex() > EnterAfter
.getBoundaryIndex())) {
1666 LLVM_DEBUG(dbgs() << ", switch avoiding interference.\n");
1668 // >>>> <<<< Non-overlapping EnterAfter/LeaveBefore interference.
1669 // |-----------| Live through.
1670 // ------======= Switch intervals between interference.
1672 selectIntv(IntvOut
);
1674 if (LeaveBefore
&& LeaveBefore
< LSP
) {
1675 Idx
= enterIntvBefore(LeaveBefore
);
1678 Idx
= enterIntvAtEnd(*MBB
);
1681 useIntv(Start
, Idx
);
1682 assert((!LeaveBefore
|| Idx
<= LeaveBefore
) && "Interference");
1683 assert((!EnterAfter
|| Idx
>= EnterAfter
) && "Interference");
1687 LLVM_DEBUG(dbgs() << ", create local intv for interference.\n");
1689 // >>><><><><<<< Overlapping EnterAfter/LeaveBefore interference.
1690 // |-----------| Live through.
1691 // ==---------== Switch intervals before/after interference.
1693 assert(LeaveBefore
<= EnterAfter
&& "Missed case");
1695 selectIntv(IntvOut
);
1696 SlotIndex Idx
= enterIntvAfter(EnterAfter
);
1698 assert((!EnterAfter
|| Idx
>= EnterAfter
) && "Interference");
1701 Idx
= leaveIntvBefore(LeaveBefore
);
1702 useIntv(Start
, Idx
);
1703 assert((!LeaveBefore
|| Idx
<= LeaveBefore
) && "Interference");
1706 void SplitEditor::splitRegInBlock(const SplitAnalysis::BlockInfo
&BI
,
1707 unsigned IntvIn
, SlotIndex LeaveBefore
) {
1708 SlotIndex Start
, Stop
;
1709 std::tie(Start
, Stop
) = LIS
.getSlotIndexes()->getMBBRange(BI
.MBB
);
1711 LLVM_DEBUG(dbgs() << printMBBReference(*BI
.MBB
) << " [" << Start
<< ';'
1712 << Stop
<< "), uses " << BI
.FirstInstr
<< '-'
1713 << BI
.LastInstr
<< ", reg-in " << IntvIn
1714 << ", leave before " << LeaveBefore
1715 << (BI
.LiveOut
? ", stack-out" : ", killed in block"));
1717 assert(IntvIn
&& "Must have register in");
1718 assert(BI
.LiveIn
&& "Must be live-in");
1719 assert((!LeaveBefore
|| LeaveBefore
> Start
) && "Bad interference");
1721 if (!BI
.LiveOut
&& (!LeaveBefore
|| LeaveBefore
>= BI
.LastInstr
)) {
1722 LLVM_DEBUG(dbgs() << " before interference.\n");
1724 // <<< Interference after kill.
1725 // |---o---x | Killed in block.
1726 // ========= Use IntvIn everywhere.
1729 useIntv(Start
, BI
.LastInstr
);
1733 SlotIndex LSP
= SA
.getLastSplitPoint(BI
.MBB
);
1735 if (!LeaveBefore
|| LeaveBefore
> BI
.LastInstr
.getBoundaryIndex()) {
1737 // <<< Possible interference after last use.
1738 // |---o---o---| Live-out on stack.
1739 // =========____ Leave IntvIn after last use.
1741 // < Interference after last use.
1742 // |---o---o--o| Live-out on stack, late last use.
1743 // ============ Copy to stack after LSP, overlap IntvIn.
1744 // \_____ Stack interval is live-out.
1746 if (BI
.LastInstr
< LSP
) {
1747 LLVM_DEBUG(dbgs() << ", spill after last use before interference.\n");
1749 SlotIndex Idx
= leaveIntvAfter(BI
.LastInstr
);
1750 useIntv(Start
, Idx
);
1751 assert((!LeaveBefore
|| Idx
<= LeaveBefore
) && "Interference");
1753 LLVM_DEBUG(dbgs() << ", spill before last split point.\n");
1755 SlotIndex Idx
= leaveIntvBefore(LSP
);
1756 overlapIntv(Idx
, BI
.LastInstr
);
1757 useIntv(Start
, Idx
);
1758 assert((!LeaveBefore
|| Idx
<= LeaveBefore
) && "Interference");
1763 // The interference is overlapping somewhere we wanted to use IntvIn. That
1764 // means we need to create a local interval that can be allocated a
1765 // different register.
1766 unsigned LocalIntv
= openIntv();
1768 LLVM_DEBUG(dbgs() << ", creating local interval " << LocalIntv
<< ".\n");
1770 if (!BI
.LiveOut
|| BI
.LastInstr
< LSP
) {
1772 // <<<<<<< Interference overlapping uses.
1773 // |---o---o---| Live-out on stack.
1774 // =====----____ Leave IntvIn before interference, then spill.
1776 SlotIndex To
= leaveIntvAfter(BI
.LastInstr
);
1777 SlotIndex From
= enterIntvBefore(LeaveBefore
);
1780 useIntv(Start
, From
);
1781 assert((!LeaveBefore
|| From
<= LeaveBefore
) && "Interference");
1785 // <<<<<<< Interference overlapping uses.
1786 // |---o---o--o| Live-out on stack, late last use.
1787 // =====------- Copy to stack before LSP, overlap LocalIntv.
1788 // \_____ Stack interval is live-out.
1790 SlotIndex To
= leaveIntvBefore(LSP
);
1791 overlapIntv(To
, BI
.LastInstr
);
1792 SlotIndex From
= enterIntvBefore(std::min(To
, LeaveBefore
));
1795 useIntv(Start
, From
);
1796 assert((!LeaveBefore
|| From
<= LeaveBefore
) && "Interference");
1799 void SplitEditor::splitRegOutBlock(const SplitAnalysis::BlockInfo
&BI
,
1800 unsigned IntvOut
, SlotIndex EnterAfter
) {
1801 SlotIndex Start
, Stop
;
1802 std::tie(Start
, Stop
) = LIS
.getSlotIndexes()->getMBBRange(BI
.MBB
);
1804 LLVM_DEBUG(dbgs() << printMBBReference(*BI
.MBB
) << " [" << Start
<< ';'
1805 << Stop
<< "), uses " << BI
.FirstInstr
<< '-'
1806 << BI
.LastInstr
<< ", reg-out " << IntvOut
1807 << ", enter after " << EnterAfter
1808 << (BI
.LiveIn
? ", stack-in" : ", defined in block"));
1810 SlotIndex LSP
= SA
.getLastSplitPoint(BI
.MBB
);
1812 assert(IntvOut
&& "Must have register out");
1813 assert(BI
.LiveOut
&& "Must be live-out");
1814 assert((!EnterAfter
|| EnterAfter
< LSP
) && "Bad interference");
1816 if (!BI
.LiveIn
&& (!EnterAfter
|| EnterAfter
<= BI
.FirstInstr
)) {
1817 LLVM_DEBUG(dbgs() << " after interference.\n");
1819 // >>>> Interference before def.
1820 // | o---o---| Defined in block.
1821 // ========= Use IntvOut everywhere.
1823 selectIntv(IntvOut
);
1824 useIntv(BI
.FirstInstr
, Stop
);
1828 if (!EnterAfter
|| EnterAfter
< BI
.FirstInstr
.getBaseIndex()) {
1829 LLVM_DEBUG(dbgs() << ", reload after interference.\n");
1831 // >>>> Interference before def.
1832 // |---o---o---| Live-through, stack-in.
1833 // ____========= Enter IntvOut before first use.
1835 selectIntv(IntvOut
);
1836 SlotIndex Idx
= enterIntvBefore(std::min(LSP
, BI
.FirstInstr
));
1838 assert((!EnterAfter
|| Idx
>= EnterAfter
) && "Interference");
1842 // The interference is overlapping somewhere we wanted to use IntvOut. That
1843 // means we need to create a local interval that can be allocated a
1844 // different register.
1845 LLVM_DEBUG(dbgs() << ", interference overlaps uses.\n");
1847 // >>>>>>> Interference overlapping uses.
1848 // |---o---o---| Live-through, stack-in.
1849 // ____---====== Create local interval for interference range.
1851 selectIntv(IntvOut
);
1852 SlotIndex Idx
= enterIntvAfter(EnterAfter
);
1854 assert((!EnterAfter
|| Idx
>= EnterAfter
) && "Interference");
1857 SlotIndex From
= enterIntvBefore(std::min(Idx
, BI
.FirstInstr
));
1861 void SplitAnalysis::BlockInfo::print(raw_ostream
&OS
) const {
1862 OS
<< "{" << printMBBReference(*MBB
) << ", "
1863 << "uses " << FirstInstr
<< " to " << LastInstr
<< ", "
1864 << "1st def " << FirstDef
<< ", "
1865 << (LiveIn
? "live in" : "dead in") << ", "
1866 << (LiveOut
? "live out" : "dead out") << "}";
1869 void SplitAnalysis::BlockInfo::dump() const {