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 "spiller"
17 #include "LiveRangeEdit.h"
19 #include "VirtRegMap.h"
20 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/raw_ostream.h"
33 class InlineSpiller : public Spiller {
34 MachineFunctionPass &pass_;
37 MachineLoopInfo &loops_;
39 MachineFrameInfo &mfi_;
40 MachineRegisterInfo &mri_;
41 const TargetInstrInfo &tii_;
42 const TargetRegisterInfo &tri_;
43 const BitVector reserved_;
45 SplitAnalysis splitAnalysis_;
47 // Variables that are valid during spill(), but used by multiple methods.
49 const TargetRegisterClass *rc_;
52 // Values of the current interval that can potentially remat.
53 SmallPtrSet<VNInfo*, 8> reMattable_;
55 // Values in reMattable_ that failed to remat at some point.
56 SmallPtrSet<VNInfo*, 8> usedValues_;
61 InlineSpiller(MachineFunctionPass &pass,
66 lis_(pass.getAnalysis<LiveIntervals>()),
67 loops_(pass.getAnalysis<MachineLoopInfo>()),
69 mfi_(*mf.getFrameInfo()),
70 mri_(mf.getRegInfo()),
71 tii_(*mf.getTarget().getInstrInfo()),
72 tri_(*mf.getTarget().getRegisterInfo()),
73 reserved_(tri_.getReservedRegs(mf_)),
74 splitAnalysis_(mf, lis_, loops_) {}
76 void spill(LiveInterval *li,
77 SmallVectorImpl<LiveInterval*> &newIntervals,
78 SmallVectorImpl<LiveInterval*> &spillIs);
80 void spill(LiveRangeEdit &);
85 bool reMaterializeFor(MachineBasicBlock::iterator MI);
86 void reMaterializeAll();
88 bool coalesceStackAccess(MachineInstr *MI);
89 bool foldMemoryOperand(MachineBasicBlock::iterator MI,
90 const SmallVectorImpl<unsigned> &Ops);
91 void insertReload(LiveInterval &NewLI, MachineBasicBlock::iterator MI);
92 void insertSpill(LiveInterval &NewLI, MachineBasicBlock::iterator MI);
97 Spiller *createInlineSpiller(MachineFunctionPass &pass,
100 return new InlineSpiller(pass, mf, vrm);
104 /// split - try splitting the current interval into pieces that may allocate
105 /// separately. Return true if successful.
106 bool InlineSpiller::split() {
107 splitAnalysis_.analyze(&edit_->getParent());
109 // Try splitting around loops.
110 if (const MachineLoop *loop = splitAnalysis_.getBestSplitLoop()) {
111 SplitEditor(splitAnalysis_, lis_, vrm_, *edit_)
112 .splitAroundLoop(loop);
116 // Try splitting into single block intervals.
117 SplitAnalysis::BlockPtrSet blocks;
118 if (splitAnalysis_.getMultiUseBlocks(blocks)) {
119 SplitEditor(splitAnalysis_, lis_, vrm_, *edit_)
120 .splitSingleBlocks(blocks);
124 // Try splitting inside a basic block.
125 if (const MachineBasicBlock *MBB = splitAnalysis_.getBlockForInsideSplit()) {
126 SplitEditor(splitAnalysis_, lis_, vrm_, *edit_)
127 .splitInsideBlock(MBB);
134 /// reMaterializeFor - Attempt to rematerialize edit_->getReg() before MI instead of
136 bool InlineSpiller::reMaterializeFor(MachineBasicBlock::iterator MI) {
137 SlotIndex UseIdx = lis_.getInstructionIndex(MI).getUseIndex();
138 VNInfo *OrigVNI = edit_->getParent().getVNInfoAt(UseIdx);
140 DEBUG(dbgs() << "\tadding <undef> flags: ");
141 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
142 MachineOperand &MO = MI->getOperand(i);
143 if (MO.isReg() && MO.isUse() && MO.getReg() == edit_->getReg())
146 DEBUG(dbgs() << UseIdx << '\t' << *MI);
149 if (!reMattable_.count(OrigVNI)) {
150 DEBUG(dbgs() << "\tusing non-remat valno " << OrigVNI->id << ": "
151 << UseIdx << '\t' << *MI);
154 MachineInstr *OrigMI = lis_.getInstructionFromIndex(OrigVNI->def);
155 if (!edit_->allUsesAvailableAt(OrigMI, OrigVNI->def, UseIdx, lis_)) {
156 usedValues_.insert(OrigVNI);
157 DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
161 // If the instruction also writes edit_->getReg(), it had better not require the same
162 // register for uses and defs.
164 SmallVector<unsigned, 8> Ops;
165 tie(Reads, Writes) = MI->readsWritesVirtualRegister(edit_->getReg(), &Ops);
167 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
168 MachineOperand &MO = MI->getOperand(Ops[i]);
169 if (MO.isUse() ? MI->isRegTiedToDefOperand(Ops[i]) : MO.getSubReg()) {
170 usedValues_.insert(OrigVNI);
171 DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
177 // Alocate a new register for the remat.
178 LiveInterval &NewLI = edit_->create(mri_, lis_, vrm_);
179 NewLI.markNotSpillable();
181 // Finally we can rematerialize OrigMI before MI.
182 MachineBasicBlock &MBB = *MI->getParent();
183 tii_.reMaterialize(MBB, MI, NewLI.reg, 0, OrigMI, tri_);
184 MachineBasicBlock::iterator RematMI = MI;
185 SlotIndex DefIdx = lis_.InsertMachineInstrInMaps(--RematMI).getDefIndex();
186 DEBUG(dbgs() << "\tremat: " << DefIdx << '\t' << *RematMI);
189 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
190 MachineOperand &MO = MI->getOperand(Ops[i]);
191 if (MO.isReg() && MO.isUse() && MO.getReg() == edit_->getReg()) {
192 MO.setReg(NewLI.reg);
196 DEBUG(dbgs() << "\t " << UseIdx << '\t' << *MI);
198 VNInfo *DefVNI = NewLI.getNextValue(DefIdx, 0, lis_.getVNInfoAllocator());
199 NewLI.addRange(LiveRange(DefIdx, UseIdx.getDefIndex(), DefVNI));
200 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
204 /// reMaterializeAll - Try to rematerialize as many uses as possible,
205 /// and trim the live ranges after.
206 void InlineSpiller::reMaterializeAll() {
207 // Do a quick scan of the interval values to find if any are remattable.
210 for (LiveInterval::const_vni_iterator I = edit_->getParent().vni_begin(),
211 E = edit_->getParent().vni_end(); I != E; ++I) {
215 MachineInstr *DefMI = lis_.getInstructionFromIndex(VNI->def);
216 if (!DefMI || !tii_.isTriviallyReMaterializable(DefMI))
218 reMattable_.insert(VNI);
221 // Often, no defs are remattable.
222 if (reMattable_.empty())
225 // Try to remat before all uses of edit_->getReg().
226 bool anyRemat = false;
227 for (MachineRegisterInfo::use_nodbg_iterator
228 RI = mri_.use_nodbg_begin(edit_->getReg());
229 MachineInstr *MI = RI.skipInstruction();)
230 anyRemat |= reMaterializeFor(MI);
235 // Remove any values that were completely rematted.
236 bool anyRemoved = false;
237 for (SmallPtrSet<VNInfo*, 8>::iterator I = reMattable_.begin(),
238 E = reMattable_.end(); I != E; ++I) {
240 if (VNI->hasPHIKill() || usedValues_.count(VNI))
242 MachineInstr *DefMI = lis_.getInstructionFromIndex(VNI->def);
243 DEBUG(dbgs() << "\tremoving dead def: " << VNI->def << '\t' << *DefMI);
244 lis_.RemoveMachineInstrFromMaps(DefMI);
245 vrm_.RemoveMachineInstrFromMaps(DefMI);
246 DefMI->eraseFromParent();
247 VNI->def = SlotIndex();
254 // Removing values may cause debug uses where parent is not live.
255 for (MachineRegisterInfo::use_iterator RI = mri_.use_begin(edit_->getReg());
256 MachineInstr *MI = RI.skipInstruction();) {
257 if (!MI->isDebugValue())
259 // Try to preserve the debug value if parent is live immediately after it.
260 MachineBasicBlock::iterator NextMI = MI;
262 if (NextMI != MI->getParent()->end() && !lis_.isNotInMIMap(NextMI)) {
263 SlotIndex Idx = lis_.getInstructionIndex(NextMI);
264 VNInfo *VNI = edit_->getParent().getVNInfoAt(Idx);
265 if (VNI && (VNI->hasPHIKill() || usedValues_.count(VNI)))
268 DEBUG(dbgs() << "Removing debug info due to remat:" << "\t" << *MI);
269 MI->eraseFromParent();
273 /// If MI is a load or store of stackSlot_, it can be removed.
274 bool InlineSpiller::coalesceStackAccess(MachineInstr *MI) {
277 if (!(reg = tii_.isLoadFromStackSlot(MI, FI)) &&
278 !(reg = tii_.isStoreToStackSlot(MI, FI)))
281 // We have a stack access. Is it the right register and slot?
282 if (reg != edit_->getReg() || FI != stackSlot_)
285 DEBUG(dbgs() << "Coalescing stack access: " << *MI);
286 lis_.RemoveMachineInstrFromMaps(MI);
287 MI->eraseFromParent();
291 /// foldMemoryOperand - Try folding stack slot references in Ops into MI.
292 /// Return true on success, and MI will be erased.
293 bool InlineSpiller::foldMemoryOperand(MachineBasicBlock::iterator MI,
294 const SmallVectorImpl<unsigned> &Ops) {
295 // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
297 SmallVector<unsigned, 8> FoldOps;
298 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
299 unsigned Idx = Ops[i];
300 MachineOperand &MO = MI->getOperand(Idx);
303 // FIXME: Teach targets to deal with subregs.
306 // Tied use operands should not be passed to foldMemoryOperand.
307 if (!MI->isRegTiedToDefOperand(Idx))
308 FoldOps.push_back(Idx);
311 MachineInstr *FoldMI = tii_.foldMemoryOperand(MI, FoldOps, stackSlot_);
314 lis_.ReplaceMachineInstrInMaps(MI, FoldMI);
315 vrm_.addSpillSlotUse(stackSlot_, FoldMI);
316 MI->eraseFromParent();
317 DEBUG(dbgs() << "\tfolded: " << *FoldMI);
321 /// insertReload - Insert a reload of NewLI.reg before MI.
322 void InlineSpiller::insertReload(LiveInterval &NewLI,
323 MachineBasicBlock::iterator MI) {
324 MachineBasicBlock &MBB = *MI->getParent();
325 SlotIndex Idx = lis_.getInstructionIndex(MI).getDefIndex();
326 tii_.loadRegFromStackSlot(MBB, MI, NewLI.reg, stackSlot_, rc_, &tri_);
327 --MI; // Point to load instruction.
328 SlotIndex LoadIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
329 vrm_.addSpillSlotUse(stackSlot_, MI);
330 DEBUG(dbgs() << "\treload: " << LoadIdx << '\t' << *MI);
331 VNInfo *LoadVNI = NewLI.getNextValue(LoadIdx, 0,
332 lis_.getVNInfoAllocator());
333 NewLI.addRange(LiveRange(LoadIdx, Idx, LoadVNI));
336 /// insertSpill - Insert a spill of NewLI.reg after MI.
337 void InlineSpiller::insertSpill(LiveInterval &NewLI,
338 MachineBasicBlock::iterator MI) {
339 MachineBasicBlock &MBB = *MI->getParent();
340 SlotIndex Idx = lis_.getInstructionIndex(MI).getDefIndex();
341 tii_.storeRegToStackSlot(MBB, ++MI, NewLI.reg, true, stackSlot_, rc_, &tri_);
342 --MI; // Point to store instruction.
343 SlotIndex StoreIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
344 vrm_.addSpillSlotUse(stackSlot_, MI);
345 DEBUG(dbgs() << "\tspilled: " << StoreIdx << '\t' << *MI);
346 VNInfo *StoreVNI = NewLI.getNextValue(Idx, 0, lis_.getVNInfoAllocator());
347 NewLI.addRange(LiveRange(Idx, StoreIdx, StoreVNI));
350 void InlineSpiller::spill(LiveInterval *li,
351 SmallVectorImpl<LiveInterval*> &newIntervals,
352 SmallVectorImpl<LiveInterval*> &spillIs) {
353 LiveRangeEdit edit(*li, newIntervals, spillIs);
357 void InlineSpiller::spill(LiveRangeEdit &edit) {
359 DEBUG(dbgs() << "Inline spilling " << edit.getParent() << "\n");
360 assert(edit.getParent().isSpillable() &&
361 "Attempting to spill already spilled value.");
362 assert(!edit.getParent().isStackSlot() && "Trying to spill a stack slot.");
369 // Remat may handle everything.
370 if (edit_->getParent().empty())
373 rc_ = mri_.getRegClass(edit.getReg());
374 stackSlot_ = vrm_.getStackSlot(edit.getReg());
375 if (stackSlot_ == VirtRegMap::NO_STACK_SLOT)
376 stackSlot_ = vrm_.assignVirt2StackSlot(edit.getReg());
378 // Iterate over instructions using register.
379 for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(edit.getReg());
380 MachineInstr *MI = RI.skipInstruction();) {
382 // Debug values are not allowed to affect codegen.
383 if (MI->isDebugValue()) {
384 // Modify DBG_VALUE now that the value is in a spill slot.
385 uint64_t Offset = MI->getOperand(1).getImm();
386 const MDNode *MDPtr = MI->getOperand(2).getMetadata();
387 DebugLoc DL = MI->getDebugLoc();
388 if (MachineInstr *NewDV = tii_.emitFrameIndexDebugValue(mf_, stackSlot_,
389 Offset, MDPtr, DL)) {
390 DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
391 MachineBasicBlock *MBB = MI->getParent();
392 MBB->insert(MBB->erase(MI), NewDV);
394 DEBUG(dbgs() << "Removing debug info due to spill:" << "\t" << *MI);
395 MI->eraseFromParent();
400 // Stack slot accesses may coalesce away.
401 if (coalesceStackAccess(MI))
404 // Analyze instruction.
406 SmallVector<unsigned, 8> Ops;
407 tie(Reads, Writes) = MI->readsWritesVirtualRegister(edit.getReg(), &Ops);
409 // Attempt to fold memory ops.
410 if (foldMemoryOperand(MI, Ops))
413 // Allocate interval around instruction.
414 // FIXME: Infer regclass from instruction alone.
415 LiveInterval &NewLI = edit.create(mri_, lis_, vrm_);
416 NewLI.markNotSpillable();
419 insertReload(NewLI, MI);
421 // Rewrite instruction operands.
422 bool hasLiveDef = false;
423 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
424 MachineOperand &MO = MI->getOperand(Ops[i]);
425 MO.setReg(NewLI.reg);
427 if (!MI->isRegTiedToDefOperand(Ops[i]))
435 // FIXME: Use a second vreg if instruction has no tied ops.
436 if (Writes && hasLiveDef)
437 insertSpill(NewLI, MI);
439 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');