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