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/Analysis/AliasAnalysis.h"
20 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
21 #include "llvm/CodeGen/LiveStackAnalysis.h"
22 #include "llvm/CodeGen/MachineDominators.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineLoopInfo.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/raw_ostream.h"
35 class InlineSpiller : public Spiller {
36 MachineFunctionPass &Pass;
41 MachineDominatorTree &MDT;
42 MachineLoopInfo &Loops;
44 MachineFrameInfo &MFI;
45 MachineRegisterInfo &MRI;
46 const TargetInstrInfo &TII;
47 const TargetRegisterInfo &TRI;
49 // Variables that are valid during spill(), but used by multiple methods.
51 const TargetRegisterClass *RC;
55 // All registers to spill to StackSlot, including the main register.
56 SmallVector<unsigned, 8> RegsToSpill;
58 // All COPY instructions to/from snippets.
59 // They are ignored since both operands refer to the same stack slot.
60 SmallPtrSet<MachineInstr*, 8> SnippetCopies;
62 // Values that failed to remat at some point.
63 SmallPtrSet<VNInfo*, 8> UsedValues;
65 // Information about a value that was defined by a copy from a sibling
68 // True when all reaching defs were reloads: No spill is necessary.
69 bool AllDefsAreReloads;
71 // The preferred register to spill.
74 // The value of SpillReg that should be spilled.
77 // A defining instruction that is not a sibling copy or a reload, or NULL.
78 // This can be used as a template for rematerialization.
81 SibValueInfo(unsigned Reg, VNInfo *VNI)
82 : AllDefsAreReloads(false), SpillReg(Reg), SpillVNI(VNI), DefMI(0) {}
85 // Values in RegsToSpill defined by sibling copies.
86 DenseMap<VNInfo*, SibValueInfo> SibValues;
91 InlineSpiller(MachineFunctionPass &pass,
96 LIS(pass.getAnalysis<LiveIntervals>()),
97 LSS(pass.getAnalysis<LiveStacks>()),
98 AA(&pass.getAnalysis<AliasAnalysis>()),
99 MDT(pass.getAnalysis<MachineDominatorTree>()),
100 Loops(pass.getAnalysis<MachineLoopInfo>()),
102 MFI(*mf.getFrameInfo()),
103 MRI(mf.getRegInfo()),
104 TII(*mf.getTarget().getInstrInfo()),
105 TRI(*mf.getTarget().getRegisterInfo()) {}
107 void spill(LiveRangeEdit &);
110 bool isSnippet(const LiveInterval &SnipLI);
111 void collectRegsToSpill();
113 void traceSiblingValue(unsigned, VNInfo*, VNInfo*);
114 void analyzeSiblingValues();
116 bool reMaterializeFor(MachineBasicBlock::iterator MI);
117 void reMaterializeAll();
119 bool coalesceStackAccess(MachineInstr *MI, unsigned Reg);
120 bool foldMemoryOperand(MachineBasicBlock::iterator MI,
121 const SmallVectorImpl<unsigned> &Ops,
122 MachineInstr *LoadMI = 0);
123 void insertReload(LiveInterval &NewLI, MachineBasicBlock::iterator MI);
124 void insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
125 MachineBasicBlock::iterator MI);
127 void spillAroundUses(unsigned Reg);
132 Spiller *createInlineSpiller(MachineFunctionPass &pass,
135 return new InlineSpiller(pass, mf, vrm);
139 //===----------------------------------------------------------------------===//
141 //===----------------------------------------------------------------------===//
143 // When spilling a virtual register, we also spill any snippets it is connected
144 // to. The snippets are small live ranges that only have a single real use,
145 // leftovers from live range splitting. Spilling them enables memory operand
146 // folding or tightens the live range around the single use.
148 // This minimizes register pressure and maximizes the store-to-load distance for
149 // spill slots which can be important in tight loops.
151 /// isFullCopyOf - If MI is a COPY to or from Reg, return the other register,
152 /// otherwise return 0.
153 static unsigned isFullCopyOf(const MachineInstr *MI, unsigned Reg) {
156 if (MI->getOperand(0).getSubReg() != 0)
158 if (MI->getOperand(1).getSubReg() != 0)
160 if (MI->getOperand(0).getReg() == Reg)
161 return MI->getOperand(1).getReg();
162 if (MI->getOperand(1).getReg() == Reg)
163 return MI->getOperand(0).getReg();
167 /// isSnippet - Identify if a live interval is a snippet that should be spilled.
168 /// It is assumed that SnipLI is a virtual register with the same original as
170 bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
171 unsigned Reg = Edit->getReg();
173 // A snippet is a tiny live range with only a single instruction using it
174 // besides copies to/from Reg or spills/fills. We accept:
176 // %snip = COPY %Reg / FILL fi#
178 // %Reg = COPY %snip / SPILL %snip, fi#
180 if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI))
183 MachineInstr *UseMI = 0;
185 // Check that all uses satisfy our criteria.
186 for (MachineRegisterInfo::reg_nodbg_iterator
187 RI = MRI.reg_nodbg_begin(SnipLI.reg);
188 MachineInstr *MI = RI.skipInstruction();) {
190 // Allow copies to/from Reg.
191 if (isFullCopyOf(MI, Reg))
194 // Allow stack slot loads.
196 if (SnipLI.reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
199 // Allow stack slot stores.
200 if (SnipLI.reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
203 // Allow a single additional instruction.
204 if (UseMI && MI != UseMI)
211 /// collectRegsToSpill - Collect live range snippets that only have a single
213 void InlineSpiller::collectRegsToSpill() {
214 unsigned Reg = Edit->getReg();
216 // Main register always spills.
217 RegsToSpill.assign(1, Reg);
218 SnippetCopies.clear();
220 // Snippets all have the same original, so there can't be any for an original
225 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
226 MachineInstr *MI = RI.skipInstruction();) {
227 unsigned SnipReg = isFullCopyOf(MI, Reg);
230 if (!TargetRegisterInfo::isVirtualRegister(SnipReg))
232 if (VRM.getOriginal(SnipReg) != Original)
234 LiveInterval &SnipLI = LIS.getInterval(SnipReg);
235 if (!isSnippet(SnipLI))
237 SnippetCopies.insert(MI);
238 if (std::find(RegsToSpill.begin(), RegsToSpill.end(),
239 SnipReg) == RegsToSpill.end())
240 RegsToSpill.push_back(SnipReg);
242 DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n');
247 //===----------------------------------------------------------------------===//
249 //===----------------------------------------------------------------------===//
251 // After live range splitting, some values to be spilled may be defined by
252 // copies from sibling registers. We trace the sibling copies back to the
253 // original value if it still exists. We need it for rematerialization.
255 // Even when the value can't be rematerialized, we still want to determine if
256 // the value has already been spilled, or we may want to hoist the spill from a
259 /// traceSiblingValue - Trace a value that is about to be spilled back to the
260 /// real defining instructions by looking through sibling copies. Always stay
261 /// within the range of OrigVNI so the registers are known to carry the same
264 /// Determine if the value is defined by all reloads, so spilling isn't
265 /// necessary - the value is already in the stack slot.
267 /// Find a defining instruction that may be a candidate for rematerialization.
269 void InlineSpiller::traceSiblingValue(unsigned UseReg, VNInfo *UseVNI,
271 DEBUG(dbgs() << "Tracing value " << PrintReg(UseReg) << ':'
272 << UseVNI->id << '@' << UseVNI->def << '\n');
273 SmallPtrSet<VNInfo*, 8> Visited;
274 SmallVector<std::pair<unsigned,VNInfo*>, 8> WorkList;
275 WorkList.push_back(std::make_pair(UseReg, UseVNI));
277 // Best spill candidate seen so far. This must dominate UseVNI.
278 SibValueInfo SVI(UseReg, UseVNI);
279 MachineBasicBlock *UseMBB = LIS.getMBBFromIndex(UseVNI->def);
280 MachineBasicBlock *SpillMBB = UseMBB;
281 unsigned SpillDepth = Loops.getLoopDepth(SpillMBB);
282 bool SeenOrigPHI = false; // Original PHI met.
287 tie(Reg, VNI) = WorkList.pop_back_val();
288 if (!Visited.insert(VNI))
291 // Is this value a better spill candidate?
292 if (VNI != SVI.SpillVNI) {
293 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
294 if (MBB == SpillMBB) {
295 // Prefer to spill a previous value in the same block.
296 if (VNI->def < SVI.SpillVNI->def)
297 SVI.SpillReg = Reg, SVI.SpillVNI = VNI;
298 } else if (MDT.dominates(MBB, UseMBB)) {
299 // This is a valid spill location dominating UseVNI.
300 // Prefer to spill at a smaller loop depth.
301 unsigned Depth = Loops.getLoopDepth(MBB);
302 if (Depth < SpillDepth) {
303 DEBUG(dbgs() << " spill depth " << Depth << ": " << PrintReg(Reg)
304 << ':' << VNI->id << '@' << VNI->def << '\n');
313 // Trace through PHI-defs created by live range splitting.
314 if (VNI->isPHIDef()) {
315 if (VNI->def == OrigVNI->def) {
316 DEBUG(dbgs() << " orig phi value " << PrintReg(Reg) << ':'
317 << VNI->id << '@' << VNI->def << '\n');
321 // Get values live-out of predecessors.
322 LiveInterval &LI = LIS.getInterval(Reg);
323 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
324 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
325 PE = MBB->pred_end(); PI != PE; ++PI) {
326 VNInfo *PVNI = LI.getVNInfoAt(LIS.getMBBEndIdx(*PI).getPrevSlot());
328 WorkList.push_back(std::make_pair(Reg, PVNI));
333 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
334 assert(MI && "Missing def");
336 // Trace through sibling copies.
337 if (unsigned SrcReg = isFullCopyOf(MI, Reg)) {
338 if (TargetRegisterInfo::isVirtualRegister(SrcReg) &&
339 VRM.getOriginal(SrcReg) == Original) {
340 LiveInterval &SrcLI = LIS.getInterval(SrcReg);
341 VNInfo *SrcVNI = SrcLI.getVNInfoAt(VNI->def.getUseIndex());
342 assert(SrcVNI && "Copy from non-existing value");
343 DEBUG(dbgs() << " copy of " << PrintReg(SrcReg) << ':'
344 << SrcVNI->id << '@' << SrcVNI->def << '\n');
345 WorkList.push_back(std::make_pair(SrcReg, SrcVNI));
350 // Track reachable reloads.
352 if (Reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot) {
353 DEBUG(dbgs() << " reload " << PrintReg(Reg) << ':'
354 << VNI->id << "@" << VNI->def << '\n');
355 SVI.AllDefsAreReloads = true;
359 // We have an 'original' def. Don't record trivial cases.
361 DEBUG(dbgs() << "Not a sibling copy.\n");
365 // Potential remat candidate.
366 DEBUG(dbgs() << " def " << PrintReg(Reg) << ':'
367 << VNI->id << '@' << VNI->def << '\t' << *MI);
369 } while (!WorkList.empty());
371 if (SeenOrigPHI || SVI.DefMI)
372 SVI.AllDefsAreReloads = false;
375 if (SVI.AllDefsAreReloads)
376 dbgs() << "All defs are reloads.\n";
378 dbgs() << "Prefer to spill " << PrintReg(SVI.SpillReg) << ':'
379 << SVI.SpillVNI->id << '@' << SVI.SpillVNI->def << '\n';
381 SibValues.insert(std::make_pair(UseVNI, SVI));
384 /// analyzeSiblingValues - Trace values defined by sibling copies back to
385 /// something that isn't a sibling copy.
386 void InlineSpiller::analyzeSiblingValues() {
389 // No siblings at all?
390 if (Edit->getReg() == Original)
393 LiveInterval &OrigLI = LIS.getInterval(Original);
394 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
395 unsigned Reg = RegsToSpill[i];
396 LiveInterval &LI = LIS.getInterval(Reg);
397 for (LiveInterval::const_vni_iterator VI = LI.vni_begin(),
398 VE = LI.vni_end(); VI != VE; ++VI) {
400 if (VNI->isUnused() || !(VNI->isPHIDef() || VNI->getCopy()))
402 VNInfo *OrigVNI = OrigLI.getVNInfoAt(VNI->def);
403 if (OrigVNI->def != VNI->def)
404 traceSiblingValue(Reg, VNI, OrigVNI);
409 /// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
410 bool InlineSpiller::reMaterializeFor(MachineBasicBlock::iterator MI) {
411 SlotIndex UseIdx = LIS.getInstructionIndex(MI).getUseIndex();
412 VNInfo *OrigVNI = Edit->getParent().getVNInfoAt(UseIdx);
415 DEBUG(dbgs() << "\tadding <undef> flags: ");
416 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
417 MachineOperand &MO = MI->getOperand(i);
418 if (MO.isReg() && MO.isUse() && MO.getReg() == Edit->getReg())
421 DEBUG(dbgs() << UseIdx << '\t' << *MI);
425 // FIXME: Properly remat for snippets as well.
426 if (SnippetCopies.count(MI)) {
427 UsedValues.insert(OrigVNI);
431 LiveRangeEdit::Remat RM(OrigVNI);
432 if (!Edit->canRematerializeAt(RM, UseIdx, false, LIS)) {
433 UsedValues.insert(OrigVNI);
434 DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
438 // If the instruction also writes Edit->getReg(), it had better not require
439 // the same register for uses and defs.
441 SmallVector<unsigned, 8> Ops;
442 tie(Reads, Writes) = MI->readsWritesVirtualRegister(Edit->getReg(), &Ops);
444 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
445 MachineOperand &MO = MI->getOperand(Ops[i]);
446 if (MO.isUse() ? MI->isRegTiedToDefOperand(Ops[i]) : MO.getSubReg()) {
447 UsedValues.insert(OrigVNI);
448 DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
454 // Before rematerializing into a register for a single instruction, try to
455 // fold a load into the instruction. That avoids allocating a new register.
456 if (RM.OrigMI->getDesc().canFoldAsLoad() &&
457 foldMemoryOperand(MI, Ops, RM.OrigMI)) {
458 Edit->markRematerialized(RM.ParentVNI);
462 // Alocate a new register for the remat.
463 LiveInterval &NewLI = Edit->create(MRI, LIS, VRM);
464 NewLI.markNotSpillable();
466 // Rematting for a copy: Set allocation hint to be the destination register.
468 MRI.setRegAllocationHint(NewLI.reg, 0, MI->getOperand(0).getReg());
470 // Finally we can rematerialize OrigMI before MI.
471 SlotIndex DefIdx = Edit->rematerializeAt(*MI->getParent(), MI, NewLI.reg, RM,
473 DEBUG(dbgs() << "\tremat: " << DefIdx << '\t'
474 << *LIS.getInstructionFromIndex(DefIdx));
477 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
478 MachineOperand &MO = MI->getOperand(Ops[i]);
479 if (MO.isReg() && MO.isUse() && MO.getReg() == Edit->getReg()) {
480 MO.setReg(NewLI.reg);
484 DEBUG(dbgs() << "\t " << UseIdx << '\t' << *MI);
486 VNInfo *DefVNI = NewLI.getNextValue(DefIdx, 0, LIS.getVNInfoAllocator());
487 NewLI.addRange(LiveRange(DefIdx, UseIdx.getDefIndex(), DefVNI));
488 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
492 /// reMaterializeAll - Try to rematerialize as many uses as possible,
493 /// and trim the live ranges after.
494 void InlineSpiller::reMaterializeAll() {
495 // Do a quick scan of the interval values to find if any are remattable.
496 if (!Edit->anyRematerializable(LIS, TII, AA))
501 // Try to remat before all uses of Edit->getReg().
502 bool anyRemat = false;
503 for (MachineRegisterInfo::use_nodbg_iterator
504 RI = MRI.use_nodbg_begin(Edit->getReg());
505 MachineInstr *MI = RI.skipInstruction();)
506 anyRemat |= reMaterializeFor(MI);
511 // Remove any values that were completely rematted.
512 bool anyRemoved = false;
513 for (LiveInterval::vni_iterator I = Edit->getParent().vni_begin(),
514 E = Edit->getParent().vni_end(); I != E; ++I) {
516 if (VNI->hasPHIKill() || !Edit->didRematerialize(VNI) ||
517 UsedValues.count(VNI))
519 MachineInstr *DefMI = LIS.getInstructionFromIndex(VNI->def);
520 DEBUG(dbgs() << "\tremoving dead def: " << VNI->def << '\t' << *DefMI);
521 LIS.RemoveMachineInstrFromMaps(DefMI);
522 VRM.RemoveMachineInstrFromMaps(DefMI);
523 DefMI->eraseFromParent();
524 VNI->def = SlotIndex();
531 // Removing values may cause debug uses where parent is not live.
532 for (MachineRegisterInfo::use_iterator RI = MRI.use_begin(Edit->getReg());
533 MachineInstr *MI = RI.skipInstruction();) {
534 if (!MI->isDebugValue())
536 // Try to preserve the debug value if parent is live immediately after it.
537 MachineBasicBlock::iterator NextMI = MI;
539 if (NextMI != MI->getParent()->end() && !LIS.isNotInMIMap(NextMI)) {
540 SlotIndex Idx = LIS.getInstructionIndex(NextMI);
541 VNInfo *VNI = Edit->getParent().getVNInfoAt(Idx);
542 if (VNI && (VNI->hasPHIKill() || UsedValues.count(VNI)))
545 DEBUG(dbgs() << "Removing debug info due to remat:" << "\t" << *MI);
546 MI->eraseFromParent();
550 /// If MI is a load or store of StackSlot, it can be removed.
551 bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, unsigned Reg) {
554 if (!(InstrReg = TII.isLoadFromStackSlot(MI, FI)) &&
555 !(InstrReg = TII.isStoreToStackSlot(MI, FI)))
558 // We have a stack access. Is it the right register and slot?
559 if (InstrReg != Reg || FI != StackSlot)
562 DEBUG(dbgs() << "Coalescing stack access: " << *MI);
563 LIS.RemoveMachineInstrFromMaps(MI);
564 MI->eraseFromParent();
568 /// foldMemoryOperand - Try folding stack slot references in Ops into MI.
569 /// @param MI Instruction using or defining the current register.
570 /// @param Ops Operand indices from readsWritesVirtualRegister().
571 /// @param LoadMI Load instruction to use instead of stack slot when non-null.
572 /// @return True on success, and MI will be erased.
573 bool InlineSpiller::foldMemoryOperand(MachineBasicBlock::iterator MI,
574 const SmallVectorImpl<unsigned> &Ops,
575 MachineInstr *LoadMI) {
576 // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
578 SmallVector<unsigned, 8> FoldOps;
579 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
580 unsigned Idx = Ops[i];
581 MachineOperand &MO = MI->getOperand(Idx);
584 // FIXME: Teach targets to deal with subregs.
587 // We cannot fold a load instruction into a def.
588 if (LoadMI && MO.isDef())
590 // Tied use operands should not be passed to foldMemoryOperand.
591 if (!MI->isRegTiedToDefOperand(Idx))
592 FoldOps.push_back(Idx);
595 MachineInstr *FoldMI =
596 LoadMI ? TII.foldMemoryOperand(MI, FoldOps, LoadMI)
597 : TII.foldMemoryOperand(MI, FoldOps, StackSlot);
600 LIS.ReplaceMachineInstrInMaps(MI, FoldMI);
602 VRM.addSpillSlotUse(StackSlot, FoldMI);
603 MI->eraseFromParent();
604 DEBUG(dbgs() << "\tfolded: " << *FoldMI);
608 /// insertReload - Insert a reload of NewLI.reg before MI.
609 void InlineSpiller::insertReload(LiveInterval &NewLI,
610 MachineBasicBlock::iterator MI) {
611 MachineBasicBlock &MBB = *MI->getParent();
612 SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex();
613 TII.loadRegFromStackSlot(MBB, MI, NewLI.reg, StackSlot, RC, &TRI);
614 --MI; // Point to load instruction.
615 SlotIndex LoadIdx = LIS.InsertMachineInstrInMaps(MI).getDefIndex();
616 VRM.addSpillSlotUse(StackSlot, MI);
617 DEBUG(dbgs() << "\treload: " << LoadIdx << '\t' << *MI);
618 VNInfo *LoadVNI = NewLI.getNextValue(LoadIdx, 0,
619 LIS.getVNInfoAllocator());
620 NewLI.addRange(LiveRange(LoadIdx, Idx, LoadVNI));
623 /// insertSpill - Insert a spill of NewLI.reg after MI.
624 void InlineSpiller::insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
625 MachineBasicBlock::iterator MI) {
626 MachineBasicBlock &MBB = *MI->getParent();
628 // Get the defined value. It could be an early clobber so keep the def index.
629 SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex();
630 VNInfo *VNI = OldLI.getVNInfoAt(Idx);
631 assert(VNI && VNI->def.getDefIndex() == Idx && "Inconsistent VNInfo");
634 TII.storeRegToStackSlot(MBB, ++MI, NewLI.reg, true, StackSlot, RC, &TRI);
635 --MI; // Point to store instruction.
636 SlotIndex StoreIdx = LIS.InsertMachineInstrInMaps(MI).getDefIndex();
637 VRM.addSpillSlotUse(StackSlot, MI);
638 DEBUG(dbgs() << "\tspilled: " << StoreIdx << '\t' << *MI);
639 VNInfo *StoreVNI = NewLI.getNextValue(Idx, 0, LIS.getVNInfoAllocator());
640 NewLI.addRange(LiveRange(Idx, StoreIdx, StoreVNI));
643 /// spillAroundUses - insert spill code around each use of Reg.
644 void InlineSpiller::spillAroundUses(unsigned Reg) {
645 LiveInterval &OldLI = LIS.getInterval(Reg);
647 // Iterate over instructions using Reg.
648 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
649 MachineInstr *MI = RI.skipInstruction();) {
651 // Debug values are not allowed to affect codegen.
652 if (MI->isDebugValue()) {
653 // Modify DBG_VALUE now that the value is in a spill slot.
654 uint64_t Offset = MI->getOperand(1).getImm();
655 const MDNode *MDPtr = MI->getOperand(2).getMetadata();
656 DebugLoc DL = MI->getDebugLoc();
657 if (MachineInstr *NewDV = TII.emitFrameIndexDebugValue(MF, StackSlot,
658 Offset, MDPtr, DL)) {
659 DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
660 MachineBasicBlock *MBB = MI->getParent();
661 MBB->insert(MBB->erase(MI), NewDV);
663 DEBUG(dbgs() << "Removing debug info due to spill:" << "\t" << *MI);
664 MI->eraseFromParent();
669 // Ignore copies to/from snippets. We'll delete them.
670 if (SnippetCopies.count(MI))
673 // Stack slot accesses may coalesce away.
674 if (coalesceStackAccess(MI, Reg))
677 // Analyze instruction.
679 SmallVector<unsigned, 8> Ops;
680 tie(Reads, Writes) = MI->readsWritesVirtualRegister(Reg, &Ops);
682 // Attempt to fold memory ops.
683 if (foldMemoryOperand(MI, Ops))
686 // Allocate interval around instruction.
687 // FIXME: Infer regclass from instruction alone.
688 LiveInterval &NewLI = Edit->create(MRI, LIS, VRM);
689 NewLI.markNotSpillable();
692 insertReload(NewLI, MI);
694 // Rewrite instruction operands.
695 bool hasLiveDef = false;
696 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
697 MachineOperand &MO = MI->getOperand(Ops[i]);
698 MO.setReg(NewLI.reg);
700 if (!MI->isRegTiedToDefOperand(Ops[i]))
708 // FIXME: Use a second vreg if instruction has no tied ops.
709 if (Writes && hasLiveDef)
710 insertSpill(NewLI, OldLI, MI);
712 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
716 void InlineSpiller::spill(LiveRangeEdit &edit) {
718 assert(!TargetRegisterInfo::isStackSlot(edit.getReg())
719 && "Trying to spill a stack slot.");
721 // Share a stack slot among all descendants of Original.
722 Original = VRM.getOriginal(edit.getReg());
723 StackSlot = VRM.getStackSlot(Original);
725 DEBUG(dbgs() << "Inline spilling "
726 << MRI.getRegClass(edit.getReg())->getName()
727 << ':' << edit.getParent() << "\nFrom original "
728 << LIS.getInterval(Original) << '\n');
729 assert(edit.getParent().isSpillable() &&
730 "Attempting to spill already spilled value.");
732 collectRegsToSpill();
734 analyzeSiblingValues();
738 // Remat may handle everything.
739 if (Edit->getParent().empty())
742 RC = MRI.getRegClass(edit.getReg());
744 if (StackSlot == VirtRegMap::NO_STACK_SLOT)
745 StackSlot = VRM.assignVirt2StackSlot(Original);
747 if (Original != edit.getReg())
748 VRM.assignVirt2StackSlot(edit.getReg(), StackSlot);
750 // Update LiveStacks now that we are committed to spilling.
751 LiveInterval &stacklvr = LSS.getOrCreateInterval(StackSlot, RC);
752 if (!stacklvr.hasAtLeastOneValue())
753 stacklvr.getNextValue(SlotIndex(), 0, LSS.getVNInfoAllocator());
754 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
755 stacklvr.MergeRangesInAsValue(LIS.getInterval(RegsToSpill[i]),
756 stacklvr.getValNumInfo(0));
758 // Spill around uses of all RegsToSpill.
759 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
760 spillAroundUses(RegsToSpill[i]);
762 // Finally delete the SnippetCopies.
763 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(edit.getReg());
764 MachineInstr *MI = RI.skipInstruction();) {
765 assert(SnippetCopies.count(MI) && "Remaining use wasn't a snippet copy");
766 // FIXME: Do this with a LiveRangeEdit callback.
767 VRM.RemoveMachineInstrFromMaps(MI);
768 LIS.RemoveMachineInstrFromMaps(MI);
769 MI->eraseFromParent();
772 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
773 edit.eraseVirtReg(RegsToSpill[i], LIS);