blob: bcbe718bc862aaa88f592e151ae79c2965fdb954 [file] [log] [blame]
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001//===-------- 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
Jakob Stoklund Olesen376dcbd2010-11-03 20:39:23 +000015#define DEBUG_TYPE "regalloc"
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000016#include "Spiller.h"
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +000017#include "LiveRangeEdit.h"
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000018#include "VirtRegMap.h"
Jakob Stoklund Olesene93198a2010-11-10 23:55:56 +000019#include "llvm/Analysis/AliasAnalysis.h"
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000020#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Jakob Stoklund Olesen0a12b802010-10-26 00:11:35 +000021#include "llvm/CodeGen/LiveStackAnalysis.h"
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000022#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000023#include "llvm/CodeGen/MachineFrameInfo.h"
24#include "llvm/CodeGen/MachineFunction.h"
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000025#include "llvm/CodeGen/MachineLoopInfo.h"
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000026#include "llvm/CodeGen/MachineRegisterInfo.h"
27#include "llvm/Target/TargetMachine.h"
28#include "llvm/Target/TargetInstrInfo.h"
29#include "llvm/Support/Debug.h"
30#include "llvm/Support/raw_ostream.h"
31
32using namespace llvm;
33
34namespace {
35class InlineSpiller : public Spiller {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000036 MachineFunctionPass &Pass;
37 MachineFunction &MF;
38 LiveIntervals &LIS;
39 LiveStacks &LSS;
40 AliasAnalysis *AA;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000041 MachineDominatorTree &MDT;
42 MachineLoopInfo &Loops;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000043 VirtRegMap &VRM;
44 MachineFrameInfo &MFI;
45 MachineRegisterInfo &MRI;
46 const TargetInstrInfo &TII;
47 const TargetRegisterInfo &TRI;
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +000048
49 // Variables that are valid during spill(), but used by multiple methods.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000050 LiveRangeEdit *Edit;
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +000051 LiveInterval *StackInt;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000052 int StackSlot;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000053 unsigned Original;
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000054
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000055 // All registers to spill to StackSlot, including the main register.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +000056 SmallVector<unsigned, 8> RegsToSpill;
57
58 // All COPY instructions to/from snippets.
59 // They are ignored since both operands refer to the same stack slot.
60 SmallPtrSet<MachineInstr*, 8> SnippetCopies;
61
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +000062 // Values that failed to remat at some point.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000063 SmallPtrSet<VNInfo*, 8> UsedValues;
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +000064
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000065 // Information about a value that was defined by a copy from a sibling
66 // register.
67 struct SibValueInfo {
68 // True when all reaching defs were reloads: No spill is necessary.
69 bool AllDefsAreReloads;
70
71 // The preferred register to spill.
72 unsigned SpillReg;
73
74 // The value of SpillReg that should be spilled.
75 VNInfo *SpillVNI;
76
77 // A defining instruction that is not a sibling copy or a reload, or NULL.
78 // This can be used as a template for rematerialization.
79 MachineInstr *DefMI;
80
81 SibValueInfo(unsigned Reg, VNInfo *VNI)
82 : AllDefsAreReloads(false), SpillReg(Reg), SpillVNI(VNI), DefMI(0) {}
83 };
84
85 // Values in RegsToSpill defined by sibling copies.
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +000086 typedef DenseMap<VNInfo*, SibValueInfo> SibValueMap;
87 SibValueMap SibValues;
88
89 // Dead defs generated during spilling.
90 SmallVector<MachineInstr*, 8> DeadDefs;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000091
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000092 ~InlineSpiller() {}
93
94public:
Jakob Stoklund Olesenf2c6e362010-07-20 23:50:15 +000095 InlineSpiller(MachineFunctionPass &pass,
96 MachineFunction &mf,
97 VirtRegMap &vrm)
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000098 : Pass(pass),
99 MF(mf),
100 LIS(pass.getAnalysis<LiveIntervals>()),
101 LSS(pass.getAnalysis<LiveStacks>()),
102 AA(&pass.getAnalysis<AliasAnalysis>()),
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000103 MDT(pass.getAnalysis<MachineDominatorTree>()),
104 Loops(pass.getAnalysis<MachineLoopInfo>()),
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000105 VRM(vrm),
106 MFI(*mf.getFrameInfo()),
107 MRI(mf.getRegInfo()),
108 TII(*mf.getTarget().getInstrInfo()),
109 TRI(*mf.getTarget().getRegisterInfo()) {}
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000110
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000111 void spill(LiveRangeEdit &);
112
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000113private:
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000114 bool isSnippet(const LiveInterval &SnipLI);
115 void collectRegsToSpill();
116
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000117 bool isRegToSpill(unsigned Reg) {
118 return std::find(RegsToSpill.begin(),
119 RegsToSpill.end(), Reg) != RegsToSpill.end();
120 }
121
122 bool isSibling(unsigned Reg);
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000123 MachineInstr *traceSiblingValue(unsigned, VNInfo*, VNInfo*);
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000124 void analyzeSiblingValues();
125
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000126 bool hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI);
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000127 void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000128
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000129 void markValueUsed(LiveInterval*, VNInfo*);
130 bool reMaterializeFor(LiveInterval&, MachineBasicBlock::iterator MI);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000131 void reMaterializeAll();
132
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000133 bool coalesceStackAccess(MachineInstr *MI, unsigned Reg);
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000134 bool foldMemoryOperand(MachineBasicBlock::iterator MI,
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000135 const SmallVectorImpl<unsigned> &Ops,
136 MachineInstr *LoadMI = 0);
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +0000137 void insertReload(LiveInterval &NewLI, SlotIndex,
138 MachineBasicBlock::iterator MI);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000139 void insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +0000140 SlotIndex, MachineBasicBlock::iterator MI);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000141
142 void spillAroundUses(unsigned Reg);
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +0000143 void spillAll();
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000144};
145}
146
147namespace llvm {
Jakob Stoklund Olesenf2c6e362010-07-20 23:50:15 +0000148Spiller *createInlineSpiller(MachineFunctionPass &pass,
149 MachineFunction &mf,
150 VirtRegMap &vrm) {
151 return new InlineSpiller(pass, mf, vrm);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000152}
153}
154
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000155//===----------------------------------------------------------------------===//
156// Snippets
157//===----------------------------------------------------------------------===//
158
159// When spilling a virtual register, we also spill any snippets it is connected
160// to. The snippets are small live ranges that only have a single real use,
161// leftovers from live range splitting. Spilling them enables memory operand
162// folding or tightens the live range around the single use.
163//
164// This minimizes register pressure and maximizes the store-to-load distance for
165// spill slots which can be important in tight loops.
166
167/// isFullCopyOf - If MI is a COPY to or from Reg, return the other register,
168/// otherwise return 0.
169static unsigned isFullCopyOf(const MachineInstr *MI, unsigned Reg) {
170 if (!MI->isCopy())
171 return 0;
172 if (MI->getOperand(0).getSubReg() != 0)
173 return 0;
174 if (MI->getOperand(1).getSubReg() != 0)
175 return 0;
176 if (MI->getOperand(0).getReg() == Reg)
177 return MI->getOperand(1).getReg();
178 if (MI->getOperand(1).getReg() == Reg)
179 return MI->getOperand(0).getReg();
180 return 0;
181}
182
183/// isSnippet - Identify if a live interval is a snippet that should be spilled.
184/// It is assumed that SnipLI is a virtual register with the same original as
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000185/// Edit->getReg().
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000186bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000187 unsigned Reg = Edit->getReg();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000188
189 // A snippet is a tiny live range with only a single instruction using it
190 // besides copies to/from Reg or spills/fills. We accept:
191 //
192 // %snip = COPY %Reg / FILL fi#
193 // %snip = USE %snip
194 // %Reg = COPY %snip / SPILL %snip, fi#
195 //
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000196 if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI))
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000197 return false;
198
199 MachineInstr *UseMI = 0;
200
201 // Check that all uses satisfy our criteria.
202 for (MachineRegisterInfo::reg_nodbg_iterator
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000203 RI = MRI.reg_nodbg_begin(SnipLI.reg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000204 MachineInstr *MI = RI.skipInstruction();) {
205
206 // Allow copies to/from Reg.
207 if (isFullCopyOf(MI, Reg))
208 continue;
209
210 // Allow stack slot loads.
211 int FI;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000212 if (SnipLI.reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000213 continue;
214
215 // Allow stack slot stores.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000216 if (SnipLI.reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000217 continue;
218
219 // Allow a single additional instruction.
220 if (UseMI && MI != UseMI)
221 return false;
222 UseMI = MI;
223 }
224 return true;
225}
226
227/// collectRegsToSpill - Collect live range snippets that only have a single
228/// real use.
229void InlineSpiller::collectRegsToSpill() {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000230 unsigned Reg = Edit->getReg();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000231
232 // Main register always spills.
233 RegsToSpill.assign(1, Reg);
234 SnippetCopies.clear();
235
236 // Snippets all have the same original, so there can't be any for an original
237 // register.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000238 if (Original == Reg)
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000239 return;
240
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000241 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000242 MachineInstr *MI = RI.skipInstruction();) {
243 unsigned SnipReg = isFullCopyOf(MI, Reg);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000244 if (!isSibling(SnipReg))
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000245 continue;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000246 LiveInterval &SnipLI = LIS.getInterval(SnipReg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000247 if (!isSnippet(SnipLI))
248 continue;
249 SnippetCopies.insert(MI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000250 if (!isRegToSpill(SnipReg))
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000251 RegsToSpill.push_back(SnipReg);
252
253 DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n');
254 }
255}
256
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000257
258//===----------------------------------------------------------------------===//
259// Sibling Values
260//===----------------------------------------------------------------------===//
261
262// After live range splitting, some values to be spilled may be defined by
263// copies from sibling registers. We trace the sibling copies back to the
264// original value if it still exists. We need it for rematerialization.
265//
266// Even when the value can't be rematerialized, we still want to determine if
267// the value has already been spilled, or we may want to hoist the spill from a
268// loop.
269
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000270bool InlineSpiller::isSibling(unsigned Reg) {
271 return TargetRegisterInfo::isVirtualRegister(Reg) &&
272 VRM.getOriginal(Reg) == Original;
273}
274
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000275/// traceSiblingValue - Trace a value that is about to be spilled back to the
276/// real defining instructions by looking through sibling copies. Always stay
277/// within the range of OrigVNI so the registers are known to carry the same
278/// value.
279///
280/// Determine if the value is defined by all reloads, so spilling isn't
281/// necessary - the value is already in the stack slot.
282///
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000283/// Return a defining instruction that may be a candidate for rematerialization.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000284///
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000285MachineInstr *InlineSpiller::traceSiblingValue(unsigned UseReg, VNInfo *UseVNI,
286 VNInfo *OrigVNI) {
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000287 DEBUG(dbgs() << "Tracing value " << PrintReg(UseReg) << ':'
288 << UseVNI->id << '@' << UseVNI->def << '\n');
289 SmallPtrSet<VNInfo*, 8> Visited;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000290 SmallVector<std::pair<unsigned, VNInfo*>, 8> WorkList;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000291 WorkList.push_back(std::make_pair(UseReg, UseVNI));
292
293 // Best spill candidate seen so far. This must dominate UseVNI.
294 SibValueInfo SVI(UseReg, UseVNI);
295 MachineBasicBlock *UseMBB = LIS.getMBBFromIndex(UseVNI->def);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000296 unsigned SpillDepth = Loops.getLoopDepth(UseMBB);
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000297 bool SeenOrigPHI = false; // Original PHI met.
298
299 do {
300 unsigned Reg;
301 VNInfo *VNI;
302 tie(Reg, VNI) = WorkList.pop_back_val();
303 if (!Visited.insert(VNI))
304 continue;
305
306 // Is this value a better spill candidate?
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000307 if (!isRegToSpill(Reg)) {
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000308 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000309 if (MBB != UseMBB && MDT.dominates(MBB, UseMBB)) {
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000310 // This is a valid spill location dominating UseVNI.
311 // Prefer to spill at a smaller loop depth.
312 unsigned Depth = Loops.getLoopDepth(MBB);
313 if (Depth < SpillDepth) {
314 DEBUG(dbgs() << " spill depth " << Depth << ": " << PrintReg(Reg)
315 << ':' << VNI->id << '@' << VNI->def << '\n');
316 SVI.SpillReg = Reg;
317 SVI.SpillVNI = VNI;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000318 SpillDepth = Depth;
319 }
320 }
321 }
322
323 // Trace through PHI-defs created by live range splitting.
324 if (VNI->isPHIDef()) {
325 if (VNI->def == OrigVNI->def) {
326 DEBUG(dbgs() << " orig phi value " << PrintReg(Reg) << ':'
327 << VNI->id << '@' << VNI->def << '\n');
328 SeenOrigPHI = true;
329 continue;
330 }
331 // Get values live-out of predecessors.
332 LiveInterval &LI = LIS.getInterval(Reg);
333 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
334 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
335 PE = MBB->pred_end(); PI != PE; ++PI) {
336 VNInfo *PVNI = LI.getVNInfoAt(LIS.getMBBEndIdx(*PI).getPrevSlot());
337 if (PVNI)
338 WorkList.push_back(std::make_pair(Reg, PVNI));
339 }
340 continue;
341 }
342
343 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
344 assert(MI && "Missing def");
345
346 // Trace through sibling copies.
347 if (unsigned SrcReg = isFullCopyOf(MI, Reg)) {
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000348 if (isSibling(SrcReg)) {
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000349 LiveInterval &SrcLI = LIS.getInterval(SrcReg);
350 VNInfo *SrcVNI = SrcLI.getVNInfoAt(VNI->def.getUseIndex());
351 assert(SrcVNI && "Copy from non-existing value");
352 DEBUG(dbgs() << " copy of " << PrintReg(SrcReg) << ':'
353 << SrcVNI->id << '@' << SrcVNI->def << '\n');
354 WorkList.push_back(std::make_pair(SrcReg, SrcVNI));
355 continue;
356 }
357 }
358
359 // Track reachable reloads.
360 int FI;
361 if (Reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot) {
362 DEBUG(dbgs() << " reload " << PrintReg(Reg) << ':'
363 << VNI->id << "@" << VNI->def << '\n');
364 SVI.AllDefsAreReloads = true;
365 continue;
366 }
367
368 // We have an 'original' def. Don't record trivial cases.
369 if (VNI == UseVNI) {
370 DEBUG(dbgs() << "Not a sibling copy.\n");
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000371 return MI;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000372 }
373
374 // Potential remat candidate.
375 DEBUG(dbgs() << " def " << PrintReg(Reg) << ':'
376 << VNI->id << '@' << VNI->def << '\t' << *MI);
377 SVI.DefMI = MI;
378 } while (!WorkList.empty());
379
380 if (SeenOrigPHI || SVI.DefMI)
381 SVI.AllDefsAreReloads = false;
382
383 DEBUG({
384 if (SVI.AllDefsAreReloads)
385 dbgs() << "All defs are reloads.\n";
386 else
387 dbgs() << "Prefer to spill " << PrintReg(SVI.SpillReg) << ':'
388 << SVI.SpillVNI->id << '@' << SVI.SpillVNI->def << '\n';
389 });
390 SibValues.insert(std::make_pair(UseVNI, SVI));
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000391 return SVI.DefMI;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000392}
393
394/// analyzeSiblingValues - Trace values defined by sibling copies back to
395/// something that isn't a sibling copy.
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000396///
397/// Keep track of values that may be rematerializable.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000398void InlineSpiller::analyzeSiblingValues() {
399 SibValues.clear();
400
401 // No siblings at all?
402 if (Edit->getReg() == Original)
403 return;
404
405 LiveInterval &OrigLI = LIS.getInterval(Original);
406 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
407 unsigned Reg = RegsToSpill[i];
408 LiveInterval &LI = LIS.getInterval(Reg);
409 for (LiveInterval::const_vni_iterator VI = LI.vni_begin(),
410 VE = LI.vni_end(); VI != VE; ++VI) {
411 VNInfo *VNI = *VI;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000412 if (VNI->isUnused())
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000413 continue;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000414 MachineInstr *DefMI = 0;
415 // Check possible sibling copies.
416 if (VNI->isPHIDef() || VNI->getCopy()) {
417 VNInfo *OrigVNI = OrigLI.getVNInfoAt(VNI->def);
418 if (OrigVNI->def != VNI->def)
419 DefMI = traceSiblingValue(Reg, VNI, OrigVNI);
420 }
421 if (!DefMI && !VNI->isPHIDef())
422 DefMI = LIS.getInstructionFromIndex(VNI->def);
423 if (DefMI)
424 Edit->checkRematerializable(VNI, DefMI, TII, AA);
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000425 }
426 }
427}
428
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000429/// hoistSpill - Given a sibling copy that defines a value to be spilled, insert
430/// a spill at a better location.
431bool InlineSpiller::hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI) {
432 SlotIndex Idx = LIS.getInstructionIndex(CopyMI);
433 VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getDefIndex());
434 assert(VNI && VNI->def == Idx.getDefIndex() && "Not defined by copy");
435 SibValueMap::const_iterator I = SibValues.find(VNI);
436 if (I == SibValues.end())
437 return false;
438
439 const SibValueInfo &SVI = I->second;
440
441 // Let the normal folding code deal with the boring case.
442 if (!SVI.AllDefsAreReloads && SVI.SpillVNI == VNI)
443 return false;
444
445 // Conservatively extend the stack slot range to the range of the original
446 // value. We may be able to do better with stack slot coloring by being more
447 // careful here.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000448 assert(StackInt && "No stack slot assigned yet.");
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000449 LiveInterval &OrigLI = LIS.getInterval(Original);
450 VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000451 StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0));
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +0000452 DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000453 << *StackInt << '\n');
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000454
455 // Already spilled everywhere.
456 if (SVI.AllDefsAreReloads)
457 return true;
458
459 // We are going to spill SVI.SpillVNI immediately after its def, so clear out
460 // any later spills of the same value.
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000461 eliminateRedundantSpills(LIS.getInterval(SVI.SpillReg), SVI.SpillVNI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000462
463 MachineBasicBlock *MBB = LIS.getMBBFromIndex(SVI.SpillVNI->def);
464 MachineBasicBlock::iterator MII;
465 if (SVI.SpillVNI->isPHIDef())
466 MII = MBB->SkipPHIsAndLabels(MBB->begin());
467 else {
468 MII = LIS.getInstructionFromIndex(SVI.SpillVNI->def);
469 ++MII;
470 }
471 // Insert spill without kill flag immediately after def.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000472 TII.storeRegToStackSlot(*MBB, MII, SVI.SpillReg, false, StackSlot,
473 MRI.getRegClass(SVI.SpillReg), &TRI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000474 --MII; // Point to store instruction.
475 LIS.InsertMachineInstrInMaps(MII);
476 VRM.addSpillSlotUse(StackSlot, MII);
477 DEBUG(dbgs() << "\thoisted: " << SVI.SpillVNI->def << '\t' << *MII);
478 return true;
479}
480
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000481/// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any
482/// redundant spills of this value in SLI.reg and sibling copies.
483void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
Jakob Stoklund Olesen682eed02011-03-20 05:44:58 +0000484 assert(VNI && "Missing value");
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000485 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
486 WorkList.push_back(std::make_pair(&SLI, VNI));
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000487 assert(StackInt && "No stack slot assigned yet.");
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000488
489 do {
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000490 LiveInterval *LI;
491 tie(LI, VNI) = WorkList.pop_back_val();
492 unsigned Reg = LI->reg;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000493 DEBUG(dbgs() << "Checking redundant spills for " << PrintReg(Reg) << ':'
494 << VNI->id << '@' << VNI->def << '\n');
495
496 // Regs to spill are taken care of.
497 if (isRegToSpill(Reg))
498 continue;
499
500 // Add all of VNI's live range to StackInt.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000501 StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0));
502 DEBUG(dbgs() << "Merged to stack int: " << *StackInt << '\n');
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000503
504 // Find all spills and copies of VNI.
505 for (MachineRegisterInfo::use_nodbg_iterator UI = MRI.use_nodbg_begin(Reg);
506 MachineInstr *MI = UI.skipInstruction();) {
507 if (!MI->isCopy() && !MI->getDesc().mayStore())
508 continue;
509 SlotIndex Idx = LIS.getInstructionIndex(MI);
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000510 if (LI->getVNInfoAt(Idx) != VNI)
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000511 continue;
512
513 // Follow sibling copies down the dominator tree.
514 if (unsigned DstReg = isFullCopyOf(MI, Reg)) {
515 if (isSibling(DstReg)) {
516 LiveInterval &DstLI = LIS.getInterval(DstReg);
517 VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getDefIndex());
518 assert(DstVNI && "Missing defined value");
519 assert(DstVNI->def == Idx.getDefIndex() && "Wrong copy def slot");
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000520 WorkList.push_back(std::make_pair(&DstLI, DstVNI));
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000521 }
522 continue;
523 }
524
525 // Erase spills.
526 int FI;
527 if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) {
528 DEBUG(dbgs() << "Redundant spill " << Idx << '\t' << *MI);
529 // eliminateDeadDefs won't normally remove stores, so switch opcode.
530 MI->setDesc(TII.get(TargetOpcode::KILL));
531 DeadDefs.push_back(MI);
532 }
533 }
534 } while (!WorkList.empty());
535}
536
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +0000537
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000538//===----------------------------------------------------------------------===//
539// Rematerialization
540//===----------------------------------------------------------------------===//
541
542/// markValueUsed - Remember that VNI failed to rematerialize, so its defining
543/// instruction cannot be eliminated. See through snippet copies
544void InlineSpiller::markValueUsed(LiveInterval *LI, VNInfo *VNI) {
545 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
546 WorkList.push_back(std::make_pair(LI, VNI));
547 do {
548 tie(LI, VNI) = WorkList.pop_back_val();
549 if (!UsedValues.insert(VNI))
550 continue;
551
552 if (VNI->isPHIDef()) {
553 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
554 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
555 PE = MBB->pred_end(); PI != PE; ++PI) {
556 VNInfo *PVNI = LI->getVNInfoAt(LIS.getMBBEndIdx(*PI).getPrevSlot());
557 if (PVNI)
558 WorkList.push_back(std::make_pair(LI, PVNI));
559 }
560 continue;
561 }
562
563 // Follow snippet copies.
564 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
565 if (!SnippetCopies.count(MI))
566 continue;
567 LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg());
568 assert(isRegToSpill(SnipLI.reg) && "Unexpected register in copy");
569 VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getUseIndex());
570 assert(SnipVNI && "Snippet undefined before copy");
571 WorkList.push_back(std::make_pair(&SnipLI, SnipVNI));
572 } while (!WorkList.empty());
573}
574
575/// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
576bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg,
577 MachineBasicBlock::iterator MI) {
578 SlotIndex UseIdx = LIS.getInstructionIndex(MI).getUseIndex();
579 VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx);
580
581 if (!ParentVNI) {
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000582 DEBUG(dbgs() << "\tadding <undef> flags: ");
583 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
584 MachineOperand &MO = MI->getOperand(i);
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000585 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg)
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000586 MO.setIsUndef();
587 }
588 DEBUG(dbgs() << UseIdx << '\t' << *MI);
589 return true;
590 }
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +0000591
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000592 if (SnippetCopies.count(MI))
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000593 return false;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000594
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000595 // Use an OrigVNI from traceSiblingValue when ParentVNI is a sibling copy.
596 LiveRangeEdit::Remat RM(ParentVNI);
597 SibValueMap::const_iterator SibI = SibValues.find(ParentVNI);
598 if (SibI != SibValues.end())
599 RM.OrigMI = SibI->second.DefMI;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000600 if (!Edit->canRematerializeAt(RM, UseIdx, false, LIS)) {
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000601 markValueUsed(&VirtReg, ParentVNI);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000602 DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
603 return false;
604 }
605
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000606 // If the instruction also writes VirtReg.reg, it had better not require the
607 // same register for uses and defs.
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000608 bool Reads, Writes;
609 SmallVector<unsigned, 8> Ops;
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000610 tie(Reads, Writes) = MI->readsWritesVirtualRegister(VirtReg.reg, &Ops);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000611 if (Writes) {
612 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
613 MachineOperand &MO = MI->getOperand(Ops[i]);
614 if (MO.isUse() ? MI->isRegTiedToDefOperand(Ops[i]) : MO.getSubReg()) {
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000615 markValueUsed(&VirtReg, ParentVNI);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000616 DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
617 return false;
618 }
619 }
620 }
621
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000622 // Before rematerializing into a register for a single instruction, try to
623 // fold a load into the instruction. That avoids allocating a new register.
624 if (RM.OrigMI->getDesc().canFoldAsLoad() &&
625 foldMemoryOperand(MI, Ops, RM.OrigMI)) {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000626 Edit->markRematerialized(RM.ParentVNI);
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000627 return true;
628 }
629
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000630 // Alocate a new register for the remat.
Jakob Stoklund Olesen312babc2011-03-31 03:54:44 +0000631 LiveInterval &NewLI = Edit->createFrom(Original, LIS, VRM);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000632 NewLI.markNotSpillable();
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000633
634 // Finally we can rematerialize OrigMI before MI.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000635 SlotIndex DefIdx = Edit->rematerializeAt(*MI->getParent(), MI, NewLI.reg, RM,
636 LIS, TII, TRI);
Jakob Stoklund Olesen7b1f4982011-02-08 19:33:55 +0000637 DEBUG(dbgs() << "\tremat: " << DefIdx << '\t'
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000638 << *LIS.getInstructionFromIndex(DefIdx));
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000639
640 // Replace operands
641 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
642 MachineOperand &MO = MI->getOperand(Ops[i]);
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000643 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg) {
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000644 MO.setReg(NewLI.reg);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000645 MO.setIsKill();
646 }
647 }
648 DEBUG(dbgs() << "\t " << UseIdx << '\t' << *MI);
649
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000650 VNInfo *DefVNI = NewLI.getNextValue(DefIdx, 0, LIS.getVNInfoAllocator());
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000651 NewLI.addRange(LiveRange(DefIdx, UseIdx.getDefIndex(), DefVNI));
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000652 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000653 return true;
654}
655
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000656/// reMaterializeAll - Try to rematerialize as many uses as possible,
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000657/// and trim the live ranges after.
658void InlineSpiller::reMaterializeAll() {
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000659 // analyzeSiblingValues has already tested all relevant defining instructions.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000660 if (!Edit->anyRematerializable(LIS, TII, AA))
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000661 return;
662
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000663 UsedValues.clear();
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +0000664
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000665 // Try to remat before all uses of snippets.
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000666 bool anyRemat = false;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000667 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
668 unsigned Reg = RegsToSpill[i];
669 LiveInterval &LI = LIS.getInterval(Reg);
670 for (MachineRegisterInfo::use_nodbg_iterator
671 RI = MRI.use_nodbg_begin(Reg);
672 MachineInstr *MI = RI.skipInstruction();)
673 anyRemat |= reMaterializeFor(LI, MI);
674 }
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000675 if (!anyRemat)
676 return;
677
678 // Remove any values that were completely rematted.
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000679 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
680 unsigned Reg = RegsToSpill[i];
681 LiveInterval &LI = LIS.getInterval(Reg);
682 for (LiveInterval::vni_iterator I = LI.vni_begin(), E = LI.vni_end();
683 I != E; ++I) {
684 VNInfo *VNI = *I;
Jakob Stoklund Olesenc1d22d82011-03-29 17:47:00 +0000685 if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI))
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +0000686 continue;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000687 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
688 MI->addRegisterDead(Reg, &TRI);
689 if (!MI->allDefsAreDead())
690 continue;
691 DEBUG(dbgs() << "All defs dead: " << *MI);
692 DeadDefs.push_back(MI);
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +0000693 }
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000694 }
Jakob Stoklund Olesenc1d22d82011-03-29 17:47:00 +0000695
696 // Eliminate dead code after remat. Note that some snippet copies may be
697 // deleted here.
698 if (DeadDefs.empty())
699 return;
700 DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n");
701 Edit->eliminateDeadDefs(DeadDefs, LIS, VRM, TII);
702
703 // Get rid of deleted and empty intervals.
704 for (unsigned i = RegsToSpill.size(); i != 0; --i) {
705 unsigned Reg = RegsToSpill[i-1];
706 if (!LIS.hasInterval(Reg)) {
707 RegsToSpill.erase(RegsToSpill.begin() + (i - 1));
708 continue;
709 }
710 LiveInterval &LI = LIS.getInterval(Reg);
711 if (!LI.empty())
712 continue;
713 Edit->eraseVirtReg(Reg, LIS);
714 RegsToSpill.erase(RegsToSpill.begin() + (i - 1));
715 }
716 DEBUG(dbgs() << RegsToSpill.size() << " registers to spill after remat.\n");
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000717}
718
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +0000719
720//===----------------------------------------------------------------------===//
721// Spilling
722//===----------------------------------------------------------------------===//
723
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000724/// If MI is a load or store of StackSlot, it can be removed.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000725bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, unsigned Reg) {
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000726 int FI = 0;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000727 unsigned InstrReg;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000728 if (!(InstrReg = TII.isLoadFromStackSlot(MI, FI)) &&
729 !(InstrReg = TII.isStoreToStackSlot(MI, FI)))
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000730 return false;
731
732 // We have a stack access. Is it the right register and slot?
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000733 if (InstrReg != Reg || FI != StackSlot)
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000734 return false;
735
736 DEBUG(dbgs() << "Coalescing stack access: " << *MI);
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000737 LIS.RemoveMachineInstrFromMaps(MI);
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000738 MI->eraseFromParent();
739 return true;
740}
741
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000742/// foldMemoryOperand - Try folding stack slot references in Ops into MI.
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000743/// @param MI Instruction using or defining the current register.
Jakob Stoklund Olesen39048252010-12-18 03:28:32 +0000744/// @param Ops Operand indices from readsWritesVirtualRegister().
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000745/// @param LoadMI Load instruction to use instead of stack slot when non-null.
746/// @return True on success, and MI will be erased.
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000747bool InlineSpiller::foldMemoryOperand(MachineBasicBlock::iterator MI,
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000748 const SmallVectorImpl<unsigned> &Ops,
749 MachineInstr *LoadMI) {
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000750 // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
751 // operands.
752 SmallVector<unsigned, 8> FoldOps;
753 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
754 unsigned Idx = Ops[i];
755 MachineOperand &MO = MI->getOperand(Idx);
756 if (MO.isImplicit())
757 continue;
758 // FIXME: Teach targets to deal with subregs.
759 if (MO.getSubReg())
760 return false;
Jakob Stoklund Olesen7b1f4982011-02-08 19:33:55 +0000761 // We cannot fold a load instruction into a def.
762 if (LoadMI && MO.isDef())
763 return false;
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000764 // Tied use operands should not be passed to foldMemoryOperand.
765 if (!MI->isRegTiedToDefOperand(Idx))
766 FoldOps.push_back(Idx);
767 }
768
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000769 MachineInstr *FoldMI =
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000770 LoadMI ? TII.foldMemoryOperand(MI, FoldOps, LoadMI)
771 : TII.foldMemoryOperand(MI, FoldOps, StackSlot);
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000772 if (!FoldMI)
773 return false;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000774 LIS.ReplaceMachineInstrInMaps(MI, FoldMI);
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000775 if (!LoadMI)
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000776 VRM.addSpillSlotUse(StackSlot, FoldMI);
Jakob Stoklund Olesene05442d2010-07-09 17:29:08 +0000777 MI->eraseFromParent();
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000778 DEBUG(dbgs() << "\tfolded: " << *FoldMI);
779 return true;
780}
781
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000782/// insertReload - Insert a reload of NewLI.reg before MI.
783void InlineSpiller::insertReload(LiveInterval &NewLI,
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +0000784 SlotIndex Idx,
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000785 MachineBasicBlock::iterator MI) {
786 MachineBasicBlock &MBB = *MI->getParent();
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000787 TII.loadRegFromStackSlot(MBB, MI, NewLI.reg, StackSlot,
788 MRI.getRegClass(NewLI.reg), &TRI);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000789 --MI; // Point to load instruction.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000790 SlotIndex LoadIdx = LIS.InsertMachineInstrInMaps(MI).getDefIndex();
791 VRM.addSpillSlotUse(StackSlot, MI);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000792 DEBUG(dbgs() << "\treload: " << LoadIdx << '\t' << *MI);
Lang Hames6e2968c2010-09-25 12:04:16 +0000793 VNInfo *LoadVNI = NewLI.getNextValue(LoadIdx, 0,
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000794 LIS.getVNInfoAllocator());
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000795 NewLI.addRange(LiveRange(LoadIdx, Idx, LoadVNI));
796}
797
798/// insertSpill - Insert a spill of NewLI.reg after MI.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000799void InlineSpiller::insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +0000800 SlotIndex Idx, MachineBasicBlock::iterator MI) {
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000801 MachineBasicBlock &MBB = *MI->getParent();
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000802 TII.storeRegToStackSlot(MBB, ++MI, NewLI.reg, true, StackSlot,
803 MRI.getRegClass(NewLI.reg), &TRI);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000804 --MI; // Point to store instruction.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000805 SlotIndex StoreIdx = LIS.InsertMachineInstrInMaps(MI).getDefIndex();
806 VRM.addSpillSlotUse(StackSlot, MI);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000807 DEBUG(dbgs() << "\tspilled: " << StoreIdx << '\t' << *MI);
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000808 VNInfo *StoreVNI = NewLI.getNextValue(Idx, 0, LIS.getVNInfoAllocator());
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000809 NewLI.addRange(LiveRange(Idx, StoreIdx, StoreVNI));
810}
811
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000812/// spillAroundUses - insert spill code around each use of Reg.
813void InlineSpiller::spillAroundUses(unsigned Reg) {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000814 LiveInterval &OldLI = LIS.getInterval(Reg);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000815
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000816 // Iterate over instructions using Reg.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000817 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000818 MachineInstr *MI = RI.skipInstruction();) {
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000819
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +0000820 // Debug values are not allowed to affect codegen.
821 if (MI->isDebugValue()) {
822 // Modify DBG_VALUE now that the value is in a spill slot.
823 uint64_t Offset = MI->getOperand(1).getImm();
824 const MDNode *MDPtr = MI->getOperand(2).getMetadata();
825 DebugLoc DL = MI->getDebugLoc();
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000826 if (MachineInstr *NewDV = TII.emitFrameIndexDebugValue(MF, StackSlot,
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +0000827 Offset, MDPtr, DL)) {
828 DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
829 MachineBasicBlock *MBB = MI->getParent();
830 MBB->insert(MBB->erase(MI), NewDV);
831 } else {
832 DEBUG(dbgs() << "Removing debug info due to spill:" << "\t" << *MI);
833 MI->eraseFromParent();
834 }
835 continue;
836 }
837
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000838 // Ignore copies to/from snippets. We'll delete them.
839 if (SnippetCopies.count(MI))
840 continue;
841
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000842 // Stack slot accesses may coalesce away.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000843 if (coalesceStackAccess(MI, Reg))
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000844 continue;
845
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000846 // Analyze instruction.
847 bool Reads, Writes;
848 SmallVector<unsigned, 8> Ops;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000849 tie(Reads, Writes) = MI->readsWritesVirtualRegister(Reg, &Ops);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000850
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +0000851 // Find the slot index where this instruction reads and writes OldLI.
852 // This is usually the def slot, except for tied early clobbers.
853 SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex();
854 if (VNInfo *VNI = OldLI.getVNInfoAt(Idx.getUseIndex()))
855 if (SlotIndex::isSameInstr(Idx, VNI->def))
856 Idx = VNI->def;
857
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000858 // Check for a sibling copy.
859 unsigned SibReg = isFullCopyOf(MI, Reg);
Jakob Stoklund Olesen682eed02011-03-20 05:44:58 +0000860 if (SibReg && isSibling(SibReg)) {
861 if (Writes) {
862 // Hoist the spill of a sib-reg copy.
863 if (hoistSpill(OldLI, MI)) {
864 // This COPY is now dead, the value is already in the stack slot.
865 MI->getOperand(0).setIsDead();
866 DeadDefs.push_back(MI);
867 continue;
868 }
869 } else {
870 // This is a reload for a sib-reg copy. Drop spills downstream.
Jakob Stoklund Olesen682eed02011-03-20 05:44:58 +0000871 LiveInterval &SibLI = LIS.getInterval(SibReg);
872 eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx));
873 // The COPY will fold to a reload below.
874 }
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000875 }
876
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000877 // Attempt to fold memory ops.
878 if (foldMemoryOperand(MI, Ops))
879 continue;
880
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000881 // Allocate interval around instruction.
882 // FIXME: Infer regclass from instruction alone.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000883 LiveInterval &NewLI = Edit->createFrom(Reg, LIS, VRM);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000884 NewLI.markNotSpillable();
885
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000886 if (Reads)
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +0000887 insertReload(NewLI, Idx, MI);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000888
889 // Rewrite instruction operands.
890 bool hasLiveDef = false;
891 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
892 MachineOperand &MO = MI->getOperand(Ops[i]);
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000893 MO.setReg(NewLI.reg);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000894 if (MO.isUse()) {
895 if (!MI->isRegTiedToDefOperand(Ops[i]))
896 MO.setIsKill();
897 } else {
898 if (!MO.isDead())
899 hasLiveDef = true;
900 }
901 }
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +0000902 DEBUG(dbgs() << "\trewrite: " << Idx << '\t' << *MI);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000903
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000904 // FIXME: Use a second vreg if instruction has no tied ops.
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000905 if (Writes && hasLiveDef)
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +0000906 insertSpill(NewLI, OldLI, Idx, MI);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000907
908 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000909 }
910}
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000911
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +0000912/// spillAll - Spill all registers remaining after rematerialization.
913void InlineSpiller::spillAll() {
914 // Update LiveStacks now that we are committed to spilling.
915 if (StackSlot == VirtRegMap::NO_STACK_SLOT) {
916 StackSlot = VRM.assignVirt2StackSlot(Original);
917 StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original));
918 StackInt->getNextValue(SlotIndex(), 0, LSS.getVNInfoAllocator());
919 } else
920 StackInt = &LSS.getInterval(StackSlot);
921
922 if (Original != Edit->getReg())
923 VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot);
924
925 assert(StackInt->getNumValNums() == 1 && "Bad stack interval values");
926 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
927 StackInt->MergeRangesInAsValue(LIS.getInterval(RegsToSpill[i]),
928 StackInt->getValNumInfo(0));
929 DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n');
930
931 // Spill around uses of all RegsToSpill.
932 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
933 spillAroundUses(RegsToSpill[i]);
934
935 // Hoisted spills may cause dead code.
936 if (!DeadDefs.empty()) {
937 DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n");
938 Edit->eliminateDeadDefs(DeadDefs, LIS, VRM, TII);
939 }
940
941 // Finally delete the SnippetCopies.
942 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Edit->getReg());
943 MachineInstr *MI = RI.skipInstruction();) {
944 assert(SnippetCopies.count(MI) && "Remaining use wasn't a snippet copy");
945 // FIXME: Do this with a LiveRangeEdit callback.
946 VRM.RemoveMachineInstrFromMaps(MI);
947 LIS.RemoveMachineInstrFromMaps(MI);
948 MI->eraseFromParent();
949 }
950
951 // Delete all spilled registers.
952 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
953 Edit->eraseVirtReg(RegsToSpill[i], LIS);
954}
955
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000956void InlineSpiller::spill(LiveRangeEdit &edit) {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000957 Edit = &edit;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000958 assert(!TargetRegisterInfo::isStackSlot(edit.getReg())
959 && "Trying to spill a stack slot.");
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000960 // Share a stack slot among all descendants of Original.
961 Original = VRM.getOriginal(edit.getReg());
962 StackSlot = VRM.getStackSlot(Original);
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000963 StackInt = 0;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000964
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000965 DEBUG(dbgs() << "Inline spilling "
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000966 << MRI.getRegClass(edit.getReg())->getName()
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000967 << ':' << edit.getParent() << "\nFrom original "
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000968 << LIS.getInterval(Original) << '\n');
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000969 assert(edit.getParent().isSpillable() &&
970 "Attempting to spill already spilled value.");
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000971 assert(DeadDefs.empty() && "Previous spill didn't remove dead defs");
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000972
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000973 collectRegsToSpill();
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000974 analyzeSiblingValues();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000975 reMaterializeAll();
976
977 // Remat may handle everything.
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +0000978 if (!RegsToSpill.empty())
979 spillAll();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000980
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +0000981 Edit->calculateRegClassAndHint(MF, LIS, Loops);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000982}