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"
19 #include "VirtRegMap.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/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
36 VerifySpills("verify-spills", cl::desc("Verify after each spill/split"));
39 ExtraSpillerSplits("extra-spiller-splits",
40 cl::desc("Enable additional splitting during splitting"));
43 class InlineSpiller : public Spiller {
44 MachineFunctionPass &pass_;
48 MachineDominatorTree &mdt_;
49 MachineLoopInfo &loops_;
51 MachineFrameInfo &mfi_;
52 MachineRegisterInfo &mri_;
53 const TargetInstrInfo &tii_;
54 const TargetRegisterInfo &tri_;
55 const BitVector reserved_;
57 SplitAnalysis splitAnalysis_;
59 // Variables that are valid during spill(), but used by multiple methods.
61 const TargetRegisterClass *rc_;
64 // Values that failed to remat at some point.
65 SmallPtrSet<VNInfo*, 8> usedValues_;
70 InlineSpiller(MachineFunctionPass &pass,
75 lis_(pass.getAnalysis<LiveIntervals>()),
76 lss_(pass.getAnalysis<LiveStacks>()),
77 mdt_(pass.getAnalysis<MachineDominatorTree>()),
78 loops_(pass.getAnalysis<MachineLoopInfo>()),
80 mfi_(*mf.getFrameInfo()),
81 mri_(mf.getRegInfo()),
82 tii_(*mf.getTarget().getInstrInfo()),
83 tri_(*mf.getTarget().getRegisterInfo()),
84 reserved_(tri_.getReservedRegs(mf_)),
85 splitAnalysis_(mf, lis_, loops_) {}
87 void spill(LiveInterval *li,
88 SmallVectorImpl<LiveInterval*> &newIntervals,
89 SmallVectorImpl<LiveInterval*> &spillIs);
91 void spill(LiveRangeEdit &);
96 bool reMaterializeFor(MachineBasicBlock::iterator MI);
97 void reMaterializeAll();
99 bool coalesceStackAccess(MachineInstr *MI);
100 bool foldMemoryOperand(MachineBasicBlock::iterator MI,
101 const SmallVectorImpl<unsigned> &Ops);
102 void insertReload(LiveInterval &NewLI, MachineBasicBlock::iterator MI);
103 void insertSpill(LiveInterval &NewLI, MachineBasicBlock::iterator MI);
108 Spiller *createInlineSpiller(MachineFunctionPass &pass,
113 return new InlineSpiller(pass, mf, vrm);
117 /// split - try splitting the current interval into pieces that may allocate
118 /// separately. Return true if successful.
119 bool InlineSpiller::split() {
120 splitAnalysis_.analyze(&edit_->getParent());
122 // Try splitting around loops.
123 if (ExtraSpillerSplits) {
124 const MachineLoop *loop = splitAnalysis_.getBestSplitLoop();
126 SplitEditor(splitAnalysis_, lis_, vrm_, mdt_, *edit_)
127 .splitAroundLoop(loop);
132 // Try splitting into single block intervals.
133 SplitAnalysis::BlockPtrSet blocks;
134 if (splitAnalysis_.getMultiUseBlocks(blocks)) {
135 SplitEditor(splitAnalysis_, lis_, vrm_, mdt_, *edit_)
136 .splitSingleBlocks(blocks);
140 // Try splitting inside a basic block.
141 if (ExtraSpillerSplits) {
142 const MachineBasicBlock *MBB = splitAnalysis_.getBlockForInsideSplit();
144 SplitEditor(splitAnalysis_, lis_, vrm_, mdt_, *edit_)
145 .splitInsideBlock(MBB);
153 /// reMaterializeFor - Attempt to rematerialize edit_->getReg() before MI instead of
155 bool InlineSpiller::reMaterializeFor(MachineBasicBlock::iterator MI) {
156 SlotIndex UseIdx = lis_.getInstructionIndex(MI).getUseIndex();
157 VNInfo *OrigVNI = edit_->getParent().getVNInfoAt(UseIdx);
160 DEBUG(dbgs() << "\tadding <undef> flags: ");
161 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
162 MachineOperand &MO = MI->getOperand(i);
163 if (MO.isReg() && MO.isUse() && MO.getReg() == edit_->getReg())
166 DEBUG(dbgs() << UseIdx << '\t' << *MI);
170 LiveRangeEdit::Remat RM = edit_->canRematerializeAt(OrigVNI, UseIdx, false,
173 usedValues_.insert(OrigVNI);
174 DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
178 // If the instruction also writes edit_->getReg(), it had better not require
179 // the same register for uses and defs.
181 SmallVector<unsigned, 8> Ops;
182 tie(Reads, Writes) = MI->readsWritesVirtualRegister(edit_->getReg(), &Ops);
184 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
185 MachineOperand &MO = MI->getOperand(Ops[i]);
186 if (MO.isUse() ? MI->isRegTiedToDefOperand(Ops[i]) : MO.getSubReg()) {
187 usedValues_.insert(OrigVNI);
188 DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
194 // Alocate a new register for the remat.
195 LiveInterval &NewLI = edit_->create(mri_, lis_, vrm_);
196 NewLI.markNotSpillable();
198 // Finally we can rematerialize OrigMI before MI.
199 SlotIndex DefIdx = edit_->rematerializeAt(*MI->getParent(), MI, NewLI.reg, RM,
201 DEBUG(dbgs() << "\tremat: " << DefIdx << '\n');
204 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
205 MachineOperand &MO = MI->getOperand(Ops[i]);
206 if (MO.isReg() && MO.isUse() && MO.getReg() == edit_->getReg()) {
207 MO.setReg(NewLI.reg);
211 DEBUG(dbgs() << "\t " << UseIdx << '\t' << *MI);
213 VNInfo *DefVNI = NewLI.getNextValue(DefIdx, 0, lis_.getVNInfoAllocator());
214 NewLI.addRange(LiveRange(DefIdx, UseIdx.getDefIndex(), DefVNI));
215 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
219 /// reMaterializeAll - Try to rematerialize as many uses as possible,
220 /// and trim the live ranges after.
221 void InlineSpiller::reMaterializeAll() {
222 // Do a quick scan of the interval values to find if any are remattable.
223 if (!edit_->anyRematerializable(lis_, tii_, 0))
228 // Try to remat before all uses of edit_->getReg().
229 bool anyRemat = false;
230 for (MachineRegisterInfo::use_nodbg_iterator
231 RI = mri_.use_nodbg_begin(edit_->getReg());
232 MachineInstr *MI = RI.skipInstruction();)
233 anyRemat |= reMaterializeFor(MI);
238 // Remove any values that were completely rematted.
239 bool anyRemoved = false;
240 for (LiveInterval::vni_iterator I = edit_->getParent().vni_begin(),
241 E = edit_->getParent().vni_end(); I != E; ++I) {
243 if (VNI->hasPHIKill() || !edit_->didRematerialize(VNI) ||
244 usedValues_.count(VNI))
246 MachineInstr *DefMI = lis_.getInstructionFromIndex(VNI->def);
247 DEBUG(dbgs() << "\tremoving dead def: " << VNI->def << '\t' << *DefMI);
248 lis_.RemoveMachineInstrFromMaps(DefMI);
249 vrm_.RemoveMachineInstrFromMaps(DefMI);
250 DefMI->eraseFromParent();
251 VNI->def = SlotIndex();
258 // Removing values may cause debug uses where parent is not live.
259 for (MachineRegisterInfo::use_iterator RI = mri_.use_begin(edit_->getReg());
260 MachineInstr *MI = RI.skipInstruction();) {
261 if (!MI->isDebugValue())
263 // Try to preserve the debug value if parent is live immediately after it.
264 MachineBasicBlock::iterator NextMI = MI;
266 if (NextMI != MI->getParent()->end() && !lis_.isNotInMIMap(NextMI)) {
267 SlotIndex Idx = lis_.getInstructionIndex(NextMI);
268 VNInfo *VNI = edit_->getParent().getVNInfoAt(Idx);
269 if (VNI && (VNI->hasPHIKill() || usedValues_.count(VNI)))
272 DEBUG(dbgs() << "Removing debug info due to remat:" << "\t" << *MI);
273 MI->eraseFromParent();
277 /// If MI is a load or store of stackSlot_, it can be removed.
278 bool InlineSpiller::coalesceStackAccess(MachineInstr *MI) {
281 if (!(reg = tii_.isLoadFromStackSlot(MI, FI)) &&
282 !(reg = tii_.isStoreToStackSlot(MI, FI)))
285 // We have a stack access. Is it the right register and slot?
286 if (reg != edit_->getReg() || FI != stackSlot_)
289 DEBUG(dbgs() << "Coalescing stack access: " << *MI);
290 lis_.RemoveMachineInstrFromMaps(MI);
291 MI->eraseFromParent();
295 /// foldMemoryOperand - Try folding stack slot references in Ops into MI.
296 /// Return true on success, and MI will be erased.
297 bool InlineSpiller::foldMemoryOperand(MachineBasicBlock::iterator MI,
298 const SmallVectorImpl<unsigned> &Ops) {
299 // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
301 SmallVector<unsigned, 8> FoldOps;
302 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
303 unsigned Idx = Ops[i];
304 MachineOperand &MO = MI->getOperand(Idx);
307 // FIXME: Teach targets to deal with subregs.
310 // Tied use operands should not be passed to foldMemoryOperand.
311 if (!MI->isRegTiedToDefOperand(Idx))
312 FoldOps.push_back(Idx);
315 MachineInstr *FoldMI = tii_.foldMemoryOperand(MI, FoldOps, stackSlot_);
318 lis_.ReplaceMachineInstrInMaps(MI, FoldMI);
319 vrm_.addSpillSlotUse(stackSlot_, FoldMI);
320 MI->eraseFromParent();
321 DEBUG(dbgs() << "\tfolded: " << *FoldMI);
325 /// insertReload - Insert a reload of NewLI.reg before MI.
326 void InlineSpiller::insertReload(LiveInterval &NewLI,
327 MachineBasicBlock::iterator MI) {
328 MachineBasicBlock &MBB = *MI->getParent();
329 SlotIndex Idx = lis_.getInstructionIndex(MI).getDefIndex();
330 tii_.loadRegFromStackSlot(MBB, MI, NewLI.reg, stackSlot_, rc_, &tri_);
331 --MI; // Point to load instruction.
332 SlotIndex LoadIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
333 vrm_.addSpillSlotUse(stackSlot_, MI);
334 DEBUG(dbgs() << "\treload: " << LoadIdx << '\t' << *MI);
335 VNInfo *LoadVNI = NewLI.getNextValue(LoadIdx, 0,
336 lis_.getVNInfoAllocator());
337 NewLI.addRange(LiveRange(LoadIdx, Idx, LoadVNI));
340 /// insertSpill - Insert a spill of NewLI.reg after MI.
341 void InlineSpiller::insertSpill(LiveInterval &NewLI,
342 MachineBasicBlock::iterator MI) {
343 MachineBasicBlock &MBB = *MI->getParent();
344 SlotIndex Idx = lis_.getInstructionIndex(MI).getDefIndex();
345 tii_.storeRegToStackSlot(MBB, ++MI, NewLI.reg, true, stackSlot_, rc_, &tri_);
346 --MI; // Point to store instruction.
347 SlotIndex StoreIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
348 vrm_.addSpillSlotUse(stackSlot_, MI);
349 DEBUG(dbgs() << "\tspilled: " << StoreIdx << '\t' << *MI);
350 VNInfo *StoreVNI = NewLI.getNextValue(Idx, 0, lis_.getVNInfoAllocator());
351 NewLI.addRange(LiveRange(Idx, StoreIdx, StoreVNI));
354 void InlineSpiller::spill(LiveInterval *li,
355 SmallVectorImpl<LiveInterval*> &newIntervals,
356 SmallVectorImpl<LiveInterval*> &spillIs) {
357 LiveRangeEdit edit(*li, newIntervals, spillIs);
363 void InlineSpiller::spill(LiveRangeEdit &edit) {
365 assert(!edit.getParent().isStackSlot() && "Trying to spill a stack slot.");
366 DEBUG(dbgs() << "Inline spilling "
367 << mri_.getRegClass(edit.getReg())->getName()
368 << ':' << edit.getParent() << "\n");
369 assert(edit.getParent().isSpillable() &&
370 "Attempting to spill already spilled value.");
377 // Remat may handle everything.
378 if (edit_->getParent().empty())
381 rc_ = mri_.getRegClass(edit.getReg());
382 stackSlot_ = vrm_.assignVirt2StackSlot(edit_->getReg());
384 // Update LiveStacks now that we are committed to spilling.
385 LiveInterval &stacklvr = lss_.getOrCreateInterval(stackSlot_, rc_);
386 assert(stacklvr.empty() && "Just created stack slot not empty");
387 stacklvr.getNextValue(SlotIndex(), 0, lss_.getVNInfoAllocator());
388 stacklvr.MergeRangesInAsValue(edit_->getParent(), stacklvr.getValNumInfo(0));
390 // Iterate over instructions using register.
391 for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(edit.getReg());
392 MachineInstr *MI = RI.skipInstruction();) {
394 // Debug values are not allowed to affect codegen.
395 if (MI->isDebugValue()) {
396 // Modify DBG_VALUE now that the value is in a spill slot.
397 uint64_t Offset = MI->getOperand(1).getImm();
398 const MDNode *MDPtr = MI->getOperand(2).getMetadata();
399 DebugLoc DL = MI->getDebugLoc();
400 if (MachineInstr *NewDV = tii_.emitFrameIndexDebugValue(mf_, stackSlot_,
401 Offset, MDPtr, DL)) {
402 DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
403 MachineBasicBlock *MBB = MI->getParent();
404 MBB->insert(MBB->erase(MI), NewDV);
406 DEBUG(dbgs() << "Removing debug info due to spill:" << "\t" << *MI);
407 MI->eraseFromParent();
412 // Stack slot accesses may coalesce away.
413 if (coalesceStackAccess(MI))
416 // Analyze instruction.
418 SmallVector<unsigned, 8> Ops;
419 tie(Reads, Writes) = MI->readsWritesVirtualRegister(edit.getReg(), &Ops);
421 // Attempt to fold memory ops.
422 if (foldMemoryOperand(MI, Ops))
425 // Allocate interval around instruction.
426 // FIXME: Infer regclass from instruction alone.
427 LiveInterval &NewLI = edit.create(mri_, lis_, vrm_);
428 NewLI.markNotSpillable();
431 insertReload(NewLI, MI);
433 // Rewrite instruction operands.
434 bool hasLiveDef = false;
435 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
436 MachineOperand &MO = MI->getOperand(Ops[i]);
437 MO.setReg(NewLI.reg);
439 if (!MI->isRegTiedToDefOperand(Ops[i]))
447 // FIXME: Use a second vreg if instruction has no tied ops.
448 if (Writes && hasLiveDef)
449 insertSpill(NewLI, MI);
451 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');