1 //===-------- InlineSpiller.cpp - Insert spills and restores inline -------===//
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 // The inline spiller modifies the machine function directly instead of
11 // inserting spills and restores in VirtRegMap.
13 //===----------------------------------------------------------------------===//
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/ADT/TinyPtrVector.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
21 #include "llvm/CodeGen/LiveRangeEdit.h"
22 #include "llvm/CodeGen/LiveStackAnalysis.h"
23 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
24 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineInstrBundle.h"
30 #include "llvm/CodeGen/MachineLoopInfo.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/VirtRegMap.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/Target/TargetMachine.h"
41 #define DEBUG_TYPE "regalloc"
43 STATISTIC(NumSpilledRanges, "Number of spilled live ranges");
44 STATISTIC(NumSnippets, "Number of spilled snippets");
45 STATISTIC(NumSpills, "Number of spills inserted");
46 STATISTIC(NumSpillsRemoved, "Number of spills removed");
47 STATISTIC(NumReloads, "Number of reloads inserted");
48 STATISTIC(NumReloadsRemoved, "Number of reloads removed");
49 STATISTIC(NumFolded, "Number of folded stack accesses");
50 STATISTIC(NumFoldedLoads, "Number of folded loads");
51 STATISTIC(NumRemats, "Number of rematerialized defs for spilling");
52 STATISTIC(NumOmitReloadSpill, "Number of omitted spills of reloads");
53 STATISTIC(NumHoists, "Number of hoisted spills");
55 static cl::opt<bool> DisableHoisting("disable-spill-hoist", cl::Hidden,
56 cl::desc("Disable inline spill hoisting"));
59 class InlineSpiller : public Spiller {
64 MachineDominatorTree &MDT;
65 MachineLoopInfo &Loops;
67 MachineFrameInfo &MFI;
68 MachineRegisterInfo &MRI;
69 const TargetInstrInfo &TII;
70 const TargetRegisterInfo &TRI;
71 const MachineBlockFrequencyInfo &MBFI;
73 // Variables that are valid during spill(), but used by multiple methods.
75 LiveInterval *StackInt;
79 // All registers to spill to StackSlot, including the main register.
80 SmallVector<unsigned, 8> RegsToSpill;
82 // All COPY instructions to/from snippets.
83 // They are ignored since both operands refer to the same stack slot.
84 SmallPtrSet<MachineInstr*, 8> SnippetCopies;
86 // Values that failed to remat at some point.
87 SmallPtrSet<VNInfo*, 8> UsedValues;
90 // Information about a value that was defined by a copy from a sibling
93 // True when all reaching defs were reloads: No spill is necessary.
94 bool AllDefsAreReloads;
96 // True when value is defined by an original PHI not from splitting.
99 // True when the COPY defining this value killed its source.
102 // The preferred register to spill.
105 // The value of SpillReg that should be spilled.
108 // The block where SpillVNI should be spilled. Currently, this must be the
109 // block containing SpillVNI->def.
110 MachineBasicBlock *SpillMBB;
112 // A defining instruction that is not a sibling copy or a reload, or NULL.
113 // This can be used as a template for rematerialization.
116 // List of values that depend on this one. These values are actually the
117 // same, but live range splitting has placed them in different registers,
118 // or SSA update needed to insert PHI-defs to preserve SSA form. This is
119 // copies of the current value and phi-kills. Usually only phi-kills cause
120 // more than one dependent value.
121 TinyPtrVector<VNInfo*> Deps;
123 SibValueInfo(unsigned Reg, VNInfo *VNI)
124 : AllDefsAreReloads(true), DefByOrigPHI(false), KillsSource(false),
125 SpillReg(Reg), SpillVNI(VNI), SpillMBB(nullptr), DefMI(nullptr) {}
127 // Returns true when a def has been found.
128 bool hasDef() const { return DefByOrigPHI || DefMI; }
132 // Values in RegsToSpill defined by sibling copies.
133 typedef DenseMap<VNInfo*, SibValueInfo> SibValueMap;
134 SibValueMap SibValues;
136 // Dead defs generated during spilling.
137 SmallVector<MachineInstr*, 8> DeadDefs;
142 InlineSpiller(MachineFunctionPass &pass, MachineFunction &mf, VirtRegMap &vrm)
143 : MF(mf), LIS(pass.getAnalysis<LiveIntervals>()),
144 LSS(pass.getAnalysis<LiveStacks>()),
145 AA(&pass.getAnalysis<AliasAnalysis>()),
146 MDT(pass.getAnalysis<MachineDominatorTree>()),
147 Loops(pass.getAnalysis<MachineLoopInfo>()), VRM(vrm),
148 MFI(*mf.getFrameInfo()), MRI(mf.getRegInfo()),
149 TII(*mf.getSubtarget().getInstrInfo()),
150 TRI(*mf.getSubtarget().getRegisterInfo()),
151 MBFI(pass.getAnalysis<MachineBlockFrequencyInfo>()) {}
153 void spill(LiveRangeEdit &) override;
156 bool isSnippet(const LiveInterval &SnipLI);
157 void collectRegsToSpill();
159 bool isRegToSpill(unsigned Reg) {
160 return std::find(RegsToSpill.begin(),
161 RegsToSpill.end(), Reg) != RegsToSpill.end();
164 bool isSibling(unsigned Reg);
165 MachineInstr *traceSiblingValue(unsigned, VNInfo*, VNInfo*);
166 void propagateSiblingValue(SibValueMap::iterator, VNInfo *VNI = nullptr);
167 void analyzeSiblingValues();
169 bool hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI);
170 void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI);
172 void markValueUsed(LiveInterval*, VNInfo*);
173 bool reMaterializeFor(LiveInterval&, MachineBasicBlock::iterator MI);
174 void reMaterializeAll();
176 bool coalesceStackAccess(MachineInstr *MI, unsigned Reg);
177 bool foldMemoryOperand(ArrayRef<std::pair<MachineInstr*, unsigned> >,
178 MachineInstr *LoadMI = nullptr);
179 void insertReload(unsigned VReg, SlotIndex, MachineBasicBlock::iterator MI);
180 void insertSpill(unsigned VReg, bool isKill, MachineBasicBlock::iterator MI);
182 void spillAroundUses(unsigned Reg);
188 Spiller *createInlineSpiller(MachineFunctionPass &pass,
191 return new InlineSpiller(pass, mf, vrm);
195 //===----------------------------------------------------------------------===//
197 //===----------------------------------------------------------------------===//
199 // When spilling a virtual register, we also spill any snippets it is connected
200 // to. The snippets are small live ranges that only have a single real use,
201 // leftovers from live range splitting. Spilling them enables memory operand
202 // folding or tightens the live range around the single use.
204 // This minimizes register pressure and maximizes the store-to-load distance for
205 // spill slots which can be important in tight loops.
207 /// isFullCopyOf - If MI is a COPY to or from Reg, return the other register,
208 /// otherwise return 0.
209 static unsigned isFullCopyOf(const MachineInstr *MI, unsigned Reg) {
210 if (!MI->isFullCopy())
212 if (MI->getOperand(0).getReg() == Reg)
213 return MI->getOperand(1).getReg();
214 if (MI->getOperand(1).getReg() == Reg)
215 return MI->getOperand(0).getReg();
219 /// isSnippet - Identify if a live interval is a snippet that should be spilled.
220 /// It is assumed that SnipLI is a virtual register with the same original as
222 bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
223 unsigned Reg = Edit->getReg();
225 // A snippet is a tiny live range with only a single instruction using it
226 // besides copies to/from Reg or spills/fills. We accept:
228 // %snip = COPY %Reg / FILL fi#
230 // %Reg = COPY %snip / SPILL %snip, fi#
232 if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI))
235 MachineInstr *UseMI = nullptr;
237 // Check that all uses satisfy our criteria.
238 for (MachineRegisterInfo::reg_instr_nodbg_iterator
239 RI = MRI.reg_instr_nodbg_begin(SnipLI.reg),
240 E = MRI.reg_instr_nodbg_end(); RI != E; ) {
241 MachineInstr *MI = &*(RI++);
243 // Allow copies to/from Reg.
244 if (isFullCopyOf(MI, Reg))
247 // Allow stack slot loads.
249 if (SnipLI.reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
252 // Allow stack slot stores.
253 if (SnipLI.reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
256 // Allow a single additional instruction.
257 if (UseMI && MI != UseMI)
264 /// collectRegsToSpill - Collect live range snippets that only have a single
266 void InlineSpiller::collectRegsToSpill() {
267 unsigned Reg = Edit->getReg();
269 // Main register always spills.
270 RegsToSpill.assign(1, Reg);
271 SnippetCopies.clear();
273 // Snippets all have the same original, so there can't be any for an original
278 for (MachineRegisterInfo::reg_instr_iterator
279 RI = MRI.reg_instr_begin(Reg), E = MRI.reg_instr_end(); RI != E; ) {
280 MachineInstr *MI = &*(RI++);
281 unsigned SnipReg = isFullCopyOf(MI, Reg);
282 if (!isSibling(SnipReg))
284 LiveInterval &SnipLI = LIS.getInterval(SnipReg);
285 if (!isSnippet(SnipLI))
287 SnippetCopies.insert(MI);
288 if (isRegToSpill(SnipReg))
290 RegsToSpill.push_back(SnipReg);
291 DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n');
297 //===----------------------------------------------------------------------===//
299 //===----------------------------------------------------------------------===//
301 // After live range splitting, some values to be spilled may be defined by
302 // copies from sibling registers. We trace the sibling copies back to the
303 // original value if it still exists. We need it for rematerialization.
305 // Even when the value can't be rematerialized, we still want to determine if
306 // the value has already been spilled, or we may want to hoist the spill from a
309 bool InlineSpiller::isSibling(unsigned Reg) {
310 return TargetRegisterInfo::isVirtualRegister(Reg) &&
311 VRM.getOriginal(Reg) == Original;
315 static raw_ostream &operator<<(raw_ostream &OS,
316 const InlineSpiller::SibValueInfo &SVI) {
317 OS << "spill " << PrintReg(SVI.SpillReg) << ':'
318 << SVI.SpillVNI->id << '@' << SVI.SpillVNI->def;
320 OS << " in BB#" << SVI.SpillMBB->getNumber();
321 if (SVI.AllDefsAreReloads)
322 OS << " all-reloads";
323 if (SVI.DefByOrigPHI)
328 for (unsigned i = 0, e = SVI.Deps.size(); i != e; ++i)
329 OS << ' ' << SVI.Deps[i]->id << '@' << SVI.Deps[i]->def;
332 OS << " def: " << *SVI.DefMI;
339 /// propagateSiblingValue - Propagate the value in SVI to dependents if it is
340 /// known. Otherwise remember the dependency for later.
342 /// @param SVIIter SibValues entry to propagate.
343 /// @param VNI Dependent value, or NULL to propagate to all saved dependents.
344 void InlineSpiller::propagateSiblingValue(SibValueMap::iterator SVIIter,
346 SibValueMap::value_type *SVI = &*SVIIter;
348 // When VNI is non-NULL, add it to SVI's deps, and only propagate to that.
349 TinyPtrVector<VNInfo*> FirstDeps;
351 FirstDeps.push_back(VNI);
352 SVI->second.Deps.push_back(VNI);
355 // Has the value been completely determined yet? If not, defer propagation.
356 if (!SVI->second.hasDef())
359 // Work list of values to propagate.
360 SmallSetVector<SibValueMap::value_type *, 8> WorkList;
361 WorkList.insert(SVI);
364 SVI = WorkList.pop_back_val();
365 TinyPtrVector<VNInfo*> *Deps = VNI ? &FirstDeps : &SVI->second.Deps;
368 SibValueInfo &SV = SVI->second;
370 SV.SpillMBB = LIS.getMBBFromIndex(SV.SpillVNI->def);
372 DEBUG(dbgs() << " prop to " << Deps->size() << ": "
373 << SVI->first->id << '@' << SVI->first->def << ":\t" << SV);
375 assert(SV.hasDef() && "Propagating undefined value");
377 // Should this value be propagated as a preferred spill candidate? We don't
378 // propagate values of registers that are about to spill.
379 bool PropSpill = !DisableHoisting && !isRegToSpill(SV.SpillReg);
380 unsigned SpillDepth = ~0u;
382 for (TinyPtrVector<VNInfo*>::iterator DepI = Deps->begin(),
383 DepE = Deps->end(); DepI != DepE; ++DepI) {
384 SibValueMap::iterator DepSVI = SibValues.find(*DepI);
385 assert(DepSVI != SibValues.end() && "Dependent value not in SibValues");
386 SibValueInfo &DepSV = DepSVI->second;
388 DepSV.SpillMBB = LIS.getMBBFromIndex(DepSV.SpillVNI->def);
390 bool Changed = false;
392 // Propagate defining instruction.
393 if (!DepSV.hasDef()) {
395 DepSV.DefMI = SV.DefMI;
396 DepSV.DefByOrigPHI = SV.DefByOrigPHI;
399 // Propagate AllDefsAreReloads. For PHI values, this computes an AND of
401 if (!SV.AllDefsAreReloads && DepSV.AllDefsAreReloads) {
403 DepSV.AllDefsAreReloads = false;
406 // Propagate best spill value.
407 if (PropSpill && SV.SpillVNI != DepSV.SpillVNI) {
408 if (SV.SpillMBB == DepSV.SpillMBB) {
409 // DepSV is in the same block. Hoist when dominated.
410 if (DepSV.KillsSource && SV.SpillVNI->def < DepSV.SpillVNI->def) {
411 // This is an alternative def earlier in the same MBB.
412 // Hoist the spill as far as possible in SpillMBB. This can ease
413 // register pressure:
419 // Hoisting the spill of s to immediately after the def removes the
420 // interference between x and y:
426 // This hoist only helps when the DepSV copy kills its source.
428 DepSV.SpillReg = SV.SpillReg;
429 DepSV.SpillVNI = SV.SpillVNI;
430 DepSV.SpillMBB = SV.SpillMBB;
433 // DepSV is in a different block.
434 if (SpillDepth == ~0u)
435 SpillDepth = Loops.getLoopDepth(SV.SpillMBB);
437 // Also hoist spills to blocks with smaller loop depth, but make sure
438 // that the new value dominates. Non-phi dependents are always
439 // dominated, phis need checking.
441 const BranchProbability MarginProb(4, 5); // 80%
442 // Hoist a spill to outer loop if there are multiple dependents (it
443 // can be beneficial if more than one dependents are hoisted) or
444 // if DepSV (the hoisting source) is hotter than SV (the hoisting
445 // destination) (we add a 80% margin to bias a little towards
447 bool HoistCondition =
448 (MBFI.getBlockFreq(DepSV.SpillMBB) >=
449 (MBFI.getBlockFreq(SV.SpillMBB) * MarginProb)) ||
452 if ((Loops.getLoopDepth(DepSV.SpillMBB) > SpillDepth) &&
454 (!DepSVI->first->isPHIDef() ||
455 MDT.dominates(SV.SpillMBB, DepSV.SpillMBB))) {
457 DepSV.SpillReg = SV.SpillReg;
458 DepSV.SpillVNI = SV.SpillVNI;
459 DepSV.SpillMBB = SV.SpillMBB;
467 // Something changed in DepSVI. Propagate to dependents.
468 WorkList.insert(&*DepSVI);
470 DEBUG(dbgs() << " update " << DepSVI->first->id << '@'
471 << DepSVI->first->def << " to:\t" << DepSV);
473 } while (!WorkList.empty());
476 /// traceSiblingValue - Trace a value that is about to be spilled back to the
477 /// real defining instructions by looking through sibling copies. Always stay
478 /// within the range of OrigVNI so the registers are known to carry the same
481 /// Determine if the value is defined by all reloads, so spilling isn't
482 /// necessary - the value is already in the stack slot.
484 /// Return a defining instruction that may be a candidate for rematerialization.
486 MachineInstr *InlineSpiller::traceSiblingValue(unsigned UseReg, VNInfo *UseVNI,
488 // Check if a cached value already exists.
489 SibValueMap::iterator SVI;
491 std::tie(SVI, Inserted) =
492 SibValues.insert(std::make_pair(UseVNI, SibValueInfo(UseReg, UseVNI)));
494 DEBUG(dbgs() << "Cached value " << PrintReg(UseReg) << ':'
495 << UseVNI->id << '@' << UseVNI->def << ' ' << SVI->second);
496 return SVI->second.DefMI;
499 DEBUG(dbgs() << "Tracing value " << PrintReg(UseReg) << ':'
500 << UseVNI->id << '@' << UseVNI->def << '\n');
502 // List of (Reg, VNI) that have been inserted into SibValues, but need to be
504 SmallVector<std::pair<unsigned, VNInfo*>, 8> WorkList;
505 WorkList.push_back(std::make_pair(UseReg, UseVNI));
510 std::tie(Reg, VNI) = WorkList.pop_back_val();
511 DEBUG(dbgs() << " " << PrintReg(Reg) << ':' << VNI->id << '@' << VNI->def
514 // First check if this value has already been computed.
515 SVI = SibValues.find(VNI);
516 assert(SVI != SibValues.end() && "Missing SibValues entry");
518 // Trace through PHI-defs created by live range splitting.
519 if (VNI->isPHIDef()) {
520 // Stop at original PHIs. We don't know the value at the predecessors.
521 if (VNI->def == OrigVNI->def) {
522 DEBUG(dbgs() << "orig phi value\n");
523 SVI->second.DefByOrigPHI = true;
524 SVI->second.AllDefsAreReloads = false;
525 propagateSiblingValue(SVI);
529 // This is a PHI inserted by live range splitting. We could trace the
530 // live-out value from predecessor blocks, but that search can be very
531 // expensive if there are many predecessors and many more PHIs as
532 // generated by tail-dup when it sees an indirectbr. Instead, look at
533 // all the non-PHI defs that have the same value as OrigVNI. They must
534 // jointly dominate VNI->def. This is not optimal since VNI may actually
535 // be jointly dominated by a smaller subset of defs, so there is a change
536 // we will miss a AllDefsAreReloads optimization.
538 // Separate all values dominated by OrigVNI into PHIs and non-PHIs.
539 SmallVector<VNInfo*, 8> PHIs, NonPHIs;
540 LiveInterval &LI = LIS.getInterval(Reg);
541 LiveInterval &OrigLI = LIS.getInterval(Original);
543 for (LiveInterval::vni_iterator VI = LI.vni_begin(), VE = LI.vni_end();
546 if (VNI2->isUnused())
548 if (!OrigLI.containsOneValue() &&
549 OrigLI.getVNInfoAt(VNI2->def) != OrigVNI)
551 if (VNI2->isPHIDef() && VNI2->def != OrigVNI->def)
552 PHIs.push_back(VNI2);
554 NonPHIs.push_back(VNI2);
556 DEBUG(dbgs() << "split phi value, checking " << PHIs.size()
557 << " phi-defs, and " << NonPHIs.size()
558 << " non-phi/orig defs\n");
560 // Create entries for all the PHIs. Don't add them to the worklist, we
561 // are processing all of them in one go here.
562 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
563 SibValues.insert(std::make_pair(PHIs[i], SibValueInfo(Reg, PHIs[i])));
565 // Add every PHI as a dependent of all the non-PHIs.
566 for (unsigned i = 0, e = NonPHIs.size(); i != e; ++i) {
567 VNInfo *NonPHI = NonPHIs[i];
568 // Known value? Try an insertion.
569 std::tie(SVI, Inserted) =
570 SibValues.insert(std::make_pair(NonPHI, SibValueInfo(Reg, NonPHI)));
571 // Add all the PHIs as dependents of NonPHI.
572 for (unsigned pi = 0, pe = PHIs.size(); pi != pe; ++pi)
573 SVI->second.Deps.push_back(PHIs[pi]);
574 // This is the first time we see NonPHI, add it to the worklist.
576 WorkList.push_back(std::make_pair(Reg, NonPHI));
578 // Propagate to all inserted PHIs, not just VNI.
579 propagateSiblingValue(SVI);
582 // Next work list item.
586 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
587 assert(MI && "Missing def");
589 // Trace through sibling copies.
590 if (unsigned SrcReg = isFullCopyOf(MI, Reg)) {
591 if (isSibling(SrcReg)) {
592 LiveInterval &SrcLI = LIS.getInterval(SrcReg);
593 LiveQueryResult SrcQ = SrcLI.Query(VNI->def);
594 assert(SrcQ.valueIn() && "Copy from non-existing value");
595 // Check if this COPY kills its source.
596 SVI->second.KillsSource = SrcQ.isKill();
597 VNInfo *SrcVNI = SrcQ.valueIn();
598 DEBUG(dbgs() << "copy of " << PrintReg(SrcReg) << ':'
599 << SrcVNI->id << '@' << SrcVNI->def
600 << " kill=" << unsigned(SVI->second.KillsSource) << '\n');
601 // Known sibling source value? Try an insertion.
602 std::tie(SVI, Inserted) = SibValues.insert(
603 std::make_pair(SrcVNI, SibValueInfo(SrcReg, SrcVNI)));
604 // This is the first time we see Src, add it to the worklist.
606 WorkList.push_back(std::make_pair(SrcReg, SrcVNI));
607 propagateSiblingValue(SVI, VNI);
608 // Next work list item.
613 // Track reachable reloads.
614 SVI->second.DefMI = MI;
615 SVI->second.SpillMBB = MI->getParent();
617 if (Reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot) {
618 DEBUG(dbgs() << "reload\n");
619 propagateSiblingValue(SVI);
620 // Next work list item.
624 // Potential remat candidate.
625 DEBUG(dbgs() << "def " << *MI);
626 SVI->second.AllDefsAreReloads = false;
627 propagateSiblingValue(SVI);
628 } while (!WorkList.empty());
630 // Look up the value we were looking for. We already did this lookup at the
631 // top of the function, but SibValues may have been invalidated.
632 SVI = SibValues.find(UseVNI);
633 assert(SVI != SibValues.end() && "Didn't compute requested info");
634 DEBUG(dbgs() << " traced to:\t" << SVI->second);
635 return SVI->second.DefMI;
638 /// analyzeSiblingValues - Trace values defined by sibling copies back to
639 /// something that isn't a sibling copy.
641 /// Keep track of values that may be rematerializable.
642 void InlineSpiller::analyzeSiblingValues() {
645 // No siblings at all?
646 if (Edit->getReg() == Original)
649 LiveInterval &OrigLI = LIS.getInterval(Original);
650 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
651 unsigned Reg = RegsToSpill[i];
652 LiveInterval &LI = LIS.getInterval(Reg);
653 for (LiveInterval::const_vni_iterator VI = LI.vni_begin(),
654 VE = LI.vni_end(); VI != VE; ++VI) {
658 MachineInstr *DefMI = nullptr;
659 if (!VNI->isPHIDef()) {
660 DefMI = LIS.getInstructionFromIndex(VNI->def);
661 assert(DefMI && "No defining instruction");
663 // Check possible sibling copies.
664 if (VNI->isPHIDef() || DefMI->isCopy()) {
665 VNInfo *OrigVNI = OrigLI.getVNInfoAt(VNI->def);
666 assert(OrigVNI && "Def outside original live range");
667 if (OrigVNI->def != VNI->def)
668 DefMI = traceSiblingValue(Reg, VNI, OrigVNI);
670 if (DefMI && Edit->checkRematerializable(VNI, DefMI, AA)) {
671 DEBUG(dbgs() << "Value " << PrintReg(Reg) << ':' << VNI->id << '@'
672 << VNI->def << " may remat from " << *DefMI);
678 /// hoistSpill - Given a sibling copy that defines a value to be spilled, insert
679 /// a spill at a better location.
680 bool InlineSpiller::hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI) {
681 SlotIndex Idx = LIS.getInstructionIndex(CopyMI);
682 VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getRegSlot());
683 assert(VNI && VNI->def == Idx.getRegSlot() && "Not defined by copy");
684 SibValueMap::iterator I = SibValues.find(VNI);
685 if (I == SibValues.end())
688 const SibValueInfo &SVI = I->second;
690 // Let the normal folding code deal with the boring case.
691 if (!SVI.AllDefsAreReloads && SVI.SpillVNI == VNI)
694 // SpillReg may have been deleted by remat and DCE.
695 if (!LIS.hasInterval(SVI.SpillReg)) {
696 DEBUG(dbgs() << "Stale interval: " << PrintReg(SVI.SpillReg) << '\n');
701 LiveInterval &SibLI = LIS.getInterval(SVI.SpillReg);
702 if (!SibLI.containsValue(SVI.SpillVNI)) {
703 DEBUG(dbgs() << "Stale value: " << PrintReg(SVI.SpillReg) << '\n');
708 // Conservatively extend the stack slot range to the range of the original
709 // value. We may be able to do better with stack slot coloring by being more
711 assert(StackInt && "No stack slot assigned yet.");
712 LiveInterval &OrigLI = LIS.getInterval(Original);
713 VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
714 StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0));
715 DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
716 << *StackInt << '\n');
718 // Already spilled everywhere.
719 if (SVI.AllDefsAreReloads) {
720 DEBUG(dbgs() << "\tno spill needed: " << SVI);
721 ++NumOmitReloadSpill;
724 // We are going to spill SVI.SpillVNI immediately after its def, so clear out
725 // any later spills of the same value.
726 eliminateRedundantSpills(SibLI, SVI.SpillVNI);
728 MachineBasicBlock *MBB = LIS.getMBBFromIndex(SVI.SpillVNI->def);
729 MachineBasicBlock::iterator MII;
730 if (SVI.SpillVNI->isPHIDef())
731 MII = MBB->SkipPHIsAndLabels(MBB->begin());
733 MachineInstr *DefMI = LIS.getInstructionFromIndex(SVI.SpillVNI->def);
734 assert(DefMI && "Defining instruction disappeared");
738 // Insert spill without kill flag immediately after def.
739 TII.storeRegToStackSlot(*MBB, MII, SVI.SpillReg, false, StackSlot,
740 MRI.getRegClass(SVI.SpillReg), &TRI);
741 --MII; // Point to store instruction.
742 LIS.InsertMachineInstrInMaps(MII);
743 DEBUG(dbgs() << "\thoisted: " << SVI.SpillVNI->def << '\t' << *MII);
750 /// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any
751 /// redundant spills of this value in SLI.reg and sibling copies.
752 void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
753 assert(VNI && "Missing value");
754 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
755 WorkList.push_back(std::make_pair(&SLI, VNI));
756 assert(StackInt && "No stack slot assigned yet.");
760 std::tie(LI, VNI) = WorkList.pop_back_val();
761 unsigned Reg = LI->reg;
762 DEBUG(dbgs() << "Checking redundant spills for "
763 << VNI->id << '@' << VNI->def << " in " << *LI << '\n');
765 // Regs to spill are taken care of.
766 if (isRegToSpill(Reg))
769 // Add all of VNI's live range to StackInt.
770 StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0));
771 DEBUG(dbgs() << "Merged to stack int: " << *StackInt << '\n');
773 // Find all spills and copies of VNI.
774 for (MachineRegisterInfo::use_instr_nodbg_iterator
775 UI = MRI.use_instr_nodbg_begin(Reg), E = MRI.use_instr_nodbg_end();
777 MachineInstr *MI = &*(UI++);
778 if (!MI->isCopy() && !MI->mayStore())
780 SlotIndex Idx = LIS.getInstructionIndex(MI);
781 if (LI->getVNInfoAt(Idx) != VNI)
784 // Follow sibling copies down the dominator tree.
785 if (unsigned DstReg = isFullCopyOf(MI, Reg)) {
786 if (isSibling(DstReg)) {
787 LiveInterval &DstLI = LIS.getInterval(DstReg);
788 VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getRegSlot());
789 assert(DstVNI && "Missing defined value");
790 assert(DstVNI->def == Idx.getRegSlot() && "Wrong copy def slot");
791 WorkList.push_back(std::make_pair(&DstLI, DstVNI));
798 if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) {
799 DEBUG(dbgs() << "Redundant spill " << Idx << '\t' << *MI);
800 // eliminateDeadDefs won't normally remove stores, so switch opcode.
801 MI->setDesc(TII.get(TargetOpcode::KILL));
802 DeadDefs.push_back(MI);
807 } while (!WorkList.empty());
811 //===----------------------------------------------------------------------===//
813 //===----------------------------------------------------------------------===//
815 /// markValueUsed - Remember that VNI failed to rematerialize, so its defining
816 /// instruction cannot be eliminated. See through snippet copies
817 void InlineSpiller::markValueUsed(LiveInterval *LI, VNInfo *VNI) {
818 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
819 WorkList.push_back(std::make_pair(LI, VNI));
821 std::tie(LI, VNI) = WorkList.pop_back_val();
822 if (!UsedValues.insert(VNI))
825 if (VNI->isPHIDef()) {
826 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
827 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
828 PE = MBB->pred_end(); PI != PE; ++PI) {
829 VNInfo *PVNI = LI->getVNInfoBefore(LIS.getMBBEndIdx(*PI));
831 WorkList.push_back(std::make_pair(LI, PVNI));
836 // Follow snippet copies.
837 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
838 if (!SnippetCopies.count(MI))
840 LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg());
841 assert(isRegToSpill(SnipLI.reg) && "Unexpected register in copy");
842 VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getRegSlot(true));
843 assert(SnipVNI && "Snippet undefined before copy");
844 WorkList.push_back(std::make_pair(&SnipLI, SnipVNI));
845 } while (!WorkList.empty());
848 /// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
849 bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg,
850 MachineBasicBlock::iterator MI) {
852 // Analyze instruction
853 SmallVector<std::pair<MachineInstr *, unsigned>, 8> Ops;
854 MIBundleOperands::VirtRegInfo RI =
855 MIBundleOperands(MI).analyzeVirtReg(VirtReg.reg, &Ops);
860 SlotIndex UseIdx = LIS.getInstructionIndex(MI).getRegSlot(true);
861 VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx.getBaseIndex());
864 DEBUG(dbgs() << "\tadding <undef> flags: ");
865 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
866 MachineOperand &MO = MI->getOperand(i);
867 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg)
870 DEBUG(dbgs() << UseIdx << '\t' << *MI);
874 if (SnippetCopies.count(MI))
877 // Use an OrigVNI from traceSiblingValue when ParentVNI is a sibling copy.
878 LiveRangeEdit::Remat RM(ParentVNI);
879 SibValueMap::const_iterator SibI = SibValues.find(ParentVNI);
880 if (SibI != SibValues.end())
881 RM.OrigMI = SibI->second.DefMI;
882 if (!Edit->canRematerializeAt(RM, UseIdx, false)) {
883 markValueUsed(&VirtReg, ParentVNI);
884 DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
888 // If the instruction also writes VirtReg.reg, it had better not require the
889 // same register for uses and defs.
891 markValueUsed(&VirtReg, ParentVNI);
892 DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
896 // Before rematerializing into a register for a single instruction, try to
897 // fold a load into the instruction. That avoids allocating a new register.
898 if (RM.OrigMI->canFoldAsLoad() &&
899 foldMemoryOperand(Ops, RM.OrigMI)) {
900 Edit->markRematerialized(RM.ParentVNI);
905 // Alocate a new register for the remat.
906 unsigned NewVReg = Edit->createFrom(Original);
908 // Finally we can rematerialize OrigMI before MI.
909 SlotIndex DefIdx = Edit->rematerializeAt(*MI->getParent(), MI, NewVReg, RM,
912 DEBUG(dbgs() << "\tremat: " << DefIdx << '\t'
913 << *LIS.getInstructionFromIndex(DefIdx));
916 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
917 MachineOperand &MO = MI->getOperand(Ops[i].second);
918 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg) {
923 DEBUG(dbgs() << "\t " << UseIdx << '\t' << *MI << '\n');
929 /// reMaterializeAll - Try to rematerialize as many uses as possible,
930 /// and trim the live ranges after.
931 void InlineSpiller::reMaterializeAll() {
932 // analyzeSiblingValues has already tested all relevant defining instructions.
933 if (!Edit->anyRematerializable(AA))
938 // Try to remat before all uses of snippets.
939 bool anyRemat = false;
940 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
941 unsigned Reg = RegsToSpill[i];
942 LiveInterval &LI = LIS.getInterval(Reg);
943 for (MachineRegisterInfo::reg_bundle_iterator
944 RegI = MRI.reg_bundle_begin(Reg), E = MRI.reg_bundle_end();
946 MachineInstr *MI = &*(RegI++);
948 // Debug values are not allowed to affect codegen.
949 if (MI->isDebugValue())
952 anyRemat |= reMaterializeFor(LI, MI);
958 // Remove any values that were completely rematted.
959 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
960 unsigned Reg = RegsToSpill[i];
961 LiveInterval &LI = LIS.getInterval(Reg);
962 for (LiveInterval::vni_iterator I = LI.vni_begin(), E = LI.vni_end();
965 if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI))
967 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
968 MI->addRegisterDead(Reg, &TRI);
969 if (!MI->allDefsAreDead())
971 DEBUG(dbgs() << "All defs dead: " << *MI);
972 DeadDefs.push_back(MI);
976 // Eliminate dead code after remat. Note that some snippet copies may be
978 if (DeadDefs.empty())
980 DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n");
981 Edit->eliminateDeadDefs(DeadDefs, RegsToSpill);
983 // Get rid of deleted and empty intervals.
984 unsigned ResultPos = 0;
985 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
986 unsigned Reg = RegsToSpill[i];
987 if (!LIS.hasInterval(Reg))
990 LiveInterval &LI = LIS.getInterval(Reg);
992 Edit->eraseVirtReg(Reg);
996 RegsToSpill[ResultPos++] = Reg;
998 RegsToSpill.erase(RegsToSpill.begin() + ResultPos, RegsToSpill.end());
999 DEBUG(dbgs() << RegsToSpill.size() << " registers to spill after remat.\n");
1003 //===----------------------------------------------------------------------===//
1005 //===----------------------------------------------------------------------===//
1007 /// If MI is a load or store of StackSlot, it can be removed.
1008 bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, unsigned Reg) {
1010 unsigned InstrReg = TII.isLoadFromStackSlot(MI, FI);
1011 bool IsLoad = InstrReg;
1013 InstrReg = TII.isStoreToStackSlot(MI, FI);
1015 // We have a stack access. Is it the right register and slot?
1016 if (InstrReg != Reg || FI != StackSlot)
1019 DEBUG(dbgs() << "Coalescing stack access: " << *MI);
1020 LIS.RemoveMachineInstrFromMaps(MI);
1021 MI->eraseFromParent();
1024 ++NumReloadsRemoved;
1034 #if !defined(NDEBUG)
1035 // Dump the range of instructions from B to E with their slot indexes.
1036 static void dumpMachineInstrRangeWithSlotIndex(MachineBasicBlock::iterator B,
1037 MachineBasicBlock::iterator E,
1038 LiveIntervals const &LIS,
1039 const char *const header,
1041 char NextLine = '\n';
1042 char SlotIndent = '\t';
1044 if (std::next(B) == E) {
1049 dbgs() << '\t' << header << ": " << NextLine;
1051 for (MachineBasicBlock::iterator I = B; I != E; ++I) {
1052 SlotIndex Idx = LIS.getInstructionIndex(I).getRegSlot();
1054 // If a register was passed in and this instruction has it as a
1055 // destination that is marked as an early clobber, print the
1056 // early-clobber slot index.
1058 MachineOperand *MO = I->findRegisterDefOperand(VReg);
1059 if (MO && MO->isEarlyClobber())
1060 Idx = Idx.getRegSlot(true);
1063 dbgs() << SlotIndent << Idx << '\t' << *I;
1068 /// foldMemoryOperand - Try folding stack slot references in Ops into their
1071 /// @param Ops Operand indices from analyzeVirtReg().
1072 /// @param LoadMI Load instruction to use instead of stack slot when non-null.
1073 /// @return True on success.
1074 bool InlineSpiller::
1075 foldMemoryOperand(ArrayRef<std::pair<MachineInstr*, unsigned> > Ops,
1076 MachineInstr *LoadMI) {
1079 // Don't attempt folding in bundles.
1080 MachineInstr *MI = Ops.front().first;
1081 if (Ops.back().first != MI || MI->isBundled())
1084 bool WasCopy = MI->isCopy();
1085 unsigned ImpReg = 0;
1087 bool SpillSubRegs = (MI->getOpcode() == TargetOpcode::PATCHPOINT ||
1088 MI->getOpcode() == TargetOpcode::STACKMAP);
1090 // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
1092 SmallVector<unsigned, 8> FoldOps;
1093 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1094 unsigned Idx = Ops[i].second;
1095 MachineOperand &MO = MI->getOperand(Idx);
1096 if (MO.isImplicit()) {
1097 ImpReg = MO.getReg();
1100 // FIXME: Teach targets to deal with subregs.
1101 if (!SpillSubRegs && MO.getSubReg())
1103 // We cannot fold a load instruction into a def.
1104 if (LoadMI && MO.isDef())
1106 // Tied use operands should not be passed to foldMemoryOperand.
1107 if (!MI->isRegTiedToDefOperand(Idx))
1108 FoldOps.push_back(Idx);
1111 MachineInstrSpan MIS(MI);
1113 MachineInstr *FoldMI =
1114 LoadMI ? TII.foldMemoryOperand(MI, FoldOps, LoadMI)
1115 : TII.foldMemoryOperand(MI, FoldOps, StackSlot);
1119 // Remove LIS for any dead defs in the original MI not in FoldMI.
1120 for (MIBundleOperands MO(MI); MO.isValid(); ++MO) {
1123 unsigned Reg = MO->getReg();
1124 if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg) ||
1125 MRI.isReserved(Reg)) {
1128 // Skip non-Defs, including undef uses and internal reads.
1131 MIBundleOperands::PhysRegInfo RI =
1132 MIBundleOperands(FoldMI).analyzePhysReg(Reg, &TRI);
1135 // FoldMI does not define this physreg. Remove the LI segment.
1136 assert(MO->isDead() && "Cannot fold physreg def");
1137 for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units) {
1138 if (LiveRange *LR = LIS.getCachedRegUnit(*Units)) {
1139 SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
1140 if (VNInfo *VNI = LR->getVNInfoAt(Idx))
1141 LR->removeValNo(VNI);
1146 LIS.ReplaceMachineInstrInMaps(MI, FoldMI);
1147 MI->eraseFromParent();
1149 // Insert any new instructions other than FoldMI into the LIS maps.
1150 assert(!MIS.empty() && "Unexpected empty span of instructions!");
1151 for (MachineBasicBlock::iterator MII = MIS.begin(), End = MIS.end();
1153 if (&*MII != FoldMI)
1154 LIS.InsertMachineInstrInMaps(&*MII);
1156 // TII.foldMemoryOperand may have left some implicit operands on the
1157 // instruction. Strip them.
1159 for (unsigned i = FoldMI->getNumOperands(); i; --i) {
1160 MachineOperand &MO = FoldMI->getOperand(i - 1);
1161 if (!MO.isReg() || !MO.isImplicit())
1163 if (MO.getReg() == ImpReg)
1164 FoldMI->RemoveOperand(i - 1);
1167 DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MIS.end(), LIS,
1172 else if (Ops.front().second == 0)
1179 void InlineSpiller::insertReload(unsigned NewVReg,
1181 MachineBasicBlock::iterator MI) {
1182 MachineBasicBlock &MBB = *MI->getParent();
1184 MachineInstrSpan MIS(MI);
1185 TII.loadRegFromStackSlot(MBB, MI, NewVReg, StackSlot,
1186 MRI.getRegClass(NewVReg), &TRI);
1188 LIS.InsertMachineInstrRangeInMaps(MIS.begin(), MI);
1190 DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MI, LIS, "reload",
1195 /// insertSpill - Insert a spill of NewVReg after MI.
1196 void InlineSpiller::insertSpill(unsigned NewVReg, bool isKill,
1197 MachineBasicBlock::iterator MI) {
1198 MachineBasicBlock &MBB = *MI->getParent();
1200 MachineInstrSpan MIS(MI);
1201 TII.storeRegToStackSlot(MBB, std::next(MI), NewVReg, isKill, StackSlot,
1202 MRI.getRegClass(NewVReg), &TRI);
1204 LIS.InsertMachineInstrRangeInMaps(std::next(MI), MIS.end());
1206 DEBUG(dumpMachineInstrRangeWithSlotIndex(std::next(MI), MIS.end(), LIS,
1211 /// spillAroundUses - insert spill code around each use of Reg.
1212 void InlineSpiller::spillAroundUses(unsigned Reg) {
1213 DEBUG(dbgs() << "spillAroundUses " << PrintReg(Reg) << '\n');
1214 LiveInterval &OldLI = LIS.getInterval(Reg);
1216 // Iterate over instructions using Reg.
1217 for (MachineRegisterInfo::reg_bundle_iterator
1218 RegI = MRI.reg_bundle_begin(Reg), E = MRI.reg_bundle_end();
1220 MachineInstr *MI = &*(RegI++);
1222 // Debug values are not allowed to affect codegen.
1223 if (MI->isDebugValue()) {
1224 // Modify DBG_VALUE now that the value is in a spill slot.
1225 bool IsIndirect = MI->isIndirectDebugValue();
1226 uint64_t Offset = IsIndirect ? MI->getOperand(1).getImm() : 0;
1227 const MDNode *MDPtr = MI->getOperand(2).getMetadata();
1228 DebugLoc DL = MI->getDebugLoc();
1229 DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
1230 MachineBasicBlock *MBB = MI->getParent();
1231 BuildMI(*MBB, MBB->erase(MI), DL, TII.get(TargetOpcode::DBG_VALUE))
1232 .addFrameIndex(StackSlot).addImm(Offset).addMetadata(MDPtr);
1236 // Ignore copies to/from snippets. We'll delete them.
1237 if (SnippetCopies.count(MI))
1240 // Stack slot accesses may coalesce away.
1241 if (coalesceStackAccess(MI, Reg))
1244 // Analyze instruction.
1245 SmallVector<std::pair<MachineInstr*, unsigned>, 8> Ops;
1246 MIBundleOperands::VirtRegInfo RI =
1247 MIBundleOperands(MI).analyzeVirtReg(Reg, &Ops);
1249 // Find the slot index where this instruction reads and writes OldLI.
1250 // This is usually the def slot, except for tied early clobbers.
1251 SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
1252 if (VNInfo *VNI = OldLI.getVNInfoAt(Idx.getRegSlot(true)))
1253 if (SlotIndex::isSameInstr(Idx, VNI->def))
1256 // Check for a sibling copy.
1257 unsigned SibReg = isFullCopyOf(MI, Reg);
1258 if (SibReg && isSibling(SibReg)) {
1259 // This may actually be a copy between snippets.
1260 if (isRegToSpill(SibReg)) {
1261 DEBUG(dbgs() << "Found new snippet copy: " << *MI);
1262 SnippetCopies.insert(MI);
1266 // Hoist the spill of a sib-reg copy.
1267 if (hoistSpill(OldLI, MI)) {
1268 // This COPY is now dead, the value is already in the stack slot.
1269 MI->getOperand(0).setIsDead();
1270 DeadDefs.push_back(MI);
1274 // This is a reload for a sib-reg copy. Drop spills downstream.
1275 LiveInterval &SibLI = LIS.getInterval(SibReg);
1276 eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx));
1277 // The COPY will fold to a reload below.
1281 // Attempt to fold memory ops.
1282 if (foldMemoryOperand(Ops))
1285 // Create a new virtual register for spill/fill.
1286 // FIXME: Infer regclass from instruction alone.
1287 unsigned NewVReg = Edit->createFrom(Reg);
1290 insertReload(NewVReg, Idx, MI);
1292 // Rewrite instruction operands.
1293 bool hasLiveDef = false;
1294 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1295 MachineOperand &MO = Ops[i].first->getOperand(Ops[i].second);
1298 if (!Ops[i].first->isRegTiedToDefOperand(Ops[i].second))
1305 DEBUG(dbgs() << "\trewrite: " << Idx << '\t' << *MI << '\n');
1307 // FIXME: Use a second vreg if instruction has no tied ops.
1310 insertSpill(NewVReg, true, MI);
1314 /// spillAll - Spill all registers remaining after rematerialization.
1315 void InlineSpiller::spillAll() {
1316 // Update LiveStacks now that we are committed to spilling.
1317 if (StackSlot == VirtRegMap::NO_STACK_SLOT) {
1318 StackSlot = VRM.assignVirt2StackSlot(Original);
1319 StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original));
1320 StackInt->getNextValue(SlotIndex(), LSS.getVNInfoAllocator());
1322 StackInt = &LSS.getInterval(StackSlot);
1324 if (Original != Edit->getReg())
1325 VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot);
1327 assert(StackInt->getNumValNums() == 1 && "Bad stack interval values");
1328 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1329 StackInt->MergeSegmentsInAsValue(LIS.getInterval(RegsToSpill[i]),
1330 StackInt->getValNumInfo(0));
1331 DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n');
1333 // Spill around uses of all RegsToSpill.
1334 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1335 spillAroundUses(RegsToSpill[i]);
1337 // Hoisted spills may cause dead code.
1338 if (!DeadDefs.empty()) {
1339 DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n");
1340 Edit->eliminateDeadDefs(DeadDefs, RegsToSpill);
1343 // Finally delete the SnippetCopies.
1344 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
1345 for (MachineRegisterInfo::reg_instr_iterator
1346 RI = MRI.reg_instr_begin(RegsToSpill[i]), E = MRI.reg_instr_end();
1348 MachineInstr *MI = &*(RI++);
1349 assert(SnippetCopies.count(MI) && "Remaining use wasn't a snippet copy");
1350 // FIXME: Do this with a LiveRangeEdit callback.
1351 LIS.RemoveMachineInstrFromMaps(MI);
1352 MI->eraseFromParent();
1356 // Delete all spilled registers.
1357 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1358 Edit->eraseVirtReg(RegsToSpill[i]);
1361 void InlineSpiller::spill(LiveRangeEdit &edit) {
1364 assert(!TargetRegisterInfo::isStackSlot(edit.getReg())
1365 && "Trying to spill a stack slot.");
1366 // Share a stack slot among all descendants of Original.
1367 Original = VRM.getOriginal(edit.getReg());
1368 StackSlot = VRM.getStackSlot(Original);
1371 DEBUG(dbgs() << "Inline spilling "
1372 << MRI.getRegClass(edit.getReg())->getName()
1373 << ':' << edit.getParent()
1374 << "\nFrom original " << PrintReg(Original) << '\n');
1375 assert(edit.getParent().isSpillable() &&
1376 "Attempting to spill already spilled value.");
1377 assert(DeadDefs.empty() && "Previous spill didn't remove dead defs");
1379 collectRegsToSpill();
1380 analyzeSiblingValues();
1383 // Remat may handle everything.
1384 if (!RegsToSpill.empty())
1387 Edit->calculateRegClassAndHint(MF, Loops, MBFI);