blob: 64211c8d31b76237823697ea15748a709a1fc31c [file] [log] [blame]
Jakob Stoklund Olesenf8889112010-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 Olesencbbd8192010-11-03 20:39:23 +000015#define DEBUG_TYPE "regalloc"
Jakob Stoklund Olesenf8889112010-06-29 23:58:39 +000016#include "Spiller.h"
Benjamin Kramerbc6666b2013-05-23 15:42:57 +000017#include "llvm/ADT/SetVector.h"
Jakob Stoklund Olesenc5a8c082011-05-05 17:22:53 +000018#include "llvm/ADT/Statistic.h"
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +000019#include "llvm/ADT/TinyPtrVector.h"
Jakob Stoklund Olesen868dd4e2010-11-10 23:55:56 +000020#include "llvm/Analysis/AliasAnalysis.h"
Jakob Stoklund Olesenf8889112010-06-29 23:58:39 +000021#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Pete Cooper3ca96f92012-04-02 22:44:18 +000022#include "llvm/CodeGen/LiveRangeEdit.h"
Jakob Stoklund Olesene2c340c2010-10-26 00:11:35 +000023#include "llvm/CodeGen/LiveStackAnalysis.h"
Benjamin Kramere2a1d892013-06-17 19:00:36 +000024#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000025#include "llvm/CodeGen/MachineDominators.h"
Jakob Stoklund Olesenf8889112010-06-29 23:58:39 +000026#include "llvm/CodeGen/MachineFrameInfo.h"
27#include "llvm/CodeGen/MachineFunction.h"
David Blaikie0252265b2013-06-16 20:34:15 +000028#include "llvm/CodeGen/MachineInstrBuilder.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include "llvm/CodeGen/MachineInstrBundle.h"
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +000030#include "llvm/CodeGen/MachineLoopInfo.h"
Jakob Stoklund Olesenf8889112010-06-29 23:58:39 +000031#include "llvm/CodeGen/MachineRegisterInfo.h"
Jakob Stoklund Olesen26c9d702012-11-28 19:13:06 +000032#include "llvm/CodeGen/VirtRegMap.h"
Jakob Stoklund Olesenbceb9e52011-09-15 21:06:00 +000033#include "llvm/Support/CommandLine.h"
Jakob Stoklund Olesenf8889112010-06-29 23:58:39 +000034#include "llvm/Support/Debug.h"
35#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Target/TargetInstrInfo.h"
37#include "llvm/Target/TargetMachine.h"
Jakob Stoklund Olesenf8889112010-06-29 23:58:39 +000038
39using namespace llvm;
40
Jakob Stoklund Olesenc5a8c082011-05-05 17:22:53 +000041STATISTIC(NumSpilledRanges, "Number of spilled live ranges");
Jakob Stoklund Olesen37eb6962011-09-15 17:54:28 +000042STATISTIC(NumSnippets, "Number of spilled snippets");
Jakob Stoklund Olesenc5a8c082011-05-05 17:22:53 +000043STATISTIC(NumSpills, "Number of spills inserted");
Jakob Stoklund Olesen37eb6962011-09-15 17:54:28 +000044STATISTIC(NumSpillsRemoved, "Number of spills removed");
Jakob Stoklund Olesenc5a8c082011-05-05 17:22:53 +000045STATISTIC(NumReloads, "Number of reloads inserted");
Jakob Stoklund Olesen37eb6962011-09-15 17:54:28 +000046STATISTIC(NumReloadsRemoved, "Number of reloads removed");
Jakob Stoklund Olesenc5a8c082011-05-05 17:22:53 +000047STATISTIC(NumFolded, "Number of folded stack accesses");
48STATISTIC(NumFoldedLoads, "Number of folded loads");
49STATISTIC(NumRemats, "Number of rematerialized defs for spilling");
Jakob Stoklund Olesen37eb6962011-09-15 17:54:28 +000050STATISTIC(NumOmitReloadSpill, "Number of omitted spills of reloads");
51STATISTIC(NumHoists, "Number of hoisted spills");
Jakob Stoklund Olesenc5a8c082011-05-05 17:22:53 +000052
Jakob Stoklund Olesenbceb9e52011-09-15 21:06:00 +000053static cl::opt<bool> DisableHoisting("disable-spill-hoist", cl::Hidden,
54 cl::desc("Disable inline spill hoisting"));
55
Jakob Stoklund Olesenf8889112010-06-29 23:58:39 +000056namespace {
57class InlineSpiller : public Spiller {
Jakob Stoklund Olesena00bab22011-03-14 19:56:43 +000058 MachineFunction &MF;
59 LiveIntervals &LIS;
60 LiveStacks &LSS;
61 AliasAnalysis *AA;
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +000062 MachineDominatorTree &MDT;
63 MachineLoopInfo &Loops;
Jakob Stoklund Olesena00bab22011-03-14 19:56:43 +000064 VirtRegMap &VRM;
65 MachineFrameInfo &MFI;
66 MachineRegisterInfo &MRI;
67 const TargetInstrInfo &TII;
68 const TargetRegisterInfo &TRI;
Benjamin Kramere2a1d892013-06-17 19:00:36 +000069 const MachineBlockFrequencyInfo &MBFI;
Jakob Stoklund Olesenbde96ad2010-06-30 23:03:52 +000070
71 // Variables that are valid during spill(), but used by multiple methods.
Jakob Stoklund Olesena00bab22011-03-14 19:56:43 +000072 LiveRangeEdit *Edit;
Jakob Stoklund Olesene4663452011-03-26 22:16:41 +000073 LiveInterval *StackInt;
Jakob Stoklund Olesena00bab22011-03-14 19:56:43 +000074 int StackSlot;
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +000075 unsigned Original;
Jakob Stoklund Olesenf8889112010-06-29 23:58:39 +000076
Jakob Stoklund Olesena00bab22011-03-14 19:56:43 +000077 // All registers to spill to StackSlot, including the main register.
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +000078 SmallVector<unsigned, 8> RegsToSpill;
79
80 // All COPY instructions to/from snippets.
81 // They are ignored since both operands refer to the same stack slot.
82 SmallPtrSet<MachineInstr*, 8> SnippetCopies;
83
Jakob Stoklund Olesen2edaa2f2010-10-20 22:00:51 +000084 // Values that failed to remat at some point.
Jakob Stoklund Olesena00bab22011-03-14 19:56:43 +000085 SmallPtrSet<VNInfo*, 8> UsedValues;
Jakob Stoklund Olesen96037182010-07-02 17:44:57 +000086
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +000087public:
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +000088 // Information about a value that was defined by a copy from a sibling
89 // register.
90 struct SibValueInfo {
91 // True when all reaching defs were reloads: No spill is necessary.
92 bool AllDefsAreReloads;
93
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +000094 // True when value is defined by an original PHI not from splitting.
95 bool DefByOrigPHI;
96
Jakob Stoklund Olesene8339b22011-09-16 00:03:33 +000097 // True when the COPY defining this value killed its source.
98 bool KillsSource;
99
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000100 // The preferred register to spill.
101 unsigned SpillReg;
102
103 // The value of SpillReg that should be spilled.
104 VNInfo *SpillVNI;
105
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000106 // The block where SpillVNI should be spilled. Currently, this must be the
107 // block containing SpillVNI->def.
108 MachineBasicBlock *SpillMBB;
109
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000110 // A defining instruction that is not a sibling copy or a reload, or NULL.
111 // This can be used as a template for rematerialization.
112 MachineInstr *DefMI;
113
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000114 // List of values that depend on this one. These values are actually the
115 // same, but live range splitting has placed them in different registers,
116 // or SSA update needed to insert PHI-defs to preserve SSA form. This is
117 // copies of the current value and phi-kills. Usually only phi-kills cause
118 // more than one dependent value.
119 TinyPtrVector<VNInfo*> Deps;
120
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000121 SibValueInfo(unsigned Reg, VNInfo *VNI)
Jakob Stoklund Olesene8339b22011-09-16 00:03:33 +0000122 : AllDefsAreReloads(true), DefByOrigPHI(false), KillsSource(false),
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000123 SpillReg(Reg), SpillVNI(VNI), SpillMBB(0), DefMI(0) {}
124
125 // Returns true when a def has been found.
126 bool hasDef() const { return DefByOrigPHI || DefMI; }
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000127 };
128
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000129private:
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000130 // Values in RegsToSpill defined by sibling copies.
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +0000131 typedef DenseMap<VNInfo*, SibValueInfo> SibValueMap;
132 SibValueMap SibValues;
133
134 // Dead defs generated during spilling.
135 SmallVector<MachineInstr*, 8> DeadDefs;
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000136
Jakob Stoklund Olesenf8889112010-06-29 23:58:39 +0000137 ~InlineSpiller() {}
138
139public:
Jakob Stoklund Olesen0fef9dd2010-07-20 23:50:15 +0000140 InlineSpiller(MachineFunctionPass &pass,
141 MachineFunction &mf,
142 VirtRegMap &vrm)
Benjamin Kramer009b1c12012-06-06 19:47:08 +0000143 : MF(mf),
Jakob Stoklund Olesena00bab22011-03-14 19:56:43 +0000144 LIS(pass.getAnalysis<LiveIntervals>()),
145 LSS(pass.getAnalysis<LiveStacks>()),
146 AA(&pass.getAnalysis<AliasAnalysis>()),
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000147 MDT(pass.getAnalysis<MachineDominatorTree>()),
148 Loops(pass.getAnalysis<MachineLoopInfo>()),
Jakob Stoklund Olesena00bab22011-03-14 19:56:43 +0000149 VRM(vrm),
150 MFI(*mf.getFrameInfo()),
151 MRI(mf.getRegInfo()),
152 TII(*mf.getTarget().getInstrInfo()),
Benjamin Kramere2a1d892013-06-17 19:00:36 +0000153 TRI(*mf.getTarget().getRegisterInfo()),
154 MBFI(pass.getAnalysis<MachineBlockFrequencyInfo>()) {}
Jakob Stoklund Olesenf8889112010-06-29 23:58:39 +0000155
Craig Topper4584cd52014-03-07 09:26:03 +0000156 void spill(LiveRangeEdit &) override;
Jakob Stoklund Olesen72911e42010-10-14 23:49:52 +0000157
Jakob Stoklund Olesen96037182010-07-02 17:44:57 +0000158private:
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +0000159 bool isSnippet(const LiveInterval &SnipLI);
160 void collectRegsToSpill();
161
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +0000162 bool isRegToSpill(unsigned Reg) {
163 return std::find(RegsToSpill.begin(),
164 RegsToSpill.end(), Reg) != RegsToSpill.end();
165 }
166
167 bool isSibling(unsigned Reg);
Jakob Stoklund Olesend8af5292011-03-29 03:12:02 +0000168 MachineInstr *traceSiblingValue(unsigned, VNInfo*, VNInfo*);
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000169 void propagateSiblingValue(SibValueMap::iterator, VNInfo *VNI = 0);
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000170 void analyzeSiblingValues();
171
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +0000172 bool hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI);
Jakob Stoklund Olesen39488642011-03-20 05:44:55 +0000173 void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI);
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +0000174
Jakob Stoklund Olesend8af5292011-03-29 03:12:02 +0000175 void markValueUsed(LiveInterval*, VNInfo*);
176 bool reMaterializeFor(LiveInterval&, MachineBasicBlock::iterator MI);
Jakob Stoklund Olesen96037182010-07-02 17:44:57 +0000177 void reMaterializeAll();
178
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +0000179 bool coalesceStackAccess(MachineInstr *MI, unsigned Reg);
Jakob Stoklund Olesenabe8c092012-03-01 01:43:25 +0000180 bool foldMemoryOperand(ArrayRef<std::pair<MachineInstr*, unsigned> >,
Jakob Stoklund Olesen3b2966d2010-12-18 03:04:14 +0000181 MachineInstr *LoadMI = 0);
Mark Lacey9d8103d2013-08-14 23:50:16 +0000182 void insertReload(unsigned VReg, SlotIndex, MachineBasicBlock::iterator MI);
183 void insertSpill(unsigned VReg, bool isKill, MachineBasicBlock::iterator MI);
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +0000184
185 void spillAroundUses(unsigned Reg);
Jakob Stoklund Olesene991f722011-03-29 21:20:19 +0000186 void spillAll();
Jakob Stoklund Olesenf8889112010-06-29 23:58:39 +0000187};
188}
189
190namespace llvm {
Jakob Stoklund Olesen0fef9dd2010-07-20 23:50:15 +0000191Spiller *createInlineSpiller(MachineFunctionPass &pass,
192 MachineFunction &mf,
193 VirtRegMap &vrm) {
194 return new InlineSpiller(pass, mf, vrm);
Jakob Stoklund Olesenf8889112010-06-29 23:58:39 +0000195}
196}
197
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +0000198//===----------------------------------------------------------------------===//
199// Snippets
200//===----------------------------------------------------------------------===//
201
202// When spilling a virtual register, we also spill any snippets it is connected
203// to. The snippets are small live ranges that only have a single real use,
204// leftovers from live range splitting. Spilling them enables memory operand
205// folding or tightens the live range around the single use.
206//
207// This minimizes register pressure and maximizes the store-to-load distance for
208// spill slots which can be important in tight loops.
209
210/// isFullCopyOf - If MI is a COPY to or from Reg, return the other register,
211/// otherwise return 0.
212static unsigned isFullCopyOf(const MachineInstr *MI, unsigned Reg) {
Rafael Espindola070f96c2011-06-30 21:15:52 +0000213 if (!MI->isFullCopy())
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +0000214 return 0;
215 if (MI->getOperand(0).getReg() == Reg)
216 return MI->getOperand(1).getReg();
217 if (MI->getOperand(1).getReg() == Reg)
218 return MI->getOperand(0).getReg();
219 return 0;
220}
221
222/// isSnippet - Identify if a live interval is a snippet that should be spilled.
223/// It is assumed that SnipLI is a virtual register with the same original as
Jakob Stoklund Olesena00bab22011-03-14 19:56:43 +0000224/// Edit->getReg().
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +0000225bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
Jakob Stoklund Olesena00bab22011-03-14 19:56:43 +0000226 unsigned Reg = Edit->getReg();
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +0000227
228 // A snippet is a tiny live range with only a single instruction using it
229 // besides copies to/from Reg or spills/fills. We accept:
230 //
231 // %snip = COPY %Reg / FILL fi#
232 // %snip = USE %snip
233 // %Reg = COPY %snip / SPILL %snip, fi#
234 //
Jakob Stoklund Olesena00bab22011-03-14 19:56:43 +0000235 if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI))
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +0000236 return false;
237
238 MachineInstr *UseMI = 0;
239
240 // Check that all uses satisfy our criteria.
Owen Andersonabb90c92014-03-13 06:02:25 +0000241 for (MachineRegisterInfo::reg_instr_nodbg_iterator
242 RI = MRI.reg_instr_nodbg_begin(SnipLI.reg),
243 E = MRI.reg_instr_nodbg_end(); RI != E; ) {
244 MachineInstr *MI = &*(RI++);
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +0000245
246 // Allow copies to/from Reg.
247 if (isFullCopyOf(MI, Reg))
248 continue;
249
250 // Allow stack slot loads.
251 int FI;
Jakob Stoklund Olesena00bab22011-03-14 19:56:43 +0000252 if (SnipLI.reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +0000253 continue;
254
255 // Allow stack slot stores.
Jakob Stoklund Olesena00bab22011-03-14 19:56:43 +0000256 if (SnipLI.reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +0000257 continue;
258
259 // Allow a single additional instruction.
260 if (UseMI && MI != UseMI)
261 return false;
262 UseMI = MI;
263 }
264 return true;
265}
266
267/// collectRegsToSpill - Collect live range snippets that only have a single
268/// real use.
269void InlineSpiller::collectRegsToSpill() {
Jakob Stoklund Olesena00bab22011-03-14 19:56:43 +0000270 unsigned Reg = Edit->getReg();
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +0000271
272 // Main register always spills.
273 RegsToSpill.assign(1, Reg);
274 SnippetCopies.clear();
275
276 // Snippets all have the same original, so there can't be any for an original
277 // register.
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000278 if (Original == Reg)
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +0000279 return;
280
Owen Andersonabb90c92014-03-13 06:02:25 +0000281 for (MachineRegisterInfo::reg_instr_iterator
282 RI = MRI.reg_instr_begin(Reg), E = MRI.reg_instr_end(); RI != E; ) {
283 MachineInstr *MI = &*(RI++);
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +0000284 unsigned SnipReg = isFullCopyOf(MI, Reg);
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +0000285 if (!isSibling(SnipReg))
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +0000286 continue;
Jakob Stoklund Olesena00bab22011-03-14 19:56:43 +0000287 LiveInterval &SnipLI = LIS.getInterval(SnipReg);
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +0000288 if (!isSnippet(SnipLI))
289 continue;
290 SnippetCopies.insert(MI);
Jakob Stoklund Olesenc5a8c082011-05-05 17:22:53 +0000291 if (isRegToSpill(SnipReg))
292 continue;
293 RegsToSpill.push_back(SnipReg);
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +0000294 DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n');
Jakob Stoklund Olesenc5a8c082011-05-05 17:22:53 +0000295 ++NumSnippets;
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +0000296 }
297}
298
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000299
300//===----------------------------------------------------------------------===//
301// Sibling Values
302//===----------------------------------------------------------------------===//
303
304// After live range splitting, some values to be spilled may be defined by
305// copies from sibling registers. We trace the sibling copies back to the
306// original value if it still exists. We need it for rematerialization.
307//
308// Even when the value can't be rematerialized, we still want to determine if
309// the value has already been spilled, or we may want to hoist the spill from a
310// loop.
311
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +0000312bool InlineSpiller::isSibling(unsigned Reg) {
313 return TargetRegisterInfo::isVirtualRegister(Reg) &&
314 VRM.getOriginal(Reg) == Original;
315}
316
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000317#ifndef NDEBUG
318static raw_ostream &operator<<(raw_ostream &OS,
319 const InlineSpiller::SibValueInfo &SVI) {
320 OS << "spill " << PrintReg(SVI.SpillReg) << ':'
321 << SVI.SpillVNI->id << '@' << SVI.SpillVNI->def;
322 if (SVI.SpillMBB)
323 OS << " in BB#" << SVI.SpillMBB->getNumber();
324 if (SVI.AllDefsAreReloads)
325 OS << " all-reloads";
326 if (SVI.DefByOrigPHI)
327 OS << " orig-phi";
Jakob Stoklund Olesene8339b22011-09-16 00:03:33 +0000328 if (SVI.KillsSource)
329 OS << " kill";
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000330 OS << " deps[";
331 for (unsigned i = 0, e = SVI.Deps.size(); i != e; ++i)
332 OS << ' ' << SVI.Deps[i]->id << '@' << SVI.Deps[i]->def;
333 OS << " ]";
334 if (SVI.DefMI)
335 OS << " def: " << *SVI.DefMI;
336 else
337 OS << '\n';
338 return OS;
339}
340#endif
341
342/// propagateSiblingValue - Propagate the value in SVI to dependents if it is
343/// known. Otherwise remember the dependency for later.
344///
Benjamin Kramerbc6666b2013-05-23 15:42:57 +0000345/// @param SVIIter SibValues entry to propagate.
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000346/// @param VNI Dependent value, or NULL to propagate to all saved dependents.
Benjamin Kramerbc6666b2013-05-23 15:42:57 +0000347void InlineSpiller::propagateSiblingValue(SibValueMap::iterator SVIIter,
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000348 VNInfo *VNI) {
Benjamin Kramerbc6666b2013-05-23 15:42:57 +0000349 SibValueMap::value_type *SVI = &*SVIIter;
350
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000351 // When VNI is non-NULL, add it to SVI's deps, and only propagate to that.
352 TinyPtrVector<VNInfo*> FirstDeps;
353 if (VNI) {
354 FirstDeps.push_back(VNI);
355 SVI->second.Deps.push_back(VNI);
356 }
357
358 // Has the value been completely determined yet? If not, defer propagation.
359 if (!SVI->second.hasDef())
360 return;
361
Benjamin Kramerbc6666b2013-05-23 15:42:57 +0000362 // Work list of values to propagate.
363 SmallSetVector<SibValueMap::value_type *, 8> WorkList;
364 WorkList.insert(SVI);
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000365
366 do {
367 SVI = WorkList.pop_back_val();
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000368 TinyPtrVector<VNInfo*> *Deps = VNI ? &FirstDeps : &SVI->second.Deps;
369 VNI = 0;
370
371 SibValueInfo &SV = SVI->second;
372 if (!SV.SpillMBB)
373 SV.SpillMBB = LIS.getMBBFromIndex(SV.SpillVNI->def);
374
375 DEBUG(dbgs() << " prop to " << Deps->size() << ": "
376 << SVI->first->id << '@' << SVI->first->def << ":\t" << SV);
377
378 assert(SV.hasDef() && "Propagating undefined value");
379
380 // Should this value be propagated as a preferred spill candidate? We don't
381 // propagate values of registers that are about to spill.
Jakob Stoklund Olesenbceb9e52011-09-15 21:06:00 +0000382 bool PropSpill = !DisableHoisting && !isRegToSpill(SV.SpillReg);
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000383 unsigned SpillDepth = ~0u;
384
385 for (TinyPtrVector<VNInfo*>::iterator DepI = Deps->begin(),
386 DepE = Deps->end(); DepI != DepE; ++DepI) {
387 SibValueMap::iterator DepSVI = SibValues.find(*DepI);
388 assert(DepSVI != SibValues.end() && "Dependent value not in SibValues");
389 SibValueInfo &DepSV = DepSVI->second;
390 if (!DepSV.SpillMBB)
391 DepSV.SpillMBB = LIS.getMBBFromIndex(DepSV.SpillVNI->def);
392
393 bool Changed = false;
394
395 // Propagate defining instruction.
396 if (!DepSV.hasDef()) {
397 Changed = true;
398 DepSV.DefMI = SV.DefMI;
399 DepSV.DefByOrigPHI = SV.DefByOrigPHI;
400 }
401
402 // Propagate AllDefsAreReloads. For PHI values, this computes an AND of
403 // all predecessors.
404 if (!SV.AllDefsAreReloads && DepSV.AllDefsAreReloads) {
405 Changed = true;
406 DepSV.AllDefsAreReloads = false;
407 }
408
409 // Propagate best spill value.
410 if (PropSpill && SV.SpillVNI != DepSV.SpillVNI) {
411 if (SV.SpillMBB == DepSV.SpillMBB) {
412 // DepSV is in the same block. Hoist when dominated.
Jakob Stoklund Olesene8339b22011-09-16 00:03:33 +0000413 if (DepSV.KillsSource && SV.SpillVNI->def < DepSV.SpillVNI->def) {
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000414 // This is an alternative def earlier in the same MBB.
415 // Hoist the spill as far as possible in SpillMBB. This can ease
416 // register pressure:
417 //
418 // x = def
419 // y = use x
420 // s = copy x
421 //
422 // Hoisting the spill of s to immediately after the def removes the
423 // interference between x and y:
424 //
425 // x = def
426 // spill x
427 // y = use x<kill>
428 //
Jakob Stoklund Olesene8339b22011-09-16 00:03:33 +0000429 // This hoist only helps when the DepSV copy kills its source.
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000430 Changed = true;
431 DepSV.SpillReg = SV.SpillReg;
432 DepSV.SpillVNI = SV.SpillVNI;
433 DepSV.SpillMBB = SV.SpillMBB;
434 }
435 } else {
436 // DepSV is in a different block.
437 if (SpillDepth == ~0u)
438 SpillDepth = Loops.getLoopDepth(SV.SpillMBB);
439
440 // Also hoist spills to blocks with smaller loop depth, but make sure
441 // that the new value dominates. Non-phi dependents are always
442 // dominated, phis need checking.
443 if ((Loops.getLoopDepth(DepSV.SpillMBB) > SpillDepth) &&
444 (!DepSVI->first->isPHIDef() ||
445 MDT.dominates(SV.SpillMBB, DepSV.SpillMBB))) {
446 Changed = true;
447 DepSV.SpillReg = SV.SpillReg;
448 DepSV.SpillVNI = SV.SpillVNI;
449 DepSV.SpillMBB = SV.SpillMBB;
450 }
451 }
452 }
453
454 if (!Changed)
455 continue;
456
457 // Something changed in DepSVI. Propagate to dependents.
Benjamin Kramerbc6666b2013-05-23 15:42:57 +0000458 WorkList.insert(&*DepSVI);
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000459
460 DEBUG(dbgs() << " update " << DepSVI->first->id << '@'
461 << DepSVI->first->def << " to:\t" << DepSV);
462 }
463 } while (!WorkList.empty());
464}
465
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000466/// traceSiblingValue - Trace a value that is about to be spilled back to the
467/// real defining instructions by looking through sibling copies. Always stay
468/// within the range of OrigVNI so the registers are known to carry the same
469/// value.
470///
471/// Determine if the value is defined by all reloads, so spilling isn't
472/// necessary - the value is already in the stack slot.
473///
Jakob Stoklund Olesend8af5292011-03-29 03:12:02 +0000474/// Return a defining instruction that may be a candidate for rematerialization.
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000475///
Jakob Stoklund Olesend8af5292011-03-29 03:12:02 +0000476MachineInstr *InlineSpiller::traceSiblingValue(unsigned UseReg, VNInfo *UseVNI,
477 VNInfo *OrigVNI) {
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000478 // Check if a cached value already exists.
479 SibValueMap::iterator SVI;
480 bool Inserted;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000481 std::tie(SVI, Inserted) =
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000482 SibValues.insert(std::make_pair(UseVNI, SibValueInfo(UseReg, UseVNI)));
483 if (!Inserted) {
484 DEBUG(dbgs() << "Cached value " << PrintReg(UseReg) << ':'
485 << UseVNI->id << '@' << UseVNI->def << ' ' << SVI->second);
486 return SVI->second.DefMI;
487 }
488
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000489 DEBUG(dbgs() << "Tracing value " << PrintReg(UseReg) << ':'
490 << UseVNI->id << '@' << UseVNI->def << '\n');
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000491
492 // List of (Reg, VNI) that have been inserted into SibValues, but need to be
493 // processed.
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +0000494 SmallVector<std::pair<unsigned, VNInfo*>, 8> WorkList;
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000495 WorkList.push_back(std::make_pair(UseReg, UseVNI));
496
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000497 do {
498 unsigned Reg;
499 VNInfo *VNI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000500 std::tie(Reg, VNI) = WorkList.pop_back_val();
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000501 DEBUG(dbgs() << " " << PrintReg(Reg) << ':' << VNI->id << '@' << VNI->def
502 << ":\t");
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000503
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000504 // First check if this value has already been computed.
505 SVI = SibValues.find(VNI);
506 assert(SVI != SibValues.end() && "Missing SibValues entry");
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000507
508 // Trace through PHI-defs created by live range splitting.
509 if (VNI->isPHIDef()) {
Jakob Stoklund Olesen07b35032011-09-15 16:41:12 +0000510 // Stop at original PHIs. We don't know the value at the predecessors.
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000511 if (VNI->def == OrigVNI->def) {
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000512 DEBUG(dbgs() << "orig phi value\n");
513 SVI->second.DefByOrigPHI = true;
514 SVI->second.AllDefsAreReloads = false;
515 propagateSiblingValue(SVI);
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000516 continue;
517 }
Jakob Stoklund Olesen07b35032011-09-15 16:41:12 +0000518
519 // This is a PHI inserted by live range splitting. We could trace the
520 // live-out value from predecessor blocks, but that search can be very
521 // expensive if there are many predecessors and many more PHIs as
522 // generated by tail-dup when it sees an indirectbr. Instead, look at
523 // all the non-PHI defs that have the same value as OrigVNI. They must
524 // jointly dominate VNI->def. This is not optimal since VNI may actually
525 // be jointly dominated by a smaller subset of defs, so there is a change
526 // we will miss a AllDefsAreReloads optimization.
527
528 // Separate all values dominated by OrigVNI into PHIs and non-PHIs.
529 SmallVector<VNInfo*, 8> PHIs, NonPHIs;
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000530 LiveInterval &LI = LIS.getInterval(Reg);
Jakob Stoklund Olesen07b35032011-09-15 16:41:12 +0000531 LiveInterval &OrigLI = LIS.getInterval(Original);
532
533 for (LiveInterval::vni_iterator VI = LI.vni_begin(), VE = LI.vni_end();
534 VI != VE; ++VI) {
535 VNInfo *VNI2 = *VI;
536 if (VNI2->isUnused())
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000537 continue;
Jakob Stoklund Olesen07b35032011-09-15 16:41:12 +0000538 if (!OrigLI.containsOneValue() &&
539 OrigLI.getVNInfoAt(VNI2->def) != OrigVNI)
540 continue;
541 if (VNI2->isPHIDef() && VNI2->def != OrigVNI->def)
542 PHIs.push_back(VNI2);
543 else
544 NonPHIs.push_back(VNI2);
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000545 }
Jakob Stoklund Olesen07b35032011-09-15 16:41:12 +0000546 DEBUG(dbgs() << "split phi value, checking " << PHIs.size()
547 << " phi-defs, and " << NonPHIs.size()
548 << " non-phi/orig defs\n");
549
550 // Create entries for all the PHIs. Don't add them to the worklist, we
551 // are processing all of them in one go here.
552 for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
553 SibValues.insert(std::make_pair(PHIs[i], SibValueInfo(Reg, PHIs[i])));
554
555 // Add every PHI as a dependent of all the non-PHIs.
556 for (unsigned i = 0, e = NonPHIs.size(); i != e; ++i) {
557 VNInfo *NonPHI = NonPHIs[i];
558 // Known value? Try an insertion.
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000559 std::tie(SVI, Inserted) =
Jakob Stoklund Olesen07b35032011-09-15 16:41:12 +0000560 SibValues.insert(std::make_pair(NonPHI, SibValueInfo(Reg, NonPHI)));
561 // Add all the PHIs as dependents of NonPHI.
562 for (unsigned pi = 0, pe = PHIs.size(); pi != pe; ++pi)
563 SVI->second.Deps.push_back(PHIs[pi]);
564 // This is the first time we see NonPHI, add it to the worklist.
565 if (Inserted)
566 WorkList.push_back(std::make_pair(Reg, NonPHI));
567 else
568 // Propagate to all inserted PHIs, not just VNI.
569 propagateSiblingValue(SVI);
570 }
571
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000572 // Next work list item.
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000573 continue;
574 }
575
576 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
577 assert(MI && "Missing def");
578
579 // Trace through sibling copies.
580 if (unsigned SrcReg = isFullCopyOf(MI, Reg)) {
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +0000581 if (isSibling(SrcReg)) {
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000582 LiveInterval &SrcLI = LIS.getInterval(SrcReg);
Matthias Braun88dd0ab2013-10-10 21:28:52 +0000583 LiveQueryResult SrcQ = SrcLI.Query(VNI->def);
Jakob Stoklund Olesen2aeead42012-05-20 02:44:33 +0000584 assert(SrcQ.valueIn() && "Copy from non-existing value");
Jakob Stoklund Olesene8339b22011-09-16 00:03:33 +0000585 // Check if this COPY kills its source.
Jakob Stoklund Olesen2aeead42012-05-20 02:44:33 +0000586 SVI->second.KillsSource = SrcQ.isKill();
587 VNInfo *SrcVNI = SrcQ.valueIn();
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000588 DEBUG(dbgs() << "copy of " << PrintReg(SrcReg) << ':'
Jakob Stoklund Olesene8339b22011-09-16 00:03:33 +0000589 << SrcVNI->id << '@' << SrcVNI->def
590 << " kill=" << unsigned(SVI->second.KillsSource) << '\n');
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000591 // Known sibling source value? Try an insertion.
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000592 std::tie(SVI, Inserted) = SibValues.insert(
593 std::make_pair(SrcVNI, SibValueInfo(SrcReg, SrcVNI)));
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000594 // This is the first time we see Src, add it to the worklist.
595 if (Inserted)
596 WorkList.push_back(std::make_pair(SrcReg, SrcVNI));
597 propagateSiblingValue(SVI, VNI);
598 // Next work list item.
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000599 continue;
600 }
601 }
602
603 // Track reachable reloads.
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000604 SVI->second.DefMI = MI;
605 SVI->second.SpillMBB = MI->getParent();
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000606 int FI;
607 if (Reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot) {
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000608 DEBUG(dbgs() << "reload\n");
609 propagateSiblingValue(SVI);
610 // Next work list item.
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000611 continue;
612 }
613
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000614 // Potential remat candidate.
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000615 DEBUG(dbgs() << "def " << *MI);
616 SVI->second.AllDefsAreReloads = false;
617 propagateSiblingValue(SVI);
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000618 } while (!WorkList.empty());
619
Logan Chien64f361e2012-09-01 12:11:41 +0000620 // Look up the value we were looking for. We already did this lookup at the
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000621 // top of the function, but SibValues may have been invalidated.
622 SVI = SibValues.find(UseVNI);
623 assert(SVI != SibValues.end() && "Didn't compute requested info");
624 DEBUG(dbgs() << " traced to:\t" << SVI->second);
625 return SVI->second.DefMI;
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000626}
627
628/// analyzeSiblingValues - Trace values defined by sibling copies back to
629/// something that isn't a sibling copy.
Jakob Stoklund Olesend8af5292011-03-29 03:12:02 +0000630///
631/// Keep track of values that may be rematerializable.
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000632void InlineSpiller::analyzeSiblingValues() {
633 SibValues.clear();
634
635 // No siblings at all?
636 if (Edit->getReg() == Original)
637 return;
638
639 LiveInterval &OrigLI = LIS.getInterval(Original);
640 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
641 unsigned Reg = RegsToSpill[i];
642 LiveInterval &LI = LIS.getInterval(Reg);
643 for (LiveInterval::const_vni_iterator VI = LI.vni_begin(),
644 VE = LI.vni_end(); VI != VE; ++VI) {
645 VNInfo *VNI = *VI;
Jakob Stoklund Olesend8af5292011-03-29 03:12:02 +0000646 if (VNI->isUnused())
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000647 continue;
Jakob Stoklund Olesend8af5292011-03-29 03:12:02 +0000648 MachineInstr *DefMI = 0;
Jakob Stoklund Olesenad6b22e2012-02-04 05:20:49 +0000649 if (!VNI->isPHIDef()) {
650 DefMI = LIS.getInstructionFromIndex(VNI->def);
651 assert(DefMI && "No defining instruction");
652 }
Jakob Stoklund Olesend8af5292011-03-29 03:12:02 +0000653 // Check possible sibling copies.
Jakob Stoklund Olesenad6b22e2012-02-04 05:20:49 +0000654 if (VNI->isPHIDef() || DefMI->isCopy()) {
Jakob Stoklund Olesend8af5292011-03-29 03:12:02 +0000655 VNInfo *OrigVNI = OrigLI.getVNInfoAt(VNI->def);
Jakob Stoklund Olesenbbad3bc2011-07-05 15:38:41 +0000656 assert(OrigVNI && "Def outside original live range");
Jakob Stoklund Olesend8af5292011-03-29 03:12:02 +0000657 if (OrigVNI->def != VNI->def)
658 DefMI = traceSiblingValue(Reg, VNI, OrigVNI);
659 }
Pete Cooper2bde2f42012-04-02 22:22:53 +0000660 if (DefMI && Edit->checkRematerializable(VNI, DefMI, AA)) {
Jakob Stoklund Olesen86e53ce2011-04-20 22:14:20 +0000661 DEBUG(dbgs() << "Value " << PrintReg(Reg) << ':' << VNI->id << '@'
662 << VNI->def << " may remat from " << *DefMI);
663 }
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +0000664 }
665 }
666}
667
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +0000668/// hoistSpill - Given a sibling copy that defines a value to be spilled, insert
669/// a spill at a better location.
670bool InlineSpiller::hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI) {
671 SlotIndex Idx = LIS.getInstructionIndex(CopyMI);
Jakob Stoklund Olesen90b5e562011-11-13 20:45:27 +0000672 VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getRegSlot());
673 assert(VNI && VNI->def == Idx.getRegSlot() && "Not defined by copy");
Jakob Stoklund Olesenec9b4a62011-04-30 06:42:21 +0000674 SibValueMap::iterator I = SibValues.find(VNI);
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +0000675 if (I == SibValues.end())
676 return false;
677
678 const SibValueInfo &SVI = I->second;
679
680 // Let the normal folding code deal with the boring case.
681 if (!SVI.AllDefsAreReloads && SVI.SpillVNI == VNI)
682 return false;
683
Jakob Stoklund Olesenec9b4a62011-04-30 06:42:21 +0000684 // SpillReg may have been deleted by remat and DCE.
685 if (!LIS.hasInterval(SVI.SpillReg)) {
686 DEBUG(dbgs() << "Stale interval: " << PrintReg(SVI.SpillReg) << '\n');
687 SibValues.erase(I);
688 return false;
689 }
690
691 LiveInterval &SibLI = LIS.getInterval(SVI.SpillReg);
692 if (!SibLI.containsValue(SVI.SpillVNI)) {
693 DEBUG(dbgs() << "Stale value: " << PrintReg(SVI.SpillReg) << '\n');
694 SibValues.erase(I);
695 return false;
696 }
697
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +0000698 // Conservatively extend the stack slot range to the range of the original
699 // value. We may be able to do better with stack slot coloring by being more
700 // careful here.
Jakob Stoklund Olesene4663452011-03-26 22:16:41 +0000701 assert(StackInt && "No stack slot assigned yet.");
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +0000702 LiveInterval &OrigLI = LIS.getInterval(Original);
703 VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
Jakob Stoklund Olesene4663452011-03-26 22:16:41 +0000704 StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0));
Jakob Stoklund Olesen86985072011-03-19 23:02:47 +0000705 DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
Jakob Stoklund Olesene4663452011-03-26 22:16:41 +0000706 << *StackInt << '\n');
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +0000707
708 // Already spilled everywhere.
Jakob Stoklund Olesenc5a8c082011-05-05 17:22:53 +0000709 if (SVI.AllDefsAreReloads) {
Jakob Stoklund Olesen278bf022011-09-09 18:11:41 +0000710 DEBUG(dbgs() << "\tno spill needed: " << SVI);
Jakob Stoklund Olesenc5a8c082011-05-05 17:22:53 +0000711 ++NumOmitReloadSpill;
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +0000712 return true;
Jakob Stoklund Olesenc5a8c082011-05-05 17:22:53 +0000713 }
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +0000714 // We are going to spill SVI.SpillVNI immediately after its def, so clear out
715 // any later spills of the same value.
Jakob Stoklund Olesenec9b4a62011-04-30 06:42:21 +0000716 eliminateRedundantSpills(SibLI, SVI.SpillVNI);
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +0000717
718 MachineBasicBlock *MBB = LIS.getMBBFromIndex(SVI.SpillVNI->def);
719 MachineBasicBlock::iterator MII;
720 if (SVI.SpillVNI->isPHIDef())
721 MII = MBB->SkipPHIsAndLabels(MBB->begin());
722 else {
Jakob Stoklund Olesenec9b4a62011-04-30 06:42:21 +0000723 MachineInstr *DefMI = LIS.getInstructionFromIndex(SVI.SpillVNI->def);
724 assert(DefMI && "Defining instruction disappeared");
725 MII = DefMI;
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +0000726 ++MII;
727 }
728 // Insert spill without kill flag immediately after def.
Jakob Stoklund Olesene4663452011-03-26 22:16:41 +0000729 TII.storeRegToStackSlot(*MBB, MII, SVI.SpillReg, false, StackSlot,
730 MRI.getRegClass(SVI.SpillReg), &TRI);
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +0000731 --MII; // Point to store instruction.
732 LIS.InsertMachineInstrInMaps(MII);
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +0000733 DEBUG(dbgs() << "\thoisted: " << SVI.SpillVNI->def << '\t' << *MII);
Jakob Stoklund Olesenc5a8c082011-05-05 17:22:53 +0000734
Jakob Stoklund Olesen37eb6962011-09-15 17:54:28 +0000735 ++NumSpills;
736 ++NumHoists;
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +0000737 return true;
738}
739
Jakob Stoklund Olesen39488642011-03-20 05:44:55 +0000740/// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any
741/// redundant spills of this value in SLI.reg and sibling copies.
742void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
Jakob Stoklund Olesene55003f2011-03-20 05:44:58 +0000743 assert(VNI && "Missing value");
Jakob Stoklund Olesen39488642011-03-20 05:44:55 +0000744 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
745 WorkList.push_back(std::make_pair(&SLI, VNI));
Jakob Stoklund Olesene4663452011-03-26 22:16:41 +0000746 assert(StackInt && "No stack slot assigned yet.");
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +0000747
748 do {
Jakob Stoklund Olesen39488642011-03-20 05:44:55 +0000749 LiveInterval *LI;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000750 std::tie(LI, VNI) = WorkList.pop_back_val();
Jakob Stoklund Olesen39488642011-03-20 05:44:55 +0000751 unsigned Reg = LI->reg;
Jakob Stoklund Olesenec9b4a62011-04-30 06:42:21 +0000752 DEBUG(dbgs() << "Checking redundant spills for "
753 << VNI->id << '@' << VNI->def << " in " << *LI << '\n');
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +0000754
755 // Regs to spill are taken care of.
756 if (isRegToSpill(Reg))
757 continue;
758
759 // Add all of VNI's live range to StackInt.
Jakob Stoklund Olesene4663452011-03-26 22:16:41 +0000760 StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0));
761 DEBUG(dbgs() << "Merged to stack int: " << *StackInt << '\n');
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +0000762
763 // Find all spills and copies of VNI.
Owen Andersonabb90c92014-03-13 06:02:25 +0000764 for (MachineRegisterInfo::use_instr_nodbg_iterator
765 UI = MRI.use_instr_nodbg_begin(Reg), E = MRI.use_instr_nodbg_end();
766 UI != E; ) {
767 MachineInstr *MI = &*(UI++);
Evan Cheng7f8e5632011-12-07 07:15:52 +0000768 if (!MI->isCopy() && !MI->mayStore())
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +0000769 continue;
770 SlotIndex Idx = LIS.getInstructionIndex(MI);
Jakob Stoklund Olesen39488642011-03-20 05:44:55 +0000771 if (LI->getVNInfoAt(Idx) != VNI)
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +0000772 continue;
773
774 // Follow sibling copies down the dominator tree.
775 if (unsigned DstReg = isFullCopyOf(MI, Reg)) {
776 if (isSibling(DstReg)) {
777 LiveInterval &DstLI = LIS.getInterval(DstReg);
Jakob Stoklund Olesen90b5e562011-11-13 20:45:27 +0000778 VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getRegSlot());
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +0000779 assert(DstVNI && "Missing defined value");
Jakob Stoklund Olesen90b5e562011-11-13 20:45:27 +0000780 assert(DstVNI->def == Idx.getRegSlot() && "Wrong copy def slot");
Jakob Stoklund Olesen39488642011-03-20 05:44:55 +0000781 WorkList.push_back(std::make_pair(&DstLI, DstVNI));
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +0000782 }
783 continue;
784 }
785
786 // Erase spills.
787 int FI;
788 if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) {
789 DEBUG(dbgs() << "Redundant spill " << Idx << '\t' << *MI);
790 // eliminateDeadDefs won't normally remove stores, so switch opcode.
791 MI->setDesc(TII.get(TargetOpcode::KILL));
792 DeadDefs.push_back(MI);
Jakob Stoklund Olesen37eb6962011-09-15 17:54:28 +0000793 ++NumSpillsRemoved;
794 --NumSpills;
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +0000795 }
796 }
797 } while (!WorkList.empty());
798}
799
Jakob Stoklund Olesen2edaa2f2010-10-20 22:00:51 +0000800
Jakob Stoklund Olesend8af5292011-03-29 03:12:02 +0000801//===----------------------------------------------------------------------===//
802// Rematerialization
803//===----------------------------------------------------------------------===//
804
805/// markValueUsed - Remember that VNI failed to rematerialize, so its defining
806/// instruction cannot be eliminated. See through snippet copies
807void InlineSpiller::markValueUsed(LiveInterval *LI, VNInfo *VNI) {
808 SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
809 WorkList.push_back(std::make_pair(LI, VNI));
810 do {
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000811 std::tie(LI, VNI) = WorkList.pop_back_val();
Jakob Stoklund Olesend8af5292011-03-29 03:12:02 +0000812 if (!UsedValues.insert(VNI))
813 continue;
814
815 if (VNI->isPHIDef()) {
816 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
817 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
818 PE = MBB->pred_end(); PI != PE; ++PI) {
Jakob Stoklund Olesend7bcf432011-11-14 01:39:36 +0000819 VNInfo *PVNI = LI->getVNInfoBefore(LIS.getMBBEndIdx(*PI));
Jakob Stoklund Olesend8af5292011-03-29 03:12:02 +0000820 if (PVNI)
821 WorkList.push_back(std::make_pair(LI, PVNI));
822 }
823 continue;
824 }
825
826 // Follow snippet copies.
827 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
828 if (!SnippetCopies.count(MI))
829 continue;
830 LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg());
831 assert(isRegToSpill(SnipLI.reg) && "Unexpected register in copy");
Jakob Stoklund Olesen90b5e562011-11-13 20:45:27 +0000832 VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getRegSlot(true));
Jakob Stoklund Olesend8af5292011-03-29 03:12:02 +0000833 assert(SnipVNI && "Snippet undefined before copy");
834 WorkList.push_back(std::make_pair(&SnipLI, SnipVNI));
835 } while (!WorkList.empty());
836}
837
838/// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
839bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg,
840 MachineBasicBlock::iterator MI) {
Jakob Stoklund Olesen90b5e562011-11-13 20:45:27 +0000841 SlotIndex UseIdx = LIS.getInstructionIndex(MI).getRegSlot(true);
Jakob Stoklund Olesenc0dd3da2011-07-18 05:31:59 +0000842 VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx.getBaseIndex());
Jakob Stoklund Olesend8af5292011-03-29 03:12:02 +0000843
844 if (!ParentVNI) {
Jakob Stoklund Olesen96037182010-07-02 17:44:57 +0000845 DEBUG(dbgs() << "\tadding <undef> flags: ");
846 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
847 MachineOperand &MO = MI->getOperand(i);
Jakob Stoklund Olesen0ed9ebc2011-03-29 17:47:02 +0000848 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg)
Jakob Stoklund Olesen96037182010-07-02 17:44:57 +0000849 MO.setIsUndef();
850 }
851 DEBUG(dbgs() << UseIdx << '\t' << *MI);
852 return true;
853 }
Jakob Stoklund Olesen2edaa2f2010-10-20 22:00:51 +0000854
Jakob Stoklund Olesend8af5292011-03-29 03:12:02 +0000855 if (SnippetCopies.count(MI))
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +0000856 return false;
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +0000857
Jakob Stoklund Olesend8af5292011-03-29 03:12:02 +0000858 // Use an OrigVNI from traceSiblingValue when ParentVNI is a sibling copy.
859 LiveRangeEdit::Remat RM(ParentVNI);
860 SibValueMap::const_iterator SibI = SibValues.find(ParentVNI);
861 if (SibI != SibValues.end())
862 RM.OrigMI = SibI->second.DefMI;
Pete Cooper2bde2f42012-04-02 22:22:53 +0000863 if (!Edit->canRematerializeAt(RM, UseIdx, false)) {
Jakob Stoklund Olesend8af5292011-03-29 03:12:02 +0000864 markValueUsed(&VirtReg, ParentVNI);
Jakob Stoklund Olesen96037182010-07-02 17:44:57 +0000865 DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
866 return false;
867 }
868
Jakob Stoklund Olesen0ed9ebc2011-03-29 17:47:02 +0000869 // If the instruction also writes VirtReg.reg, it had better not require the
870 // same register for uses and defs.
Jakob Stoklund Olesenabe8c092012-03-01 01:43:25 +0000871 SmallVector<std::pair<MachineInstr*, unsigned>, 8> Ops;
James Molloy381fab92012-09-12 10:03:31 +0000872 MIBundleOperands::VirtRegInfo RI =
Jakob Stoklund Olesenabe8c092012-03-01 01:43:25 +0000873 MIBundleOperands(MI).analyzeVirtReg(VirtReg.reg, &Ops);
874 if (RI.Tied) {
875 markValueUsed(&VirtReg, ParentVNI);
876 DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
877 return false;
Jakob Stoklund Olesen96037182010-07-02 17:44:57 +0000878 }
879
Jakob Stoklund Olesen3b2966d2010-12-18 03:04:14 +0000880 // Before rematerializing into a register for a single instruction, try to
881 // fold a load into the instruction. That avoids allocating a new register.
Evan Cheng7f8e5632011-12-07 07:15:52 +0000882 if (RM.OrigMI->canFoldAsLoad() &&
Jakob Stoklund Olesenabe8c092012-03-01 01:43:25 +0000883 foldMemoryOperand(Ops, RM.OrigMI)) {
Jakob Stoklund Olesena00bab22011-03-14 19:56:43 +0000884 Edit->markRematerialized(RM.ParentVNI);
Jakob Stoklund Olesenc5a8c082011-05-05 17:22:53 +0000885 ++NumFoldedLoads;
Jakob Stoklund Olesen3b2966d2010-12-18 03:04:14 +0000886 return true;
887 }
888
Jakob Stoklund Olesen96037182010-07-02 17:44:57 +0000889 // Alocate a new register for the remat.
Mark Lacey9d8103d2013-08-14 23:50:16 +0000890 unsigned NewVReg = Edit->createFrom(Original);
Jakob Stoklund Olesen96037182010-07-02 17:44:57 +0000891
892 // Finally we can rematerialize OrigMI before MI.
Mark Lacey9d8103d2013-08-14 23:50:16 +0000893 SlotIndex DefIdx = Edit->rematerializeAt(*MI->getParent(), MI, NewVReg, RM,
Pete Cooper2bde2f42012-04-02 22:22:53 +0000894 TRI);
Mark Lacey9d8103d2013-08-14 23:50:16 +0000895 (void)DefIdx;
Jakob Stoklund Olesenc6a20412011-02-08 19:33:55 +0000896 DEBUG(dbgs() << "\tremat: " << DefIdx << '\t'
Jakob Stoklund Olesena00bab22011-03-14 19:56:43 +0000897 << *LIS.getInstructionFromIndex(DefIdx));
Jakob Stoklund Olesen96037182010-07-02 17:44:57 +0000898
899 // Replace operands
900 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
Jakob Stoklund Olesenabe8c092012-03-01 01:43:25 +0000901 MachineOperand &MO = MI->getOperand(Ops[i].second);
Jakob Stoklund Olesen0ed9ebc2011-03-29 17:47:02 +0000902 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg) {
Mark Lacey9d8103d2013-08-14 23:50:16 +0000903 MO.setReg(NewVReg);
Jakob Stoklund Olesen96037182010-07-02 17:44:57 +0000904 MO.setIsKill();
905 }
906 }
Mark Lacey9d8103d2013-08-14 23:50:16 +0000907 DEBUG(dbgs() << "\t " << UseIdx << '\t' << *MI << '\n');
Jakob Stoklund Olesen96037182010-07-02 17:44:57 +0000908
Jakob Stoklund Olesenc5a8c082011-05-05 17:22:53 +0000909 ++NumRemats;
Jakob Stoklund Olesenbde96ad2010-06-30 23:03:52 +0000910 return true;
911}
912
Jakob Stoklund Olesen72911e42010-10-14 23:49:52 +0000913/// reMaterializeAll - Try to rematerialize as many uses as possible,
Jakob Stoklund Olesen96037182010-07-02 17:44:57 +0000914/// and trim the live ranges after.
915void InlineSpiller::reMaterializeAll() {
Jakob Stoklund Olesend8af5292011-03-29 03:12:02 +0000916 // analyzeSiblingValues has already tested all relevant defining instructions.
Pete Cooper2bde2f42012-04-02 22:22:53 +0000917 if (!Edit->anyRematerializable(AA))
Jakob Stoklund Olesen96037182010-07-02 17:44:57 +0000918 return;
919
Jakob Stoklund Olesena00bab22011-03-14 19:56:43 +0000920 UsedValues.clear();
Jakob Stoklund Olesen2edaa2f2010-10-20 22:00:51 +0000921
Jakob Stoklund Olesend8af5292011-03-29 03:12:02 +0000922 // Try to remat before all uses of snippets.
Jakob Stoklund Olesen96037182010-07-02 17:44:57 +0000923 bool anyRemat = false;
Jakob Stoklund Olesend8af5292011-03-29 03:12:02 +0000924 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
925 unsigned Reg = RegsToSpill[i];
926 LiveInterval &LI = LIS.getInterval(Reg);
Owen Andersonabb90c92014-03-13 06:02:25 +0000927 for (MachineRegisterInfo::use_bundle_nodbg_iterator
928 RI = MRI.use_bundle_nodbg_begin(Reg), E = MRI.use_bundle_nodbg_end();
929 RI != E; ) {
930 MachineInstr *MI = &*(RI++);
Jakob Stoklund Olesend8af5292011-03-29 03:12:02 +0000931 anyRemat |= reMaterializeFor(LI, MI);
Owen Andersonabb90c92014-03-13 06:02:25 +0000932 }
Jakob Stoklund Olesend8af5292011-03-29 03:12:02 +0000933 }
Jakob Stoklund Olesen96037182010-07-02 17:44:57 +0000934 if (!anyRemat)
935 return;
936
937 // Remove any values that were completely rematted.
Jakob Stoklund Olesend8af5292011-03-29 03:12:02 +0000938 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
939 unsigned Reg = RegsToSpill[i];
940 LiveInterval &LI = LIS.getInterval(Reg);
941 for (LiveInterval::vni_iterator I = LI.vni_begin(), E = LI.vni_end();
942 I != E; ++I) {
943 VNInfo *VNI = *I;
Jakob Stoklund Olesenadd79c62011-03-29 17:47:00 +0000944 if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI))
Jakob Stoklund Olesencf6c5c92010-07-02 19:54:40 +0000945 continue;
Jakob Stoklund Olesend8af5292011-03-29 03:12:02 +0000946 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
947 MI->addRegisterDead(Reg, &TRI);
948 if (!MI->allDefsAreDead())
949 continue;
950 DEBUG(dbgs() << "All defs dead: " << *MI);
951 DeadDefs.push_back(MI);
Jakob Stoklund Olesencf6c5c92010-07-02 19:54:40 +0000952 }
Jakob Stoklund Olesen96037182010-07-02 17:44:57 +0000953 }
Jakob Stoklund Olesenadd79c62011-03-29 17:47:00 +0000954
955 // Eliminate dead code after remat. Note that some snippet copies may be
956 // deleted here.
957 if (DeadDefs.empty())
958 return;
959 DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n");
Pete Cooper2bde2f42012-04-02 22:22:53 +0000960 Edit->eliminateDeadDefs(DeadDefs, RegsToSpill);
Jakob Stoklund Olesenadd79c62011-03-29 17:47:00 +0000961
962 // Get rid of deleted and empty intervals.
Benjamin Kramer391f5a62013-05-05 11:29:14 +0000963 unsigned ResultPos = 0;
964 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
965 unsigned Reg = RegsToSpill[i];
966 if (!LIS.hasInterval(Reg))
967 continue;
968
969 LiveInterval &LI = LIS.getInterval(Reg);
970 if (LI.empty()) {
971 Edit->eraseVirtReg(Reg);
Jakob Stoklund Olesenadd79c62011-03-29 17:47:00 +0000972 continue;
973 }
Benjamin Kramer391f5a62013-05-05 11:29:14 +0000974
975 RegsToSpill[ResultPos++] = Reg;
Jakob Stoklund Olesenadd79c62011-03-29 17:47:00 +0000976 }
Benjamin Kramer391f5a62013-05-05 11:29:14 +0000977 RegsToSpill.erase(RegsToSpill.begin() + ResultPos, RegsToSpill.end());
Jakob Stoklund Olesenadd79c62011-03-29 17:47:00 +0000978 DEBUG(dbgs() << RegsToSpill.size() << " registers to spill after remat.\n");
Jakob Stoklund Olesen96037182010-07-02 17:44:57 +0000979}
980
Jakob Stoklund Olesene991f722011-03-29 21:20:19 +0000981
982//===----------------------------------------------------------------------===//
983// Spilling
984//===----------------------------------------------------------------------===//
985
Jakob Stoklund Olesena00bab22011-03-14 19:56:43 +0000986/// If MI is a load or store of StackSlot, it can be removed.
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +0000987bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, unsigned Reg) {
Jakob Stoklund Olesen7fd49052010-08-04 22:35:11 +0000988 int FI = 0;
Jakob Stoklund Olesen37eb6962011-09-15 17:54:28 +0000989 unsigned InstrReg = TII.isLoadFromStackSlot(MI, FI);
990 bool IsLoad = InstrReg;
991 if (!IsLoad)
992 InstrReg = TII.isStoreToStackSlot(MI, FI);
Jakob Stoklund Olesen7fd49052010-08-04 22:35:11 +0000993
994 // We have a stack access. Is it the right register and slot?
Jakob Stoklund Olesena00bab22011-03-14 19:56:43 +0000995 if (InstrReg != Reg || FI != StackSlot)
Jakob Stoklund Olesen7fd49052010-08-04 22:35:11 +0000996 return false;
997
998 DEBUG(dbgs() << "Coalescing stack access: " << *MI);
Jakob Stoklund Olesena00bab22011-03-14 19:56:43 +0000999 LIS.RemoveMachineInstrFromMaps(MI);
Jakob Stoklund Olesen7fd49052010-08-04 22:35:11 +00001000 MI->eraseFromParent();
Jakob Stoklund Olesen37eb6962011-09-15 17:54:28 +00001001
1002 if (IsLoad) {
1003 ++NumReloadsRemoved;
1004 --NumReloads;
1005 } else {
1006 ++NumSpillsRemoved;
1007 --NumSpills;
1008 }
1009
Jakob Stoklund Olesen7fd49052010-08-04 22:35:11 +00001010 return true;
1011}
1012
Mark Lacey9d8103d2013-08-14 23:50:16 +00001013#if !defined(NDEBUG)
1014// Dump the range of instructions from B to E with their slot indexes.
1015static void dumpMachineInstrRangeWithSlotIndex(MachineBasicBlock::iterator B,
1016 MachineBasicBlock::iterator E,
1017 LiveIntervals const &LIS,
1018 const char *const header,
1019 unsigned VReg =0) {
1020 char NextLine = '\n';
1021 char SlotIndent = '\t';
1022
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001023 if (std::next(B) == E) {
Mark Lacey9d8103d2013-08-14 23:50:16 +00001024 NextLine = ' ';
1025 SlotIndent = ' ';
1026 }
1027
1028 dbgs() << '\t' << header << ": " << NextLine;
1029
1030 for (MachineBasicBlock::iterator I = B; I != E; ++I) {
1031 SlotIndex Idx = LIS.getInstructionIndex(I).getRegSlot();
1032
1033 // If a register was passed in and this instruction has it as a
1034 // destination that is marked as an early clobber, print the
1035 // early-clobber slot index.
1036 if (VReg) {
1037 MachineOperand *MO = I->findRegisterDefOperand(VReg);
1038 if (MO && MO->isEarlyClobber())
1039 Idx = Idx.getRegSlot(true);
1040 }
1041
1042 dbgs() << SlotIndent << Idx << '\t' << *I;
1043 }
1044}
1045#endif
1046
Jakob Stoklund Olesenabe8c092012-03-01 01:43:25 +00001047/// foldMemoryOperand - Try folding stack slot references in Ops into their
1048/// instructions.
1049///
1050/// @param Ops Operand indices from analyzeVirtReg().
Jakob Stoklund Olesen3b2966d2010-12-18 03:04:14 +00001051/// @param LoadMI Load instruction to use instead of stack slot when non-null.
Jakob Stoklund Olesenabe8c092012-03-01 01:43:25 +00001052/// @return True on success.
1053bool InlineSpiller::
1054foldMemoryOperand(ArrayRef<std::pair<MachineInstr*, unsigned> > Ops,
1055 MachineInstr *LoadMI) {
1056 if (Ops.empty())
1057 return false;
1058 // Don't attempt folding in bundles.
1059 MachineInstr *MI = Ops.front().first;
1060 if (Ops.back().first != MI || MI->isBundled())
1061 return false;
1062
Jakob Stoklund Olesenc94c9672011-09-15 18:22:52 +00001063 bool WasCopy = MI->isCopy();
Jakob Stoklund Oleseneef48b62011-11-10 00:17:03 +00001064 unsigned ImpReg = 0;
1065
Andrew Trick10d5be42013-11-17 01:36:23 +00001066 bool SpillSubRegs = (MI->getOpcode() == TargetOpcode::PATCHPOINT ||
1067 MI->getOpcode() == TargetOpcode::STACKMAP);
1068
Jakob Stoklund Olesen8656a452010-07-01 00:13:04 +00001069 // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
1070 // operands.
1071 SmallVector<unsigned, 8> FoldOps;
1072 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
Jakob Stoklund Olesenabe8c092012-03-01 01:43:25 +00001073 unsigned Idx = Ops[i].second;
Jakob Stoklund Olesen8656a452010-07-01 00:13:04 +00001074 MachineOperand &MO = MI->getOperand(Idx);
Jakob Stoklund Oleseneef48b62011-11-10 00:17:03 +00001075 if (MO.isImplicit()) {
1076 ImpReg = MO.getReg();
Jakob Stoklund Olesen8656a452010-07-01 00:13:04 +00001077 continue;
Jakob Stoklund Oleseneef48b62011-11-10 00:17:03 +00001078 }
Jakob Stoklund Olesen8656a452010-07-01 00:13:04 +00001079 // FIXME: Teach targets to deal with subregs.
Andrew Trick10d5be42013-11-17 01:36:23 +00001080 if (!SpillSubRegs && MO.getSubReg())
Jakob Stoklund Olesen8656a452010-07-01 00:13:04 +00001081 return false;
Jakob Stoklund Olesenc6a20412011-02-08 19:33:55 +00001082 // We cannot fold a load instruction into a def.
1083 if (LoadMI && MO.isDef())
1084 return false;
Jakob Stoklund Olesen8656a452010-07-01 00:13:04 +00001085 // Tied use operands should not be passed to foldMemoryOperand.
1086 if (!MI->isRegTiedToDefOperand(Idx))
1087 FoldOps.push_back(Idx);
1088 }
1089
Mark Lacey9d8103d2013-08-14 23:50:16 +00001090 MachineInstrSpan MIS(MI);
1091
Jakob Stoklund Olesen3b2966d2010-12-18 03:04:14 +00001092 MachineInstr *FoldMI =
Jakob Stoklund Olesena00bab22011-03-14 19:56:43 +00001093 LoadMI ? TII.foldMemoryOperand(MI, FoldOps, LoadMI)
1094 : TII.foldMemoryOperand(MI, FoldOps, StackSlot);
Jakob Stoklund Olesen8656a452010-07-01 00:13:04 +00001095 if (!FoldMI)
1096 return false;
Andrew Trick5749b8b2013-06-21 18:33:26 +00001097
1098 // Remove LIS for any dead defs in the original MI not in FoldMI.
1099 for (MIBundleOperands MO(MI); MO.isValid(); ++MO) {
1100 if (!MO->isReg())
1101 continue;
1102 unsigned Reg = MO->getReg();
1103 if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg) ||
1104 MRI.isReserved(Reg)) {
1105 continue;
1106 }
Andrew Trickdfacda32014-01-07 07:31:10 +00001107 // Skip non-Defs, including undef uses and internal reads.
1108 if (MO->isUse())
1109 continue;
Andrew Trick5749b8b2013-06-21 18:33:26 +00001110 MIBundleOperands::PhysRegInfo RI =
1111 MIBundleOperands(FoldMI).analyzePhysReg(Reg, &TRI);
Andrew Trick5749b8b2013-06-21 18:33:26 +00001112 if (RI.Defines)
1113 continue;
1114 // FoldMI does not define this physreg. Remove the LI segment.
1115 assert(MO->isDead() && "Cannot fold physreg def");
1116 for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units) {
Matthias Braun34e1be92013-10-10 21:29:02 +00001117 if (LiveRange *LR = LIS.getCachedRegUnit(*Units)) {
Andrew Trick5749b8b2013-06-21 18:33:26 +00001118 SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
Matthias Braun34e1be92013-10-10 21:29:02 +00001119 if (VNInfo *VNI = LR->getVNInfoAt(Idx))
1120 LR->removeValNo(VNI);
Andrew Trick5749b8b2013-06-21 18:33:26 +00001121 }
1122 }
1123 }
Mark Lacey9d8103d2013-08-14 23:50:16 +00001124
Jakob Stoklund Olesena00bab22011-03-14 19:56:43 +00001125 LIS.ReplaceMachineInstrInMaps(MI, FoldMI);
Jakob Stoklund Olesenbd953d12010-07-09 17:29:08 +00001126 MI->eraseFromParent();
Jakob Stoklund Oleseneef48b62011-11-10 00:17:03 +00001127
Mark Lacey9d8103d2013-08-14 23:50:16 +00001128 // Insert any new instructions other than FoldMI into the LIS maps.
1129 assert(!MIS.empty() && "Unexpected empty span of instructions!");
1130 for (MachineBasicBlock::iterator MII = MIS.begin(), End = MIS.end();
1131 MII != End; ++MII)
1132 if (&*MII != FoldMI)
1133 LIS.InsertMachineInstrInMaps(&*MII);
1134
Jakob Stoklund Oleseneef48b62011-11-10 00:17:03 +00001135 // TII.foldMemoryOperand may have left some implicit operands on the
1136 // instruction. Strip them.
1137 if (ImpReg)
1138 for (unsigned i = FoldMI->getNumOperands(); i; --i) {
1139 MachineOperand &MO = FoldMI->getOperand(i - 1);
1140 if (!MO.isReg() || !MO.isImplicit())
1141 break;
1142 if (MO.getReg() == ImpReg)
1143 FoldMI->RemoveOperand(i - 1);
1144 }
1145
Mark Lacey9d8103d2013-08-14 23:50:16 +00001146 DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MIS.end(), LIS,
1147 "folded"));
1148
Jakob Stoklund Olesenc94c9672011-09-15 18:22:52 +00001149 if (!WasCopy)
1150 ++NumFolded;
Jakob Stoklund Olesenabe8c092012-03-01 01:43:25 +00001151 else if (Ops.front().second == 0)
Jakob Stoklund Olesenc94c9672011-09-15 18:22:52 +00001152 ++NumSpills;
1153 else
1154 ++NumReloads;
Jakob Stoklund Olesen8656a452010-07-01 00:13:04 +00001155 return true;
1156}
1157
Mark Lacey9d8103d2013-08-14 23:50:16 +00001158void InlineSpiller::insertReload(unsigned NewVReg,
Jakob Stoklund Olesen9f294a92011-04-18 20:23:27 +00001159 SlotIndex Idx,
Jakob Stoklund Olesenbde96ad2010-06-30 23:03:52 +00001160 MachineBasicBlock::iterator MI) {
1161 MachineBasicBlock &MBB = *MI->getParent();
Mark Lacey9d8103d2013-08-14 23:50:16 +00001162
1163 MachineInstrSpan MIS(MI);
1164 TII.loadRegFromStackSlot(MBB, MI, NewVReg, StackSlot,
1165 MRI.getRegClass(NewVReg), &TRI);
1166
1167 LIS.InsertMachineInstrRangeInMaps(MIS.begin(), MI);
1168
1169 DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MI, LIS, "reload",
1170 NewVReg));
Jakob Stoklund Olesenc5a8c082011-05-05 17:22:53 +00001171 ++NumReloads;
Jakob Stoklund Olesenbde96ad2010-06-30 23:03:52 +00001172}
1173
Mark Lacey9d8103d2013-08-14 23:50:16 +00001174/// insertSpill - Insert a spill of NewVReg after MI.
1175void InlineSpiller::insertSpill(unsigned NewVReg, bool isKill,
1176 MachineBasicBlock::iterator MI) {
Jakob Stoklund Olesenbde96ad2010-06-30 23:03:52 +00001177 MachineBasicBlock &MBB = *MI->getParent();
Mark Lacey9d8103d2013-08-14 23:50:16 +00001178
1179 MachineInstrSpan MIS(MI);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001180 TII.storeRegToStackSlot(MBB, std::next(MI), NewVReg, isKill, StackSlot,
Mark Lacey9d8103d2013-08-14 23:50:16 +00001181 MRI.getRegClass(NewVReg), &TRI);
1182
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001183 LIS.InsertMachineInstrRangeInMaps(std::next(MI), MIS.end());
Mark Lacey9d8103d2013-08-14 23:50:16 +00001184
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001185 DEBUG(dumpMachineInstrRangeWithSlotIndex(std::next(MI), MIS.end(), LIS,
Mark Lacey9d8103d2013-08-14 23:50:16 +00001186 "spill"));
Jakob Stoklund Olesenc5a8c082011-05-05 17:22:53 +00001187 ++NumSpills;
Jakob Stoklund Olesenbde96ad2010-06-30 23:03:52 +00001188}
1189
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +00001190/// spillAroundUses - insert spill code around each use of Reg.
1191void InlineSpiller::spillAroundUses(unsigned Reg) {
Jakob Stoklund Olesen31a0b5e2011-05-11 18:25:10 +00001192 DEBUG(dbgs() << "spillAroundUses " << PrintReg(Reg) << '\n');
Jakob Stoklund Olesena00bab22011-03-14 19:56:43 +00001193 LiveInterval &OldLI = LIS.getInterval(Reg);
Jakob Stoklund Olesenf8889112010-06-29 23:58:39 +00001194
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +00001195 // Iterate over instructions using Reg.
Owen Andersonabb90c92014-03-13 06:02:25 +00001196 for (MachineRegisterInfo::reg_bundle_iterator
1197 RegI = MRI.reg_bundle_begin(Reg), E = MRI.reg_bundle_end();
1198 RegI != E; ) {
Owen Andersonec5d4802014-03-14 05:02:18 +00001199 MachineInstr *MI = &*(RegI++);
Jakob Stoklund Olesenf8889112010-06-29 23:58:39 +00001200
Jakob Stoklund Olesencf6c5c92010-07-02 19:54:40 +00001201 // Debug values are not allowed to affect codegen.
1202 if (MI->isDebugValue()) {
1203 // Modify DBG_VALUE now that the value is in a spill slot.
Adrian Prantldb3e26d2013-09-16 23:29:03 +00001204 bool IsIndirect = MI->isIndirectDebugValue();
Adrian Prantlc31ec1c2013-07-10 16:56:47 +00001205 uint64_t Offset = IsIndirect ? MI->getOperand(1).getImm() : 0;
Jakob Stoklund Olesencf6c5c92010-07-02 19:54:40 +00001206 const MDNode *MDPtr = MI->getOperand(2).getMetadata();
1207 DebugLoc DL = MI->getDebugLoc();
David Blaikie0252265b2013-06-16 20:34:15 +00001208 DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
1209 MachineBasicBlock *MBB = MI->getParent();
1210 BuildMI(*MBB, MBB->erase(MI), DL, TII.get(TargetOpcode::DBG_VALUE))
1211 .addFrameIndex(StackSlot).addImm(Offset).addMetadata(MDPtr);
Jakob Stoklund Olesencf6c5c92010-07-02 19:54:40 +00001212 continue;
1213 }
1214
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +00001215 // Ignore copies to/from snippets. We'll delete them.
1216 if (SnippetCopies.count(MI))
1217 continue;
1218
Jakob Stoklund Olesen7fd49052010-08-04 22:35:11 +00001219 // Stack slot accesses may coalesce away.
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +00001220 if (coalesceStackAccess(MI, Reg))
Jakob Stoklund Olesen7fd49052010-08-04 22:35:11 +00001221 continue;
1222
Jakob Stoklund Olesenf8889112010-06-29 23:58:39 +00001223 // Analyze instruction.
Jakob Stoklund Olesenabe8c092012-03-01 01:43:25 +00001224 SmallVector<std::pair<MachineInstr*, unsigned>, 8> Ops;
James Molloy381fab92012-09-12 10:03:31 +00001225 MIBundleOperands::VirtRegInfo RI =
Jakob Stoklund Olesenabe8c092012-03-01 01:43:25 +00001226 MIBundleOperands(MI).analyzeVirtReg(Reg, &Ops);
Jakob Stoklund Olesenf8889112010-06-29 23:58:39 +00001227
Jakob Stoklund Olesen9f294a92011-04-18 20:23:27 +00001228 // Find the slot index where this instruction reads and writes OldLI.
1229 // This is usually the def slot, except for tied early clobbers.
Jakob Stoklund Olesen90b5e562011-11-13 20:45:27 +00001230 SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
1231 if (VNInfo *VNI = OldLI.getVNInfoAt(Idx.getRegSlot(true)))
Jakob Stoklund Olesen9f294a92011-04-18 20:23:27 +00001232 if (SlotIndex::isSameInstr(Idx, VNI->def))
1233 Idx = VNI->def;
1234
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +00001235 // Check for a sibling copy.
1236 unsigned SibReg = isFullCopyOf(MI, Reg);
Jakob Stoklund Olesene55003f2011-03-20 05:44:58 +00001237 if (SibReg && isSibling(SibReg)) {
Jakob Stoklund Olesen31a0b5e2011-05-11 18:25:10 +00001238 // This may actually be a copy between snippets.
1239 if (isRegToSpill(SibReg)) {
1240 DEBUG(dbgs() << "Found new snippet copy: " << *MI);
1241 SnippetCopies.insert(MI);
1242 continue;
1243 }
Jakob Stoklund Olesenabe8c092012-03-01 01:43:25 +00001244 if (RI.Writes) {
Jakob Stoklund Olesene55003f2011-03-20 05:44:58 +00001245 // Hoist the spill of a sib-reg copy.
1246 if (hoistSpill(OldLI, MI)) {
1247 // This COPY is now dead, the value is already in the stack slot.
1248 MI->getOperand(0).setIsDead();
1249 DeadDefs.push_back(MI);
1250 continue;
1251 }
1252 } else {
1253 // This is a reload for a sib-reg copy. Drop spills downstream.
Jakob Stoklund Olesene55003f2011-03-20 05:44:58 +00001254 LiveInterval &SibLI = LIS.getInterval(SibReg);
1255 eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx));
1256 // The COPY will fold to a reload below.
1257 }
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +00001258 }
1259
Jakob Stoklund Olesen96037182010-07-02 17:44:57 +00001260 // Attempt to fold memory ops.
Jakob Stoklund Olesenabe8c092012-03-01 01:43:25 +00001261 if (foldMemoryOperand(Ops))
Jakob Stoklund Olesen96037182010-07-02 17:44:57 +00001262 continue;
1263
Mark Lacey9d8103d2013-08-14 23:50:16 +00001264 // Create a new virtual register for spill/fill.
Jakob Stoklund Olesenf8889112010-06-29 23:58:39 +00001265 // FIXME: Infer regclass from instruction alone.
Mark Lacey9d8103d2013-08-14 23:50:16 +00001266 unsigned NewVReg = Edit->createFrom(Reg);
Jakob Stoklund Olesenf8889112010-06-29 23:58:39 +00001267
Jakob Stoklund Olesenabe8c092012-03-01 01:43:25 +00001268 if (RI.Reads)
Mark Lacey9d8103d2013-08-14 23:50:16 +00001269 insertReload(NewVReg, Idx, MI);
Jakob Stoklund Olesenf8889112010-06-29 23:58:39 +00001270
1271 // Rewrite instruction operands.
1272 bool hasLiveDef = false;
1273 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
Jakob Stoklund Olesenabe8c092012-03-01 01:43:25 +00001274 MachineOperand &MO = Ops[i].first->getOperand(Ops[i].second);
Mark Lacey9d8103d2013-08-14 23:50:16 +00001275 MO.setReg(NewVReg);
Jakob Stoklund Olesenf8889112010-06-29 23:58:39 +00001276 if (MO.isUse()) {
Jakob Stoklund Olesenabe8c092012-03-01 01:43:25 +00001277 if (!Ops[i].first->isRegTiedToDefOperand(Ops[i].second))
Jakob Stoklund Olesenf8889112010-06-29 23:58:39 +00001278 MO.setIsKill();
1279 } else {
1280 if (!MO.isDead())
1281 hasLiveDef = true;
1282 }
1283 }
Mark Lacey9d8103d2013-08-14 23:50:16 +00001284 DEBUG(dbgs() << "\trewrite: " << Idx << '\t' << *MI << '\n');
Jakob Stoklund Olesenf8889112010-06-29 23:58:39 +00001285
Jakob Stoklund Olesenf8889112010-06-29 23:58:39 +00001286 // FIXME: Use a second vreg if instruction has no tied ops.
Mark Lacey9d8103d2013-08-14 23:50:16 +00001287 if (RI.Writes)
Jakob Stoklund Olesenabe8c092012-03-01 01:43:25 +00001288 if (hasLiveDef)
Mark Lacey9d8103d2013-08-14 23:50:16 +00001289 insertSpill(NewVReg, true, MI);
Jakob Stoklund Olesenf8889112010-06-29 23:58:39 +00001290 }
1291}
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +00001292
Jakob Stoklund Olesene991f722011-03-29 21:20:19 +00001293/// spillAll - Spill all registers remaining after rematerialization.
1294void InlineSpiller::spillAll() {
1295 // Update LiveStacks now that we are committed to spilling.
1296 if (StackSlot == VirtRegMap::NO_STACK_SLOT) {
1297 StackSlot = VRM.assignVirt2StackSlot(Original);
1298 StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original));
Jakob Stoklund Olesenad6b22e2012-02-04 05:20:49 +00001299 StackInt->getNextValue(SlotIndex(), LSS.getVNInfoAllocator());
Jakob Stoklund Olesene991f722011-03-29 21:20:19 +00001300 } else
1301 StackInt = &LSS.getInterval(StackSlot);
1302
1303 if (Original != Edit->getReg())
1304 VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot);
1305
1306 assert(StackInt->getNumValNums() == 1 && "Bad stack interval values");
1307 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
Matthias Braun13ddb7c2013-10-10 21:28:43 +00001308 StackInt->MergeSegmentsInAsValue(LIS.getInterval(RegsToSpill[i]),
1309 StackInt->getValNumInfo(0));
Jakob Stoklund Olesene991f722011-03-29 21:20:19 +00001310 DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n');
1311
1312 // Spill around uses of all RegsToSpill.
1313 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1314 spillAroundUses(RegsToSpill[i]);
1315
1316 // Hoisted spills may cause dead code.
1317 if (!DeadDefs.empty()) {
1318 DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n");
Pete Cooper2bde2f42012-04-02 22:22:53 +00001319 Edit->eliminateDeadDefs(DeadDefs, RegsToSpill);
Jakob Stoklund Olesene991f722011-03-29 21:20:19 +00001320 }
1321
1322 // Finally delete the SnippetCopies.
Jakob Stoklund Olesen31a0b5e2011-05-11 18:25:10 +00001323 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
Owen Andersonabb90c92014-03-13 06:02:25 +00001324 for (MachineRegisterInfo::reg_instr_iterator
1325 RI = MRI.reg_instr_begin(RegsToSpill[i]), E = MRI.reg_instr_end();
1326 RI != E; ) {
1327 MachineInstr *MI = &*(RI++);
Jakob Stoklund Olesen31a0b5e2011-05-11 18:25:10 +00001328 assert(SnippetCopies.count(MI) && "Remaining use wasn't a snippet copy");
1329 // FIXME: Do this with a LiveRangeEdit callback.
Jakob Stoklund Olesen31a0b5e2011-05-11 18:25:10 +00001330 LIS.RemoveMachineInstrFromMaps(MI);
1331 MI->eraseFromParent();
1332 }
Jakob Stoklund Olesene991f722011-03-29 21:20:19 +00001333 }
1334
1335 // Delete all spilled registers.
1336 for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
Pete Cooper2bde2f42012-04-02 22:22:53 +00001337 Edit->eraseVirtReg(RegsToSpill[i]);
Jakob Stoklund Olesene991f722011-03-29 21:20:19 +00001338}
1339
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +00001340void InlineSpiller::spill(LiveRangeEdit &edit) {
Jakob Stoklund Olesenc5a8c082011-05-05 17:22:53 +00001341 ++NumSpilledRanges;
Jakob Stoklund Olesena00bab22011-03-14 19:56:43 +00001342 Edit = &edit;
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +00001343 assert(!TargetRegisterInfo::isStackSlot(edit.getReg())
1344 && "Trying to spill a stack slot.");
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +00001345 // Share a stack slot among all descendants of Original.
1346 Original = VRM.getOriginal(edit.getReg());
1347 StackSlot = VRM.getStackSlot(Original);
Jakob Stoklund Olesene4663452011-03-26 22:16:41 +00001348 StackInt = 0;
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +00001349
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +00001350 DEBUG(dbgs() << "Inline spilling "
Jakob Stoklund Olesena00bab22011-03-14 19:56:43 +00001351 << MRI.getRegClass(edit.getReg())->getName()
Matthias Braunf6fe6bf2013-10-10 21:29:05 +00001352 << ':' << edit.getParent()
Mark Lacey9d8103d2013-08-14 23:50:16 +00001353 << "\nFrom original " << PrintReg(Original) << '\n');
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +00001354 assert(edit.getParent().isSpillable() &&
1355 "Attempting to spill already spilled value.");
Jakob Stoklund Olesen27320cb2011-03-18 04:23:06 +00001356 assert(DeadDefs.empty() && "Previous spill didn't remove dead defs");
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +00001357
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +00001358 collectRegsToSpill();
Jakob Stoklund Olesena0d5ec12011-03-15 21:13:25 +00001359 analyzeSiblingValues();
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +00001360 reMaterializeAll();
1361
1362 // Remat may handle everything.
Jakob Stoklund Olesene991f722011-03-29 21:20:19 +00001363 if (!RegsToSpill.empty())
1364 spillAll();
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +00001365
Benjamin Kramere2a1d892013-06-17 19:00:36 +00001366 Edit->calculateRegClassAndHint(MF, Loops, MBFI);
Jakob Stoklund Olesena86595e2011-03-12 04:17:20 +00001367}