Sink DwarfUnit::SectionSym into DwarfCompileUnit as it's only needed/used there.
[oota-llvm.git] / lib / CodeGen / InlineSpiller.cpp
1 //===-------- InlineSpiller.cpp - Insert spills and restores inline -------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // The inline spiller modifies the machine function directly instead of
11 // inserting spills and restores in VirtRegMap.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "Spiller.h"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/ADT/TinyPtrVector.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
21 #include "llvm/CodeGen/LiveRangeEdit.h"
22 #include "llvm/CodeGen/LiveStackAnalysis.h"
23 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
24 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
25 #include "llvm/CodeGen/MachineDominators.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineInstrBundle.h"
30 #include "llvm/CodeGen/MachineLoopInfo.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/VirtRegMap.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37
38 using namespace llvm;
39
40 #define DEBUG_TYPE "regalloc"
41
42 STATISTIC(NumSpilledRanges,   "Number of spilled live ranges");
43 STATISTIC(NumSnippets,        "Number of spilled snippets");
44 STATISTIC(NumSpills,          "Number of spills inserted");
45 STATISTIC(NumSpillsRemoved,   "Number of spills removed");
46 STATISTIC(NumReloads,         "Number of reloads inserted");
47 STATISTIC(NumReloadsRemoved,  "Number of reloads removed");
48 STATISTIC(NumFolded,          "Number of folded stack accesses");
49 STATISTIC(NumFoldedLoads,     "Number of folded loads");
50 STATISTIC(NumRemats,          "Number of rematerialized defs for spilling");
51 STATISTIC(NumOmitReloadSpill, "Number of omitted spills of reloads");
52 STATISTIC(NumHoists,          "Number of hoisted spills");
53
54 static cl::opt<bool> DisableHoisting("disable-spill-hoist", cl::Hidden,
55                                      cl::desc("Disable inline spill hoisting"));
56
57 namespace {
58 class InlineSpiller : public Spiller {
59   MachineFunction &MF;
60   LiveIntervals &LIS;
61   LiveStacks &LSS;
62   AliasAnalysis *AA;
63   MachineDominatorTree &MDT;
64   MachineLoopInfo &Loops;
65   VirtRegMap &VRM;
66   MachineFrameInfo &MFI;
67   MachineRegisterInfo &MRI;
68   const TargetInstrInfo &TII;
69   const TargetRegisterInfo &TRI;
70   const MachineBlockFrequencyInfo &MBFI;
71
72   // Variables that are valid during spill(), but used by multiple methods.
73   LiveRangeEdit *Edit;
74   LiveInterval *StackInt;
75   int StackSlot;
76   unsigned Original;
77
78   // All registers to spill to StackSlot, including the main register.
79   SmallVector<unsigned, 8> RegsToSpill;
80
81   // All COPY instructions to/from snippets.
82   // They are ignored since both operands refer to the same stack slot.
83   SmallPtrSet<MachineInstr*, 8> SnippetCopies;
84
85   // Values that failed to remat at some point.
86   SmallPtrSet<VNInfo*, 8> UsedValues;
87
88 public:
89   // Information about a value that was defined by a copy from a sibling
90   // register.
91   struct SibValueInfo {
92     // True when all reaching defs were reloads: No spill is necessary.
93     bool AllDefsAreReloads;
94
95     // True when value is defined by an original PHI not from splitting.
96     bool DefByOrigPHI;
97
98     // True when the COPY defining this value killed its source.
99     bool KillsSource;
100
101     // The preferred register to spill.
102     unsigned SpillReg;
103
104     // The value of SpillReg that should be spilled.
105     VNInfo *SpillVNI;
106
107     // The block where SpillVNI should be spilled. Currently, this must be the
108     // block containing SpillVNI->def.
109     MachineBasicBlock *SpillMBB;
110
111     // A defining instruction that is not a sibling copy or a reload, or NULL.
112     // This can be used as a template for rematerialization.
113     MachineInstr *DefMI;
114
115     // List of values that depend on this one.  These values are actually the
116     // same, but live range splitting has placed them in different registers,
117     // or SSA update needed to insert PHI-defs to preserve SSA form.  This is
118     // copies of the current value and phi-kills.  Usually only phi-kills cause
119     // more than one dependent value.
120     TinyPtrVector<VNInfo*> Deps;
121
122     SibValueInfo(unsigned Reg, VNInfo *VNI)
123       : AllDefsAreReloads(true), DefByOrigPHI(false), KillsSource(false),
124         SpillReg(Reg), SpillVNI(VNI), SpillMBB(nullptr), DefMI(nullptr) {}
125
126     // Returns true when a def has been found.
127     bool hasDef() const { return DefByOrigPHI || DefMI; }
128   };
129
130 private:
131   // Values in RegsToSpill defined by sibling copies.
132   typedef DenseMap<VNInfo*, SibValueInfo> SibValueMap;
133   SibValueMap SibValues;
134
135   // Dead defs generated during spilling.
136   SmallVector<MachineInstr*, 8> DeadDefs;
137
138   ~InlineSpiller() {}
139
140 public:
141   InlineSpiller(MachineFunctionPass &pass, MachineFunction &mf, VirtRegMap &vrm)
142       : MF(mf), LIS(pass.getAnalysis<LiveIntervals>()),
143         LSS(pass.getAnalysis<LiveStacks>()),
144         AA(&pass.getAnalysis<AliasAnalysis>()),
145         MDT(pass.getAnalysis<MachineDominatorTree>()),
146         Loops(pass.getAnalysis<MachineLoopInfo>()), VRM(vrm),
147         MFI(*mf.getFrameInfo()), MRI(mf.getRegInfo()),
148         TII(*mf.getSubtarget().getInstrInfo()),
149         TRI(*mf.getSubtarget().getRegisterInfo()),
150         MBFI(pass.getAnalysis<MachineBlockFrequencyInfo>()) {}
151
152   void spill(LiveRangeEdit &) override;
153
154 private:
155   bool isSnippet(const LiveInterval &SnipLI);
156   void collectRegsToSpill();
157
158   bool isRegToSpill(unsigned Reg) {
159     return std::find(RegsToSpill.begin(),
160                      RegsToSpill.end(), Reg) != RegsToSpill.end();
161   }
162
163   bool isSibling(unsigned Reg);
164   MachineInstr *traceSiblingValue(unsigned, VNInfo*, VNInfo*);
165   void propagateSiblingValue(SibValueMap::iterator, VNInfo *VNI = nullptr);
166   void analyzeSiblingValues();
167
168   bool hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI);
169   void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI);
170
171   void markValueUsed(LiveInterval*, VNInfo*);
172   bool reMaterializeFor(LiveInterval&, MachineBasicBlock::iterator MI);
173   void reMaterializeAll();
174
175   bool coalesceStackAccess(MachineInstr *MI, unsigned Reg);
176   bool foldMemoryOperand(ArrayRef<std::pair<MachineInstr*, unsigned> >,
177                          MachineInstr *LoadMI = nullptr);
178   void insertReload(unsigned VReg, SlotIndex, MachineBasicBlock::iterator MI);
179   void insertSpill(unsigned VReg, bool isKill, MachineBasicBlock::iterator MI);
180
181   void spillAroundUses(unsigned Reg);
182   void spillAll();
183 };
184 }
185
186 namespace llvm {
187 Spiller *createInlineSpiller(MachineFunctionPass &pass,
188                              MachineFunction &mf,
189                              VirtRegMap &vrm) {
190   return new InlineSpiller(pass, mf, vrm);
191 }
192 }
193
194 //===----------------------------------------------------------------------===//
195 //                                Snippets
196 //===----------------------------------------------------------------------===//
197
198 // When spilling a virtual register, we also spill any snippets it is connected
199 // to. The snippets are small live ranges that only have a single real use,
200 // leftovers from live range splitting. Spilling them enables memory operand
201 // folding or tightens the live range around the single use.
202 //
203 // This minimizes register pressure and maximizes the store-to-load distance for
204 // spill slots which can be important in tight loops.
205
206 /// isFullCopyOf - If MI is a COPY to or from Reg, return the other register,
207 /// otherwise return 0.
208 static unsigned isFullCopyOf(const MachineInstr *MI, unsigned Reg) {
209   if (!MI->isFullCopy())
210     return 0;
211   if (MI->getOperand(0).getReg() == Reg)
212       return MI->getOperand(1).getReg();
213   if (MI->getOperand(1).getReg() == Reg)
214       return MI->getOperand(0).getReg();
215   return 0;
216 }
217
218 /// isSnippet - Identify if a live interval is a snippet that should be spilled.
219 /// It is assumed that SnipLI is a virtual register with the same original as
220 /// Edit->getReg().
221 bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
222   unsigned Reg = Edit->getReg();
223
224   // A snippet is a tiny live range with only a single instruction using it
225   // besides copies to/from Reg or spills/fills. We accept:
226   //
227   //   %snip = COPY %Reg / FILL fi#
228   //   %snip = USE %snip
229   //   %Reg = COPY %snip / SPILL %snip, fi#
230   //
231   if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI))
232     return false;
233
234   MachineInstr *UseMI = nullptr;
235
236   // Check that all uses satisfy our criteria.
237   for (MachineRegisterInfo::reg_instr_nodbg_iterator
238        RI = MRI.reg_instr_nodbg_begin(SnipLI.reg),
239        E = MRI.reg_instr_nodbg_end(); RI != E; ) {
240     MachineInstr *MI = &*(RI++);
241
242     // Allow copies to/from Reg.
243     if (isFullCopyOf(MI, Reg))
244       continue;
245
246     // Allow stack slot loads.
247     int FI;
248     if (SnipLI.reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
249       continue;
250
251     // Allow stack slot stores.
252     if (SnipLI.reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
253       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.
265 void InlineSpiller::collectRegsToSpill() {
266   unsigned Reg = Edit->getReg();
267
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.
274   if (Original == Reg)
275     return;
276
277   for (MachineRegisterInfo::reg_instr_iterator
278        RI = MRI.reg_instr_begin(Reg), E = MRI.reg_instr_end(); RI != E; ) {
279     MachineInstr *MI = &*(RI++);
280     unsigned SnipReg = isFullCopyOf(MI, Reg);
281     if (!isSibling(SnipReg))
282       continue;
283     LiveInterval &SnipLI = LIS.getInterval(SnipReg);
284     if (!isSnippet(SnipLI))
285       continue;
286     SnippetCopies.insert(MI);
287     if (isRegToSpill(SnipReg))
288       continue;
289     RegsToSpill.push_back(SnipReg);
290     DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n');
291     ++NumSnippets;
292   }
293 }
294
295
296 //===----------------------------------------------------------------------===//
297 //                            Sibling Values
298 //===----------------------------------------------------------------------===//
299
300 // After live range splitting, some values to be spilled may be defined by
301 // copies from sibling registers. We trace the sibling copies back to the
302 // original value if it still exists. We need it for rematerialization.
303 //
304 // Even when the value can't be rematerialized, we still want to determine if
305 // the value has already been spilled, or we may want to hoist the spill from a
306 // loop.
307
308 bool InlineSpiller::isSibling(unsigned Reg) {
309   return TargetRegisterInfo::isVirtualRegister(Reg) &&
310            VRM.getOriginal(Reg) == Original;
311 }
312
313 #ifndef NDEBUG
314 static raw_ostream &operator<<(raw_ostream &OS,
315                                const InlineSpiller::SibValueInfo &SVI) {
316   OS << "spill " << PrintReg(SVI.SpillReg) << ':'
317      << SVI.SpillVNI->id << '@' << SVI.SpillVNI->def;
318   if (SVI.SpillMBB)
319     OS << " in BB#" << SVI.SpillMBB->getNumber();
320   if (SVI.AllDefsAreReloads)
321     OS << " all-reloads";
322   if (SVI.DefByOrigPHI)
323     OS << " orig-phi";
324   if (SVI.KillsSource)
325     OS << " kill";
326   OS << " deps[";
327   for (unsigned i = 0, e = SVI.Deps.size(); i != e; ++i)
328     OS << ' ' << SVI.Deps[i]->id << '@' << SVI.Deps[i]->def;
329   OS << " ]";
330   if (SVI.DefMI)
331     OS << " def: " << *SVI.DefMI;
332   else
333     OS << '\n';
334   return OS;
335 }
336 #endif
337
338 /// propagateSiblingValue - Propagate the value in SVI to dependents if it is
339 /// known.  Otherwise remember the dependency for later.
340 ///
341 /// @param SVIIter SibValues entry to propagate.
342 /// @param VNI Dependent value, or NULL to propagate to all saved dependents.
343 void InlineSpiller::propagateSiblingValue(SibValueMap::iterator SVIIter,
344                                           VNInfo *VNI) {
345   SibValueMap::value_type *SVI = &*SVIIter;
346
347   // When VNI is non-NULL, add it to SVI's deps, and only propagate to that.
348   TinyPtrVector<VNInfo*> FirstDeps;
349   if (VNI) {
350     FirstDeps.push_back(VNI);
351     SVI->second.Deps.push_back(VNI);
352   }
353
354   // Has the value been completely determined yet?  If not, defer propagation.
355   if (!SVI->second.hasDef())
356     return;
357
358   // Work list of values to propagate.
359   SmallSetVector<SibValueMap::value_type *, 8> WorkList;
360   WorkList.insert(SVI);
361
362   do {
363     SVI = WorkList.pop_back_val();
364     TinyPtrVector<VNInfo*> *Deps = VNI ? &FirstDeps : &SVI->second.Deps;
365     VNI = nullptr;
366
367     SibValueInfo &SV = SVI->second;
368     if (!SV.SpillMBB)
369       SV.SpillMBB = LIS.getMBBFromIndex(SV.SpillVNI->def);
370
371     DEBUG(dbgs() << "  prop to " << Deps->size() << ": "
372                  << SVI->first->id << '@' << SVI->first->def << ":\t" << SV);
373
374     assert(SV.hasDef() && "Propagating undefined value");
375
376     // Should this value be propagated as a preferred spill candidate?  We don't
377     // propagate values of registers that are about to spill.
378     bool PropSpill = !DisableHoisting && !isRegToSpill(SV.SpillReg);
379     unsigned SpillDepth = ~0u;
380
381     for (TinyPtrVector<VNInfo*>::iterator DepI = Deps->begin(),
382          DepE = Deps->end(); DepI != DepE; ++DepI) {
383       SibValueMap::iterator DepSVI = SibValues.find(*DepI);
384       assert(DepSVI != SibValues.end() && "Dependent value not in SibValues");
385       SibValueInfo &DepSV = DepSVI->second;
386       if (!DepSV.SpillMBB)
387         DepSV.SpillMBB = LIS.getMBBFromIndex(DepSV.SpillVNI->def);
388
389       bool Changed = false;
390
391       // Propagate defining instruction.
392       if (!DepSV.hasDef()) {
393         Changed = true;
394         DepSV.DefMI = SV.DefMI;
395         DepSV.DefByOrigPHI = SV.DefByOrigPHI;
396       }
397
398       // Propagate AllDefsAreReloads.  For PHI values, this computes an AND of
399       // all predecessors.
400       if (!SV.AllDefsAreReloads && DepSV.AllDefsAreReloads) {
401         Changed = true;
402         DepSV.AllDefsAreReloads = false;
403       }
404
405       // Propagate best spill value.
406       if (PropSpill && SV.SpillVNI != DepSV.SpillVNI) {
407         if (SV.SpillMBB == DepSV.SpillMBB) {
408           // DepSV is in the same block.  Hoist when dominated.
409           if (DepSV.KillsSource && SV.SpillVNI->def < DepSV.SpillVNI->def) {
410             // This is an alternative def earlier in the same MBB.
411             // Hoist the spill as far as possible in SpillMBB. This can ease
412             // register pressure:
413             //
414             //   x = def
415             //   y = use x
416             //   s = copy x
417             //
418             // Hoisting the spill of s to immediately after the def removes the
419             // interference between x and y:
420             //
421             //   x = def
422             //   spill x
423             //   y = use x<kill>
424             //
425             // This hoist only helps when the DepSV copy kills its source.
426             Changed = true;
427             DepSV.SpillReg = SV.SpillReg;
428             DepSV.SpillVNI = SV.SpillVNI;
429             DepSV.SpillMBB = SV.SpillMBB;
430           }
431         } else {
432           // DepSV is in a different block.
433           if (SpillDepth == ~0u)
434             SpillDepth = Loops.getLoopDepth(SV.SpillMBB);
435
436           // Also hoist spills to blocks with smaller loop depth, but make sure
437           // that the new value dominates.  Non-phi dependents are always
438           // dominated, phis need checking.
439
440           const BranchProbability MarginProb(4, 5); // 80%
441           // Hoist a spill to outer loop if there are multiple dependents (it
442           // can be beneficial if more than one dependents are hoisted) or
443           // if DepSV (the hoisting source) is hotter than SV (the hoisting
444           // destination) (we add a 80% margin to bias a little towards
445           // loop depth).
446           bool HoistCondition =
447             (MBFI.getBlockFreq(DepSV.SpillMBB) >=
448              (MBFI.getBlockFreq(SV.SpillMBB) * MarginProb)) ||
449             Deps->size() > 1;
450
451           if ((Loops.getLoopDepth(DepSV.SpillMBB) > SpillDepth) &&
452               HoistCondition &&
453               (!DepSVI->first->isPHIDef() ||
454                MDT.dominates(SV.SpillMBB, DepSV.SpillMBB))) {
455             Changed = true;
456             DepSV.SpillReg = SV.SpillReg;
457             DepSV.SpillVNI = SV.SpillVNI;
458             DepSV.SpillMBB = SV.SpillMBB;
459           }
460         }
461       }
462
463       if (!Changed)
464         continue;
465
466       // Something changed in DepSVI. Propagate to dependents.
467       WorkList.insert(&*DepSVI);
468
469       DEBUG(dbgs() << "  update " << DepSVI->first->id << '@'
470             << DepSVI->first->def << " to:\t" << DepSV);
471     }
472   } while (!WorkList.empty());
473 }
474
475 /// traceSiblingValue - Trace a value that is about to be spilled back to the
476 /// real defining instructions by looking through sibling copies. Always stay
477 /// within the range of OrigVNI so the registers are known to carry the same
478 /// value.
479 ///
480 /// Determine if the value is defined by all reloads, so spilling isn't
481 /// necessary - the value is already in the stack slot.
482 ///
483 /// Return a defining instruction that may be a candidate for rematerialization.
484 ///
485 MachineInstr *InlineSpiller::traceSiblingValue(unsigned UseReg, VNInfo *UseVNI,
486                                                VNInfo *OrigVNI) {
487   // Check if a cached value already exists.
488   SibValueMap::iterator SVI;
489   bool Inserted;
490   std::tie(SVI, Inserted) =
491     SibValues.insert(std::make_pair(UseVNI, SibValueInfo(UseReg, UseVNI)));
492   if (!Inserted) {
493     DEBUG(dbgs() << "Cached value " << PrintReg(UseReg) << ':'
494                  << UseVNI->id << '@' << UseVNI->def << ' ' << SVI->second);
495     return SVI->second.DefMI;
496   }
497
498   DEBUG(dbgs() << "Tracing value " << PrintReg(UseReg) << ':'
499                << UseVNI->id << '@' << UseVNI->def << '\n');
500
501   // List of (Reg, VNI) that have been inserted into SibValues, but need to be
502   // processed.
503   SmallVector<std::pair<unsigned, VNInfo*>, 8> WorkList;
504   WorkList.push_back(std::make_pair(UseReg, UseVNI));
505
506   do {
507     unsigned Reg;
508     VNInfo *VNI;
509     std::tie(Reg, VNI) = WorkList.pop_back_val();
510     DEBUG(dbgs() << "  " << PrintReg(Reg) << ':' << VNI->id << '@' << VNI->def
511                  << ":\t");
512
513     // First check if this value has already been computed.
514     SVI = SibValues.find(VNI);
515     assert(SVI != SibValues.end() && "Missing SibValues entry");
516
517     // Trace through PHI-defs created by live range splitting.
518     if (VNI->isPHIDef()) {
519       // Stop at original PHIs.  We don't know the value at the predecessors.
520       if (VNI->def == OrigVNI->def) {
521         DEBUG(dbgs() << "orig phi value\n");
522         SVI->second.DefByOrigPHI = true;
523         SVI->second.AllDefsAreReloads = false;
524         propagateSiblingValue(SVI);
525         continue;
526       }
527
528       // This is a PHI inserted by live range splitting.  We could trace the
529       // live-out value from predecessor blocks, but that search can be very
530       // expensive if there are many predecessors and many more PHIs as
531       // generated by tail-dup when it sees an indirectbr.  Instead, look at
532       // all the non-PHI defs that have the same value as OrigVNI.  They must
533       // jointly dominate VNI->def.  This is not optimal since VNI may actually
534       // be jointly dominated by a smaller subset of defs, so there is a change
535       // we will miss a AllDefsAreReloads optimization.
536
537       // Separate all values dominated by OrigVNI into PHIs and non-PHIs.
538       SmallVector<VNInfo*, 8> PHIs, NonPHIs;
539       LiveInterval &LI = LIS.getInterval(Reg);
540       LiveInterval &OrigLI = LIS.getInterval(Original);
541
542       for (LiveInterval::vni_iterator VI = LI.vni_begin(), VE = LI.vni_end();
543            VI != VE; ++VI) {
544         VNInfo *VNI2 = *VI;
545         if (VNI2->isUnused())
546           continue;
547         if (!OrigLI.containsOneValue() &&
548             OrigLI.getVNInfoAt(VNI2->def) != OrigVNI)
549           continue;
550         if (VNI2->isPHIDef() && VNI2->def != OrigVNI->def)
551           PHIs.push_back(VNI2);
552         else
553           NonPHIs.push_back(VNI2);
554       }
555       DEBUG(dbgs() << "split phi value, checking " << PHIs.size()
556                    << " phi-defs, and " << NonPHIs.size()
557                    << " non-phi/orig defs\n");
558
559       // Create entries for all the PHIs.  Don't add them to the worklist, we
560       // are processing all of them in one go here.
561       for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
562         SibValues.insert(std::make_pair(PHIs[i], SibValueInfo(Reg, PHIs[i])));
563
564       // Add every PHI as a dependent of all the non-PHIs.
565       for (unsigned i = 0, e = NonPHIs.size(); i != e; ++i) {
566         VNInfo *NonPHI = NonPHIs[i];
567         // Known value? Try an insertion.
568         std::tie(SVI, Inserted) =
569           SibValues.insert(std::make_pair(NonPHI, SibValueInfo(Reg, NonPHI)));
570         // Add all the PHIs as dependents of NonPHI.
571         for (unsigned pi = 0, pe = PHIs.size(); pi != pe; ++pi)
572           SVI->second.Deps.push_back(PHIs[pi]);
573         // This is the first time we see NonPHI, add it to the worklist.
574         if (Inserted)
575           WorkList.push_back(std::make_pair(Reg, NonPHI));
576         else
577           // Propagate to all inserted PHIs, not just VNI.
578           propagateSiblingValue(SVI);
579       }
580
581       // Next work list item.
582       continue;
583     }
584
585     MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
586     assert(MI && "Missing def");
587
588     // Trace through sibling copies.
589     if (unsigned SrcReg = isFullCopyOf(MI, Reg)) {
590       if (isSibling(SrcReg)) {
591         LiveInterval &SrcLI = LIS.getInterval(SrcReg);
592         LiveQueryResult SrcQ = SrcLI.Query(VNI->def);
593         assert(SrcQ.valueIn() && "Copy from non-existing value");
594         // Check if this COPY kills its source.
595         SVI->second.KillsSource = SrcQ.isKill();
596         VNInfo *SrcVNI = SrcQ.valueIn();
597         DEBUG(dbgs() << "copy of " << PrintReg(SrcReg) << ':'
598                      << SrcVNI->id << '@' << SrcVNI->def
599                      << " kill=" << unsigned(SVI->second.KillsSource) << '\n');
600         // Known sibling source value? Try an insertion.
601         std::tie(SVI, Inserted) = SibValues.insert(
602             std::make_pair(SrcVNI, SibValueInfo(SrcReg, SrcVNI)));
603         // This is the first time we see Src, add it to the worklist.
604         if (Inserted)
605           WorkList.push_back(std::make_pair(SrcReg, SrcVNI));
606         propagateSiblingValue(SVI, VNI);
607         // Next work list item.
608         continue;
609       }
610     }
611
612     // Track reachable reloads.
613     SVI->second.DefMI = MI;
614     SVI->second.SpillMBB = MI->getParent();
615     int FI;
616     if (Reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot) {
617       DEBUG(dbgs() << "reload\n");
618       propagateSiblingValue(SVI);
619       // Next work list item.
620       continue;
621     }
622
623     // Potential remat candidate.
624     DEBUG(dbgs() << "def " << *MI);
625     SVI->second.AllDefsAreReloads = false;
626     propagateSiblingValue(SVI);
627   } while (!WorkList.empty());
628
629   // Look up the value we were looking for.  We already did this lookup at the
630   // top of the function, but SibValues may have been invalidated.
631   SVI = SibValues.find(UseVNI);
632   assert(SVI != SibValues.end() && "Didn't compute requested info");
633   DEBUG(dbgs() << "  traced to:\t" << SVI->second);
634   return SVI->second.DefMI;
635 }
636
637 /// analyzeSiblingValues - Trace values defined by sibling copies back to
638 /// something that isn't a sibling copy.
639 ///
640 /// Keep track of values that may be rematerializable.
641 void InlineSpiller::analyzeSiblingValues() {
642   SibValues.clear();
643
644   // No siblings at all?
645   if (Edit->getReg() == Original)
646     return;
647
648   LiveInterval &OrigLI = LIS.getInterval(Original);
649   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
650     unsigned Reg = RegsToSpill[i];
651     LiveInterval &LI = LIS.getInterval(Reg);
652     for (LiveInterval::const_vni_iterator VI = LI.vni_begin(),
653          VE = LI.vni_end(); VI != VE; ++VI) {
654       VNInfo *VNI = *VI;
655       if (VNI->isUnused())
656         continue;
657       MachineInstr *DefMI = nullptr;
658       if (!VNI->isPHIDef()) {
659        DefMI = LIS.getInstructionFromIndex(VNI->def);
660        assert(DefMI && "No defining instruction");
661       }
662       // Check possible sibling copies.
663       if (VNI->isPHIDef() || DefMI->isCopy()) {
664         VNInfo *OrigVNI = OrigLI.getVNInfoAt(VNI->def);
665         assert(OrigVNI && "Def outside original live range");
666         if (OrigVNI->def != VNI->def)
667           DefMI = traceSiblingValue(Reg, VNI, OrigVNI);
668       }
669       if (DefMI && Edit->checkRematerializable(VNI, DefMI, AA)) {
670         DEBUG(dbgs() << "Value " << PrintReg(Reg) << ':' << VNI->id << '@'
671                      << VNI->def << " may remat from " << *DefMI);
672       }
673     }
674   }
675 }
676
677 /// hoistSpill - Given a sibling copy that defines a value to be spilled, insert
678 /// a spill at a better location.
679 bool InlineSpiller::hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI) {
680   SlotIndex Idx = LIS.getInstructionIndex(CopyMI);
681   VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getRegSlot());
682   assert(VNI && VNI->def == Idx.getRegSlot() && "Not defined by copy");
683   SibValueMap::iterator I = SibValues.find(VNI);
684   if (I == SibValues.end())
685     return false;
686
687   const SibValueInfo &SVI = I->second;
688
689   // Let the normal folding code deal with the boring case.
690   if (!SVI.AllDefsAreReloads && SVI.SpillVNI == VNI)
691     return false;
692
693   // SpillReg may have been deleted by remat and DCE.
694   if (!LIS.hasInterval(SVI.SpillReg)) {
695     DEBUG(dbgs() << "Stale interval: " << PrintReg(SVI.SpillReg) << '\n');
696     SibValues.erase(I);
697     return false;
698   }
699
700   LiveInterval &SibLI = LIS.getInterval(SVI.SpillReg);
701   if (!SibLI.containsValue(SVI.SpillVNI)) {
702     DEBUG(dbgs() << "Stale value: " << PrintReg(SVI.SpillReg) << '\n');
703     SibValues.erase(I);
704     return false;
705   }
706
707   // Conservatively extend the stack slot range to the range of the original
708   // value. We may be able to do better with stack slot coloring by being more
709   // careful here.
710   assert(StackInt && "No stack slot assigned yet.");
711   LiveInterval &OrigLI = LIS.getInterval(Original);
712   VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
713   StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0));
714   DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
715                << *StackInt << '\n');
716
717   // Already spilled everywhere.
718   if (SVI.AllDefsAreReloads) {
719     DEBUG(dbgs() << "\tno spill needed: " << SVI);
720     ++NumOmitReloadSpill;
721     return true;
722   }
723   // We are going to spill SVI.SpillVNI immediately after its def, so clear out
724   // any later spills of the same value.
725   eliminateRedundantSpills(SibLI, SVI.SpillVNI);
726
727   MachineBasicBlock *MBB = LIS.getMBBFromIndex(SVI.SpillVNI->def);
728   MachineBasicBlock::iterator MII;
729   if (SVI.SpillVNI->isPHIDef())
730     MII = MBB->SkipPHIsAndLabels(MBB->begin());
731   else {
732     MachineInstr *DefMI = LIS.getInstructionFromIndex(SVI.SpillVNI->def);
733     assert(DefMI && "Defining instruction disappeared");
734     MII = DefMI;
735     ++MII;
736   }
737   // Insert spill without kill flag immediately after def.
738   TII.storeRegToStackSlot(*MBB, MII, SVI.SpillReg, false, StackSlot,
739                           MRI.getRegClass(SVI.SpillReg), &TRI);
740   --MII; // Point to store instruction.
741   LIS.InsertMachineInstrInMaps(MII);
742   DEBUG(dbgs() << "\thoisted: " << SVI.SpillVNI->def << '\t' << *MII);
743
744   ++NumSpills;
745   ++NumHoists;
746   return true;
747 }
748
749 /// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any
750 /// redundant spills of this value in SLI.reg and sibling copies.
751 void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
752   assert(VNI && "Missing value");
753   SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
754   WorkList.push_back(std::make_pair(&SLI, VNI));
755   assert(StackInt && "No stack slot assigned yet.");
756
757   do {
758     LiveInterval *LI;
759     std::tie(LI, VNI) = WorkList.pop_back_val();
760     unsigned Reg = LI->reg;
761     DEBUG(dbgs() << "Checking redundant spills for "
762                  << VNI->id << '@' << VNI->def << " in " << *LI << '\n');
763
764     // Regs to spill are taken care of.
765     if (isRegToSpill(Reg))
766       continue;
767
768     // Add all of VNI's live range to StackInt.
769     StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0));
770     DEBUG(dbgs() << "Merged to stack int: " << *StackInt << '\n');
771
772     // Find all spills and copies of VNI.
773     for (MachineRegisterInfo::use_instr_nodbg_iterator
774          UI = MRI.use_instr_nodbg_begin(Reg), E = MRI.use_instr_nodbg_end();
775          UI != E; ) {
776       MachineInstr *MI = &*(UI++);
777       if (!MI->isCopy() && !MI->mayStore())
778         continue;
779       SlotIndex Idx = LIS.getInstructionIndex(MI);
780       if (LI->getVNInfoAt(Idx) != VNI)
781         continue;
782
783       // Follow sibling copies down the dominator tree.
784       if (unsigned DstReg = isFullCopyOf(MI, Reg)) {
785         if (isSibling(DstReg)) {
786            LiveInterval &DstLI = LIS.getInterval(DstReg);
787            VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getRegSlot());
788            assert(DstVNI && "Missing defined value");
789            assert(DstVNI->def == Idx.getRegSlot() && "Wrong copy def slot");
790            WorkList.push_back(std::make_pair(&DstLI, DstVNI));
791         }
792         continue;
793       }
794
795       // Erase spills.
796       int FI;
797       if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) {
798         DEBUG(dbgs() << "Redundant spill " << Idx << '\t' << *MI);
799         // eliminateDeadDefs won't normally remove stores, so switch opcode.
800         MI->setDesc(TII.get(TargetOpcode::KILL));
801         DeadDefs.push_back(MI);
802         ++NumSpillsRemoved;
803         --NumSpills;
804       }
805     }
806   } while (!WorkList.empty());
807 }
808
809
810 //===----------------------------------------------------------------------===//
811 //                            Rematerialization
812 //===----------------------------------------------------------------------===//
813
814 /// markValueUsed - Remember that VNI failed to rematerialize, so its defining
815 /// instruction cannot be eliminated. See through snippet copies
816 void InlineSpiller::markValueUsed(LiveInterval *LI, VNInfo *VNI) {
817   SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
818   WorkList.push_back(std::make_pair(LI, VNI));
819   do {
820     std::tie(LI, VNI) = WorkList.pop_back_val();
821     if (!UsedValues.insert(VNI))
822       continue;
823
824     if (VNI->isPHIDef()) {
825       MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
826       for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
827              PE = MBB->pred_end(); PI != PE; ++PI) {
828         VNInfo *PVNI = LI->getVNInfoBefore(LIS.getMBBEndIdx(*PI));
829         if (PVNI)
830           WorkList.push_back(std::make_pair(LI, PVNI));
831       }
832       continue;
833     }
834
835     // Follow snippet copies.
836     MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
837     if (!SnippetCopies.count(MI))
838       continue;
839     LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg());
840     assert(isRegToSpill(SnipLI.reg) && "Unexpected register in copy");
841     VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getRegSlot(true));
842     assert(SnipVNI && "Snippet undefined before copy");
843     WorkList.push_back(std::make_pair(&SnipLI, SnipVNI));
844   } while (!WorkList.empty());
845 }
846
847 /// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
848 bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg,
849                                      MachineBasicBlock::iterator MI) {
850
851   // Analyze instruction
852   SmallVector<std::pair<MachineInstr *, unsigned>, 8> Ops;
853   MIBundleOperands::VirtRegInfo RI =
854     MIBundleOperands(MI).analyzeVirtReg(VirtReg.reg, &Ops);
855
856   if (!RI.Reads)
857     return false;
858
859   SlotIndex UseIdx = LIS.getInstructionIndex(MI).getRegSlot(true);
860   VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx.getBaseIndex());
861
862   if (!ParentVNI) {
863     DEBUG(dbgs() << "\tadding <undef> flags: ");
864     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
865       MachineOperand &MO = MI->getOperand(i);
866       if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg)
867         MO.setIsUndef();
868     }
869     DEBUG(dbgs() << UseIdx << '\t' << *MI);
870     return true;
871   }
872
873   if (SnippetCopies.count(MI))
874     return false;
875
876   // Use an OrigVNI from traceSiblingValue when ParentVNI is a sibling copy.
877   LiveRangeEdit::Remat RM(ParentVNI);
878   SibValueMap::const_iterator SibI = SibValues.find(ParentVNI);
879   if (SibI != SibValues.end())
880     RM.OrigMI = SibI->second.DefMI;
881   if (!Edit->canRematerializeAt(RM, UseIdx, false)) {
882     markValueUsed(&VirtReg, ParentVNI);
883     DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
884     return false;
885   }
886
887   // If the instruction also writes VirtReg.reg, it had better not require the
888   // same register for uses and defs.
889   if (RI.Tied) {
890     markValueUsed(&VirtReg, ParentVNI);
891     DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
892     return false;
893   }
894
895   // Before rematerializing into a register for a single instruction, try to
896   // fold a load into the instruction. That avoids allocating a new register.
897   if (RM.OrigMI->canFoldAsLoad() &&
898       foldMemoryOperand(Ops, RM.OrigMI)) {
899     Edit->markRematerialized(RM.ParentVNI);
900     ++NumFoldedLoads;
901     return true;
902   }
903
904   // Alocate a new register for the remat.
905   unsigned NewVReg = Edit->createFrom(Original);
906
907   // Finally we can rematerialize OrigMI before MI.
908   SlotIndex DefIdx = Edit->rematerializeAt(*MI->getParent(), MI, NewVReg, RM,
909                                            TRI);
910   (void)DefIdx;
911   DEBUG(dbgs() << "\tremat:  " << DefIdx << '\t'
912                << *LIS.getInstructionFromIndex(DefIdx));
913
914   // Replace operands
915   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
916     MachineOperand &MO = MI->getOperand(Ops[i].second);
917     if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg) {
918       MO.setReg(NewVReg);
919       MO.setIsKill();
920     }
921   }
922   DEBUG(dbgs() << "\t        " << UseIdx << '\t' << *MI << '\n');
923
924   ++NumRemats;
925   return true;
926 }
927
928 /// reMaterializeAll - Try to rematerialize as many uses as possible,
929 /// and trim the live ranges after.
930 void InlineSpiller::reMaterializeAll() {
931   // analyzeSiblingValues has already tested all relevant defining instructions.
932   if (!Edit->anyRematerializable(AA))
933     return;
934
935   UsedValues.clear();
936
937   // Try to remat before all uses of snippets.
938   bool anyRemat = false;
939   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
940     unsigned Reg = RegsToSpill[i];
941     LiveInterval &LI = LIS.getInterval(Reg);
942     for (MachineRegisterInfo::reg_bundle_iterator
943            RegI = MRI.reg_bundle_begin(Reg), E = MRI.reg_bundle_end();
944          RegI != E; ) {
945       MachineInstr *MI = &*(RegI++);
946
947       // Debug values are not allowed to affect codegen.
948       if (MI->isDebugValue())
949         continue;
950
951       anyRemat |= reMaterializeFor(LI, MI);
952     }
953   }
954   if (!anyRemat)
955     return;
956
957   // Remove any values that were completely rematted.
958   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
959     unsigned Reg = RegsToSpill[i];
960     LiveInterval &LI = LIS.getInterval(Reg);
961     for (LiveInterval::vni_iterator I = LI.vni_begin(), E = LI.vni_end();
962          I != E; ++I) {
963       VNInfo *VNI = *I;
964       if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI))
965         continue;
966       MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
967       MI->addRegisterDead(Reg, &TRI);
968       if (!MI->allDefsAreDead())
969         continue;
970       DEBUG(dbgs() << "All defs dead: " << *MI);
971       DeadDefs.push_back(MI);
972     }
973   }
974
975   // Eliminate dead code after remat. Note that some snippet copies may be
976   // deleted here.
977   if (DeadDefs.empty())
978     return;
979   DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n");
980   Edit->eliminateDeadDefs(DeadDefs, RegsToSpill);
981
982   // Get rid of deleted and empty intervals.
983   unsigned ResultPos = 0;
984   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
985     unsigned Reg = RegsToSpill[i];
986     if (!LIS.hasInterval(Reg))
987       continue;
988
989     LiveInterval &LI = LIS.getInterval(Reg);
990     if (LI.empty()) {
991       Edit->eraseVirtReg(Reg);
992       continue;
993     }
994
995     RegsToSpill[ResultPos++] = Reg;
996   }
997   RegsToSpill.erase(RegsToSpill.begin() + ResultPos, RegsToSpill.end());
998   DEBUG(dbgs() << RegsToSpill.size() << " registers to spill after remat.\n");
999 }
1000
1001
1002 //===----------------------------------------------------------------------===//
1003 //                                 Spilling
1004 //===----------------------------------------------------------------------===//
1005
1006 /// If MI is a load or store of StackSlot, it can be removed.
1007 bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, unsigned Reg) {
1008   int FI = 0;
1009   unsigned InstrReg = TII.isLoadFromStackSlot(MI, FI);
1010   bool IsLoad = InstrReg;
1011   if (!IsLoad)
1012     InstrReg = TII.isStoreToStackSlot(MI, FI);
1013
1014   // We have a stack access. Is it the right register and slot?
1015   if (InstrReg != Reg || FI != StackSlot)
1016     return false;
1017
1018   DEBUG(dbgs() << "Coalescing stack access: " << *MI);
1019   LIS.RemoveMachineInstrFromMaps(MI);
1020   MI->eraseFromParent();
1021
1022   if (IsLoad) {
1023     ++NumReloadsRemoved;
1024     --NumReloads;
1025   } else {
1026     ++NumSpillsRemoved;
1027     --NumSpills;
1028   }
1029
1030   return true;
1031 }
1032
1033 #if !defined(NDEBUG)
1034 // Dump the range of instructions from B to E with their slot indexes.
1035 static void dumpMachineInstrRangeWithSlotIndex(MachineBasicBlock::iterator B,
1036                                                MachineBasicBlock::iterator E,
1037                                                LiveIntervals const &LIS,
1038                                                const char *const header,
1039                                                unsigned VReg =0) {
1040   char NextLine = '\n';
1041   char SlotIndent = '\t';
1042
1043   if (std::next(B) == E) {
1044     NextLine = ' ';
1045     SlotIndent = ' ';
1046   }
1047
1048   dbgs() << '\t' << header << ": " << NextLine;
1049
1050   for (MachineBasicBlock::iterator I = B; I != E; ++I) {
1051     SlotIndex Idx = LIS.getInstructionIndex(I).getRegSlot();
1052
1053     // If a register was passed in and this instruction has it as a
1054     // destination that is marked as an early clobber, print the
1055     // early-clobber slot index.
1056     if (VReg) {
1057       MachineOperand *MO = I->findRegisterDefOperand(VReg);
1058       if (MO && MO->isEarlyClobber())
1059         Idx = Idx.getRegSlot(true);
1060     }
1061
1062     dbgs() << SlotIndent << Idx << '\t' << *I;
1063   }
1064 }
1065 #endif
1066
1067 /// foldMemoryOperand - Try folding stack slot references in Ops into their
1068 /// instructions.
1069 ///
1070 /// @param Ops    Operand indices from analyzeVirtReg().
1071 /// @param LoadMI Load instruction to use instead of stack slot when non-null.
1072 /// @return       True on success.
1073 bool InlineSpiller::
1074 foldMemoryOperand(ArrayRef<std::pair<MachineInstr*, unsigned> > Ops,
1075                   MachineInstr *LoadMI) {
1076   if (Ops.empty())
1077     return false;
1078   // Don't attempt folding in bundles.
1079   MachineInstr *MI = Ops.front().first;
1080   if (Ops.back().first != MI || MI->isBundled())
1081     return false;
1082
1083   bool WasCopy = MI->isCopy();
1084   unsigned ImpReg = 0;
1085
1086   bool SpillSubRegs = (MI->getOpcode() == TargetOpcode::PATCHPOINT ||
1087                        MI->getOpcode() == TargetOpcode::STACKMAP);
1088
1089   // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
1090   // operands.
1091   SmallVector<unsigned, 8> FoldOps;
1092   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1093     unsigned Idx = Ops[i].second;
1094     MachineOperand &MO = MI->getOperand(Idx);
1095     if (MO.isImplicit()) {
1096       ImpReg = MO.getReg();
1097       continue;
1098     }
1099     // FIXME: Teach targets to deal with subregs.
1100     if (!SpillSubRegs && MO.getSubReg())
1101       return false;
1102     // We cannot fold a load instruction into a def.
1103     if (LoadMI && MO.isDef())
1104       return false;
1105     // Tied use operands should not be passed to foldMemoryOperand.
1106     if (!MI->isRegTiedToDefOperand(Idx))
1107       FoldOps.push_back(Idx);
1108   }
1109
1110   MachineInstrSpan MIS(MI);
1111
1112   MachineInstr *FoldMI =
1113                 LoadMI ? TII.foldMemoryOperand(MI, FoldOps, LoadMI)
1114                        : TII.foldMemoryOperand(MI, FoldOps, StackSlot);
1115   if (!FoldMI)
1116     return false;
1117
1118   // Remove LIS for any dead defs in the original MI not in FoldMI.
1119   for (MIBundleOperands MO(MI); MO.isValid(); ++MO) {
1120     if (!MO->isReg())
1121       continue;
1122     unsigned Reg = MO->getReg();
1123     if (!Reg || TargetRegisterInfo::isVirtualRegister(Reg) ||
1124         MRI.isReserved(Reg)) {
1125       continue;
1126     }
1127     // Skip non-Defs, including undef uses and internal reads.
1128     if (MO->isUse())
1129       continue;
1130     MIBundleOperands::PhysRegInfo RI =
1131       MIBundleOperands(FoldMI).analyzePhysReg(Reg, &TRI);
1132     if (RI.Defines)
1133       continue;
1134     // FoldMI does not define this physreg. Remove the LI segment.
1135     assert(MO->isDead() && "Cannot fold physreg def");
1136     for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units) {
1137       if (LiveRange *LR = LIS.getCachedRegUnit(*Units)) {
1138         SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
1139         if (VNInfo *VNI = LR->getVNInfoAt(Idx))
1140           LR->removeValNo(VNI);
1141       }
1142     }
1143   }
1144
1145   LIS.ReplaceMachineInstrInMaps(MI, FoldMI);
1146   MI->eraseFromParent();
1147
1148   // Insert any new instructions other than FoldMI into the LIS maps.
1149   assert(!MIS.empty() && "Unexpected empty span of instructions!");
1150   for (MachineBasicBlock::iterator MII = MIS.begin(), End = MIS.end();
1151        MII != End; ++MII)
1152     if (&*MII != FoldMI)
1153       LIS.InsertMachineInstrInMaps(&*MII);
1154
1155   // TII.foldMemoryOperand may have left some implicit operands on the
1156   // instruction.  Strip them.
1157   if (ImpReg)
1158     for (unsigned i = FoldMI->getNumOperands(); i; --i) {
1159       MachineOperand &MO = FoldMI->getOperand(i - 1);
1160       if (!MO.isReg() || !MO.isImplicit())
1161         break;
1162       if (MO.getReg() == ImpReg)
1163         FoldMI->RemoveOperand(i - 1);
1164     }
1165
1166   DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MIS.end(), LIS,
1167                                            "folded"));
1168
1169   if (!WasCopy)
1170     ++NumFolded;
1171   else if (Ops.front().second == 0)
1172     ++NumSpills;
1173   else
1174     ++NumReloads;
1175   return true;
1176 }
1177
1178 void InlineSpiller::insertReload(unsigned NewVReg,
1179                                  SlotIndex Idx,
1180                                  MachineBasicBlock::iterator MI) {
1181   MachineBasicBlock &MBB = *MI->getParent();
1182
1183   MachineInstrSpan MIS(MI);
1184   TII.loadRegFromStackSlot(MBB, MI, NewVReg, StackSlot,
1185                            MRI.getRegClass(NewVReg), &TRI);
1186
1187   LIS.InsertMachineInstrRangeInMaps(MIS.begin(), MI);
1188
1189   DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MI, LIS, "reload",
1190                                            NewVReg));
1191   ++NumReloads;
1192 }
1193
1194 /// insertSpill - Insert a spill of NewVReg after MI.
1195 void InlineSpiller::insertSpill(unsigned NewVReg, bool isKill,
1196                                  MachineBasicBlock::iterator MI) {
1197   MachineBasicBlock &MBB = *MI->getParent();
1198
1199   MachineInstrSpan MIS(MI);
1200   TII.storeRegToStackSlot(MBB, std::next(MI), NewVReg, isKill, StackSlot,
1201                           MRI.getRegClass(NewVReg), &TRI);
1202
1203   LIS.InsertMachineInstrRangeInMaps(std::next(MI), MIS.end());
1204
1205   DEBUG(dumpMachineInstrRangeWithSlotIndex(std::next(MI), MIS.end(), LIS,
1206                                            "spill"));
1207   ++NumSpills;
1208 }
1209
1210 /// spillAroundUses - insert spill code around each use of Reg.
1211 void InlineSpiller::spillAroundUses(unsigned Reg) {
1212   DEBUG(dbgs() << "spillAroundUses " << PrintReg(Reg) << '\n');
1213   LiveInterval &OldLI = LIS.getInterval(Reg);
1214
1215   // Iterate over instructions using Reg.
1216   for (MachineRegisterInfo::reg_bundle_iterator
1217        RegI = MRI.reg_bundle_begin(Reg), E = MRI.reg_bundle_end();
1218        RegI != E; ) {
1219     MachineInstr *MI = &*(RegI++);
1220
1221     // Debug values are not allowed to affect codegen.
1222     if (MI->isDebugValue()) {
1223       // Modify DBG_VALUE now that the value is in a spill slot.
1224       bool IsIndirect = MI->isIndirectDebugValue();
1225       uint64_t Offset = IsIndirect ? MI->getOperand(1).getImm() : 0;
1226       const MDNode *Var = MI->getDebugVariable();
1227       const MDNode *Expr = MI->getDebugExpression();
1228       DebugLoc DL = MI->getDebugLoc();
1229       DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
1230       MachineBasicBlock *MBB = MI->getParent();
1231       BuildMI(*MBB, MBB->erase(MI), DL, TII.get(TargetOpcode::DBG_VALUE))
1232           .addFrameIndex(StackSlot)
1233           .addImm(Offset)
1234           .addMetadata(Var)
1235           .addMetadata(Expr);
1236       continue;
1237     }
1238
1239     // Ignore copies to/from snippets. We'll delete them.
1240     if (SnippetCopies.count(MI))
1241       continue;
1242
1243     // Stack slot accesses may coalesce away.
1244     if (coalesceStackAccess(MI, Reg))
1245       continue;
1246
1247     // Analyze instruction.
1248     SmallVector<std::pair<MachineInstr*, unsigned>, 8> Ops;
1249     MIBundleOperands::VirtRegInfo RI =
1250       MIBundleOperands(MI).analyzeVirtReg(Reg, &Ops);
1251
1252     // Find the slot index where this instruction reads and writes OldLI.
1253     // This is usually the def slot, except for tied early clobbers.
1254     SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
1255     if (VNInfo *VNI = OldLI.getVNInfoAt(Idx.getRegSlot(true)))
1256       if (SlotIndex::isSameInstr(Idx, VNI->def))
1257         Idx = VNI->def;
1258
1259     // Check for a sibling copy.
1260     unsigned SibReg = isFullCopyOf(MI, Reg);
1261     if (SibReg && isSibling(SibReg)) {
1262       // This may actually be a copy between snippets.
1263       if (isRegToSpill(SibReg)) {
1264         DEBUG(dbgs() << "Found new snippet copy: " << *MI);
1265         SnippetCopies.insert(MI);
1266         continue;
1267       }
1268       if (RI.Writes) {
1269         // Hoist the spill of a sib-reg copy.
1270         if (hoistSpill(OldLI, MI)) {
1271           // This COPY is now dead, the value is already in the stack slot.
1272           MI->getOperand(0).setIsDead();
1273           DeadDefs.push_back(MI);
1274           continue;
1275         }
1276       } else {
1277         // This is a reload for a sib-reg copy. Drop spills downstream.
1278         LiveInterval &SibLI = LIS.getInterval(SibReg);
1279         eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx));
1280         // The COPY will fold to a reload below.
1281       }
1282     }
1283
1284     // Attempt to fold memory ops.
1285     if (foldMemoryOperand(Ops))
1286       continue;
1287
1288     // Create a new virtual register for spill/fill.
1289     // FIXME: Infer regclass from instruction alone.
1290     unsigned NewVReg = Edit->createFrom(Reg);
1291
1292     if (RI.Reads)
1293       insertReload(NewVReg, Idx, MI);
1294
1295     // Rewrite instruction operands.
1296     bool hasLiveDef = false;
1297     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1298       MachineOperand &MO = Ops[i].first->getOperand(Ops[i].second);
1299       MO.setReg(NewVReg);
1300       if (MO.isUse()) {
1301         if (!Ops[i].first->isRegTiedToDefOperand(Ops[i].second))
1302           MO.setIsKill();
1303       } else {
1304         if (!MO.isDead())
1305           hasLiveDef = true;
1306       }
1307     }
1308     DEBUG(dbgs() << "\trewrite: " << Idx << '\t' << *MI << '\n');
1309
1310     // FIXME: Use a second vreg if instruction has no tied ops.
1311     if (RI.Writes)
1312       if (hasLiveDef)
1313         insertSpill(NewVReg, true, MI);
1314   }
1315 }
1316
1317 /// spillAll - Spill all registers remaining after rematerialization.
1318 void InlineSpiller::spillAll() {
1319   // Update LiveStacks now that we are committed to spilling.
1320   if (StackSlot == VirtRegMap::NO_STACK_SLOT) {
1321     StackSlot = VRM.assignVirt2StackSlot(Original);
1322     StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original));
1323     StackInt->getNextValue(SlotIndex(), LSS.getVNInfoAllocator());
1324   } else
1325     StackInt = &LSS.getInterval(StackSlot);
1326
1327   if (Original != Edit->getReg())
1328     VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot);
1329
1330   assert(StackInt->getNumValNums() == 1 && "Bad stack interval values");
1331   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1332     StackInt->MergeSegmentsInAsValue(LIS.getInterval(RegsToSpill[i]),
1333                                      StackInt->getValNumInfo(0));
1334   DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n');
1335
1336   // Spill around uses of all RegsToSpill.
1337   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1338     spillAroundUses(RegsToSpill[i]);
1339
1340   // Hoisted spills may cause dead code.
1341   if (!DeadDefs.empty()) {
1342     DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n");
1343     Edit->eliminateDeadDefs(DeadDefs, RegsToSpill);
1344   }
1345
1346   // Finally delete the SnippetCopies.
1347   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
1348     for (MachineRegisterInfo::reg_instr_iterator
1349          RI = MRI.reg_instr_begin(RegsToSpill[i]), E = MRI.reg_instr_end();
1350          RI != E; ) {
1351       MachineInstr *MI = &*(RI++);
1352       assert(SnippetCopies.count(MI) && "Remaining use wasn't a snippet copy");
1353       // FIXME: Do this with a LiveRangeEdit callback.
1354       LIS.RemoveMachineInstrFromMaps(MI);
1355       MI->eraseFromParent();
1356     }
1357   }
1358
1359   // Delete all spilled registers.
1360   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1361     Edit->eraseVirtReg(RegsToSpill[i]);
1362 }
1363
1364 void InlineSpiller::spill(LiveRangeEdit &edit) {
1365   ++NumSpilledRanges;
1366   Edit = &edit;
1367   assert(!TargetRegisterInfo::isStackSlot(edit.getReg())
1368          && "Trying to spill a stack slot.");
1369   // Share a stack slot among all descendants of Original.
1370   Original = VRM.getOriginal(edit.getReg());
1371   StackSlot = VRM.getStackSlot(Original);
1372   StackInt = nullptr;
1373
1374   DEBUG(dbgs() << "Inline spilling "
1375                << MRI.getRegClass(edit.getReg())->getName()
1376                << ':' << edit.getParent()
1377                << "\nFrom original " << PrintReg(Original) << '\n');
1378   assert(edit.getParent().isSpillable() &&
1379          "Attempting to spill already spilled value.");
1380   assert(DeadDefs.empty() && "Previous spill didn't remove dead defs");
1381
1382   collectRegsToSpill();
1383   analyzeSiblingValues();
1384   reMaterializeAll();
1385
1386   // Remat may handle everything.
1387   if (!RegsToSpill.empty())
1388     spillAll();
1389
1390   Edit->calculateRegClassAndHint(MF, Loops, MBFI);
1391 }