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