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 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "regalloc"
17 #include "LiveRangeEdit.h"
18 #include "VirtRegMap.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/ADT/TinyPtrVector.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
23 #include "llvm/CodeGen/LiveStackAnalysis.h"
24 #include "llvm/CodeGen/MachineDominators.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineLoopInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
36 STATISTIC(NumSpilledRanges, "Number of spilled live ranges");
37 STATISTIC(NumSnippets, "Number of snippets included in spills");
38 STATISTIC(NumSpills, "Number of spills inserted");
39 STATISTIC(NumReloads, "Number of reloads inserted");
40 STATISTIC(NumFolded, "Number of folded stack accesses");
41 STATISTIC(NumFoldedLoads, "Number of folded loads");
42 STATISTIC(NumRemats, "Number of rematerialized defs for spilling");
43 STATISTIC(NumOmitReloadSpill, "Number of omitted spills after reloads");
44 STATISTIC(NumHoistLocal, "Number of locally hoisted spills");
45 STATISTIC(NumHoistGlobal, "Number of globally hoisted spills");
46 STATISTIC(NumRedundantSpills, "Number of redundant spills identified");
49 class InlineSpiller : public Spiller {
50 MachineFunctionPass &Pass;
55 MachineDominatorTree &MDT;
56 MachineLoopInfo &Loops;
58 MachineFrameInfo &MFI;
59 MachineRegisterInfo &MRI;
60 const TargetInstrInfo &TII;
61 const TargetRegisterInfo &TRI;
63 // Variables that are valid during spill(), but used by multiple methods.
65 LiveInterval *StackInt;
69 // All registers to spill to StackSlot, including the main register.
70 SmallVector<unsigned, 8> RegsToSpill;
72 // All COPY instructions to/from snippets.
73 // They are ignored since both operands refer to the same stack slot.
74 SmallPtrSet<MachineInstr*, 8> SnippetCopies;
76 // Values that failed to remat at some point.
77 SmallPtrSet<VNInfo*, 8> UsedValues;
80 // Information about a value that was defined by a copy from a sibling
83 // True when all reaching defs were reloads: No spill is necessary.
84 bool AllDefsAreReloads;
86 // True when value is defined by an original PHI not from splitting.
89 // The preferred register to spill.
92 // The value of SpillReg that should be spilled.
95 // The block where SpillVNI should be spilled. Currently, this must be the
96 // block containing SpillVNI->def.
97 MachineBasicBlock *SpillMBB;
99 // A defining instruction that is not a sibling copy or a reload, or NULL.
100 // This can be used as a template for rematerialization.
103 // List of values that depend on this one. These values are actually the
104 // same, but live range splitting has placed them in different registers,
105 // or SSA update needed to insert PHI-defs to preserve SSA form. This is
106 // copies of the current value and phi-kills. Usually only phi-kills cause
107 // more than one dependent value.
108 TinyPtrVector<VNInfo*> Deps;
110 SibValueInfo(unsigned Reg, VNInfo *VNI)
111 : AllDefsAreReloads(true), DefByOrigPHI(false),
112 SpillReg(Reg), SpillVNI(VNI), SpillMBB(0), DefMI(0) {}
114 // Returns true when a def has been found.
115 bool hasDef() const { return DefByOrigPHI || DefMI; }
119 // Values in RegsToSpill defined by sibling copies.
120 typedef DenseMap<VNInfo*, SibValueInfo> SibValueMap;
121 SibValueMap SibValues;
123 // Values live-out from basic blocks. This is the same as
124 // LI.getVNInfoAt(LIS.getMBBEndIdx(MBB).getPrevSlot())
125 typedef DenseMap<MachineBasicBlock*, VNInfo*> LiveOutMap;
126 LiveOutMap LiveOutValues;
128 // Dead defs generated during spilling.
129 SmallVector<MachineInstr*, 8> DeadDefs;
134 InlineSpiller(MachineFunctionPass &pass,
139 LIS(pass.getAnalysis<LiveIntervals>()),
140 LSS(pass.getAnalysis<LiveStacks>()),
141 AA(&pass.getAnalysis<AliasAnalysis>()),
142 MDT(pass.getAnalysis<MachineDominatorTree>()),
143 Loops(pass.getAnalysis<MachineLoopInfo>()),
145 MFI(*mf.getFrameInfo()),
146 MRI(mf.getRegInfo()),
147 TII(*mf.getTarget().getInstrInfo()),
148 TRI(*mf.getTarget().getRegisterInfo()) {}
150 void spill(LiveRangeEdit &);
153 bool isSnippet(const LiveInterval &SnipLI);
154 void collectRegsToSpill();
156 bool isRegToSpill(unsigned Reg) {
157 return std::find(RegsToSpill.begin(),
158 RegsToSpill.end(), Reg) != RegsToSpill.end();
161 bool isSibling(unsigned Reg);
162 MachineInstr *traceSiblingValue(unsigned, VNInfo*, VNInfo*);
163 void propagateSiblingValue(SibValueMap::iterator, VNInfo *VNI = 0);
164 void analyzeSiblingValues();
166 bool hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI);
167 void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI);
169 void markValueUsed(LiveInterval*, VNInfo*);
170 bool reMaterializeFor(LiveInterval&, MachineBasicBlock::iterator MI);
171 void reMaterializeAll();
173 bool coalesceStackAccess(MachineInstr *MI, unsigned Reg);
174 bool foldMemoryOperand(MachineBasicBlock::iterator MI,
175 const SmallVectorImpl<unsigned> &Ops,
176 MachineInstr *LoadMI = 0);
177 void insertReload(LiveInterval &NewLI, SlotIndex,
178 MachineBasicBlock::iterator MI);
179 void insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
180 SlotIndex, 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 = 0;
237 // Check that all uses satisfy our criteria.
238 for (MachineRegisterInfo::reg_nodbg_iterator
239 RI = MRI.reg_nodbg_begin(SnipLI.reg);
240 MachineInstr *MI = RI.skipInstruction();) {
242 // Allow copies to/from Reg.
243 if (isFullCopyOf(MI, Reg))
246 // Allow stack slot loads.
248 if (SnipLI.reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
251 // Allow stack slot stores.
252 if (SnipLI.reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
255 // Allow a single additional instruction.
256 if (UseMI && MI != UseMI)
263 /// collectRegsToSpill - Collect live range snippets that only have a single
265 void InlineSpiller::collectRegsToSpill() {
266 unsigned Reg = Edit->getReg();
268 // Main register always spills.
269 RegsToSpill.assign(1, Reg);
270 SnippetCopies.clear();
272 // Snippets all have the same original, so there can't be any for an original
277 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
278 MachineInstr *MI = RI.skipInstruction();) {
279 unsigned SnipReg = isFullCopyOf(MI, Reg);
280 if (!isSibling(SnipReg))
282 LiveInterval &SnipLI = LIS.getInterval(SnipReg);
283 if (!isSnippet(SnipLI))
285 SnippetCopies.insert(MI);
286 if (isRegToSpill(SnipReg))
288 RegsToSpill.push_back(SnipReg);
289 DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n');
295 //===----------------------------------------------------------------------===//
297 //===----------------------------------------------------------------------===//
299 // After live range splitting, some values to be spilled may be defined by
300 // copies from sibling registers. We trace the sibling copies back to the
301 // original value if it still exists. We need it for rematerialization.
303 // Even when the value can't be rematerialized, we still want to determine if
304 // the value has already been spilled, or we may want to hoist the spill from a
307 bool InlineSpiller::isSibling(unsigned Reg) {
308 return TargetRegisterInfo::isVirtualRegister(Reg) &&
309 VRM.getOriginal(Reg) == Original;
313 static raw_ostream &operator<<(raw_ostream &OS,
314 const InlineSpiller::SibValueInfo &SVI) {
315 OS << "spill " << PrintReg(SVI.SpillReg) << ':'
316 << SVI.SpillVNI->id << '@' << SVI.SpillVNI->def;
318 OS << " in BB#" << SVI.SpillMBB->getNumber();
319 if (SVI.AllDefsAreReloads)
320 OS << " all-reloads";
321 if (SVI.DefByOrigPHI)
324 for (unsigned i = 0, e = SVI.Deps.size(); i != e; ++i)
325 OS << ' ' << SVI.Deps[i]->id << '@' << SVI.Deps[i]->def;
328 OS << " def: " << *SVI.DefMI;
335 /// propagateSiblingValue - Propagate the value in SVI to dependents if it is
336 /// known. Otherwise remember the dependency for later.
338 /// @param SVI SibValues entry to propagate.
339 /// @param VNI Dependent value, or NULL to propagate to all saved dependents.
340 void InlineSpiller::propagateSiblingValue(SibValueMap::iterator SVI,
342 // When VNI is non-NULL, add it to SVI's deps, and only propagate to that.
343 TinyPtrVector<VNInfo*> FirstDeps;
345 FirstDeps.push_back(VNI);
346 SVI->second.Deps.push_back(VNI);
349 // Has the value been completely determined yet? If not, defer propagation.
350 if (!SVI->second.hasDef())
353 // Work list of values to propagate. It would be nice to use a SetVector
354 // here, but then we would be forced to use a SmallSet.
355 SmallVector<SibValueMap::iterator, 8> WorkList(1, SVI);
356 SmallPtrSet<VNInfo*, 8> WorkSet;
359 SVI = WorkList.pop_back_val();
360 WorkSet.erase(SVI->first);
361 TinyPtrVector<VNInfo*> *Deps = VNI ? &FirstDeps : &SVI->second.Deps;
364 SibValueInfo &SV = SVI->second;
366 SV.SpillMBB = LIS.getMBBFromIndex(SV.SpillVNI->def);
368 DEBUG(dbgs() << " prop to " << Deps->size() << ": "
369 << SVI->first->id << '@' << SVI->first->def << ":\t" << SV);
371 assert(SV.hasDef() && "Propagating undefined value");
373 // Should this value be propagated as a preferred spill candidate? We don't
374 // propagate values of registers that are about to spill.
375 bool PropSpill = !isRegToSpill(SV.SpillReg);
376 unsigned SpillDepth = ~0u;
378 for (TinyPtrVector<VNInfo*>::iterator DepI = Deps->begin(),
379 DepE = Deps->end(); DepI != DepE; ++DepI) {
380 SibValueMap::iterator DepSVI = SibValues.find(*DepI);
381 assert(DepSVI != SibValues.end() && "Dependent value not in SibValues");
382 SibValueInfo &DepSV = DepSVI->second;
384 DepSV.SpillMBB = LIS.getMBBFromIndex(DepSV.SpillVNI->def);
386 bool Changed = false;
388 // Propagate defining instruction.
389 if (!DepSV.hasDef()) {
391 DepSV.DefMI = SV.DefMI;
392 DepSV.DefByOrigPHI = SV.DefByOrigPHI;
395 // Propagate AllDefsAreReloads. For PHI values, this computes an AND of
397 if (!SV.AllDefsAreReloads && DepSV.AllDefsAreReloads) {
399 DepSV.AllDefsAreReloads = false;
402 // Propagate best spill value.
403 if (PropSpill && SV.SpillVNI != DepSV.SpillVNI) {
404 if (SV.SpillMBB == DepSV.SpillMBB) {
405 // DepSV is in the same block. Hoist when dominated.
406 if (SV.SpillVNI->def < DepSV.SpillVNI->def) {
407 // This is an alternative def earlier in the same MBB.
408 // Hoist the spill as far as possible in SpillMBB. This can ease
409 // register pressure:
415 // Hoisting the spill of s to immediately after the def removes the
416 // interference between x and y:
423 DepSV.SpillReg = SV.SpillReg;
424 DepSV.SpillVNI = SV.SpillVNI;
425 DepSV.SpillMBB = SV.SpillMBB;
428 // DepSV is in a different block.
429 if (SpillDepth == ~0u)
430 SpillDepth = Loops.getLoopDepth(SV.SpillMBB);
432 // Also hoist spills to blocks with smaller loop depth, but make sure
433 // that the new value dominates. Non-phi dependents are always
434 // dominated, phis need checking.
435 if ((Loops.getLoopDepth(DepSV.SpillMBB) > SpillDepth) &&
436 (!DepSVI->first->isPHIDef() ||
437 MDT.dominates(SV.SpillMBB, DepSV.SpillMBB))) {
439 DepSV.SpillReg = SV.SpillReg;
440 DepSV.SpillVNI = SV.SpillVNI;
441 DepSV.SpillMBB = SV.SpillMBB;
449 // Something changed in DepSVI. Propagate to dependents.
450 if (WorkSet.insert(DepSVI->first))
451 WorkList.push_back(DepSVI);
453 DEBUG(dbgs() << " update " << DepSVI->first->id << '@'
454 << DepSVI->first->def << " to:\t" << DepSV);
456 } while (!WorkList.empty());
459 /// traceSiblingValue - Trace a value that is about to be spilled back to the
460 /// real defining instructions by looking through sibling copies. Always stay
461 /// within the range of OrigVNI so the registers are known to carry the same
464 /// Determine if the value is defined by all reloads, so spilling isn't
465 /// necessary - the value is already in the stack slot.
467 /// Return a defining instruction that may be a candidate for rematerialization.
469 MachineInstr *InlineSpiller::traceSiblingValue(unsigned UseReg, VNInfo *UseVNI,
471 // Check if a cached value already exists.
472 SibValueMap::iterator SVI;
475 SibValues.insert(std::make_pair(UseVNI, SibValueInfo(UseReg, UseVNI)));
477 DEBUG(dbgs() << "Cached value " << PrintReg(UseReg) << ':'
478 << UseVNI->id << '@' << UseVNI->def << ' ' << SVI->second);
479 return SVI->second.DefMI;
482 DEBUG(dbgs() << "Tracing value " << PrintReg(UseReg) << ':'
483 << UseVNI->id << '@' << UseVNI->def << '\n');
485 // List of (Reg, VNI) that have been inserted into SibValues, but need to be
487 SmallVector<std::pair<unsigned, VNInfo*>, 8> WorkList;
488 WorkList.push_back(std::make_pair(UseReg, UseVNI));
493 tie(Reg, VNI) = WorkList.pop_back_val();
494 DEBUG(dbgs() << " " << PrintReg(Reg) << ':' << VNI->id << '@' << VNI->def
497 // First check if this value has already been computed.
498 SVI = SibValues.find(VNI);
499 assert(SVI != SibValues.end() && "Missing SibValues entry");
501 // Trace through PHI-defs created by live range splitting.
502 if (VNI->isPHIDef()) {
503 if (VNI->def == OrigVNI->def) {
504 DEBUG(dbgs() << "orig phi value\n");
505 SVI->second.DefByOrigPHI = true;
506 SVI->second.AllDefsAreReloads = false;
507 propagateSiblingValue(SVI);
510 // Get values live-out of predecessors.
511 LiveInterval &LI = LIS.getInterval(Reg);
512 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
513 DEBUG(dbgs() << "split phi value, check " << MBB->pred_size()
515 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
516 PE = MBB->pred_end(); PI != PE; ++PI) {
517 // Use a cache of block live-out values. This is faster than using
518 // getVNInfoAt on complex intervals.
519 VNInfo *&PVNI = LiveOutValues[*PI];
521 PVNI = LI.getVNInfoAt(LIS.getMBBEndIdx(*PI).getPrevSlot());
524 // Known predecessor value? Try an insertion.
526 SibValues.insert(std::make_pair(PVNI, SibValueInfo(Reg, PVNI)));
527 // This is the first time we see PVNI, add it to the worklist.
529 WorkList.push_back(std::make_pair(Reg, PVNI));
530 propagateSiblingValue(SVI, VNI);
532 // Next work list item.
536 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
537 assert(MI && "Missing def");
539 // Trace through sibling copies.
540 if (unsigned SrcReg = isFullCopyOf(MI, Reg)) {
541 if (isSibling(SrcReg)) {
542 LiveInterval &SrcLI = LIS.getInterval(SrcReg);
543 VNInfo *SrcVNI = SrcLI.getVNInfoAt(VNI->def.getUseIndex());
544 assert(SrcVNI && "Copy from non-existing value");
545 DEBUG(dbgs() << "copy of " << PrintReg(SrcReg) << ':'
546 << SrcVNI->id << '@' << SrcVNI->def << '\n');
547 // Known sibling source value? Try an insertion.
548 tie(SVI, Inserted) = SibValues.insert(std::make_pair(SrcVNI,
549 SibValueInfo(SrcReg, SrcVNI)));
550 // This is the first time we see Src, add it to the worklist.
552 WorkList.push_back(std::make_pair(SrcReg, SrcVNI));
553 propagateSiblingValue(SVI, VNI);
554 // Next work list item.
559 // Track reachable reloads.
560 SVI->second.DefMI = MI;
561 SVI->second.SpillMBB = MI->getParent();
563 if (Reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot) {
564 DEBUG(dbgs() << "reload\n");
565 propagateSiblingValue(SVI);
566 // Next work list item.
570 // Potential remat candidate.
571 DEBUG(dbgs() << "def " << *MI);
572 SVI->second.AllDefsAreReloads = false;
573 propagateSiblingValue(SVI);
574 } while (!WorkList.empty());
576 // Look up the value we were looking for. We already did this lokup at the
577 // top of the function, but SibValues may have been invalidated.
578 SVI = SibValues.find(UseVNI);
579 assert(SVI != SibValues.end() && "Didn't compute requested info");
580 DEBUG(dbgs() << " traced to:\t" << SVI->second);
581 return SVI->second.DefMI;
584 /// analyzeSiblingValues - Trace values defined by sibling copies back to
585 /// something that isn't a sibling copy.
587 /// Keep track of values that may be rematerializable.
588 void InlineSpiller::analyzeSiblingValues() {
590 LiveOutValues.clear();
592 // No siblings at all?
593 if (Edit->getReg() == Original)
596 LiveInterval &OrigLI = LIS.getInterval(Original);
597 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
598 unsigned Reg = RegsToSpill[i];
599 LiveInterval &LI = LIS.getInterval(Reg);
600 for (LiveInterval::const_vni_iterator VI = LI.vni_begin(),
601 VE = LI.vni_end(); VI != VE; ++VI) {
605 MachineInstr *DefMI = 0;
606 // Check possible sibling copies.
607 if (VNI->isPHIDef() || VNI->getCopy()) {
608 VNInfo *OrigVNI = OrigLI.getVNInfoAt(VNI->def);
609 assert(OrigVNI && "Def outside original live range");
610 if (OrigVNI->def != VNI->def)
611 DefMI = traceSiblingValue(Reg, VNI, OrigVNI);
613 if (!DefMI && !VNI->isPHIDef())
614 DefMI = LIS.getInstructionFromIndex(VNI->def);
615 if (DefMI && Edit->checkRematerializable(VNI, DefMI, TII, AA)) {
616 DEBUG(dbgs() << "Value " << PrintReg(Reg) << ':' << VNI->id << '@'
617 << VNI->def << " may remat from " << *DefMI);
623 /// hoistSpill - Given a sibling copy that defines a value to be spilled, insert
624 /// a spill at a better location.
625 bool InlineSpiller::hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI) {
626 SlotIndex Idx = LIS.getInstructionIndex(CopyMI);
627 VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getDefIndex());
628 assert(VNI && VNI->def == Idx.getDefIndex() && "Not defined by copy");
629 SibValueMap::iterator I = SibValues.find(VNI);
630 if (I == SibValues.end())
633 const SibValueInfo &SVI = I->second;
635 // Let the normal folding code deal with the boring case.
636 if (!SVI.AllDefsAreReloads && SVI.SpillVNI == VNI)
639 // SpillReg may have been deleted by remat and DCE.
640 if (!LIS.hasInterval(SVI.SpillReg)) {
641 DEBUG(dbgs() << "Stale interval: " << PrintReg(SVI.SpillReg) << '\n');
646 LiveInterval &SibLI = LIS.getInterval(SVI.SpillReg);
647 if (!SibLI.containsValue(SVI.SpillVNI)) {
648 DEBUG(dbgs() << "Stale value: " << PrintReg(SVI.SpillReg) << '\n');
653 // Conservatively extend the stack slot range to the range of the original
654 // value. We may be able to do better with stack slot coloring by being more
656 assert(StackInt && "No stack slot assigned yet.");
657 LiveInterval &OrigLI = LIS.getInterval(Original);
658 VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
659 StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0));
660 DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
661 << *StackInt << '\n');
663 // Already spilled everywhere.
664 if (SVI.AllDefsAreReloads) {
665 DEBUG(dbgs() << "\tno spill needed: " << SVI);
666 ++NumOmitReloadSpill;
669 // We are going to spill SVI.SpillVNI immediately after its def, so clear out
670 // any later spills of the same value.
671 eliminateRedundantSpills(SibLI, SVI.SpillVNI);
673 MachineBasicBlock *MBB = LIS.getMBBFromIndex(SVI.SpillVNI->def);
674 MachineBasicBlock::iterator MII;
675 if (SVI.SpillVNI->isPHIDef())
676 MII = MBB->SkipPHIsAndLabels(MBB->begin());
678 MachineInstr *DefMI = LIS.getInstructionFromIndex(SVI.SpillVNI->def);
679 assert(DefMI && "Defining instruction disappeared");
683 // Insert spill without kill flag immediately after def.
684 TII.storeRegToStackSlot(*MBB, MII, SVI.SpillReg, false, StackSlot,
685 MRI.getRegClass(SVI.SpillReg), &TRI);
686 --MII; // Point to store instruction.
687 LIS.InsertMachineInstrInMaps(MII);
688 VRM.addSpillSlotUse(StackSlot, MII);
689 DEBUG(dbgs() << "\thoisted: " << SVI.SpillVNI->def << '\t' << *MII);
691 if (MBB == CopyMI->getParent())
698 /// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any
699 /// redundant spills of this value in SLI.reg and sibling copies.
700 void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
701 assert(VNI && "Missing value");
702 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
703 WorkList.push_back(std::make_pair(&SLI, VNI));
704 assert(StackInt && "No stack slot assigned yet.");
708 tie(LI, VNI) = WorkList.pop_back_val();
709 unsigned Reg = LI->reg;
710 DEBUG(dbgs() << "Checking redundant spills for "
711 << VNI->id << '@' << VNI->def << " in " << *LI << '\n');
713 // Regs to spill are taken care of.
714 if (isRegToSpill(Reg))
717 // Add all of VNI's live range to StackInt.
718 StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0));
719 DEBUG(dbgs() << "Merged to stack int: " << *StackInt << '\n');
721 // Find all spills and copies of VNI.
722 for (MachineRegisterInfo::use_nodbg_iterator UI = MRI.use_nodbg_begin(Reg);
723 MachineInstr *MI = UI.skipInstruction();) {
724 if (!MI->isCopy() && !MI->getDesc().mayStore())
726 SlotIndex Idx = LIS.getInstructionIndex(MI);
727 if (LI->getVNInfoAt(Idx) != VNI)
730 // Follow sibling copies down the dominator tree.
731 if (unsigned DstReg = isFullCopyOf(MI, Reg)) {
732 if (isSibling(DstReg)) {
733 LiveInterval &DstLI = LIS.getInterval(DstReg);
734 VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getDefIndex());
735 assert(DstVNI && "Missing defined value");
736 assert(DstVNI->def == Idx.getDefIndex() && "Wrong copy def slot");
737 WorkList.push_back(std::make_pair(&DstLI, DstVNI));
744 if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) {
745 DEBUG(dbgs() << "Redundant spill " << Idx << '\t' << *MI);
746 // eliminateDeadDefs won't normally remove stores, so switch opcode.
747 MI->setDesc(TII.get(TargetOpcode::KILL));
748 DeadDefs.push_back(MI);
749 ++NumRedundantSpills;
752 } while (!WorkList.empty());
756 //===----------------------------------------------------------------------===//
758 //===----------------------------------------------------------------------===//
760 /// markValueUsed - Remember that VNI failed to rematerialize, so its defining
761 /// instruction cannot be eliminated. See through snippet copies
762 void InlineSpiller::markValueUsed(LiveInterval *LI, VNInfo *VNI) {
763 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
764 WorkList.push_back(std::make_pair(LI, VNI));
766 tie(LI, VNI) = WorkList.pop_back_val();
767 if (!UsedValues.insert(VNI))
770 if (VNI->isPHIDef()) {
771 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
772 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
773 PE = MBB->pred_end(); PI != PE; ++PI) {
774 VNInfo *PVNI = LI->getVNInfoAt(LIS.getMBBEndIdx(*PI).getPrevSlot());
776 WorkList.push_back(std::make_pair(LI, PVNI));
781 // Follow snippet copies.
782 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
783 if (!SnippetCopies.count(MI))
785 LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg());
786 assert(isRegToSpill(SnipLI.reg) && "Unexpected register in copy");
787 VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getUseIndex());
788 assert(SnipVNI && "Snippet undefined before copy");
789 WorkList.push_back(std::make_pair(&SnipLI, SnipVNI));
790 } while (!WorkList.empty());
793 /// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
794 bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg,
795 MachineBasicBlock::iterator MI) {
796 SlotIndex UseIdx = LIS.getInstructionIndex(MI).getUseIndex();
797 VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx.getBaseIndex());
800 DEBUG(dbgs() << "\tadding <undef> flags: ");
801 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
802 MachineOperand &MO = MI->getOperand(i);
803 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg)
806 DEBUG(dbgs() << UseIdx << '\t' << *MI);
810 if (SnippetCopies.count(MI))
813 // Use an OrigVNI from traceSiblingValue when ParentVNI is a sibling copy.
814 LiveRangeEdit::Remat RM(ParentVNI);
815 SibValueMap::const_iterator SibI = SibValues.find(ParentVNI);
816 if (SibI != SibValues.end())
817 RM.OrigMI = SibI->second.DefMI;
818 if (!Edit->canRematerializeAt(RM, UseIdx, false, LIS)) {
819 markValueUsed(&VirtReg, ParentVNI);
820 DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
824 // If the instruction also writes VirtReg.reg, it had better not require the
825 // same register for uses and defs.
827 SmallVector<unsigned, 8> Ops;
828 tie(Reads, Writes) = MI->readsWritesVirtualRegister(VirtReg.reg, &Ops);
830 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
831 MachineOperand &MO = MI->getOperand(Ops[i]);
832 if (MO.isUse() ? MI->isRegTiedToDefOperand(Ops[i]) : MO.getSubReg()) {
833 markValueUsed(&VirtReg, ParentVNI);
834 DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
840 // Before rematerializing into a register for a single instruction, try to
841 // fold a load into the instruction. That avoids allocating a new register.
842 if (RM.OrigMI->getDesc().canFoldAsLoad() &&
843 foldMemoryOperand(MI, Ops, RM.OrigMI)) {
844 Edit->markRematerialized(RM.ParentVNI);
849 // Alocate a new register for the remat.
850 LiveInterval &NewLI = Edit->createFrom(Original, LIS, VRM);
851 NewLI.markNotSpillable();
853 // Finally we can rematerialize OrigMI before MI.
854 SlotIndex DefIdx = Edit->rematerializeAt(*MI->getParent(), MI, NewLI.reg, RM,
856 DEBUG(dbgs() << "\tremat: " << DefIdx << '\t'
857 << *LIS.getInstructionFromIndex(DefIdx));
860 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
861 MachineOperand &MO = MI->getOperand(Ops[i]);
862 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg) {
863 MO.setReg(NewLI.reg);
867 DEBUG(dbgs() << "\t " << UseIdx << '\t' << *MI);
869 VNInfo *DefVNI = NewLI.getNextValue(DefIdx, 0, LIS.getVNInfoAllocator());
870 NewLI.addRange(LiveRange(DefIdx, UseIdx.getDefIndex(), DefVNI));
871 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
876 /// reMaterializeAll - Try to rematerialize as many uses as possible,
877 /// and trim the live ranges after.
878 void InlineSpiller::reMaterializeAll() {
879 // analyzeSiblingValues has already tested all relevant defining instructions.
880 if (!Edit->anyRematerializable(LIS, TII, AA))
885 // Try to remat before all uses of snippets.
886 bool anyRemat = false;
887 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
888 unsigned Reg = RegsToSpill[i];
889 LiveInterval &LI = LIS.getInterval(Reg);
890 for (MachineRegisterInfo::use_nodbg_iterator
891 RI = MRI.use_nodbg_begin(Reg);
892 MachineInstr *MI = RI.skipInstruction();)
893 anyRemat |= reMaterializeFor(LI, MI);
898 // Remove any values that were completely rematted.
899 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
900 unsigned Reg = RegsToSpill[i];
901 LiveInterval &LI = LIS.getInterval(Reg);
902 for (LiveInterval::vni_iterator I = LI.vni_begin(), E = LI.vni_end();
905 if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI))
907 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
908 MI->addRegisterDead(Reg, &TRI);
909 if (!MI->allDefsAreDead())
911 DEBUG(dbgs() << "All defs dead: " << *MI);
912 DeadDefs.push_back(MI);
916 // Eliminate dead code after remat. Note that some snippet copies may be
918 if (DeadDefs.empty())
920 DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n");
921 Edit->eliminateDeadDefs(DeadDefs, LIS, VRM, TII);
923 // Get rid of deleted and empty intervals.
924 for (unsigned i = RegsToSpill.size(); i != 0; --i) {
925 unsigned Reg = RegsToSpill[i-1];
926 if (!LIS.hasInterval(Reg)) {
927 RegsToSpill.erase(RegsToSpill.begin() + (i - 1));
930 LiveInterval &LI = LIS.getInterval(Reg);
933 Edit->eraseVirtReg(Reg, LIS);
934 RegsToSpill.erase(RegsToSpill.begin() + (i - 1));
936 DEBUG(dbgs() << RegsToSpill.size() << " registers to spill after remat.\n");
940 //===----------------------------------------------------------------------===//
942 //===----------------------------------------------------------------------===//
944 /// If MI is a load or store of StackSlot, it can be removed.
945 bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, unsigned Reg) {
948 if (!(InstrReg = TII.isLoadFromStackSlot(MI, FI)) &&
949 !(InstrReg = TII.isStoreToStackSlot(MI, FI)))
952 // We have a stack access. Is it the right register and slot?
953 if (InstrReg != Reg || FI != StackSlot)
956 DEBUG(dbgs() << "Coalescing stack access: " << *MI);
957 LIS.RemoveMachineInstrFromMaps(MI);
958 MI->eraseFromParent();
962 /// foldMemoryOperand - Try folding stack slot references in Ops into MI.
963 /// @param MI Instruction using or defining the current register.
964 /// @param Ops Operand indices from readsWritesVirtualRegister().
965 /// @param LoadMI Load instruction to use instead of stack slot when non-null.
966 /// @return True on success, and MI will be erased.
967 bool InlineSpiller::foldMemoryOperand(MachineBasicBlock::iterator MI,
968 const SmallVectorImpl<unsigned> &Ops,
969 MachineInstr *LoadMI) {
970 // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
972 SmallVector<unsigned, 8> FoldOps;
973 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
974 unsigned Idx = Ops[i];
975 MachineOperand &MO = MI->getOperand(Idx);
978 // FIXME: Teach targets to deal with subregs.
981 // We cannot fold a load instruction into a def.
982 if (LoadMI && MO.isDef())
984 // Tied use operands should not be passed to foldMemoryOperand.
985 if (!MI->isRegTiedToDefOperand(Idx))
986 FoldOps.push_back(Idx);
989 MachineInstr *FoldMI =
990 LoadMI ? TII.foldMemoryOperand(MI, FoldOps, LoadMI)
991 : TII.foldMemoryOperand(MI, FoldOps, StackSlot);
994 LIS.ReplaceMachineInstrInMaps(MI, FoldMI);
996 VRM.addSpillSlotUse(StackSlot, FoldMI);
997 MI->eraseFromParent();
998 DEBUG(dbgs() << "\tfolded: " << *FoldMI);
1003 /// insertReload - Insert a reload of NewLI.reg before MI.
1004 void InlineSpiller::insertReload(LiveInterval &NewLI,
1006 MachineBasicBlock::iterator MI) {
1007 MachineBasicBlock &MBB = *MI->getParent();
1008 TII.loadRegFromStackSlot(MBB, MI, NewLI.reg, StackSlot,
1009 MRI.getRegClass(NewLI.reg), &TRI);
1010 --MI; // Point to load instruction.
1011 SlotIndex LoadIdx = LIS.InsertMachineInstrInMaps(MI).getDefIndex();
1012 VRM.addSpillSlotUse(StackSlot, MI);
1013 DEBUG(dbgs() << "\treload: " << LoadIdx << '\t' << *MI);
1014 VNInfo *LoadVNI = NewLI.getNextValue(LoadIdx, 0,
1015 LIS.getVNInfoAllocator());
1016 NewLI.addRange(LiveRange(LoadIdx, Idx, LoadVNI));
1020 /// insertSpill - Insert a spill of NewLI.reg after MI.
1021 void InlineSpiller::insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
1022 SlotIndex Idx, MachineBasicBlock::iterator MI) {
1023 MachineBasicBlock &MBB = *MI->getParent();
1024 TII.storeRegToStackSlot(MBB, ++MI, NewLI.reg, true, StackSlot,
1025 MRI.getRegClass(NewLI.reg), &TRI);
1026 --MI; // Point to store instruction.
1027 SlotIndex StoreIdx = LIS.InsertMachineInstrInMaps(MI).getDefIndex();
1028 VRM.addSpillSlotUse(StackSlot, MI);
1029 DEBUG(dbgs() << "\tspilled: " << StoreIdx << '\t' << *MI);
1030 VNInfo *StoreVNI = NewLI.getNextValue(Idx, 0, LIS.getVNInfoAllocator());
1031 NewLI.addRange(LiveRange(Idx, StoreIdx, StoreVNI));
1035 /// spillAroundUses - insert spill code around each use of Reg.
1036 void InlineSpiller::spillAroundUses(unsigned Reg) {
1037 DEBUG(dbgs() << "spillAroundUses " << PrintReg(Reg) << '\n');
1038 LiveInterval &OldLI = LIS.getInterval(Reg);
1040 // Iterate over instructions using Reg.
1041 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
1042 MachineInstr *MI = RI.skipInstruction();) {
1044 // Debug values are not allowed to affect codegen.
1045 if (MI->isDebugValue()) {
1046 // Modify DBG_VALUE now that the value is in a spill slot.
1047 uint64_t Offset = MI->getOperand(1).getImm();
1048 const MDNode *MDPtr = MI->getOperand(2).getMetadata();
1049 DebugLoc DL = MI->getDebugLoc();
1050 if (MachineInstr *NewDV = TII.emitFrameIndexDebugValue(MF, StackSlot,
1051 Offset, MDPtr, DL)) {
1052 DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
1053 MachineBasicBlock *MBB = MI->getParent();
1054 MBB->insert(MBB->erase(MI), NewDV);
1056 DEBUG(dbgs() << "Removing debug info due to spill:" << "\t" << *MI);
1057 MI->eraseFromParent();
1062 // Ignore copies to/from snippets. We'll delete them.
1063 if (SnippetCopies.count(MI))
1066 // Stack slot accesses may coalesce away.
1067 if (coalesceStackAccess(MI, Reg))
1070 // Analyze instruction.
1072 SmallVector<unsigned, 8> Ops;
1073 tie(Reads, Writes) = MI->readsWritesVirtualRegister(Reg, &Ops);
1075 // Find the slot index where this instruction reads and writes OldLI.
1076 // This is usually the def slot, except for tied early clobbers.
1077 SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex();
1078 if (VNInfo *VNI = OldLI.getVNInfoAt(Idx.getUseIndex()))
1079 if (SlotIndex::isSameInstr(Idx, VNI->def))
1082 // Check for a sibling copy.
1083 unsigned SibReg = isFullCopyOf(MI, Reg);
1084 if (SibReg && isSibling(SibReg)) {
1085 // This may actually be a copy between snippets.
1086 if (isRegToSpill(SibReg)) {
1087 DEBUG(dbgs() << "Found new snippet copy: " << *MI);
1088 SnippetCopies.insert(MI);
1092 // Hoist the spill of a sib-reg copy.
1093 if (hoistSpill(OldLI, MI)) {
1094 // This COPY is now dead, the value is already in the stack slot.
1095 MI->getOperand(0).setIsDead();
1096 DeadDefs.push_back(MI);
1100 // This is a reload for a sib-reg copy. Drop spills downstream.
1101 LiveInterval &SibLI = LIS.getInterval(SibReg);
1102 eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx));
1103 // The COPY will fold to a reload below.
1107 // Attempt to fold memory ops.
1108 if (foldMemoryOperand(MI, Ops))
1111 // Allocate interval around instruction.
1112 // FIXME: Infer regclass from instruction alone.
1113 LiveInterval &NewLI = Edit->createFrom(Reg, LIS, VRM);
1114 NewLI.markNotSpillable();
1117 insertReload(NewLI, Idx, MI);
1119 // Rewrite instruction operands.
1120 bool hasLiveDef = false;
1121 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1122 MachineOperand &MO = MI->getOperand(Ops[i]);
1123 MO.setReg(NewLI.reg);
1125 if (!MI->isRegTiedToDefOperand(Ops[i]))
1132 DEBUG(dbgs() << "\trewrite: " << Idx << '\t' << *MI);
1134 // FIXME: Use a second vreg if instruction has no tied ops.
1135 if (Writes && hasLiveDef)
1136 insertSpill(NewLI, OldLI, Idx, MI);
1138 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
1142 /// spillAll - Spill all registers remaining after rematerialization.
1143 void InlineSpiller::spillAll() {
1144 // Update LiveStacks now that we are committed to spilling.
1145 if (StackSlot == VirtRegMap::NO_STACK_SLOT) {
1146 StackSlot = VRM.assignVirt2StackSlot(Original);
1147 StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original));
1148 StackInt->getNextValue(SlotIndex(), 0, LSS.getVNInfoAllocator());
1150 StackInt = &LSS.getInterval(StackSlot);
1152 if (Original != Edit->getReg())
1153 VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot);
1155 assert(StackInt->getNumValNums() == 1 && "Bad stack interval values");
1156 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1157 StackInt->MergeRangesInAsValue(LIS.getInterval(RegsToSpill[i]),
1158 StackInt->getValNumInfo(0));
1159 DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n');
1161 // Spill around uses of all RegsToSpill.
1162 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1163 spillAroundUses(RegsToSpill[i]);
1165 // Hoisted spills may cause dead code.
1166 if (!DeadDefs.empty()) {
1167 DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n");
1168 Edit->eliminateDeadDefs(DeadDefs, LIS, VRM, TII);
1171 // Finally delete the SnippetCopies.
1172 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
1173 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(RegsToSpill[i]);
1174 MachineInstr *MI = RI.skipInstruction();) {
1175 assert(SnippetCopies.count(MI) && "Remaining use wasn't a snippet copy");
1176 // FIXME: Do this with a LiveRangeEdit callback.
1177 VRM.RemoveMachineInstrFromMaps(MI);
1178 LIS.RemoveMachineInstrFromMaps(MI);
1179 MI->eraseFromParent();
1183 // Delete all spilled registers.
1184 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1185 Edit->eraseVirtReg(RegsToSpill[i], LIS);
1188 void InlineSpiller::spill(LiveRangeEdit &edit) {
1191 assert(!TargetRegisterInfo::isStackSlot(edit.getReg())
1192 && "Trying to spill a stack slot.");
1193 // Share a stack slot among all descendants of Original.
1194 Original = VRM.getOriginal(edit.getReg());
1195 StackSlot = VRM.getStackSlot(Original);
1198 DEBUG(dbgs() << "Inline spilling "
1199 << MRI.getRegClass(edit.getReg())->getName()
1200 << ':' << edit.getParent() << "\nFrom original "
1201 << LIS.getInterval(Original) << '\n');
1202 assert(edit.getParent().isSpillable() &&
1203 "Attempting to spill already spilled value.");
1204 assert(DeadDefs.empty() && "Previous spill didn't remove dead defs");
1206 collectRegsToSpill();
1207 analyzeSiblingValues();
1210 // Remat may handle everything.
1211 if (!RegsToSpill.empty())
1214 Edit->calculateRegClassAndHint(MF, LIS, Loops);