blob: 397943bf3c4b5a37a0108f29e0b02cef52b9215b [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 Olesen9e55afb2010-06-30 23:03:52 +0000137 void insertReload(LiveInterval &NewLI, MachineBasicBlock::iterator MI);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000138 void insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
139 MachineBasicBlock::iterator MI);
140
141 void spillAroundUses(unsigned Reg);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000142};
143}
144
145namespace llvm {
Jakob Stoklund Olesenf2c6e362010-07-20 23:50:15 +0000146Spiller *createInlineSpiller(MachineFunctionPass &pass,
147 MachineFunction &mf,
148 VirtRegMap &vrm) {
149 return new InlineSpiller(pass, mf, vrm);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000150}
151}
152
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000153//===----------------------------------------------------------------------===//
154// Snippets
155//===----------------------------------------------------------------------===//
156
157// When spilling a virtual register, we also spill any snippets it is connected
158// to. The snippets are small live ranges that only have a single real use,
159// leftovers from live range splitting. Spilling them enables memory operand
160// folding or tightens the live range around the single use.
161//
162// This minimizes register pressure and maximizes the store-to-load distance for
163// spill slots which can be important in tight loops.
164
165/// isFullCopyOf - If MI is a COPY to or from Reg, return the other register,
166/// otherwise return 0.
167static unsigned isFullCopyOf(const MachineInstr *MI, unsigned Reg) {
168 if (!MI->isCopy())
169 return 0;
170 if (MI->getOperand(0).getSubReg() != 0)
171 return 0;
172 if (MI->getOperand(1).getSubReg() != 0)
173 return 0;
174 if (MI->getOperand(0).getReg() == Reg)
175 return MI->getOperand(1).getReg();
176 if (MI->getOperand(1).getReg() == Reg)
177 return MI->getOperand(0).getReg();
178 return 0;
179}
180
181/// isSnippet - Identify if a live interval is a snippet that should be spilled.
182/// It is assumed that SnipLI is a virtual register with the same original as
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000183/// Edit->getReg().
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000184bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000185 unsigned Reg = Edit->getReg();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000186
187 // A snippet is a tiny live range with only a single instruction using it
188 // besides copies to/from Reg or spills/fills. We accept:
189 //
190 // %snip = COPY %Reg / FILL fi#
191 // %snip = USE %snip
192 // %Reg = COPY %snip / SPILL %snip, fi#
193 //
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000194 if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI))
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000195 return false;
196
197 MachineInstr *UseMI = 0;
198
199 // Check that all uses satisfy our criteria.
200 for (MachineRegisterInfo::reg_nodbg_iterator
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000201 RI = MRI.reg_nodbg_begin(SnipLI.reg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000202 MachineInstr *MI = RI.skipInstruction();) {
203
204 // Allow copies to/from Reg.
205 if (isFullCopyOf(MI, Reg))
206 continue;
207
208 // Allow stack slot loads.
209 int FI;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000210 if (SnipLI.reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000211 continue;
212
213 // Allow stack slot stores.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000214 if (SnipLI.reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000215 continue;
216
217 // Allow a single additional instruction.
218 if (UseMI && MI != UseMI)
219 return false;
220 UseMI = MI;
221 }
222 return true;
223}
224
225/// collectRegsToSpill - Collect live range snippets that only have a single
226/// real use.
227void InlineSpiller::collectRegsToSpill() {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000228 unsigned Reg = Edit->getReg();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000229
230 // Main register always spills.
231 RegsToSpill.assign(1, Reg);
232 SnippetCopies.clear();
233
234 // Snippets all have the same original, so there can't be any for an original
235 // register.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000236 if (Original == Reg)
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000237 return;
238
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000239 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000240 MachineInstr *MI = RI.skipInstruction();) {
241 unsigned SnipReg = isFullCopyOf(MI, Reg);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000242 if (!isSibling(SnipReg))
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000243 continue;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000244 LiveInterval &SnipLI = LIS.getInterval(SnipReg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000245 if (!isSnippet(SnipLI))
246 continue;
247 SnippetCopies.insert(MI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000248 if (!isRegToSpill(SnipReg))
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000249 RegsToSpill.push_back(SnipReg);
250
251 DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n');
252 }
253}
254
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000255
256//===----------------------------------------------------------------------===//
257// Sibling Values
258//===----------------------------------------------------------------------===//
259
260// After live range splitting, some values to be spilled may be defined by
261// copies from sibling registers. We trace the sibling copies back to the
262// original value if it still exists. We need it for rematerialization.
263//
264// Even when the value can't be rematerialized, we still want to determine if
265// the value has already been spilled, or we may want to hoist the spill from a
266// loop.
267
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000268bool InlineSpiller::isSibling(unsigned Reg) {
269 return TargetRegisterInfo::isVirtualRegister(Reg) &&
270 VRM.getOriginal(Reg) == Original;
271}
272
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000273/// traceSiblingValue - Trace a value that is about to be spilled back to the
274/// real defining instructions by looking through sibling copies. Always stay
275/// within the range of OrigVNI so the registers are known to carry the same
276/// value.
277///
278/// Determine if the value is defined by all reloads, so spilling isn't
279/// necessary - the value is already in the stack slot.
280///
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000281/// Return a defining instruction that may be a candidate for rematerialization.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000282///
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000283MachineInstr *InlineSpiller::traceSiblingValue(unsigned UseReg, VNInfo *UseVNI,
284 VNInfo *OrigVNI) {
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000285 DEBUG(dbgs() << "Tracing value " << PrintReg(UseReg) << ':'
286 << UseVNI->id << '@' << UseVNI->def << '\n');
287 SmallPtrSet<VNInfo*, 8> Visited;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000288 SmallVector<std::pair<unsigned, VNInfo*>, 8> WorkList;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000289 WorkList.push_back(std::make_pair(UseReg, UseVNI));
290
291 // Best spill candidate seen so far. This must dominate UseVNI.
292 SibValueInfo SVI(UseReg, UseVNI);
293 MachineBasicBlock *UseMBB = LIS.getMBBFromIndex(UseVNI->def);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000294 unsigned SpillDepth = Loops.getLoopDepth(UseMBB);
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000295 bool SeenOrigPHI = false; // Original PHI met.
296
297 do {
298 unsigned Reg;
299 VNInfo *VNI;
300 tie(Reg, VNI) = WorkList.pop_back_val();
301 if (!Visited.insert(VNI))
302 continue;
303
304 // Is this value a better spill candidate?
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000305 if (!isRegToSpill(Reg)) {
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000306 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000307 if (MBB != UseMBB && MDT.dominates(MBB, UseMBB)) {
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000308 // This is a valid spill location dominating UseVNI.
309 // Prefer to spill at a smaller loop depth.
310 unsigned Depth = Loops.getLoopDepth(MBB);
311 if (Depth < SpillDepth) {
312 DEBUG(dbgs() << " spill depth " << Depth << ": " << PrintReg(Reg)
313 << ':' << VNI->id << '@' << VNI->def << '\n');
314 SVI.SpillReg = Reg;
315 SVI.SpillVNI = VNI;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000316 SpillDepth = Depth;
317 }
318 }
319 }
320
321 // Trace through PHI-defs created by live range splitting.
322 if (VNI->isPHIDef()) {
323 if (VNI->def == OrigVNI->def) {
324 DEBUG(dbgs() << " orig phi value " << PrintReg(Reg) << ':'
325 << VNI->id << '@' << VNI->def << '\n');
326 SeenOrigPHI = true;
327 continue;
328 }
329 // Get values live-out of predecessors.
330 LiveInterval &LI = LIS.getInterval(Reg);
331 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
332 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
333 PE = MBB->pred_end(); PI != PE; ++PI) {
334 VNInfo *PVNI = LI.getVNInfoAt(LIS.getMBBEndIdx(*PI).getPrevSlot());
335 if (PVNI)
336 WorkList.push_back(std::make_pair(Reg, PVNI));
337 }
338 continue;
339 }
340
341 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
342 assert(MI && "Missing def");
343
344 // Trace through sibling copies.
345 if (unsigned SrcReg = isFullCopyOf(MI, Reg)) {
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000346 if (isSibling(SrcReg)) {
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000347 LiveInterval &SrcLI = LIS.getInterval(SrcReg);
348 VNInfo *SrcVNI = SrcLI.getVNInfoAt(VNI->def.getUseIndex());
349 assert(SrcVNI && "Copy from non-existing value");
350 DEBUG(dbgs() << " copy of " << PrintReg(SrcReg) << ':'
351 << SrcVNI->id << '@' << SrcVNI->def << '\n');
352 WorkList.push_back(std::make_pair(SrcReg, SrcVNI));
353 continue;
354 }
355 }
356
357 // Track reachable reloads.
358 int FI;
359 if (Reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot) {
360 DEBUG(dbgs() << " reload " << PrintReg(Reg) << ':'
361 << VNI->id << "@" << VNI->def << '\n');
362 SVI.AllDefsAreReloads = true;
363 continue;
364 }
365
366 // We have an 'original' def. Don't record trivial cases.
367 if (VNI == UseVNI) {
368 DEBUG(dbgs() << "Not a sibling copy.\n");
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000369 return MI;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000370 }
371
372 // Potential remat candidate.
373 DEBUG(dbgs() << " def " << PrintReg(Reg) << ':'
374 << VNI->id << '@' << VNI->def << '\t' << *MI);
375 SVI.DefMI = MI;
376 } while (!WorkList.empty());
377
378 if (SeenOrigPHI || SVI.DefMI)
379 SVI.AllDefsAreReloads = false;
380
381 DEBUG({
382 if (SVI.AllDefsAreReloads)
383 dbgs() << "All defs are reloads.\n";
384 else
385 dbgs() << "Prefer to spill " << PrintReg(SVI.SpillReg) << ':'
386 << SVI.SpillVNI->id << '@' << SVI.SpillVNI->def << '\n';
387 });
388 SibValues.insert(std::make_pair(UseVNI, SVI));
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000389 return SVI.DefMI;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000390}
391
392/// analyzeSiblingValues - Trace values defined by sibling copies back to
393/// something that isn't a sibling copy.
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000394///
395/// Keep track of values that may be rematerializable.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000396void InlineSpiller::analyzeSiblingValues() {
397 SibValues.clear();
398
399 // No siblings at all?
400 if (Edit->getReg() == Original)
401 return;
402
403 LiveInterval &OrigLI = LIS.getInterval(Original);
404 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
405 unsigned Reg = RegsToSpill[i];
406 LiveInterval &LI = LIS.getInterval(Reg);
407 for (LiveInterval::const_vni_iterator VI = LI.vni_begin(),
408 VE = LI.vni_end(); VI != VE; ++VI) {
409 VNInfo *VNI = *VI;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000410 if (VNI->isUnused())
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000411 continue;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000412 MachineInstr *DefMI = 0;
413 // Check possible sibling copies.
414 if (VNI->isPHIDef() || VNI->getCopy()) {
415 VNInfo *OrigVNI = OrigLI.getVNInfoAt(VNI->def);
416 if (OrigVNI->def != VNI->def)
417 DefMI = traceSiblingValue(Reg, VNI, OrigVNI);
418 }
419 if (!DefMI && !VNI->isPHIDef())
420 DefMI = LIS.getInstructionFromIndex(VNI->def);
421 if (DefMI)
422 Edit->checkRematerializable(VNI, DefMI, TII, AA);
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000423 }
424 }
425}
426
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000427/// hoistSpill - Given a sibling copy that defines a value to be spilled, insert
428/// a spill at a better location.
429bool InlineSpiller::hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI) {
430 SlotIndex Idx = LIS.getInstructionIndex(CopyMI);
431 VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getDefIndex());
432 assert(VNI && VNI->def == Idx.getDefIndex() && "Not defined by copy");
433 SibValueMap::const_iterator I = SibValues.find(VNI);
434 if (I == SibValues.end())
435 return false;
436
437 const SibValueInfo &SVI = I->second;
438
439 // Let the normal folding code deal with the boring case.
440 if (!SVI.AllDefsAreReloads && SVI.SpillVNI == VNI)
441 return false;
442
443 // Conservatively extend the stack slot range to the range of the original
444 // value. We may be able to do better with stack slot coloring by being more
445 // careful here.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000446 assert(StackInt && "No stack slot assigned yet.");
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000447 LiveInterval &OrigLI = LIS.getInterval(Original);
448 VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000449 StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0));
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +0000450 DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000451 << *StackInt << '\n');
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000452
453 // Already spilled everywhere.
454 if (SVI.AllDefsAreReloads)
455 return true;
456
457 // We are going to spill SVI.SpillVNI immediately after its def, so clear out
458 // any later spills of the same value.
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000459 eliminateRedundantSpills(LIS.getInterval(SVI.SpillReg), SVI.SpillVNI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000460
461 MachineBasicBlock *MBB = LIS.getMBBFromIndex(SVI.SpillVNI->def);
462 MachineBasicBlock::iterator MII;
463 if (SVI.SpillVNI->isPHIDef())
464 MII = MBB->SkipPHIsAndLabels(MBB->begin());
465 else {
466 MII = LIS.getInstructionFromIndex(SVI.SpillVNI->def);
467 ++MII;
468 }
469 // Insert spill without kill flag immediately after def.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000470 TII.storeRegToStackSlot(*MBB, MII, SVI.SpillReg, false, StackSlot,
471 MRI.getRegClass(SVI.SpillReg), &TRI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000472 --MII; // Point to store instruction.
473 LIS.InsertMachineInstrInMaps(MII);
474 VRM.addSpillSlotUse(StackSlot, MII);
475 DEBUG(dbgs() << "\thoisted: " << SVI.SpillVNI->def << '\t' << *MII);
476 return true;
477}
478
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000479/// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any
480/// redundant spills of this value in SLI.reg and sibling copies.
481void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
Jakob Stoklund Olesen682eed02011-03-20 05:44:58 +0000482 assert(VNI && "Missing value");
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000483 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
484 WorkList.push_back(std::make_pair(&SLI, VNI));
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000485 assert(StackInt && "No stack slot assigned yet.");
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000486
487 do {
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000488 LiveInterval *LI;
489 tie(LI, VNI) = WorkList.pop_back_val();
490 unsigned Reg = LI->reg;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000491 DEBUG(dbgs() << "Checking redundant spills for " << PrintReg(Reg) << ':'
492 << VNI->id << '@' << VNI->def << '\n');
493
494 // Regs to spill are taken care of.
495 if (isRegToSpill(Reg))
496 continue;
497
498 // Add all of VNI's live range to StackInt.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000499 StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0));
500 DEBUG(dbgs() << "Merged to stack int: " << *StackInt << '\n');
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000501
502 // Find all spills and copies of VNI.
503 for (MachineRegisterInfo::use_nodbg_iterator UI = MRI.use_nodbg_begin(Reg);
504 MachineInstr *MI = UI.skipInstruction();) {
505 if (!MI->isCopy() && !MI->getDesc().mayStore())
506 continue;
507 SlotIndex Idx = LIS.getInstructionIndex(MI);
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000508 if (LI->getVNInfoAt(Idx) != VNI)
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000509 continue;
510
511 // Follow sibling copies down the dominator tree.
512 if (unsigned DstReg = isFullCopyOf(MI, Reg)) {
513 if (isSibling(DstReg)) {
514 LiveInterval &DstLI = LIS.getInterval(DstReg);
515 VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getDefIndex());
516 assert(DstVNI && "Missing defined value");
517 assert(DstVNI->def == Idx.getDefIndex() && "Wrong copy def slot");
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000518 WorkList.push_back(std::make_pair(&DstLI, DstVNI));
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000519 }
520 continue;
521 }
522
523 // Erase spills.
524 int FI;
525 if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) {
526 DEBUG(dbgs() << "Redundant spill " << Idx << '\t' << *MI);
527 // eliminateDeadDefs won't normally remove stores, so switch opcode.
528 MI->setDesc(TII.get(TargetOpcode::KILL));
529 DeadDefs.push_back(MI);
530 }
531 }
532 } while (!WorkList.empty());
533}
534
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +0000535
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000536//===----------------------------------------------------------------------===//
537// Rematerialization
538//===----------------------------------------------------------------------===//
539
540/// markValueUsed - Remember that VNI failed to rematerialize, so its defining
541/// instruction cannot be eliminated. See through snippet copies
542void InlineSpiller::markValueUsed(LiveInterval *LI, VNInfo *VNI) {
543 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
544 WorkList.push_back(std::make_pair(LI, VNI));
545 do {
546 tie(LI, VNI) = WorkList.pop_back_val();
547 if (!UsedValues.insert(VNI))
548 continue;
549
550 if (VNI->isPHIDef()) {
551 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
552 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
553 PE = MBB->pred_end(); PI != PE; ++PI) {
554 VNInfo *PVNI = LI->getVNInfoAt(LIS.getMBBEndIdx(*PI).getPrevSlot());
555 if (PVNI)
556 WorkList.push_back(std::make_pair(LI, PVNI));
557 }
558 continue;
559 }
560
561 // Follow snippet copies.
562 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
563 if (!SnippetCopies.count(MI))
564 continue;
565 LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg());
566 assert(isRegToSpill(SnipLI.reg) && "Unexpected register in copy");
567 VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getUseIndex());
568 assert(SnipVNI && "Snippet undefined before copy");
569 WorkList.push_back(std::make_pair(&SnipLI, SnipVNI));
570 } while (!WorkList.empty());
571}
572
573/// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
574bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg,
575 MachineBasicBlock::iterator MI) {
576 SlotIndex UseIdx = LIS.getInstructionIndex(MI).getUseIndex();
577 VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx);
578
579 if (!ParentVNI) {
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000580 DEBUG(dbgs() << "\tadding <undef> flags: ");
581 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
582 MachineOperand &MO = MI->getOperand(i);
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000583 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg)
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000584 MO.setIsUndef();
585 }
586 DEBUG(dbgs() << UseIdx << '\t' << *MI);
587 return true;
588 }
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +0000589
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000590 if (SnippetCopies.count(MI))
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000591 return false;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000592
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000593 // Use an OrigVNI from traceSiblingValue when ParentVNI is a sibling copy.
594 LiveRangeEdit::Remat RM(ParentVNI);
595 SibValueMap::const_iterator SibI = SibValues.find(ParentVNI);
596 if (SibI != SibValues.end())
597 RM.OrigMI = SibI->second.DefMI;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000598 if (!Edit->canRematerializeAt(RM, UseIdx, false, LIS)) {
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000599 markValueUsed(&VirtReg, ParentVNI);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000600 DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
601 return false;
602 }
603
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000604 // If the instruction also writes VirtReg.reg, it had better not require the
605 // same register for uses and defs.
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000606 bool Reads, Writes;
607 SmallVector<unsigned, 8> Ops;
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000608 tie(Reads, Writes) = MI->readsWritesVirtualRegister(VirtReg.reg, &Ops);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000609 if (Writes) {
610 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
611 MachineOperand &MO = MI->getOperand(Ops[i]);
612 if (MO.isUse() ? MI->isRegTiedToDefOperand(Ops[i]) : MO.getSubReg()) {
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000613 markValueUsed(&VirtReg, ParentVNI);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000614 DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
615 return false;
616 }
617 }
618 }
619
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000620 // Before rematerializing into a register for a single instruction, try to
621 // fold a load into the instruction. That avoids allocating a new register.
622 if (RM.OrigMI->getDesc().canFoldAsLoad() &&
623 foldMemoryOperand(MI, Ops, RM.OrigMI)) {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000624 Edit->markRematerialized(RM.ParentVNI);
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000625 return true;
626 }
627
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000628 // Alocate a new register for the remat.
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000629 LiveInterval &NewLI = Edit->createFrom(VirtReg.reg, LIS, VRM);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000630 NewLI.markNotSpillable();
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000631
Jakob Stoklund Olesenc3dca3f2011-02-09 00:25:36 +0000632 // Rematting for a copy: Set allocation hint to be the destination register.
633 if (MI->isCopy())
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000634 MRI.setRegAllocationHint(NewLI.reg, 0, MI->getOperand(0).getReg());
Jakob Stoklund Olesenc3dca3f2011-02-09 00:25:36 +0000635
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000636 // Finally we can rematerialize OrigMI before MI.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000637 SlotIndex DefIdx = Edit->rematerializeAt(*MI->getParent(), MI, NewLI.reg, RM,
638 LIS, TII, TRI);
Jakob Stoklund Olesen7b1f4982011-02-08 19:33:55 +0000639 DEBUG(dbgs() << "\tremat: " << DefIdx << '\t'
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000640 << *LIS.getInstructionFromIndex(DefIdx));
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000641
642 // Replace operands
643 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
644 MachineOperand &MO = MI->getOperand(Ops[i]);
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000645 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg) {
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000646 MO.setReg(NewLI.reg);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000647 MO.setIsKill();
648 }
649 }
650 DEBUG(dbgs() << "\t " << UseIdx << '\t' << *MI);
651
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000652 VNInfo *DefVNI = NewLI.getNextValue(DefIdx, 0, LIS.getVNInfoAllocator());
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000653 NewLI.addRange(LiveRange(DefIdx, UseIdx.getDefIndex(), DefVNI));
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000654 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000655 return true;
656}
657
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000658/// reMaterializeAll - Try to rematerialize as many uses as possible,
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000659/// and trim the live ranges after.
660void InlineSpiller::reMaterializeAll() {
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000661 // analyzeSiblingValues has already tested all relevant defining instructions.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000662 if (!Edit->anyRematerializable(LIS, TII, AA))
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000663 return;
664
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000665 UsedValues.clear();
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +0000666
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000667 // Try to remat before all uses of snippets.
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000668 bool anyRemat = false;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000669 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
670 unsigned Reg = RegsToSpill[i];
671 LiveInterval &LI = LIS.getInterval(Reg);
672 for (MachineRegisterInfo::use_nodbg_iterator
673 RI = MRI.use_nodbg_begin(Reg);
674 MachineInstr *MI = RI.skipInstruction();)
675 anyRemat |= reMaterializeFor(LI, MI);
676 }
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000677 if (!anyRemat)
678 return;
679
680 // Remove any values that were completely rematted.
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000681 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
682 unsigned Reg = RegsToSpill[i];
683 LiveInterval &LI = LIS.getInterval(Reg);
684 for (LiveInterval::vni_iterator I = LI.vni_begin(), E = LI.vni_end();
685 I != E; ++I) {
686 VNInfo *VNI = *I;
Jakob Stoklund Olesenc1d22d82011-03-29 17:47:00 +0000687 if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI))
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +0000688 continue;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000689 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
690 MI->addRegisterDead(Reg, &TRI);
691 if (!MI->allDefsAreDead())
692 continue;
693 DEBUG(dbgs() << "All defs dead: " << *MI);
694 DeadDefs.push_back(MI);
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +0000695 }
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000696 }
Jakob Stoklund Olesenc1d22d82011-03-29 17:47:00 +0000697
698 // Eliminate dead code after remat. Note that some snippet copies may be
699 // deleted here.
700 if (DeadDefs.empty())
701 return;
702 DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n");
703 Edit->eliminateDeadDefs(DeadDefs, LIS, VRM, TII);
704
705 // Get rid of deleted and empty intervals.
706 for (unsigned i = RegsToSpill.size(); i != 0; --i) {
707 unsigned Reg = RegsToSpill[i-1];
708 if (!LIS.hasInterval(Reg)) {
709 RegsToSpill.erase(RegsToSpill.begin() + (i - 1));
710 continue;
711 }
712 LiveInterval &LI = LIS.getInterval(Reg);
713 if (!LI.empty())
714 continue;
715 Edit->eraseVirtReg(Reg, LIS);
716 RegsToSpill.erase(RegsToSpill.begin() + (i - 1));
717 }
718 DEBUG(dbgs() << RegsToSpill.size() << " registers to spill after remat.\n");
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000719}
720
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000721/// If MI is a load or store of StackSlot, it can be removed.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000722bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, unsigned Reg) {
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000723 int FI = 0;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000724 unsigned InstrReg;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000725 if (!(InstrReg = TII.isLoadFromStackSlot(MI, FI)) &&
726 !(InstrReg = TII.isStoreToStackSlot(MI, FI)))
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000727 return false;
728
729 // We have a stack access. Is it the right register and slot?
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000730 if (InstrReg != Reg || FI != StackSlot)
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000731 return false;
732
733 DEBUG(dbgs() << "Coalescing stack access: " << *MI);
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000734 LIS.RemoveMachineInstrFromMaps(MI);
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000735 MI->eraseFromParent();
736 return true;
737}
738
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000739/// foldMemoryOperand - Try folding stack slot references in Ops into MI.
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000740/// @param MI Instruction using or defining the current register.
Jakob Stoklund Olesen39048252010-12-18 03:28:32 +0000741/// @param Ops Operand indices from readsWritesVirtualRegister().
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000742/// @param LoadMI Load instruction to use instead of stack slot when non-null.
743/// @return True on success, and MI will be erased.
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000744bool InlineSpiller::foldMemoryOperand(MachineBasicBlock::iterator MI,
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000745 const SmallVectorImpl<unsigned> &Ops,
746 MachineInstr *LoadMI) {
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000747 // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
748 // operands.
749 SmallVector<unsigned, 8> FoldOps;
750 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
751 unsigned Idx = Ops[i];
752 MachineOperand &MO = MI->getOperand(Idx);
753 if (MO.isImplicit())
754 continue;
755 // FIXME: Teach targets to deal with subregs.
756 if (MO.getSubReg())
757 return false;
Jakob Stoklund Olesen7b1f4982011-02-08 19:33:55 +0000758 // We cannot fold a load instruction into a def.
759 if (LoadMI && MO.isDef())
760 return false;
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000761 // Tied use operands should not be passed to foldMemoryOperand.
762 if (!MI->isRegTiedToDefOperand(Idx))
763 FoldOps.push_back(Idx);
764 }
765
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000766 MachineInstr *FoldMI =
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000767 LoadMI ? TII.foldMemoryOperand(MI, FoldOps, LoadMI)
768 : TII.foldMemoryOperand(MI, FoldOps, StackSlot);
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000769 if (!FoldMI)
770 return false;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000771 LIS.ReplaceMachineInstrInMaps(MI, FoldMI);
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000772 if (!LoadMI)
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000773 VRM.addSpillSlotUse(StackSlot, FoldMI);
Jakob Stoklund Olesene05442d2010-07-09 17:29:08 +0000774 MI->eraseFromParent();
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +0000775 DEBUG(dbgs() << "\tfolded: " << *FoldMI);
776 return true;
777}
778
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000779/// insertReload - Insert a reload of NewLI.reg before MI.
780void InlineSpiller::insertReload(LiveInterval &NewLI,
781 MachineBasicBlock::iterator MI) {
782 MachineBasicBlock &MBB = *MI->getParent();
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000783 SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex();
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000784 TII.loadRegFromStackSlot(MBB, MI, NewLI.reg, StackSlot,
785 MRI.getRegClass(NewLI.reg), &TRI);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000786 --MI; // Point to load instruction.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000787 SlotIndex LoadIdx = LIS.InsertMachineInstrInMaps(MI).getDefIndex();
788 VRM.addSpillSlotUse(StackSlot, MI);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000789 DEBUG(dbgs() << "\treload: " << LoadIdx << '\t' << *MI);
Lang Hames6e2968c2010-09-25 12:04:16 +0000790 VNInfo *LoadVNI = NewLI.getNextValue(LoadIdx, 0,
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000791 LIS.getVNInfoAllocator());
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000792 NewLI.addRange(LiveRange(LoadIdx, Idx, LoadVNI));
793}
794
795/// insertSpill - Insert a spill of NewLI.reg after MI.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000796void InlineSpiller::insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000797 MachineBasicBlock::iterator MI) {
798 MachineBasicBlock &MBB = *MI->getParent();
Jakob Stoklund Olesen68257e62010-11-15 20:55:49 +0000799
800 // Get the defined value. It could be an early clobber so keep the def index.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000801 SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000802 VNInfo *VNI = OldLI.getVNInfoAt(Idx);
Jakob Stoklund Olesen68257e62010-11-15 20:55:49 +0000803 assert(VNI && VNI->def.getDefIndex() == Idx && "Inconsistent VNInfo");
804 Idx = VNI->def;
805
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000806 TII.storeRegToStackSlot(MBB, ++MI, NewLI.reg, true, StackSlot,
807 MRI.getRegClass(NewLI.reg), &TRI);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000808 --MI; // Point to store instruction.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000809 SlotIndex StoreIdx = LIS.InsertMachineInstrInMaps(MI).getDefIndex();
810 VRM.addSpillSlotUse(StackSlot, MI);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000811 DEBUG(dbgs() << "\tspilled: " << StoreIdx << '\t' << *MI);
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000812 VNInfo *StoreVNI = NewLI.getNextValue(Idx, 0, LIS.getVNInfoAllocator());
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000813 NewLI.addRange(LiveRange(Idx, StoreIdx, StoreVNI));
814}
815
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000816/// spillAroundUses - insert spill code around each use of Reg.
817void InlineSpiller::spillAroundUses(unsigned Reg) {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000818 LiveInterval &OldLI = LIS.getInterval(Reg);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000819
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000820 // Iterate over instructions using Reg.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000821 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000822 MachineInstr *MI = RI.skipInstruction();) {
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000823
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +0000824 // Debug values are not allowed to affect codegen.
825 if (MI->isDebugValue()) {
826 // Modify DBG_VALUE now that the value is in a spill slot.
827 uint64_t Offset = MI->getOperand(1).getImm();
828 const MDNode *MDPtr = MI->getOperand(2).getMetadata();
829 DebugLoc DL = MI->getDebugLoc();
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000830 if (MachineInstr *NewDV = TII.emitFrameIndexDebugValue(MF, StackSlot,
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +0000831 Offset, MDPtr, DL)) {
832 DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
833 MachineBasicBlock *MBB = MI->getParent();
834 MBB->insert(MBB->erase(MI), NewDV);
835 } else {
836 DEBUG(dbgs() << "Removing debug info due to spill:" << "\t" << *MI);
837 MI->eraseFromParent();
838 }
839 continue;
840 }
841
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000842 // Ignore copies to/from snippets. We'll delete them.
843 if (SnippetCopies.count(MI))
844 continue;
845
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000846 // Stack slot accesses may coalesce away.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000847 if (coalesceStackAccess(MI, Reg))
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000848 continue;
849
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000850 // Analyze instruction.
851 bool Reads, Writes;
852 SmallVector<unsigned, 8> Ops;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000853 tie(Reads, Writes) = MI->readsWritesVirtualRegister(Reg, &Ops);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000854
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000855 // Check for a sibling copy.
856 unsigned SibReg = isFullCopyOf(MI, Reg);
Jakob Stoklund Olesen682eed02011-03-20 05:44:58 +0000857 if (SibReg && isSibling(SibReg)) {
858 if (Writes) {
859 // Hoist the spill of a sib-reg copy.
860 if (hoistSpill(OldLI, MI)) {
861 // This COPY is now dead, the value is already in the stack slot.
862 MI->getOperand(0).setIsDead();
863 DeadDefs.push_back(MI);
864 continue;
865 }
866 } else {
867 // This is a reload for a sib-reg copy. Drop spills downstream.
868 SlotIndex Idx = LIS.getInstructionIndex(MI).getDefIndex();
869 LiveInterval &SibLI = LIS.getInterval(SibReg);
870 eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx));
871 // The COPY will fold to a reload below.
872 }
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000873 }
874
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000875 // Attempt to fold memory ops.
876 if (foldMemoryOperand(MI, Ops))
877 continue;
878
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000879 // Allocate interval around instruction.
880 // FIXME: Infer regclass from instruction alone.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000881 LiveInterval &NewLI = Edit->createFrom(Reg, LIS, VRM);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000882 NewLI.markNotSpillable();
883
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000884 if (Reads)
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000885 insertReload(NewLI, MI);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000886
887 // Rewrite instruction operands.
888 bool hasLiveDef = false;
889 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
890 MachineOperand &MO = MI->getOperand(Ops[i]);
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000891 MO.setReg(NewLI.reg);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000892 if (MO.isUse()) {
893 if (!MI->isRegTiedToDefOperand(Ops[i]))
894 MO.setIsKill();
895 } else {
896 if (!MO.isDead())
897 hasLiveDef = true;
898 }
899 }
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000900
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000901 // FIXME: Use a second vreg if instruction has no tied ops.
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000902 if (Writes && hasLiveDef)
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000903 insertSpill(NewLI, OldLI, MI);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000904
905 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000906 }
907}
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000908
909void InlineSpiller::spill(LiveRangeEdit &edit) {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000910 Edit = &edit;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000911 assert(!TargetRegisterInfo::isStackSlot(edit.getReg())
912 && "Trying to spill a stack slot.");
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000913 // Share a stack slot among all descendants of Original.
914 Original = VRM.getOriginal(edit.getReg());
915 StackSlot = VRM.getStackSlot(Original);
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000916 StackInt = 0;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000917
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000918 DEBUG(dbgs() << "Inline spilling "
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000919 << MRI.getRegClass(edit.getReg())->getName()
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000920 << ':' << edit.getParent() << "\nFrom original "
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000921 << LIS.getInterval(Original) << '\n');
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000922 assert(edit.getParent().isSpillable() &&
923 "Attempting to spill already spilled value.");
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000924 assert(DeadDefs.empty() && "Previous spill didn't remove dead defs");
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000925
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000926 collectRegsToSpill();
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000927 analyzeSiblingValues();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000928 reMaterializeAll();
929
930 // Remat may handle everything.
Jakob Stoklund Olesenc1d22d82011-03-29 17:47:00 +0000931 if (RegsToSpill.empty())
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000932 return;
933
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000934 // Update LiveStacks now that we are committed to spilling.
935 if (StackSlot == VirtRegMap::NO_STACK_SLOT) {
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000936 StackSlot = VRM.assignVirt2StackSlot(Original);
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000937 StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original));
938 StackInt->getNextValue(SlotIndex(), 0, LSS.getVNInfoAllocator());
939 } else
940 StackInt = &LSS.getInterval(StackSlot);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000941
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000942 if (Original != edit.getReg())
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000943 VRM.assignVirt2StackSlot(edit.getReg(), StackSlot);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000944
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000945 assert(StackInt->getNumValNums() == 1 && "Bad stack interval values");
Jakob Stoklund Olesenb1adbd12011-03-12 04:25:36 +0000946 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000947 StackInt->MergeRangesInAsValue(LIS.getInterval(RegsToSpill[i]),
948 StackInt->getValNumInfo(0));
949 DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n');
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000950
951 // Spill around uses of all RegsToSpill.
952 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
953 spillAroundUses(RegsToSpill[i]);
954
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000955 // Hoisted spills may cause dead code.
956 if (!DeadDefs.empty()) {
957 DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n");
958 Edit->eliminateDeadDefs(DeadDefs, LIS, VRM, TII);
959 }
960
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000961 // Finally delete the SnippetCopies.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000962 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(edit.getReg());
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000963 MachineInstr *MI = RI.skipInstruction();) {
964 assert(SnippetCopies.count(MI) && "Remaining use wasn't a snippet copy");
965 // FIXME: Do this with a LiveRangeEdit callback.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000966 VRM.RemoveMachineInstrFromMaps(MI);
967 LIS.RemoveMachineInstrFromMaps(MI);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000968 MI->eraseFromParent();
969 }
970
Jakob Stoklund Olesen7792e982011-03-13 01:23:11 +0000971 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000972 edit.eraseVirtReg(RegsToSpill[i], LIS);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000973}