blob: c6d1a18dbd066091405e483b4e4932b5a6efa573 [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 Olesene9bd4ea2011-05-05 17:22:53 +000017#include "llvm/ADT/Statistic.h"
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +000018#include "llvm/ADT/TinyPtrVector.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"
Pete Cooper789d5d82012-04-02 22:44:18 +000021#include "llvm/CodeGen/LiveRangeEdit.h"
Jakob Stoklund Olesen0a12b802010-10-26 00:11:35 +000022#include "llvm/CodeGen/LiveStackAnalysis.h"
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000023#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000024#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineFunction.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000026#include "llvm/CodeGen/MachineInstrBundle.h"
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000027#include "llvm/CodeGen/MachineLoopInfo.h"
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000028#include "llvm/CodeGen/MachineRegisterInfo.h"
Jakob Stoklund Olesen1ead68d2012-11-28 19:13:06 +000029#include "llvm/CodeGen/VirtRegMap.h"
Jakob Stoklund Olesenb9edad02011-09-15 21:06:00 +000030#include "llvm/Support/CommandLine.h"
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000031#include "llvm/Support/Debug.h"
32#include "llvm/Support/raw_ostream.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000033#include "llvm/Target/TargetInstrInfo.h"
34#include "llvm/Target/TargetMachine.h"
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000035
36using namespace llvm;
37
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +000038STATISTIC(NumSpilledRanges, "Number of spilled live ranges");
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +000039STATISTIC(NumSnippets, "Number of spilled snippets");
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +000040STATISTIC(NumSpills, "Number of spills inserted");
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +000041STATISTIC(NumSpillsRemoved, "Number of spills removed");
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +000042STATISTIC(NumReloads, "Number of reloads inserted");
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +000043STATISTIC(NumReloadsRemoved, "Number of reloads removed");
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +000044STATISTIC(NumFolded, "Number of folded stack accesses");
45STATISTIC(NumFoldedLoads, "Number of folded loads");
46STATISTIC(NumRemats, "Number of rematerialized defs for spilling");
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +000047STATISTIC(NumOmitReloadSpill, "Number of omitted spills of reloads");
48STATISTIC(NumHoists, "Number of hoisted spills");
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +000049
Jakob Stoklund Olesenb9edad02011-09-15 21:06:00 +000050static cl::opt<bool> DisableHoisting("disable-spill-hoist", cl::Hidden,
51 cl::desc("Disable inline spill hoisting"));
52
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000053namespace {
54class InlineSpiller : public Spiller {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000055 MachineFunction &MF;
56 LiveIntervals &LIS;
57 LiveStacks &LSS;
58 AliasAnalysis *AA;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000059 MachineDominatorTree &MDT;
60 MachineLoopInfo &Loops;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000061 VirtRegMap &VRM;
62 MachineFrameInfo &MFI;
63 MachineRegisterInfo &MRI;
64 const TargetInstrInfo &TII;
65 const TargetRegisterInfo &TRI;
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +000066
67 // Variables that are valid during spill(), but used by multiple methods.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000068 LiveRangeEdit *Edit;
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +000069 LiveInterval *StackInt;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000070 int StackSlot;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000071 unsigned Original;
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +000072
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000073 // All registers to spill to StackSlot, including the main register.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +000074 SmallVector<unsigned, 8> RegsToSpill;
75
76 // All COPY instructions to/from snippets.
77 // They are ignored since both operands refer to the same stack slot.
78 SmallPtrSet<MachineInstr*, 8> SnippetCopies;
79
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +000080 // Values that failed to remat at some point.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +000081 SmallPtrSet<VNInfo*, 8> UsedValues;
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +000082
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +000083public:
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000084 // Information about a value that was defined by a copy from a sibling
85 // register.
86 struct SibValueInfo {
87 // True when all reaching defs were reloads: No spill is necessary.
88 bool AllDefsAreReloads;
89
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +000090 // True when value is defined by an original PHI not from splitting.
91 bool DefByOrigPHI;
92
Jakob Stoklund Olesen69cf1ca2011-09-16 00:03:33 +000093 // True when the COPY defining this value killed its source.
94 bool KillsSource;
95
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +000096 // The preferred register to spill.
97 unsigned SpillReg;
98
99 // The value of SpillReg that should be spilled.
100 VNInfo *SpillVNI;
101
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000102 // The block where SpillVNI should be spilled. Currently, this must be the
103 // block containing SpillVNI->def.
104 MachineBasicBlock *SpillMBB;
105
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000106 // A defining instruction that is not a sibling copy or a reload, or NULL.
107 // This can be used as a template for rematerialization.
108 MachineInstr *DefMI;
109
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000110 // List of values that depend on this one. These values are actually the
111 // same, but live range splitting has placed them in different registers,
112 // or SSA update needed to insert PHI-defs to preserve SSA form. This is
113 // copies of the current value and phi-kills. Usually only phi-kills cause
114 // more than one dependent value.
115 TinyPtrVector<VNInfo*> Deps;
116
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000117 SibValueInfo(unsigned Reg, VNInfo *VNI)
Jakob Stoklund Olesen69cf1ca2011-09-16 00:03:33 +0000118 : AllDefsAreReloads(true), DefByOrigPHI(false), KillsSource(false),
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000119 SpillReg(Reg), SpillVNI(VNI), SpillMBB(0), DefMI(0) {}
120
121 // Returns true when a def has been found.
122 bool hasDef() const { return DefByOrigPHI || DefMI; }
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000123 };
124
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000125private:
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000126 // Values in RegsToSpill defined by sibling copies.
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000127 typedef DenseMap<VNInfo*, SibValueInfo> SibValueMap;
128 SibValueMap SibValues;
129
130 // Dead defs generated during spilling.
131 SmallVector<MachineInstr*, 8> DeadDefs;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000132
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000133 ~InlineSpiller() {}
134
135public:
Jakob Stoklund Olesenf2c6e362010-07-20 23:50:15 +0000136 InlineSpiller(MachineFunctionPass &pass,
137 MachineFunction &mf,
138 VirtRegMap &vrm)
Benjamin Kramer95a9d932012-06-06 19:47:08 +0000139 : MF(mf),
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000140 LIS(pass.getAnalysis<LiveIntervals>()),
141 LSS(pass.getAnalysis<LiveStacks>()),
142 AA(&pass.getAnalysis<AliasAnalysis>()),
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000143 MDT(pass.getAnalysis<MachineDominatorTree>()),
144 Loops(pass.getAnalysis<MachineLoopInfo>()),
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000145 VRM(vrm),
146 MFI(*mf.getFrameInfo()),
147 MRI(mf.getRegInfo()),
148 TII(*mf.getTarget().getInstrInfo()),
149 TRI(*mf.getTarget().getRegisterInfo()) {}
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000150
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000151 void spill(LiveRangeEdit &);
152
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000153private:
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000154 bool isSnippet(const LiveInterval &SnipLI);
155 void collectRegsToSpill();
156
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000157 bool isRegToSpill(unsigned Reg) {
158 return std::find(RegsToSpill.begin(),
159 RegsToSpill.end(), Reg) != RegsToSpill.end();
160 }
161
162 bool isSibling(unsigned Reg);
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000163 MachineInstr *traceSiblingValue(unsigned, VNInfo*, VNInfo*);
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000164 void propagateSiblingValue(SibValueMap::iterator, VNInfo *VNI = 0);
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000165 void analyzeSiblingValues();
166
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000167 bool hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI);
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000168 void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000169
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000170 void markValueUsed(LiveInterval*, VNInfo*);
171 bool reMaterializeFor(LiveInterval&, MachineBasicBlock::iterator MI);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000172 void reMaterializeAll();
173
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000174 bool coalesceStackAccess(MachineInstr *MI, unsigned Reg);
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +0000175 bool foldMemoryOperand(ArrayRef<std::pair<MachineInstr*, unsigned> >,
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000176 MachineInstr *LoadMI = 0);
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +0000177 void insertReload(LiveInterval &NewLI, SlotIndex,
178 MachineBasicBlock::iterator MI);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000179 void insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +0000180 SlotIndex, MachineBasicBlock::iterator MI);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000181
182 void spillAroundUses(unsigned Reg);
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +0000183 void spillAll();
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000184};
185}
186
187namespace llvm {
Jakob Stoklund Olesenf2c6e362010-07-20 23:50:15 +0000188Spiller *createInlineSpiller(MachineFunctionPass &pass,
189 MachineFunction &mf,
190 VirtRegMap &vrm) {
191 return new InlineSpiller(pass, mf, vrm);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +0000192}
193}
194
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000195//===----------------------------------------------------------------------===//
196// Snippets
197//===----------------------------------------------------------------------===//
198
199// When spilling a virtual register, we also spill any snippets it is connected
200// to. The snippets are small live ranges that only have a single real use,
201// leftovers from live range splitting. Spilling them enables memory operand
202// folding or tightens the live range around the single use.
203//
204// This minimizes register pressure and maximizes the store-to-load distance for
205// spill slots which can be important in tight loops.
206
207/// isFullCopyOf - If MI is a COPY to or from Reg, return the other register,
208/// otherwise return 0.
209static unsigned isFullCopyOf(const MachineInstr *MI, unsigned Reg) {
Rafael Espindolacfe52542011-06-30 21:15:52 +0000210 if (!MI->isFullCopy())
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000211 return 0;
212 if (MI->getOperand(0).getReg() == Reg)
213 return MI->getOperand(1).getReg();
214 if (MI->getOperand(1).getReg() == Reg)
215 return MI->getOperand(0).getReg();
216 return 0;
217}
218
219/// isSnippet - Identify if a live interval is a snippet that should be spilled.
220/// It is assumed that SnipLI is a virtual register with the same original as
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000221/// Edit->getReg().
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000222bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000223 unsigned Reg = Edit->getReg();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000224
225 // A snippet is a tiny live range with only a single instruction using it
226 // besides copies to/from Reg or spills/fills. We accept:
227 //
228 // %snip = COPY %Reg / FILL fi#
229 // %snip = USE %snip
230 // %Reg = COPY %snip / SPILL %snip, fi#
231 //
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000232 if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI))
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000233 return false;
234
235 MachineInstr *UseMI = 0;
236
237 // Check that all uses satisfy our criteria.
238 for (MachineRegisterInfo::reg_nodbg_iterator
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000239 RI = MRI.reg_nodbg_begin(SnipLI.reg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000240 MachineInstr *MI = RI.skipInstruction();) {
241
242 // Allow copies to/from Reg.
243 if (isFullCopyOf(MI, Reg))
244 continue;
245
246 // Allow stack slot loads.
247 int FI;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000248 if (SnipLI.reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000249 continue;
250
251 // Allow stack slot stores.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000252 if (SnipLI.reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000253 continue;
254
255 // Allow a single additional instruction.
256 if (UseMI && MI != UseMI)
257 return false;
258 UseMI = MI;
259 }
260 return true;
261}
262
263/// collectRegsToSpill - Collect live range snippets that only have a single
264/// real use.
265void InlineSpiller::collectRegsToSpill() {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000266 unsigned Reg = Edit->getReg();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000267
268 // Main register always spills.
269 RegsToSpill.assign(1, Reg);
270 SnippetCopies.clear();
271
272 // Snippets all have the same original, so there can't be any for an original
273 // register.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000274 if (Original == Reg)
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000275 return;
276
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000277 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000278 MachineInstr *MI = RI.skipInstruction();) {
279 unsigned SnipReg = isFullCopyOf(MI, Reg);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000280 if (!isSibling(SnipReg))
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000281 continue;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000282 LiveInterval &SnipLI = LIS.getInterval(SnipReg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000283 if (!isSnippet(SnipLI))
284 continue;
285 SnippetCopies.insert(MI);
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000286 if (isRegToSpill(SnipReg))
287 continue;
288 RegsToSpill.push_back(SnipReg);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000289 DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n');
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000290 ++NumSnippets;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000291 }
292}
293
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000294
295//===----------------------------------------------------------------------===//
296// Sibling Values
297//===----------------------------------------------------------------------===//
298
299// After live range splitting, some values to be spilled may be defined by
300// copies from sibling registers. We trace the sibling copies back to the
301// original value if it still exists. We need it for rematerialization.
302//
303// Even when the value can't be rematerialized, we still want to determine if
304// the value has already been spilled, or we may want to hoist the spill from a
305// loop.
306
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000307bool InlineSpiller::isSibling(unsigned Reg) {
308 return TargetRegisterInfo::isVirtualRegister(Reg) &&
309 VRM.getOriginal(Reg) == Original;
310}
311
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000312#ifndef NDEBUG
313static raw_ostream &operator<<(raw_ostream &OS,
314 const InlineSpiller::SibValueInfo &SVI) {
315 OS << "spill " << PrintReg(SVI.SpillReg) << ':'
316 << SVI.SpillVNI->id << '@' << SVI.SpillVNI->def;
317 if (SVI.SpillMBB)
318 OS << " in BB#" << SVI.SpillMBB->getNumber();
319 if (SVI.AllDefsAreReloads)
320 OS << " all-reloads";
321 if (SVI.DefByOrigPHI)
322 OS << " orig-phi";
Jakob Stoklund Olesen69cf1ca2011-09-16 00:03:33 +0000323 if (SVI.KillsSource)
324 OS << " kill";
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000325 OS << " deps[";
326 for (unsigned i = 0, e = SVI.Deps.size(); i != e; ++i)
327 OS << ' ' << SVI.Deps[i]->id << '@' << SVI.Deps[i]->def;
328 OS << " ]";
329 if (SVI.DefMI)
330 OS << " def: " << *SVI.DefMI;
331 else
332 OS << '\n';
333 return OS;
334}
335#endif
336
337/// propagateSiblingValue - Propagate the value in SVI to dependents if it is
338/// known. Otherwise remember the dependency for later.
339///
340/// @param SVI SibValues entry to propagate.
341/// @param VNI Dependent value, or NULL to propagate to all saved dependents.
342void InlineSpiller::propagateSiblingValue(SibValueMap::iterator SVI,
343 VNInfo *VNI) {
344 // When VNI is non-NULL, add it to SVI's deps, and only propagate to that.
345 TinyPtrVector<VNInfo*> FirstDeps;
346 if (VNI) {
347 FirstDeps.push_back(VNI);
348 SVI->second.Deps.push_back(VNI);
349 }
350
351 // Has the value been completely determined yet? If not, defer propagation.
352 if (!SVI->second.hasDef())
353 return;
354
355 // Work list of values to propagate. It would be nice to use a SetVector
356 // here, but then we would be forced to use a SmallSet.
357 SmallVector<SibValueMap::iterator, 8> WorkList(1, SVI);
358 SmallPtrSet<VNInfo*, 8> WorkSet;
359
360 do {
361 SVI = WorkList.pop_back_val();
362 WorkSet.erase(SVI->first);
363 TinyPtrVector<VNInfo*> *Deps = VNI ? &FirstDeps : &SVI->second.Deps;
364 VNI = 0;
365
366 SibValueInfo &SV = SVI->second;
367 if (!SV.SpillMBB)
368 SV.SpillMBB = LIS.getMBBFromIndex(SV.SpillVNI->def);
369
370 DEBUG(dbgs() << " prop to " << Deps->size() << ": "
371 << SVI->first->id << '@' << SVI->first->def << ":\t" << SV);
372
373 assert(SV.hasDef() && "Propagating undefined value");
374
375 // Should this value be propagated as a preferred spill candidate? We don't
376 // propagate values of registers that are about to spill.
Jakob Stoklund Olesenb9edad02011-09-15 21:06:00 +0000377 bool PropSpill = !DisableHoisting && !isRegToSpill(SV.SpillReg);
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000378 unsigned SpillDepth = ~0u;
379
380 for (TinyPtrVector<VNInfo*>::iterator DepI = Deps->begin(),
381 DepE = Deps->end(); DepI != DepE; ++DepI) {
382 SibValueMap::iterator DepSVI = SibValues.find(*DepI);
383 assert(DepSVI != SibValues.end() && "Dependent value not in SibValues");
384 SibValueInfo &DepSV = DepSVI->second;
385 if (!DepSV.SpillMBB)
386 DepSV.SpillMBB = LIS.getMBBFromIndex(DepSV.SpillVNI->def);
387
388 bool Changed = false;
389
390 // Propagate defining instruction.
391 if (!DepSV.hasDef()) {
392 Changed = true;
393 DepSV.DefMI = SV.DefMI;
394 DepSV.DefByOrigPHI = SV.DefByOrigPHI;
395 }
396
397 // Propagate AllDefsAreReloads. For PHI values, this computes an AND of
398 // all predecessors.
399 if (!SV.AllDefsAreReloads && DepSV.AllDefsAreReloads) {
400 Changed = true;
401 DepSV.AllDefsAreReloads = false;
402 }
403
404 // Propagate best spill value.
405 if (PropSpill && SV.SpillVNI != DepSV.SpillVNI) {
406 if (SV.SpillMBB == DepSV.SpillMBB) {
407 // DepSV is in the same block. Hoist when dominated.
Jakob Stoklund Olesen69cf1ca2011-09-16 00:03:33 +0000408 if (DepSV.KillsSource && SV.SpillVNI->def < DepSV.SpillVNI->def) {
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000409 // This is an alternative def earlier in the same MBB.
410 // Hoist the spill as far as possible in SpillMBB. This can ease
411 // register pressure:
412 //
413 // x = def
414 // y = use x
415 // s = copy x
416 //
417 // Hoisting the spill of s to immediately after the def removes the
418 // interference between x and y:
419 //
420 // x = def
421 // spill x
422 // y = use x<kill>
423 //
Jakob Stoklund Olesen69cf1ca2011-09-16 00:03:33 +0000424 // This hoist only helps when the DepSV copy kills its source.
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000425 Changed = true;
426 DepSV.SpillReg = SV.SpillReg;
427 DepSV.SpillVNI = SV.SpillVNI;
428 DepSV.SpillMBB = SV.SpillMBB;
429 }
430 } else {
431 // DepSV is in a different block.
432 if (SpillDepth == ~0u)
433 SpillDepth = Loops.getLoopDepth(SV.SpillMBB);
434
435 // Also hoist spills to blocks with smaller loop depth, but make sure
436 // that the new value dominates. Non-phi dependents are always
437 // dominated, phis need checking.
438 if ((Loops.getLoopDepth(DepSV.SpillMBB) > SpillDepth) &&
439 (!DepSVI->first->isPHIDef() ||
440 MDT.dominates(SV.SpillMBB, DepSV.SpillMBB))) {
441 Changed = true;
442 DepSV.SpillReg = SV.SpillReg;
443 DepSV.SpillVNI = SV.SpillVNI;
444 DepSV.SpillMBB = SV.SpillMBB;
445 }
446 }
447 }
448
449 if (!Changed)
450 continue;
451
452 // Something changed in DepSVI. Propagate to dependents.
453 if (WorkSet.insert(DepSVI->first))
454 WorkList.push_back(DepSVI);
455
456 DEBUG(dbgs() << " update " << DepSVI->first->id << '@'
457 << DepSVI->first->def << " to:\t" << DepSV);
458 }
459 } while (!WorkList.empty());
460}
461
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000462/// traceSiblingValue - Trace a value that is about to be spilled back to the
463/// real defining instructions by looking through sibling copies. Always stay
464/// within the range of OrigVNI so the registers are known to carry the same
465/// value.
466///
467/// Determine if the value is defined by all reloads, so spilling isn't
468/// necessary - the value is already in the stack slot.
469///
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000470/// Return a defining instruction that may be a candidate for rematerialization.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000471///
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000472MachineInstr *InlineSpiller::traceSiblingValue(unsigned UseReg, VNInfo *UseVNI,
473 VNInfo *OrigVNI) {
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000474 // Check if a cached value already exists.
475 SibValueMap::iterator SVI;
476 bool Inserted;
477 tie(SVI, Inserted) =
478 SibValues.insert(std::make_pair(UseVNI, SibValueInfo(UseReg, UseVNI)));
479 if (!Inserted) {
480 DEBUG(dbgs() << "Cached value " << PrintReg(UseReg) << ':'
481 << UseVNI->id << '@' << UseVNI->def << ' ' << SVI->second);
482 return SVI->second.DefMI;
483 }
484
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000485 DEBUG(dbgs() << "Tracing value " << PrintReg(UseReg) << ':'
486 << UseVNI->id << '@' << UseVNI->def << '\n');
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000487
488 // List of (Reg, VNI) that have been inserted into SibValues, but need to be
489 // processed.
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000490 SmallVector<std::pair<unsigned, VNInfo*>, 8> WorkList;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000491 WorkList.push_back(std::make_pair(UseReg, UseVNI));
492
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000493 do {
494 unsigned Reg;
495 VNInfo *VNI;
496 tie(Reg, VNI) = WorkList.pop_back_val();
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000497 DEBUG(dbgs() << " " << PrintReg(Reg) << ':' << VNI->id << '@' << VNI->def
498 << ":\t");
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000499
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000500 // First check if this value has already been computed.
501 SVI = SibValues.find(VNI);
502 assert(SVI != SibValues.end() && "Missing SibValues entry");
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000503
504 // Trace through PHI-defs created by live range splitting.
505 if (VNI->isPHIDef()) {
Jakob Stoklund Olesen6b6e32d2011-09-15 16:41:12 +0000506 // Stop at original PHIs. We don't know the value at the predecessors.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000507 if (VNI->def == OrigVNI->def) {
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000508 DEBUG(dbgs() << "orig phi value\n");
509 SVI->second.DefByOrigPHI = true;
510 SVI->second.AllDefsAreReloads = false;
511 propagateSiblingValue(SVI);
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000512 continue;
513 }
Jakob Stoklund Olesen6b6e32d2011-09-15 16:41:12 +0000514
515 // This is a PHI inserted by live range splitting. We could trace the
516 // live-out value from predecessor blocks, but that search can be very
517 // expensive if there are many predecessors and many more PHIs as
518 // generated by tail-dup when it sees an indirectbr. Instead, look at
519 // all the non-PHI defs that have the same value as OrigVNI. They must
520 // jointly dominate VNI->def. This is not optimal since VNI may actually
521 // be jointly dominated by a smaller subset of defs, so there is a change
522 // we will miss a AllDefsAreReloads optimization.
523
524 // Separate all values dominated by OrigVNI into PHIs and non-PHIs.
525 SmallVector<VNInfo*, 8> PHIs, NonPHIs;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000526 LiveInterval &LI = LIS.getInterval(Reg);
Jakob Stoklund Olesen6b6e32d2011-09-15 16:41:12 +0000527 LiveInterval &OrigLI = LIS.getInterval(Original);
528
529 for (LiveInterval::vni_iterator VI = LI.vni_begin(), VE = LI.vni_end();
530 VI != VE; ++VI) {
531 VNInfo *VNI2 = *VI;
532 if (VNI2->isUnused())
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000533 continue;
Jakob Stoklund Olesen6b6e32d2011-09-15 16:41:12 +0000534 if (!OrigLI.containsOneValue() &&
535 OrigLI.getVNInfoAt(VNI2->def) != OrigVNI)
536 continue;
537 if (VNI2->isPHIDef() && VNI2->def != OrigVNI->def)
538 PHIs.push_back(VNI2);
539 else
540 NonPHIs.push_back(VNI2);
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000541 }
Jakob Stoklund Olesen6b6e32d2011-09-15 16:41:12 +0000542 DEBUG(dbgs() << "split phi value, checking " << PHIs.size()
543 << " phi-defs, and " << NonPHIs.size()
544 << " non-phi/orig defs\n");
545
546 // Create entries for all the PHIs. Don't add them to the worklist, we
547 // are processing all of them in one go here.
548 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
549 SibValues.insert(std::make_pair(PHIs[i], SibValueInfo(Reg, PHIs[i])));
550
551 // Add every PHI as a dependent of all the non-PHIs.
552 for (unsigned i = 0, e = NonPHIs.size(); i != e; ++i) {
553 VNInfo *NonPHI = NonPHIs[i];
554 // Known value? Try an insertion.
555 tie(SVI, Inserted) =
556 SibValues.insert(std::make_pair(NonPHI, SibValueInfo(Reg, NonPHI)));
557 // Add all the PHIs as dependents of NonPHI.
558 for (unsigned pi = 0, pe = PHIs.size(); pi != pe; ++pi)
559 SVI->second.Deps.push_back(PHIs[pi]);
560 // This is the first time we see NonPHI, add it to the worklist.
561 if (Inserted)
562 WorkList.push_back(std::make_pair(Reg, NonPHI));
563 else
564 // Propagate to all inserted PHIs, not just VNI.
565 propagateSiblingValue(SVI);
566 }
567
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000568 // Next work list item.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000569 continue;
570 }
571
572 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
573 assert(MI && "Missing def");
574
575 // Trace through sibling copies.
576 if (unsigned SrcReg = isFullCopyOf(MI, Reg)) {
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000577 if (isSibling(SrcReg)) {
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000578 LiveInterval &SrcLI = LIS.getInterval(SrcReg);
Jakob Stoklund Olesen92a05fa2012-05-20 02:44:33 +0000579 LiveRangeQuery SrcQ(SrcLI, VNI->def);
580 assert(SrcQ.valueIn() && "Copy from non-existing value");
Jakob Stoklund Olesen69cf1ca2011-09-16 00:03:33 +0000581 // Check if this COPY kills its source.
Jakob Stoklund Olesen92a05fa2012-05-20 02:44:33 +0000582 SVI->second.KillsSource = SrcQ.isKill();
583 VNInfo *SrcVNI = SrcQ.valueIn();
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000584 DEBUG(dbgs() << "copy of " << PrintReg(SrcReg) << ':'
Jakob Stoklund Olesen69cf1ca2011-09-16 00:03:33 +0000585 << SrcVNI->id << '@' << SrcVNI->def
586 << " kill=" << unsigned(SVI->second.KillsSource) << '\n');
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000587 // Known sibling source value? Try an insertion.
588 tie(SVI, Inserted) = SibValues.insert(std::make_pair(SrcVNI,
589 SibValueInfo(SrcReg, SrcVNI)));
590 // This is the first time we see Src, add it to the worklist.
591 if (Inserted)
592 WorkList.push_back(std::make_pair(SrcReg, SrcVNI));
593 propagateSiblingValue(SVI, VNI);
594 // Next work list item.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000595 continue;
596 }
597 }
598
599 // Track reachable reloads.
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000600 SVI->second.DefMI = MI;
601 SVI->second.SpillMBB = MI->getParent();
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000602 int FI;
603 if (Reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot) {
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000604 DEBUG(dbgs() << "reload\n");
605 propagateSiblingValue(SVI);
606 // Next work list item.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000607 continue;
608 }
609
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000610 // Potential remat candidate.
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000611 DEBUG(dbgs() << "def " << *MI);
612 SVI->second.AllDefsAreReloads = false;
613 propagateSiblingValue(SVI);
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000614 } while (!WorkList.empty());
615
Logan Chiene2ac5522012-09-01 12:11:41 +0000616 // Look up the value we were looking for. We already did this lookup at the
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000617 // top of the function, but SibValues may have been invalidated.
618 SVI = SibValues.find(UseVNI);
619 assert(SVI != SibValues.end() && "Didn't compute requested info");
620 DEBUG(dbgs() << " traced to:\t" << SVI->second);
621 return SVI->second.DefMI;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000622}
623
624/// analyzeSiblingValues - Trace values defined by sibling copies back to
625/// something that isn't a sibling copy.
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000626///
627/// Keep track of values that may be rematerializable.
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000628void InlineSpiller::analyzeSiblingValues() {
629 SibValues.clear();
630
631 // No siblings at all?
632 if (Edit->getReg() == Original)
633 return;
634
635 LiveInterval &OrigLI = LIS.getInterval(Original);
636 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
637 unsigned Reg = RegsToSpill[i];
638 LiveInterval &LI = LIS.getInterval(Reg);
639 for (LiveInterval::const_vni_iterator VI = LI.vni_begin(),
640 VE = LI.vni_end(); VI != VE; ++VI) {
641 VNInfo *VNI = *VI;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000642 if (VNI->isUnused())
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000643 continue;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000644 MachineInstr *DefMI = 0;
Jakob Stoklund Olesen3b1088a2012-02-04 05:20:49 +0000645 if (!VNI->isPHIDef()) {
646 DefMI = LIS.getInstructionFromIndex(VNI->def);
647 assert(DefMI && "No defining instruction");
648 }
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000649 // Check possible sibling copies.
Jakob Stoklund Olesen3b1088a2012-02-04 05:20:49 +0000650 if (VNI->isPHIDef() || DefMI->isCopy()) {
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000651 VNInfo *OrigVNI = OrigLI.getVNInfoAt(VNI->def);
Jakob Stoklund Olesen9693d4c2011-07-05 15:38:41 +0000652 assert(OrigVNI && "Def outside original live range");
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000653 if (OrigVNI->def != VNI->def)
654 DefMI = traceSiblingValue(Reg, VNI, OrigVNI);
655 }
Pete Cooper8a06af92012-04-02 22:22:53 +0000656 if (DefMI && Edit->checkRematerializable(VNI, DefMI, AA)) {
Jakob Stoklund Olesen3b7d9172011-04-20 22:14:20 +0000657 DEBUG(dbgs() << "Value " << PrintReg(Reg) << ':' << VNI->id << '@'
658 << VNI->def << " may remat from " << *DefMI);
659 }
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +0000660 }
661 }
662}
663
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000664/// hoistSpill - Given a sibling copy that defines a value to be spilled, insert
665/// a spill at a better location.
666bool InlineSpiller::hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI) {
667 SlotIndex Idx = LIS.getInstructionIndex(CopyMI);
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000668 VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getRegSlot());
669 assert(VNI && VNI->def == Idx.getRegSlot() && "Not defined by copy");
Jakob Stoklund Olesen6ee56e62011-04-30 06:42:21 +0000670 SibValueMap::iterator I = SibValues.find(VNI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000671 if (I == SibValues.end())
672 return false;
673
674 const SibValueInfo &SVI = I->second;
675
676 // Let the normal folding code deal with the boring case.
677 if (!SVI.AllDefsAreReloads && SVI.SpillVNI == VNI)
678 return false;
679
Jakob Stoklund Olesen6ee56e62011-04-30 06:42:21 +0000680 // SpillReg may have been deleted by remat and DCE.
681 if (!LIS.hasInterval(SVI.SpillReg)) {
682 DEBUG(dbgs() << "Stale interval: " << PrintReg(SVI.SpillReg) << '\n');
683 SibValues.erase(I);
684 return false;
685 }
686
687 LiveInterval &SibLI = LIS.getInterval(SVI.SpillReg);
688 if (!SibLI.containsValue(SVI.SpillVNI)) {
689 DEBUG(dbgs() << "Stale value: " << PrintReg(SVI.SpillReg) << '\n');
690 SibValues.erase(I);
691 return false;
692 }
693
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000694 // Conservatively extend the stack slot range to the range of the original
695 // value. We may be able to do better with stack slot coloring by being more
696 // careful here.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000697 assert(StackInt && "No stack slot assigned yet.");
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000698 LiveInterval &OrigLI = LIS.getInterval(Original);
699 VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000700 StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0));
Jakob Stoklund Olesenc1655e12011-03-19 23:02:47 +0000701 DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000702 << *StackInt << '\n');
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000703
704 // Already spilled everywhere.
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000705 if (SVI.AllDefsAreReloads) {
Jakob Stoklund Olesen1ab7c8e2011-09-09 18:11:41 +0000706 DEBUG(dbgs() << "\tno spill needed: " << SVI);
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000707 ++NumOmitReloadSpill;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000708 return true;
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000709 }
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000710 // We are going to spill SVI.SpillVNI immediately after its def, so clear out
711 // any later spills of the same value.
Jakob Stoklund Olesen6ee56e62011-04-30 06:42:21 +0000712 eliminateRedundantSpills(SibLI, SVI.SpillVNI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000713
714 MachineBasicBlock *MBB = LIS.getMBBFromIndex(SVI.SpillVNI->def);
715 MachineBasicBlock::iterator MII;
716 if (SVI.SpillVNI->isPHIDef())
717 MII = MBB->SkipPHIsAndLabels(MBB->begin());
718 else {
Jakob Stoklund Olesen6ee56e62011-04-30 06:42:21 +0000719 MachineInstr *DefMI = LIS.getInstructionFromIndex(SVI.SpillVNI->def);
720 assert(DefMI && "Defining instruction disappeared");
721 MII = DefMI;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000722 ++MII;
723 }
724 // Insert spill without kill flag immediately after def.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000725 TII.storeRegToStackSlot(*MBB, MII, SVI.SpillReg, false, StackSlot,
726 MRI.getRegClass(SVI.SpillReg), &TRI);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000727 --MII; // Point to store instruction.
728 LIS.InsertMachineInstrInMaps(MII);
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000729 DEBUG(dbgs() << "\thoisted: " << SVI.SpillVNI->def << '\t' << *MII);
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000730
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +0000731 ++NumSpills;
732 ++NumHoists;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000733 return true;
734}
735
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000736/// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any
737/// redundant spills of this value in SLI.reg and sibling copies.
738void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
Jakob Stoklund Olesen682eed02011-03-20 05:44:58 +0000739 assert(VNI && "Missing value");
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000740 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
741 WorkList.push_back(std::make_pair(&SLI, VNI));
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000742 assert(StackInt && "No stack slot assigned yet.");
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000743
744 do {
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000745 LiveInterval *LI;
746 tie(LI, VNI) = WorkList.pop_back_val();
747 unsigned Reg = LI->reg;
Jakob Stoklund Olesen6ee56e62011-04-30 06:42:21 +0000748 DEBUG(dbgs() << "Checking redundant spills for "
749 << VNI->id << '@' << VNI->def << " in " << *LI << '\n');
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000750
751 // Regs to spill are taken care of.
752 if (isRegToSpill(Reg))
753 continue;
754
755 // Add all of VNI's live range to StackInt.
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +0000756 StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0));
757 DEBUG(dbgs() << "Merged to stack int: " << *StackInt << '\n');
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000758
759 // Find all spills and copies of VNI.
760 for (MachineRegisterInfo::use_nodbg_iterator UI = MRI.use_nodbg_begin(Reg);
761 MachineInstr *MI = UI.skipInstruction();) {
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000762 if (!MI->isCopy() && !MI->mayStore())
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000763 continue;
764 SlotIndex Idx = LIS.getInstructionIndex(MI);
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000765 if (LI->getVNInfoAt(Idx) != VNI)
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000766 continue;
767
768 // Follow sibling copies down the dominator tree.
769 if (unsigned DstReg = isFullCopyOf(MI, Reg)) {
770 if (isSibling(DstReg)) {
771 LiveInterval &DstLI = LIS.getInterval(DstReg);
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000772 VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getRegSlot());
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000773 assert(DstVNI && "Missing defined value");
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000774 assert(DstVNI->def == Idx.getRegSlot() && "Wrong copy def slot");
Jakob Stoklund Olesen01a46c82011-03-20 05:44:55 +0000775 WorkList.push_back(std::make_pair(&DstLI, DstVNI));
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000776 }
777 continue;
778 }
779
780 // Erase spills.
781 int FI;
782 if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) {
783 DEBUG(dbgs() << "Redundant spill " << Idx << '\t' << *MI);
784 // eliminateDeadDefs won't normally remove stores, so switch opcode.
785 MI->setDesc(TII.get(TargetOpcode::KILL));
786 DeadDefs.push_back(MI);
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +0000787 ++NumSpillsRemoved;
788 --NumSpills;
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +0000789 }
790 }
791 } while (!WorkList.empty());
792}
793
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +0000794
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000795//===----------------------------------------------------------------------===//
796// Rematerialization
797//===----------------------------------------------------------------------===//
798
799/// markValueUsed - Remember that VNI failed to rematerialize, so its defining
800/// instruction cannot be eliminated. See through snippet copies
801void InlineSpiller::markValueUsed(LiveInterval *LI, VNInfo *VNI) {
802 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
803 WorkList.push_back(std::make_pair(LI, VNI));
804 do {
805 tie(LI, VNI) = WorkList.pop_back_val();
806 if (!UsedValues.insert(VNI))
807 continue;
808
809 if (VNI->isPHIDef()) {
810 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
811 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
812 PE = MBB->pred_end(); PI != PE; ++PI) {
Jakob Stoklund Olesen194eb712011-11-14 01:39:36 +0000813 VNInfo *PVNI = LI->getVNInfoBefore(LIS.getMBBEndIdx(*PI));
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000814 if (PVNI)
815 WorkList.push_back(std::make_pair(LI, PVNI));
816 }
817 continue;
818 }
819
820 // Follow snippet copies.
821 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
822 if (!SnippetCopies.count(MI))
823 continue;
824 LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg());
825 assert(isRegToSpill(SnipLI.reg) && "Unexpected register in copy");
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000826 VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getRegSlot(true));
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000827 assert(SnipVNI && "Snippet undefined before copy");
828 WorkList.push_back(std::make_pair(&SnipLI, SnipVNI));
829 } while (!WorkList.empty());
830}
831
832/// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
833bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg,
834 MachineBasicBlock::iterator MI) {
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000835 SlotIndex UseIdx = LIS.getInstructionIndex(MI).getRegSlot(true);
Jakob Stoklund Olesen79413502011-07-18 05:31:59 +0000836 VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx.getBaseIndex());
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000837
838 if (!ParentVNI) {
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000839 DEBUG(dbgs() << "\tadding <undef> flags: ");
840 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
841 MachineOperand &MO = MI->getOperand(i);
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000842 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg)
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000843 MO.setIsUndef();
844 }
845 DEBUG(dbgs() << UseIdx << '\t' << *MI);
846 return true;
847 }
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +0000848
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000849 if (SnippetCopies.count(MI))
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000850 return false;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000851
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000852 // Use an OrigVNI from traceSiblingValue when ParentVNI is a sibling copy.
853 LiveRangeEdit::Remat RM(ParentVNI);
854 SibValueMap::const_iterator SibI = SibValues.find(ParentVNI);
855 if (SibI != SibValues.end())
856 RM.OrigMI = SibI->second.DefMI;
Pete Cooper8a06af92012-04-02 22:22:53 +0000857 if (!Edit->canRematerializeAt(RM, UseIdx, false)) {
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000858 markValueUsed(&VirtReg, ParentVNI);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000859 DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
860 return false;
861 }
862
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000863 // If the instruction also writes VirtReg.reg, it had better not require the
864 // same register for uses and defs.
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +0000865 SmallVector<std::pair<MachineInstr*, unsigned>, 8> Ops;
James Molloyb17cf292012-09-12 10:03:31 +0000866 MIBundleOperands::VirtRegInfo RI =
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +0000867 MIBundleOperands(MI).analyzeVirtReg(VirtReg.reg, &Ops);
868 if (RI.Tied) {
869 markValueUsed(&VirtReg, ParentVNI);
870 DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
871 return false;
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000872 }
873
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000874 // Before rematerializing into a register for a single instruction, try to
875 // fold a load into the instruction. That avoids allocating a new register.
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000876 if (RM.OrigMI->canFoldAsLoad() &&
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +0000877 foldMemoryOperand(Ops, RM.OrigMI)) {
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000878 Edit->markRematerialized(RM.ParentVNI);
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000879 ++NumFoldedLoads;
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +0000880 return true;
881 }
882
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000883 // Alocate a new register for the remat.
Pete Cooper8a06af92012-04-02 22:22:53 +0000884 LiveInterval &NewLI = Edit->createFrom(Original);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000885 NewLI.markNotSpillable();
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000886
887 // Finally we can rematerialize OrigMI before MI.
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000888 SlotIndex DefIdx = Edit->rematerializeAt(*MI->getParent(), MI, NewLI.reg, RM,
Pete Cooper8a06af92012-04-02 22:22:53 +0000889 TRI);
Jakob Stoklund Olesen7b1f4982011-02-08 19:33:55 +0000890 DEBUG(dbgs() << "\tremat: " << DefIdx << '\t'
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000891 << *LIS.getInstructionFromIndex(DefIdx));
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000892
893 // Replace operands
894 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +0000895 MachineOperand &MO = MI->getOperand(Ops[i].second);
Jakob Stoklund Olesencf610d02011-03-29 17:47:02 +0000896 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg) {
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000897 MO.setReg(NewLI.reg);
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000898 MO.setIsKill();
899 }
900 }
901 DEBUG(dbgs() << "\t " << UseIdx << '\t' << *MI);
902
Jakob Stoklund Olesen3b1088a2012-02-04 05:20:49 +0000903 VNInfo *DefVNI = NewLI.getNextValue(DefIdx, LIS.getVNInfoAllocator());
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000904 NewLI.addRange(LiveRange(DefIdx, UseIdx.getRegSlot(), DefVNI));
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000905 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +0000906 ++NumRemats;
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +0000907 return true;
908}
909
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +0000910/// reMaterializeAll - Try to rematerialize as many uses as possible,
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000911/// and trim the live ranges after.
912void InlineSpiller::reMaterializeAll() {
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000913 // analyzeSiblingValues has already tested all relevant defining instructions.
Pete Cooper8a06af92012-04-02 22:22:53 +0000914 if (!Edit->anyRematerializable(AA))
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000915 return;
916
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000917 UsedValues.clear();
Jakob Stoklund Olesen080c3162010-10-20 22:00:51 +0000918
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000919 // Try to remat before all uses of snippets.
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000920 bool anyRemat = false;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000921 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
922 unsigned Reg = RegsToSpill[i];
923 LiveInterval &LI = LIS.getInterval(Reg);
924 for (MachineRegisterInfo::use_nodbg_iterator
925 RI = MRI.use_nodbg_begin(Reg);
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +0000926 MachineInstr *MI = RI.skipBundle();)
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000927 anyRemat |= reMaterializeFor(LI, MI);
928 }
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000929 if (!anyRemat)
930 return;
931
932 // Remove any values that were completely rematted.
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000933 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
934 unsigned Reg = RegsToSpill[i];
935 LiveInterval &LI = LIS.getInterval(Reg);
936 for (LiveInterval::vni_iterator I = LI.vni_begin(), E = LI.vni_end();
937 I != E; ++I) {
938 VNInfo *VNI = *I;
Jakob Stoklund Olesenc1d22d82011-03-29 17:47:00 +0000939 if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI))
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +0000940 continue;
Jakob Stoklund Olesen2ef661b2011-03-29 03:12:02 +0000941 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
942 MI->addRegisterDead(Reg, &TRI);
943 if (!MI->allDefsAreDead())
944 continue;
945 DEBUG(dbgs() << "All defs dead: " << *MI);
946 DeadDefs.push_back(MI);
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +0000947 }
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000948 }
Jakob Stoklund Olesenc1d22d82011-03-29 17:47:00 +0000949
950 // Eliminate dead code after remat. Note that some snippet copies may be
951 // deleted here.
952 if (DeadDefs.empty())
953 return;
954 DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n");
Pete Cooper8a06af92012-04-02 22:22:53 +0000955 Edit->eliminateDeadDefs(DeadDefs, RegsToSpill);
Jakob Stoklund Olesenc1d22d82011-03-29 17:47:00 +0000956
957 // Get rid of deleted and empty intervals.
958 for (unsigned i = RegsToSpill.size(); i != 0; --i) {
959 unsigned Reg = RegsToSpill[i-1];
960 if (!LIS.hasInterval(Reg)) {
961 RegsToSpill.erase(RegsToSpill.begin() + (i - 1));
962 continue;
963 }
964 LiveInterval &LI = LIS.getInterval(Reg);
965 if (!LI.empty())
966 continue;
Pete Cooper8a06af92012-04-02 22:22:53 +0000967 Edit->eraseVirtReg(Reg);
Jakob Stoklund Olesenc1d22d82011-03-29 17:47:00 +0000968 RegsToSpill.erase(RegsToSpill.begin() + (i - 1));
969 }
970 DEBUG(dbgs() << RegsToSpill.size() << " registers to spill after remat.\n");
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +0000971}
972
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +0000973
974//===----------------------------------------------------------------------===//
975// Spilling
976//===----------------------------------------------------------------------===//
977
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000978/// If MI is a load or store of StackSlot, it can be removed.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +0000979bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, unsigned Reg) {
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000980 int FI = 0;
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +0000981 unsigned InstrReg = TII.isLoadFromStackSlot(MI, FI);
982 bool IsLoad = InstrReg;
983 if (!IsLoad)
984 InstrReg = TII.isStoreToStackSlot(MI, FI);
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000985
986 // We have a stack access. Is it the right register and slot?
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000987 if (InstrReg != Reg || FI != StackSlot)
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000988 return false;
989
990 DEBUG(dbgs() << "Coalescing stack access: " << *MI);
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +0000991 LIS.RemoveMachineInstrFromMaps(MI);
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +0000992 MI->eraseFromParent();
Jakob Stoklund Olesen79c40a02011-09-15 17:54:28 +0000993
994 if (IsLoad) {
995 ++NumReloadsRemoved;
996 --NumReloads;
997 } else {
998 ++NumSpillsRemoved;
999 --NumSpills;
1000 }
1001
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +00001002 return true;
1003}
1004
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001005/// foldMemoryOperand - Try folding stack slot references in Ops into their
1006/// instructions.
1007///
1008/// @param Ops Operand indices from analyzeVirtReg().
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +00001009/// @param LoadMI Load instruction to use instead of stack slot when non-null.
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001010/// @return True on success.
1011bool InlineSpiller::
1012foldMemoryOperand(ArrayRef<std::pair<MachineInstr*, unsigned> > Ops,
1013 MachineInstr *LoadMI) {
1014 if (Ops.empty())
1015 return false;
1016 // Don't attempt folding in bundles.
1017 MachineInstr *MI = Ops.front().first;
1018 if (Ops.back().first != MI || MI->isBundled())
1019 return false;
1020
Jakob Stoklund Olesend205f7a2011-09-15 18:22:52 +00001021 bool WasCopy = MI->isCopy();
Jakob Stoklund Olesen17afb062011-11-10 00:17:03 +00001022 unsigned ImpReg = 0;
1023
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +00001024 // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
1025 // operands.
1026 SmallVector<unsigned, 8> FoldOps;
1027 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001028 unsigned Idx = Ops[i].second;
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +00001029 MachineOperand &MO = MI->getOperand(Idx);
Jakob Stoklund Olesen17afb062011-11-10 00:17:03 +00001030 if (MO.isImplicit()) {
1031 ImpReg = MO.getReg();
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +00001032 continue;
Jakob Stoklund Olesen17afb062011-11-10 00:17:03 +00001033 }
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +00001034 // FIXME: Teach targets to deal with subregs.
1035 if (MO.getSubReg())
1036 return false;
Jakob Stoklund Olesen7b1f4982011-02-08 19:33:55 +00001037 // We cannot fold a load instruction into a def.
1038 if (LoadMI && MO.isDef())
1039 return false;
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +00001040 // Tied use operands should not be passed to foldMemoryOperand.
1041 if (!MI->isRegTiedToDefOperand(Idx))
1042 FoldOps.push_back(Idx);
1043 }
1044
Jakob Stoklund Olesen83d1ba52010-12-18 03:04:14 +00001045 MachineInstr *FoldMI =
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001046 LoadMI ? TII.foldMemoryOperand(MI, FoldOps, LoadMI)
1047 : TII.foldMemoryOperand(MI, FoldOps, StackSlot);
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +00001048 if (!FoldMI)
1049 return false;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001050 LIS.ReplaceMachineInstrInMaps(MI, FoldMI);
Jakob Stoklund Olesene05442d2010-07-09 17:29:08 +00001051 MI->eraseFromParent();
Jakob Stoklund Olesen17afb062011-11-10 00:17:03 +00001052
1053 // TII.foldMemoryOperand may have left some implicit operands on the
1054 // instruction. Strip them.
1055 if (ImpReg)
1056 for (unsigned i = FoldMI->getNumOperands(); i; --i) {
1057 MachineOperand &MO = FoldMI->getOperand(i - 1);
1058 if (!MO.isReg() || !MO.isImplicit())
1059 break;
1060 if (MO.getReg() == ImpReg)
1061 FoldMI->RemoveOperand(i - 1);
1062 }
1063
1064 DEBUG(dbgs() << "\tfolded: " << LIS.getInstructionIndex(FoldMI) << '\t'
1065 << *FoldMI);
Jakob Stoklund Olesend205f7a2011-09-15 18:22:52 +00001066 if (!WasCopy)
1067 ++NumFolded;
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001068 else if (Ops.front().second == 0)
Jakob Stoklund Olesend205f7a2011-09-15 18:22:52 +00001069 ++NumSpills;
1070 else
1071 ++NumReloads;
Jakob Stoklund Olesene72a5c52010-07-01 00:13:04 +00001072 return true;
1073}
1074
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001075/// insertReload - Insert a reload of NewLI.reg before MI.
1076void InlineSpiller::insertReload(LiveInterval &NewLI,
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +00001077 SlotIndex Idx,
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001078 MachineBasicBlock::iterator MI) {
1079 MachineBasicBlock &MBB = *MI->getParent();
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +00001080 TII.loadRegFromStackSlot(MBB, MI, NewLI.reg, StackSlot,
1081 MRI.getRegClass(NewLI.reg), &TRI);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001082 --MI; // Point to load instruction.
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +00001083 SlotIndex LoadIdx = LIS.InsertMachineInstrInMaps(MI).getRegSlot();
Jakob Stoklund Olesen27982e12012-07-14 18:45:35 +00001084 // Some (out-of-tree) targets have EC reload instructions.
1085 if (MachineOperand *MO = MI->findRegisterDefOperand(NewLI.reg))
1086 if (MO->isEarlyClobber())
1087 LoadIdx = LoadIdx.getRegSlot(true);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001088 DEBUG(dbgs() << "\treload: " << LoadIdx << '\t' << *MI);
Jakob Stoklund Olesen3b1088a2012-02-04 05:20:49 +00001089 VNInfo *LoadVNI = NewLI.getNextValue(LoadIdx, LIS.getVNInfoAllocator());
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001090 NewLI.addRange(LiveRange(LoadIdx, Idx, LoadVNI));
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +00001091 ++NumReloads;
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001092}
1093
1094/// insertSpill - Insert a spill of NewLI.reg after MI.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001095void InlineSpiller::insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +00001096 SlotIndex Idx, MachineBasicBlock::iterator MI) {
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001097 MachineBasicBlock &MBB = *MI->getParent();
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +00001098 TII.storeRegToStackSlot(MBB, ++MI, NewLI.reg, true, StackSlot,
1099 MRI.getRegClass(NewLI.reg), &TRI);
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001100 --MI; // Point to store instruction.
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +00001101 SlotIndex StoreIdx = LIS.InsertMachineInstrInMaps(MI).getRegSlot();
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001102 DEBUG(dbgs() << "\tspilled: " << StoreIdx << '\t' << *MI);
Jakob Stoklund Olesen3b1088a2012-02-04 05:20:49 +00001103 VNInfo *StoreVNI = NewLI.getNextValue(Idx, LIS.getVNInfoAllocator());
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001104 NewLI.addRange(LiveRange(Idx, StoreIdx, StoreVNI));
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +00001105 ++NumSpills;
Jakob Stoklund Olesen9e55afb2010-06-30 23:03:52 +00001106}
1107
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001108/// spillAroundUses - insert spill code around each use of Reg.
1109void InlineSpiller::spillAroundUses(unsigned Reg) {
Jakob Stoklund Olesen443443c2011-05-11 18:25:10 +00001110 DEBUG(dbgs() << "spillAroundUses " << PrintReg(Reg) << '\n');
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001111 LiveInterval &OldLI = LIS.getInterval(Reg);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001112
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001113 // Iterate over instructions using Reg.
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001114 for (MachineRegisterInfo::reg_iterator RegI = MRI.reg_begin(Reg);
1115 MachineInstr *MI = RegI.skipBundle();) {
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001116
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +00001117 // Debug values are not allowed to affect codegen.
1118 if (MI->isDebugValue()) {
1119 // Modify DBG_VALUE now that the value is in a spill slot.
1120 uint64_t Offset = MI->getOperand(1).getImm();
1121 const MDNode *MDPtr = MI->getOperand(2).getMetadata();
1122 DebugLoc DL = MI->getDebugLoc();
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001123 if (MachineInstr *NewDV = TII.emitFrameIndexDebugValue(MF, StackSlot,
Jakob Stoklund Olesen3b9c7eb2010-07-02 19:54:40 +00001124 Offset, MDPtr, DL)) {
1125 DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
1126 MachineBasicBlock *MBB = MI->getParent();
1127 MBB->insert(MBB->erase(MI), NewDV);
1128 } else {
1129 DEBUG(dbgs() << "Removing debug info due to spill:" << "\t" << *MI);
1130 MI->eraseFromParent();
1131 }
1132 continue;
1133 }
1134
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001135 // Ignore copies to/from snippets. We'll delete them.
1136 if (SnippetCopies.count(MI))
1137 continue;
1138
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +00001139 // Stack slot accesses may coalesce away.
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001140 if (coalesceStackAccess(MI, Reg))
Jakob Stoklund Olesen1a0f91b2010-08-04 22:35:11 +00001141 continue;
1142
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001143 // Analyze instruction.
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001144 SmallVector<std::pair<MachineInstr*, unsigned>, 8> Ops;
James Molloyb17cf292012-09-12 10:03:31 +00001145 MIBundleOperands::VirtRegInfo RI =
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001146 MIBundleOperands(MI).analyzeVirtReg(Reg, &Ops);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001147
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +00001148 // Find the slot index where this instruction reads and writes OldLI.
1149 // This is usually the def slot, except for tied early clobbers.
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +00001150 SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
1151 if (VNInfo *VNI = OldLI.getVNInfoAt(Idx.getRegSlot(true)))
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +00001152 if (SlotIndex::isSameInstr(Idx, VNI->def))
1153 Idx = VNI->def;
1154
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +00001155 // Check for a sibling copy.
1156 unsigned SibReg = isFullCopyOf(MI, Reg);
Jakob Stoklund Olesen682eed02011-03-20 05:44:58 +00001157 if (SibReg && isSibling(SibReg)) {
Jakob Stoklund Olesen443443c2011-05-11 18:25:10 +00001158 // This may actually be a copy between snippets.
1159 if (isRegToSpill(SibReg)) {
1160 DEBUG(dbgs() << "Found new snippet copy: " << *MI);
1161 SnippetCopies.insert(MI);
1162 continue;
1163 }
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001164 if (RI.Writes) {
Jakob Stoklund Olesen682eed02011-03-20 05:44:58 +00001165 // Hoist the spill of a sib-reg copy.
1166 if (hoistSpill(OldLI, MI)) {
1167 // This COPY is now dead, the value is already in the stack slot.
1168 MI->getOperand(0).setIsDead();
1169 DeadDefs.push_back(MI);
1170 continue;
1171 }
1172 } else {
1173 // This is a reload for a sib-reg copy. Drop spills downstream.
Jakob Stoklund Olesen682eed02011-03-20 05:44:58 +00001174 LiveInterval &SibLI = LIS.getInterval(SibReg);
1175 eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx));
1176 // The COPY will fold to a reload below.
1177 }
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +00001178 }
1179
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +00001180 // Attempt to fold memory ops.
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001181 if (foldMemoryOperand(Ops))
Jakob Stoklund Olesen8de3b1e2010-07-02 17:44:57 +00001182 continue;
1183
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001184 // Allocate interval around instruction.
1185 // FIXME: Infer regclass from instruction alone.
Pete Cooper8a06af92012-04-02 22:22:53 +00001186 LiveInterval &NewLI = Edit->createFrom(Reg);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001187 NewLI.markNotSpillable();
1188
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001189 if (RI.Reads)
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +00001190 insertReload(NewLI, Idx, MI);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001191
1192 // Rewrite instruction operands.
1193 bool hasLiveDef = false;
1194 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001195 MachineOperand &MO = Ops[i].first->getOperand(Ops[i].second);
Jakob Stoklund Olesena17768f2010-10-14 23:49:52 +00001196 MO.setReg(NewLI.reg);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001197 if (MO.isUse()) {
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001198 if (!Ops[i].first->isRegTiedToDefOperand(Ops[i].second))
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001199 MO.setIsKill();
1200 } else {
1201 if (!MO.isDead())
1202 hasLiveDef = true;
1203 }
1204 }
Jakob Stoklund Olesen5d5ef4a2011-04-18 20:23:27 +00001205 DEBUG(dbgs() << "\trewrite: " << Idx << '\t' << *MI);
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001206
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001207 // FIXME: Use a second vreg if instruction has no tied ops.
Jakob Stoklund Olesen66c994c2012-03-01 01:43:25 +00001208 if (RI.Writes) {
1209 if (hasLiveDef)
1210 insertSpill(NewLI, OldLI, Idx, MI);
1211 else {
1212 // This instruction defines a dead value. We don't need to spill it,
1213 // but do create a live range for the dead value.
1214 VNInfo *VNI = NewLI.getNextValue(Idx, LIS.getVNInfoAllocator());
1215 NewLI.addRange(LiveRange(Idx, Idx.getDeadSlot(), VNI));
1216 }
Jakob Stoklund Olesena80444f2011-10-14 00:34:31 +00001217 }
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001218
1219 DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
Jakob Stoklund Olesen914f2ff2010-06-29 23:58:39 +00001220 }
1221}
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001222
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001223/// spillAll - Spill all registers remaining after rematerialization.
1224void InlineSpiller::spillAll() {
1225 // Update LiveStacks now that we are committed to spilling.
1226 if (StackSlot == VirtRegMap::NO_STACK_SLOT) {
1227 StackSlot = VRM.assignVirt2StackSlot(Original);
1228 StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original));
Jakob Stoklund Olesen3b1088a2012-02-04 05:20:49 +00001229 StackInt->getNextValue(SlotIndex(), LSS.getVNInfoAllocator());
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001230 } else
1231 StackInt = &LSS.getInterval(StackSlot);
1232
1233 if (Original != Edit->getReg())
1234 VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot);
1235
1236 assert(StackInt->getNumValNums() == 1 && "Bad stack interval values");
1237 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1238 StackInt->MergeRangesInAsValue(LIS.getInterval(RegsToSpill[i]),
1239 StackInt->getValNumInfo(0));
1240 DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n');
1241
1242 // Spill around uses of all RegsToSpill.
1243 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1244 spillAroundUses(RegsToSpill[i]);
1245
1246 // Hoisted spills may cause dead code.
1247 if (!DeadDefs.empty()) {
1248 DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n");
Pete Cooper8a06af92012-04-02 22:22:53 +00001249 Edit->eliminateDeadDefs(DeadDefs, RegsToSpill);
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001250 }
1251
1252 // Finally delete the SnippetCopies.
Jakob Stoklund Olesen443443c2011-05-11 18:25:10 +00001253 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
1254 for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(RegsToSpill[i]);
1255 MachineInstr *MI = RI.skipInstruction();) {
1256 assert(SnippetCopies.count(MI) && "Remaining use wasn't a snippet copy");
1257 // FIXME: Do this with a LiveRangeEdit callback.
Jakob Stoklund Olesen443443c2011-05-11 18:25:10 +00001258 LIS.RemoveMachineInstrFromMaps(MI);
1259 MI->eraseFromParent();
1260 }
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001261 }
1262
1263 // Delete all spilled registers.
1264 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
Pete Cooper8a06af92012-04-02 22:22:53 +00001265 Edit->eraseVirtReg(RegsToSpill[i]);
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001266}
1267
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001268void InlineSpiller::spill(LiveRangeEdit &edit) {
Jakob Stoklund Olesene9bd4ea2011-05-05 17:22:53 +00001269 ++NumSpilledRanges;
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001270 Edit = &edit;
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001271 assert(!TargetRegisterInfo::isStackSlot(edit.getReg())
1272 && "Trying to spill a stack slot.");
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +00001273 // Share a stack slot among all descendants of Original.
1274 Original = VRM.getOriginal(edit.getReg());
1275 StackSlot = VRM.getStackSlot(Original);
Jakob Stoklund Olesene9c50732011-03-26 22:16:41 +00001276 StackInt = 0;
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +00001277
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001278 DEBUG(dbgs() << "Inline spilling "
Jakob Stoklund Olesen766faf42011-03-14 19:56:43 +00001279 << MRI.getRegClass(edit.getReg())->getName()
Jakob Stoklund Olesen127cdba2012-06-15 23:47:09 +00001280 << ':' << PrintReg(edit.getReg()) << ' ' << edit.getParent()
1281 << "\nFrom original " << LIS.getInterval(Original) << '\n');
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001282 assert(edit.getParent().isSpillable() &&
1283 "Attempting to spill already spilled value.");
Jakob Stoklund Olesen2a72bfa2011-03-18 04:23:06 +00001284 assert(DeadDefs.empty() && "Previous spill didn't remove dead defs");
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001285
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001286 collectRegsToSpill();
Jakob Stoklund Olesen13ba2522011-03-15 21:13:25 +00001287 analyzeSiblingValues();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001288 reMaterializeAll();
1289
1290 // Remat may handle everything.
Jakob Stoklund Olesen6094bd82011-03-29 21:20:19 +00001291 if (!RegsToSpill.empty())
1292 spillAll();
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001293
Pete Cooper8a06af92012-04-02 22:22:53 +00001294 Edit->calculateRegClassAndHint(MF, Loops);
Jakob Stoklund Olesen10a43322011-03-12 04:17:20 +00001295}