Rip out live range splitting support from the inline spiller.
[oota-llvm.git] / lib / CodeGen / InlineSpiller.cpp
1 //===-------- InlineSpiller.cpp - Insert spills and restores inline -------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // The inline spiller modifies the machine function directly instead of
11 // inserting spills and restores in VirtRegMap.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "regalloc"
16 #include "Spiller.h"
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/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
30
31 using namespace llvm;
32
33 static cl::opt<bool>
34 VerifySpills("verify-spills", cl::desc("Verify after each spill/split"));
35
36 namespace {
37 class InlineSpiller : public Spiller {
38   MachineFunctionPass &pass_;
39   MachineFunction &mf_;
40   LiveIntervals &lis_;
41   LiveStacks &lss_;
42   AliasAnalysis *aa_;
43   VirtRegMap &vrm_;
44   MachineFrameInfo &mfi_;
45   MachineRegisterInfo &mri_;
46   const TargetInstrInfo &tii_;
47   const TargetRegisterInfo &tri_;
48   const BitVector reserved_;
49
50   // Variables that are valid during spill(), but used by multiple methods.
51   LiveRangeEdit *edit_;
52   const TargetRegisterClass *rc_;
53   int stackSlot_;
54
55   // Values that failed to remat at some point.
56   SmallPtrSet<VNInfo*, 8> usedValues_;
57
58   ~InlineSpiller() {}
59
60 public:
61   InlineSpiller(MachineFunctionPass &pass,
62                 MachineFunction &mf,
63                 VirtRegMap &vrm)
64     : pass_(pass),
65       mf_(mf),
66       lis_(pass.getAnalysis<LiveIntervals>()),
67       lss_(pass.getAnalysis<LiveStacks>()),
68       aa_(&pass.getAnalysis<AliasAnalysis>()),
69       vrm_(vrm),
70       mfi_(*mf.getFrameInfo()),
71       mri_(mf.getRegInfo()),
72       tii_(*mf.getTarget().getInstrInfo()),
73       tri_(*mf.getTarget().getRegisterInfo()),
74       reserved_(tri_.getReservedRegs(mf_)) {}
75
76   void spill(LiveInterval *li,
77              SmallVectorImpl<LiveInterval*> &newIntervals,
78              const SmallVectorImpl<LiveInterval*> &spillIs);
79
80   void spill(LiveRangeEdit &);
81
82 private:
83   bool reMaterializeFor(MachineBasicBlock::iterator MI);
84   void reMaterializeAll();
85
86   bool coalesceStackAccess(MachineInstr *MI);
87   bool foldMemoryOperand(MachineBasicBlock::iterator MI,
88                          const SmallVectorImpl<unsigned> &Ops);
89   void insertReload(LiveInterval &NewLI, MachineBasicBlock::iterator MI);
90   void insertSpill(LiveInterval &NewLI, MachineBasicBlock::iterator MI);
91 };
92 }
93
94 namespace llvm {
95 Spiller *createInlineSpiller(MachineFunctionPass &pass,
96                              MachineFunction &mf,
97                              VirtRegMap &vrm) {
98   if (VerifySpills)
99     mf.verify(&pass);
100   return new InlineSpiller(pass, mf, vrm);
101 }
102 }
103
104 /// reMaterializeFor - Attempt to rematerialize edit_->getReg() before MI instead of
105 /// reloading it.
106 bool InlineSpiller::reMaterializeFor(MachineBasicBlock::iterator MI) {
107   SlotIndex UseIdx = lis_.getInstructionIndex(MI).getUseIndex();
108   VNInfo *OrigVNI = edit_->getParent().getVNInfoAt(UseIdx);
109
110   if (!OrigVNI) {
111     DEBUG(dbgs() << "\tadding <undef> flags: ");
112     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
113       MachineOperand &MO = MI->getOperand(i);
114       if (MO.isReg() && MO.isUse() && MO.getReg() == edit_->getReg())
115         MO.setIsUndef();
116     }
117     DEBUG(dbgs() << UseIdx << '\t' << *MI);
118     return true;
119   }
120
121   LiveRangeEdit::Remat RM(OrigVNI);
122   if (!edit_->canRematerializeAt(RM, UseIdx, false, lis_)) {
123     usedValues_.insert(OrigVNI);
124     DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
125     return false;
126   }
127
128   // If the instruction also writes edit_->getReg(), it had better not require
129   // the same register for uses and defs.
130   bool Reads, Writes;
131   SmallVector<unsigned, 8> Ops;
132   tie(Reads, Writes) = MI->readsWritesVirtualRegister(edit_->getReg(), &Ops);
133   if (Writes) {
134     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
135       MachineOperand &MO = MI->getOperand(Ops[i]);
136       if (MO.isUse() ? MI->isRegTiedToDefOperand(Ops[i]) : MO.getSubReg()) {
137         usedValues_.insert(OrigVNI);
138         DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
139         return false;
140       }
141     }
142   }
143
144   // Alocate a new register for the remat.
145   LiveInterval &NewLI = edit_->create(mri_, lis_, vrm_);
146   NewLI.markNotSpillable();
147
148   // Finally we can rematerialize OrigMI before MI.
149   SlotIndex DefIdx = edit_->rematerializeAt(*MI->getParent(), MI, NewLI.reg, RM,
150                                             lis_, tii_, tri_);
151   DEBUG(dbgs() << "\tremat:  " << DefIdx << '\n');
152
153   // Replace operands
154   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
155     MachineOperand &MO = MI->getOperand(Ops[i]);
156     if (MO.isReg() && MO.isUse() && MO.getReg() == edit_->getReg()) {
157       MO.setReg(NewLI.reg);
158       MO.setIsKill();
159     }
160   }
161   DEBUG(dbgs() << "\t        " << UseIdx << '\t' << *MI);
162
163   VNInfo *DefVNI = NewLI.getNextValue(DefIdx, 0, lis_.getVNInfoAllocator());
164   NewLI.addRange(LiveRange(DefIdx, UseIdx.getDefIndex(), DefVNI));
165   DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
166   return true;
167 }
168
169 /// reMaterializeAll - Try to rematerialize as many uses as possible,
170 /// and trim the live ranges after.
171 void InlineSpiller::reMaterializeAll() {
172   // Do a quick scan of the interval values to find if any are remattable.
173   if (!edit_->anyRematerializable(lis_, tii_, aa_))
174     return;
175
176   usedValues_.clear();
177
178   // Try to remat before all uses of edit_->getReg().
179   bool anyRemat = false;
180   for (MachineRegisterInfo::use_nodbg_iterator
181        RI = mri_.use_nodbg_begin(edit_->getReg());
182        MachineInstr *MI = RI.skipInstruction();)
183      anyRemat |= reMaterializeFor(MI);
184
185   if (!anyRemat)
186     return;
187
188   // Remove any values that were completely rematted.
189   bool anyRemoved = false;
190   for (LiveInterval::vni_iterator I = edit_->getParent().vni_begin(),
191        E = edit_->getParent().vni_end(); I != E; ++I) {
192     VNInfo *VNI = *I;
193     if (VNI->hasPHIKill() || !edit_->didRematerialize(VNI) ||
194         usedValues_.count(VNI))
195       continue;
196     MachineInstr *DefMI = lis_.getInstructionFromIndex(VNI->def);
197     DEBUG(dbgs() << "\tremoving dead def: " << VNI->def << '\t' << *DefMI);
198     lis_.RemoveMachineInstrFromMaps(DefMI);
199     vrm_.RemoveMachineInstrFromMaps(DefMI);
200     DefMI->eraseFromParent();
201     VNI->def = SlotIndex();
202     anyRemoved = true;
203   }
204
205   if (!anyRemoved)
206     return;
207
208   // Removing values may cause debug uses where parent is not live.
209   for (MachineRegisterInfo::use_iterator RI = mri_.use_begin(edit_->getReg());
210        MachineInstr *MI = RI.skipInstruction();) {
211     if (!MI->isDebugValue())
212       continue;
213     // Try to preserve the debug value if parent is live immediately after it.
214     MachineBasicBlock::iterator NextMI = MI;
215     ++NextMI;
216     if (NextMI != MI->getParent()->end() && !lis_.isNotInMIMap(NextMI)) {
217       SlotIndex Idx = lis_.getInstructionIndex(NextMI);
218       VNInfo *VNI = edit_->getParent().getVNInfoAt(Idx);
219       if (VNI && (VNI->hasPHIKill() || usedValues_.count(VNI)))
220         continue;
221     }
222     DEBUG(dbgs() << "Removing debug info due to remat:" << "\t" << *MI);
223     MI->eraseFromParent();
224   }
225 }
226
227 /// If MI is a load or store of stackSlot_, it can be removed.
228 bool InlineSpiller::coalesceStackAccess(MachineInstr *MI) {
229   int FI = 0;
230   unsigned reg;
231   if (!(reg = tii_.isLoadFromStackSlot(MI, FI)) &&
232       !(reg = tii_.isStoreToStackSlot(MI, FI)))
233     return false;
234
235   // We have a stack access. Is it the right register and slot?
236   if (reg != edit_->getReg() || FI != stackSlot_)
237     return false;
238
239   DEBUG(dbgs() << "Coalescing stack access: " << *MI);
240   lis_.RemoveMachineInstrFromMaps(MI);
241   MI->eraseFromParent();
242   return true;
243 }
244
245 /// foldMemoryOperand - Try folding stack slot references in Ops into MI.
246 /// Return true on success, and MI will be erased.
247 bool InlineSpiller::foldMemoryOperand(MachineBasicBlock::iterator MI,
248                                       const SmallVectorImpl<unsigned> &Ops) {
249   // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
250   // operands.
251   SmallVector<unsigned, 8> FoldOps;
252   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
253     unsigned Idx = Ops[i];
254     MachineOperand &MO = MI->getOperand(Idx);
255     if (MO.isImplicit())
256       continue;
257     // FIXME: Teach targets to deal with subregs.
258     if (MO.getSubReg())
259       return false;
260     // Tied use operands should not be passed to foldMemoryOperand.
261     if (!MI->isRegTiedToDefOperand(Idx))
262       FoldOps.push_back(Idx);
263   }
264
265   MachineInstr *FoldMI = tii_.foldMemoryOperand(MI, FoldOps, stackSlot_);
266   if (!FoldMI)
267     return false;
268   lis_.ReplaceMachineInstrInMaps(MI, FoldMI);
269   vrm_.addSpillSlotUse(stackSlot_, FoldMI);
270   MI->eraseFromParent();
271   DEBUG(dbgs() << "\tfolded: " << *FoldMI);
272   return true;
273 }
274
275 /// insertReload - Insert a reload of NewLI.reg before MI.
276 void InlineSpiller::insertReload(LiveInterval &NewLI,
277                                  MachineBasicBlock::iterator MI) {
278   MachineBasicBlock &MBB = *MI->getParent();
279   SlotIndex Idx = lis_.getInstructionIndex(MI).getDefIndex();
280   tii_.loadRegFromStackSlot(MBB, MI, NewLI.reg, stackSlot_, rc_, &tri_);
281   --MI; // Point to load instruction.
282   SlotIndex LoadIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
283   vrm_.addSpillSlotUse(stackSlot_, MI);
284   DEBUG(dbgs() << "\treload:  " << LoadIdx << '\t' << *MI);
285   VNInfo *LoadVNI = NewLI.getNextValue(LoadIdx, 0,
286                                        lis_.getVNInfoAllocator());
287   NewLI.addRange(LiveRange(LoadIdx, Idx, LoadVNI));
288 }
289
290 /// insertSpill - Insert a spill of NewLI.reg after MI.
291 void InlineSpiller::insertSpill(LiveInterval &NewLI,
292                                 MachineBasicBlock::iterator MI) {
293   MachineBasicBlock &MBB = *MI->getParent();
294
295   // Get the defined value. It could be an early clobber so keep the def index.
296   SlotIndex Idx = lis_.getInstructionIndex(MI).getDefIndex();
297   VNInfo *VNI = edit_->getParent().getVNInfoAt(Idx);
298   assert(VNI && VNI->def.getDefIndex() == Idx && "Inconsistent VNInfo");
299   Idx = VNI->def;
300
301   tii_.storeRegToStackSlot(MBB, ++MI, NewLI.reg, true, stackSlot_, rc_, &tri_);
302   --MI; // Point to store instruction.
303   SlotIndex StoreIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
304   vrm_.addSpillSlotUse(stackSlot_, MI);
305   DEBUG(dbgs() << "\tspilled: " << StoreIdx << '\t' << *MI);
306   VNInfo *StoreVNI = NewLI.getNextValue(Idx, 0, lis_.getVNInfoAllocator());
307   NewLI.addRange(LiveRange(Idx, StoreIdx, StoreVNI));
308 }
309
310 void InlineSpiller::spill(LiveInterval *li,
311                           SmallVectorImpl<LiveInterval*> &newIntervals,
312                           const SmallVectorImpl<LiveInterval*> &spillIs) {
313   LiveRangeEdit edit(*li, newIntervals, spillIs);
314   spill(edit);
315   if (VerifySpills)
316     mf_.verify(&pass_);
317 }
318
319 void InlineSpiller::spill(LiveRangeEdit &edit) {
320   edit_ = &edit;
321   assert(!edit.getParent().isStackSlot() && "Trying to spill a stack slot.");
322   DEBUG(dbgs() << "Inline spilling "
323                << mri_.getRegClass(edit.getReg())->getName()
324                << ':' << edit.getParent() << "\n");
325   assert(edit.getParent().isSpillable() &&
326          "Attempting to spill already spilled value.");
327
328   reMaterializeAll();
329
330   // Remat may handle everything.
331   if (edit_->getParent().empty())
332     return;
333
334   rc_ = mri_.getRegClass(edit.getReg());
335   stackSlot_ = vrm_.assignVirt2StackSlot(edit_->getReg());
336
337   // Update LiveStacks now that we are committed to spilling.
338   LiveInterval &stacklvr = lss_.getOrCreateInterval(stackSlot_, rc_);
339   assert(stacklvr.empty() && "Just created stack slot not empty");
340   stacklvr.getNextValue(SlotIndex(), 0, lss_.getVNInfoAllocator());
341   stacklvr.MergeRangesInAsValue(edit_->getParent(), stacklvr.getValNumInfo(0));
342
343   // Iterate over instructions using register.
344   for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(edit.getReg());
345        MachineInstr *MI = RI.skipInstruction();) {
346
347     // Debug values are not allowed to affect codegen.
348     if (MI->isDebugValue()) {
349       // Modify DBG_VALUE now that the value is in a spill slot.
350       uint64_t Offset = MI->getOperand(1).getImm();
351       const MDNode *MDPtr = MI->getOperand(2).getMetadata();
352       DebugLoc DL = MI->getDebugLoc();
353       if (MachineInstr *NewDV = tii_.emitFrameIndexDebugValue(mf_, stackSlot_,
354                                                            Offset, MDPtr, DL)) {
355         DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
356         MachineBasicBlock *MBB = MI->getParent();
357         MBB->insert(MBB->erase(MI), NewDV);
358       } else {
359         DEBUG(dbgs() << "Removing debug info due to spill:" << "\t" << *MI);
360         MI->eraseFromParent();
361       }
362       continue;
363     }
364
365     // Stack slot accesses may coalesce away.
366     if (coalesceStackAccess(MI))
367       continue;
368
369     // Analyze instruction.
370     bool Reads, Writes;
371     SmallVector<unsigned, 8> Ops;
372     tie(Reads, Writes) = MI->readsWritesVirtualRegister(edit.getReg(), &Ops);
373
374     // Attempt to fold memory ops.
375     if (foldMemoryOperand(MI, Ops))
376       continue;
377
378     // Allocate interval around instruction.
379     // FIXME: Infer regclass from instruction alone.
380     LiveInterval &NewLI = edit.create(mri_, lis_, vrm_);
381     NewLI.markNotSpillable();
382
383     if (Reads)
384       insertReload(NewLI, MI);
385
386     // Rewrite instruction operands.
387     bool hasLiveDef = false;
388     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
389       MachineOperand &MO = MI->getOperand(Ops[i]);
390       MO.setReg(NewLI.reg);
391       if (MO.isUse()) {
392         if (!MI->isRegTiedToDefOperand(Ops[i]))
393           MO.setIsKill();
394       } else {
395         if (!MO.isDead())
396           hasLiveDef = true;
397       }
398     }
399
400     // FIXME: Use a second vreg if instruction has no tied ops.
401     if (Writes && hasLiveDef)
402       insertSpill(NewLI, MI);
403
404     DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
405   }
406 }