InlineSpiller: Store bucket pointers instead of iterators.
[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 #define DEBUG_TYPE "regalloc"
16 #include "Spiller.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/ADT/TinyPtrVector.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
22 #include "llvm/CodeGen/LiveRangeEdit.h"
23 #include "llvm/CodeGen/LiveStackAnalysis.h"
24 #include "llvm/CodeGen/MachineDominators.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBundle.h"
28 #include "llvm/CodeGen/MachineLoopInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/VirtRegMap.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetInstrInfo.h"
35 #include "llvm/Target/TargetMachine.h"
36
37 using namespace llvm;
38
39 STATISTIC(NumSpilledRanges,   "Number of spilled live ranges");
40 STATISTIC(NumSnippets,        "Number of spilled snippets");
41 STATISTIC(NumSpills,          "Number of spills inserted");
42 STATISTIC(NumSpillsRemoved,   "Number of spills removed");
43 STATISTIC(NumReloads,         "Number of reloads inserted");
44 STATISTIC(NumReloadsRemoved,  "Number of reloads removed");
45 STATISTIC(NumFolded,          "Number of folded stack accesses");
46 STATISTIC(NumFoldedLoads,     "Number of folded loads");
47 STATISTIC(NumRemats,          "Number of rematerialized defs for spilling");
48 STATISTIC(NumOmitReloadSpill, "Number of omitted spills of reloads");
49 STATISTIC(NumHoists,          "Number of hoisted spills");
50
51 static cl::opt<bool> DisableHoisting("disable-spill-hoist", cl::Hidden,
52                                      cl::desc("Disable inline spill hoisting"));
53
54 namespace {
55 class InlineSpiller : public Spiller {
56   MachineFunction &MF;
57   LiveIntervals &LIS;
58   LiveStacks &LSS;
59   AliasAnalysis *AA;
60   MachineDominatorTree &MDT;
61   MachineLoopInfo &Loops;
62   VirtRegMap &VRM;
63   MachineFrameInfo &MFI;
64   MachineRegisterInfo &MRI;
65   const TargetInstrInfo &TII;
66   const TargetRegisterInfo &TRI;
67
68   // Variables that are valid during spill(), but used by multiple methods.
69   LiveRangeEdit *Edit;
70   LiveInterval *StackInt;
71   int StackSlot;
72   unsigned Original;
73
74   // All registers to spill to StackSlot, including the main register.
75   SmallVector<unsigned, 8> RegsToSpill;
76
77   // All COPY instructions to/from snippets.
78   // They are ignored since both operands refer to the same stack slot.
79   SmallPtrSet<MachineInstr*, 8> SnippetCopies;
80
81   // Values that failed to remat at some point.
82   SmallPtrSet<VNInfo*, 8> UsedValues;
83
84 public:
85   // Information about a value that was defined by a copy from a sibling
86   // register.
87   struct SibValueInfo {
88     // True when all reaching defs were reloads: No spill is necessary.
89     bool AllDefsAreReloads;
90
91     // True when value is defined by an original PHI not from splitting.
92     bool DefByOrigPHI;
93
94     // True when the COPY defining this value killed its source.
95     bool KillsSource;
96
97     // The preferred register to spill.
98     unsigned SpillReg;
99
100     // The value of SpillReg that should be spilled.
101     VNInfo *SpillVNI;
102
103     // The block where SpillVNI should be spilled. Currently, this must be the
104     // block containing SpillVNI->def.
105     MachineBasicBlock *SpillMBB;
106
107     // A defining instruction that is not a sibling copy or a reload, or NULL.
108     // This can be used as a template for rematerialization.
109     MachineInstr *DefMI;
110
111     // List of values that depend on this one.  These values are actually the
112     // same, but live range splitting has placed them in different registers,
113     // or SSA update needed to insert PHI-defs to preserve SSA form.  This is
114     // copies of the current value and phi-kills.  Usually only phi-kills cause
115     // more than one dependent value.
116     TinyPtrVector<VNInfo*> Deps;
117
118     SibValueInfo(unsigned Reg, VNInfo *VNI)
119       : AllDefsAreReloads(true), DefByOrigPHI(false), KillsSource(false),
120         SpillReg(Reg), SpillVNI(VNI), SpillMBB(0), DefMI(0) {}
121
122     // Returns true when a def has been found.
123     bool hasDef() const { return DefByOrigPHI || DefMI; }
124   };
125
126 private:
127   // Values in RegsToSpill defined by sibling copies.
128   typedef DenseMap<VNInfo*, SibValueInfo> SibValueMap;
129   SibValueMap SibValues;
130
131   // Dead defs generated during spilling.
132   SmallVector<MachineInstr*, 8> DeadDefs;
133
134   ~InlineSpiller() {}
135
136 public:
137   InlineSpiller(MachineFunctionPass &pass,
138                 MachineFunction &mf,
139                 VirtRegMap &vrm)
140     : MF(mf),
141       LIS(pass.getAnalysis<LiveIntervals>()),
142       LSS(pass.getAnalysis<LiveStacks>()),
143       AA(&pass.getAnalysis<AliasAnalysis>()),
144       MDT(pass.getAnalysis<MachineDominatorTree>()),
145       Loops(pass.getAnalysis<MachineLoopInfo>()),
146       VRM(vrm),
147       MFI(*mf.getFrameInfo()),
148       MRI(mf.getRegInfo()),
149       TII(*mf.getTarget().getInstrInfo()),
150       TRI(*mf.getTarget().getRegisterInfo()) {}
151
152   void spill(LiveRangeEdit &);
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 = 0);
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 = 0);
178   void insertReload(LiveInterval &NewLI, SlotIndex,
179                     MachineBasicBlock::iterator MI);
180   void insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
181                    SlotIndex, MachineBasicBlock::iterator MI);
182
183   void spillAroundUses(unsigned Reg);
184   void spillAll();
185 };
186 }
187
188 namespace llvm {
189 Spiller *createInlineSpiller(MachineFunctionPass &pass,
190                              MachineFunction &mf,
191                              VirtRegMap &vrm) {
192   return new InlineSpiller(pass, mf, vrm);
193 }
194 }
195
196 //===----------------------------------------------------------------------===//
197 //                                Snippets
198 //===----------------------------------------------------------------------===//
199
200 // When spilling a virtual register, we also spill any snippets it is connected
201 // to. The snippets are small live ranges that only have a single real use,
202 // leftovers from live range splitting. Spilling them enables memory operand
203 // folding or tightens the live range around the single use.
204 //
205 // This minimizes register pressure and maximizes the store-to-load distance for
206 // spill slots which can be important in tight loops.
207
208 /// isFullCopyOf - If MI is a COPY to or from Reg, return the other register,
209 /// otherwise return 0.
210 static unsigned isFullCopyOf(const MachineInstr *MI, unsigned Reg) {
211   if (!MI->isFullCopy())
212     return 0;
213   if (MI->getOperand(0).getReg() == Reg)
214       return MI->getOperand(1).getReg();
215   if (MI->getOperand(1).getReg() == Reg)
216       return MI->getOperand(0).getReg();
217   return 0;
218 }
219
220 /// isSnippet - Identify if a live interval is a snippet that should be spilled.
221 /// It is assumed that SnipLI is a virtual register with the same original as
222 /// Edit->getReg().
223 bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
224   unsigned Reg = Edit->getReg();
225
226   // A snippet is a tiny live range with only a single instruction using it
227   // besides copies to/from Reg or spills/fills. We accept:
228   //
229   //   %snip = COPY %Reg / FILL fi#
230   //   %snip = USE %snip
231   //   %Reg = COPY %snip / SPILL %snip, fi#
232   //
233   if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI))
234     return false;
235
236   MachineInstr *UseMI = 0;
237
238   // Check that all uses satisfy our criteria.
239   for (MachineRegisterInfo::reg_nodbg_iterator
240          RI = MRI.reg_nodbg_begin(SnipLI.reg);
241        MachineInstr *MI = RI.skipInstruction();) {
242
243     // Allow copies to/from Reg.
244     if (isFullCopyOf(MI, Reg))
245       continue;
246
247     // Allow stack slot loads.
248     int FI;
249     if (SnipLI.reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
250       continue;
251
252     // Allow stack slot stores.
253     if (SnipLI.reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
254       continue;
255
256     // Allow a single additional instruction.
257     if (UseMI && MI != UseMI)
258       return false;
259     UseMI = MI;
260   }
261   return true;
262 }
263
264 /// collectRegsToSpill - Collect live range snippets that only have a single
265 /// real use.
266 void InlineSpiller::collectRegsToSpill() {
267   unsigned Reg = Edit->getReg();
268
269   // Main register always spills.
270   RegsToSpill.assign(1, Reg);
271   SnippetCopies.clear();
272
273   // Snippets all have the same original, so there can't be any for an original
274   // register.
275   if (Original == Reg)
276     return;
277
278   for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(Reg);
279        MachineInstr *MI = RI.skipInstruction();) {
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 = 0;
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           if ((Loops.getLoopDepth(DepSV.SpillMBB) > SpillDepth) &&
440               (!DepSVI->first->isPHIDef() ||
441                MDT.dominates(SV.SpillMBB, DepSV.SpillMBB))) {
442             Changed = true;
443             DepSV.SpillReg = SV.SpillReg;
444             DepSV.SpillVNI = SV.SpillVNI;
445             DepSV.SpillMBB = SV.SpillMBB;
446           }
447         }
448       }
449
450       if (!Changed)
451         continue;
452
453       // Something changed in DepSVI. Propagate to dependents.
454       WorkList.insert(&*DepSVI);
455
456       DEBUG(dbgs() << "  update " << DepSVI->first->id << '@'
457             << DepSVI->first->def << " to:\t" << DepSV);
458     }
459   } while (!WorkList.empty());
460 }
461
462 /// traceSiblingValue - Trace a value that is about to be spilled back to the
463 /// real defining instructions by looking through sibling copies. Always stay
464 /// within the range of OrigVNI so the registers are known to carry the same
465 /// value.
466 ///
467 /// Determine if the value is defined by all reloads, so spilling isn't
468 /// necessary - the value is already in the stack slot.
469 ///
470 /// Return a defining instruction that may be a candidate for rematerialization.
471 ///
472 MachineInstr *InlineSpiller::traceSiblingValue(unsigned UseReg, VNInfo *UseVNI,
473                                                VNInfo *OrigVNI) {
474   // Check if a cached value already exists.
475   SibValueMap::iterator SVI;
476   bool Inserted;
477   tie(SVI, Inserted) =
478     SibValues.insert(std::make_pair(UseVNI, SibValueInfo(UseReg, UseVNI)));
479   if (!Inserted) {
480     DEBUG(dbgs() << "Cached value " << PrintReg(UseReg) << ':'
481                  << UseVNI->id << '@' << UseVNI->def << ' ' << SVI->second);
482     return SVI->second.DefMI;
483   }
484
485   DEBUG(dbgs() << "Tracing value " << PrintReg(UseReg) << ':'
486                << UseVNI->id << '@' << UseVNI->def << '\n');
487
488   // List of (Reg, VNI) that have been inserted into SibValues, but need to be
489   // processed.
490   SmallVector<std::pair<unsigned, VNInfo*>, 8> WorkList;
491   WorkList.push_back(std::make_pair(UseReg, UseVNI));
492
493   do {
494     unsigned Reg;
495     VNInfo *VNI;
496     tie(Reg, VNI) = WorkList.pop_back_val();
497     DEBUG(dbgs() << "  " << PrintReg(Reg) << ':' << VNI->id << '@' << VNI->def
498                  << ":\t");
499
500     // First check if this value has already been computed.
501     SVI = SibValues.find(VNI);
502     assert(SVI != SibValues.end() && "Missing SibValues entry");
503
504     // Trace through PHI-defs created by live range splitting.
505     if (VNI->isPHIDef()) {
506       // Stop at original PHIs.  We don't know the value at the predecessors.
507       if (VNI->def == OrigVNI->def) {
508         DEBUG(dbgs() << "orig phi value\n");
509         SVI->second.DefByOrigPHI = true;
510         SVI->second.AllDefsAreReloads = false;
511         propagateSiblingValue(SVI);
512         continue;
513       }
514
515       // This is a PHI inserted by live range splitting.  We could trace the
516       // live-out value from predecessor blocks, but that search can be very
517       // expensive if there are many predecessors and many more PHIs as
518       // generated by tail-dup when it sees an indirectbr.  Instead, look at
519       // all the non-PHI defs that have the same value as OrigVNI.  They must
520       // jointly dominate VNI->def.  This is not optimal since VNI may actually
521       // be jointly dominated by a smaller subset of defs, so there is a change
522       // we will miss a AllDefsAreReloads optimization.
523
524       // Separate all values dominated by OrigVNI into PHIs and non-PHIs.
525       SmallVector<VNInfo*, 8> PHIs, NonPHIs;
526       LiveInterval &LI = LIS.getInterval(Reg);
527       LiveInterval &OrigLI = LIS.getInterval(Original);
528
529       for (LiveInterval::vni_iterator VI = LI.vni_begin(), VE = LI.vni_end();
530            VI != VE; ++VI) {
531         VNInfo *VNI2 = *VI;
532         if (VNI2->isUnused())
533           continue;
534         if (!OrigLI.containsOneValue() &&
535             OrigLI.getVNInfoAt(VNI2->def) != OrigVNI)
536           continue;
537         if (VNI2->isPHIDef() && VNI2->def != OrigVNI->def)
538           PHIs.push_back(VNI2);
539         else
540           NonPHIs.push_back(VNI2);
541       }
542       DEBUG(dbgs() << "split phi value, checking " << PHIs.size()
543                    << " phi-defs, and " << NonPHIs.size()
544                    << " non-phi/orig defs\n");
545
546       // Create entries for all the PHIs.  Don't add them to the worklist, we
547       // are processing all of them in one go here.
548       for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
549         SibValues.insert(std::make_pair(PHIs[i], SibValueInfo(Reg, PHIs[i])));
550
551       // Add every PHI as a dependent of all the non-PHIs.
552       for (unsigned i = 0, e = NonPHIs.size(); i != e; ++i) {
553         VNInfo *NonPHI = NonPHIs[i];
554         // Known value? Try an insertion.
555         tie(SVI, Inserted) =
556           SibValues.insert(std::make_pair(NonPHI, SibValueInfo(Reg, NonPHI)));
557         // Add all the PHIs as dependents of NonPHI.
558         for (unsigned pi = 0, pe = PHIs.size(); pi != pe; ++pi)
559           SVI->second.Deps.push_back(PHIs[pi]);
560         // This is the first time we see NonPHI, add it to the worklist.
561         if (Inserted)
562           WorkList.push_back(std::make_pair(Reg, NonPHI));
563         else
564           // Propagate to all inserted PHIs, not just VNI.
565           propagateSiblingValue(SVI);
566       }
567
568       // Next work list item.
569       continue;
570     }
571
572     MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
573     assert(MI && "Missing def");
574
575     // Trace through sibling copies.
576     if (unsigned SrcReg = isFullCopyOf(MI, Reg)) {
577       if (isSibling(SrcReg)) {
578         LiveInterval &SrcLI = LIS.getInterval(SrcReg);
579         LiveRangeQuery SrcQ(SrcLI, VNI->def);
580         assert(SrcQ.valueIn() && "Copy from non-existing value");
581         // Check if this COPY kills its source.
582         SVI->second.KillsSource = SrcQ.isKill();
583         VNInfo *SrcVNI = SrcQ.valueIn();
584         DEBUG(dbgs() << "copy of " << PrintReg(SrcReg) << ':'
585                      << SrcVNI->id << '@' << SrcVNI->def
586                      << " kill=" << unsigned(SVI->second.KillsSource) << '\n');
587         // Known sibling source value? Try an insertion.
588         tie(SVI, Inserted) = SibValues.insert(std::make_pair(SrcVNI,
589                                                  SibValueInfo(SrcReg, SrcVNI)));
590         // This is the first time we see Src, add it to the worklist.
591         if (Inserted)
592           WorkList.push_back(std::make_pair(SrcReg, SrcVNI));
593         propagateSiblingValue(SVI, VNI);
594         // Next work list item.
595         continue;
596       }
597     }
598
599     // Track reachable reloads.
600     SVI->second.DefMI = MI;
601     SVI->second.SpillMBB = MI->getParent();
602     int FI;
603     if (Reg == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot) {
604       DEBUG(dbgs() << "reload\n");
605       propagateSiblingValue(SVI);
606       // Next work list item.
607       continue;
608     }
609
610     // Potential remat candidate.
611     DEBUG(dbgs() << "def " << *MI);
612     SVI->second.AllDefsAreReloads = false;
613     propagateSiblingValue(SVI);
614   } while (!WorkList.empty());
615
616   // Look up the value we were looking for.  We already did this lookup at the
617   // top of the function, but SibValues may have been invalidated.
618   SVI = SibValues.find(UseVNI);
619   assert(SVI != SibValues.end() && "Didn't compute requested info");
620   DEBUG(dbgs() << "  traced to:\t" << SVI->second);
621   return SVI->second.DefMI;
622 }
623
624 /// analyzeSiblingValues - Trace values defined by sibling copies back to
625 /// something that isn't a sibling copy.
626 ///
627 /// Keep track of values that may be rematerializable.
628 void InlineSpiller::analyzeSiblingValues() {
629   SibValues.clear();
630
631   // No siblings at all?
632   if (Edit->getReg() == Original)
633     return;
634
635   LiveInterval &OrigLI = LIS.getInterval(Original);
636   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
637     unsigned Reg = RegsToSpill[i];
638     LiveInterval &LI = LIS.getInterval(Reg);
639     for (LiveInterval::const_vni_iterator VI = LI.vni_begin(),
640          VE = LI.vni_end(); VI != VE; ++VI) {
641       VNInfo *VNI = *VI;
642       if (VNI->isUnused())
643         continue;
644       MachineInstr *DefMI = 0;
645       if (!VNI->isPHIDef()) {
646        DefMI = LIS.getInstructionFromIndex(VNI->def);
647        assert(DefMI && "No defining instruction");
648       }
649       // Check possible sibling copies.
650       if (VNI->isPHIDef() || DefMI->isCopy()) {
651         VNInfo *OrigVNI = OrigLI.getVNInfoAt(VNI->def);
652         assert(OrigVNI && "Def outside original live range");
653         if (OrigVNI->def != VNI->def)
654           DefMI = traceSiblingValue(Reg, VNI, OrigVNI);
655       }
656       if (DefMI && Edit->checkRematerializable(VNI, DefMI, AA)) {
657         DEBUG(dbgs() << "Value " << PrintReg(Reg) << ':' << VNI->id << '@'
658                      << VNI->def << " may remat from " << *DefMI);
659       }
660     }
661   }
662 }
663
664 /// hoistSpill - Given a sibling copy that defines a value to be spilled, insert
665 /// a spill at a better location.
666 bool InlineSpiller::hoistSpill(LiveInterval &SpillLI, MachineInstr *CopyMI) {
667   SlotIndex Idx = LIS.getInstructionIndex(CopyMI);
668   VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getRegSlot());
669   assert(VNI && VNI->def == Idx.getRegSlot() && "Not defined by copy");
670   SibValueMap::iterator I = SibValues.find(VNI);
671   if (I == SibValues.end())
672     return false;
673
674   const SibValueInfo &SVI = I->second;
675
676   // Let the normal folding code deal with the boring case.
677   if (!SVI.AllDefsAreReloads && SVI.SpillVNI == VNI)
678     return false;
679
680   // SpillReg may have been deleted by remat and DCE.
681   if (!LIS.hasInterval(SVI.SpillReg)) {
682     DEBUG(dbgs() << "Stale interval: " << PrintReg(SVI.SpillReg) << '\n');
683     SibValues.erase(I);
684     return false;
685   }
686
687   LiveInterval &SibLI = LIS.getInterval(SVI.SpillReg);
688   if (!SibLI.containsValue(SVI.SpillVNI)) {
689     DEBUG(dbgs() << "Stale value: " << PrintReg(SVI.SpillReg) << '\n');
690     SibValues.erase(I);
691     return false;
692   }
693
694   // Conservatively extend the stack slot range to the range of the original
695   // value. We may be able to do better with stack slot coloring by being more
696   // careful here.
697   assert(StackInt && "No stack slot assigned yet.");
698   LiveInterval &OrigLI = LIS.getInterval(Original);
699   VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
700   StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0));
701   DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
702                << *StackInt << '\n');
703
704   // Already spilled everywhere.
705   if (SVI.AllDefsAreReloads) {
706     DEBUG(dbgs() << "\tno spill needed: " << SVI);
707     ++NumOmitReloadSpill;
708     return true;
709   }
710   // We are going to spill SVI.SpillVNI immediately after its def, so clear out
711   // any later spills of the same value.
712   eliminateRedundantSpills(SibLI, SVI.SpillVNI);
713
714   MachineBasicBlock *MBB = LIS.getMBBFromIndex(SVI.SpillVNI->def);
715   MachineBasicBlock::iterator MII;
716   if (SVI.SpillVNI->isPHIDef())
717     MII = MBB->SkipPHIsAndLabels(MBB->begin());
718   else {
719     MachineInstr *DefMI = LIS.getInstructionFromIndex(SVI.SpillVNI->def);
720     assert(DefMI && "Defining instruction disappeared");
721     MII = DefMI;
722     ++MII;
723   }
724   // Insert spill without kill flag immediately after def.
725   TII.storeRegToStackSlot(*MBB, MII, SVI.SpillReg, false, StackSlot,
726                           MRI.getRegClass(SVI.SpillReg), &TRI);
727   --MII; // Point to store instruction.
728   LIS.InsertMachineInstrInMaps(MII);
729   DEBUG(dbgs() << "\thoisted: " << SVI.SpillVNI->def << '\t' << *MII);
730
731   ++NumSpills;
732   ++NumHoists;
733   return true;
734 }
735
736 /// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any
737 /// redundant spills of this value in SLI.reg and sibling copies.
738 void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
739   assert(VNI && "Missing value");
740   SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
741   WorkList.push_back(std::make_pair(&SLI, VNI));
742   assert(StackInt && "No stack slot assigned yet.");
743
744   do {
745     LiveInterval *LI;
746     tie(LI, VNI) = WorkList.pop_back_val();
747     unsigned Reg = LI->reg;
748     DEBUG(dbgs() << "Checking redundant spills for "
749                  << VNI->id << '@' << VNI->def << " in " << *LI << '\n');
750
751     // Regs to spill are taken care of.
752     if (isRegToSpill(Reg))
753       continue;
754
755     // Add all of VNI's live range to StackInt.
756     StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0));
757     DEBUG(dbgs() << "Merged to stack int: " << *StackInt << '\n');
758
759     // Find all spills and copies of VNI.
760     for (MachineRegisterInfo::use_nodbg_iterator UI = MRI.use_nodbg_begin(Reg);
761          MachineInstr *MI = UI.skipInstruction();) {
762       if (!MI->isCopy() && !MI->mayStore())
763         continue;
764       SlotIndex Idx = LIS.getInstructionIndex(MI);
765       if (LI->getVNInfoAt(Idx) != VNI)
766         continue;
767
768       // Follow sibling copies down the dominator tree.
769       if (unsigned DstReg = isFullCopyOf(MI, Reg)) {
770         if (isSibling(DstReg)) {
771            LiveInterval &DstLI = LIS.getInterval(DstReg);
772            VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getRegSlot());
773            assert(DstVNI && "Missing defined value");
774            assert(DstVNI->def == Idx.getRegSlot() && "Wrong copy def slot");
775            WorkList.push_back(std::make_pair(&DstLI, DstVNI));
776         }
777         continue;
778       }
779
780       // Erase spills.
781       int FI;
782       if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) {
783         DEBUG(dbgs() << "Redundant spill " << Idx << '\t' << *MI);
784         // eliminateDeadDefs won't normally remove stores, so switch opcode.
785         MI->setDesc(TII.get(TargetOpcode::KILL));
786         DeadDefs.push_back(MI);
787         ++NumSpillsRemoved;
788         --NumSpills;
789       }
790     }
791   } while (!WorkList.empty());
792 }
793
794
795 //===----------------------------------------------------------------------===//
796 //                            Rematerialization
797 //===----------------------------------------------------------------------===//
798
799 /// markValueUsed - Remember that VNI failed to rematerialize, so its defining
800 /// instruction cannot be eliminated. See through snippet copies
801 void InlineSpiller::markValueUsed(LiveInterval *LI, VNInfo *VNI) {
802   SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
803   WorkList.push_back(std::make_pair(LI, VNI));
804   do {
805     tie(LI, VNI) = WorkList.pop_back_val();
806     if (!UsedValues.insert(VNI))
807       continue;
808
809     if (VNI->isPHIDef()) {
810       MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
811       for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
812              PE = MBB->pred_end(); PI != PE; ++PI) {
813         VNInfo *PVNI = LI->getVNInfoBefore(LIS.getMBBEndIdx(*PI));
814         if (PVNI)
815           WorkList.push_back(std::make_pair(LI, PVNI));
816       }
817       continue;
818     }
819
820     // Follow snippet copies.
821     MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
822     if (!SnippetCopies.count(MI))
823       continue;
824     LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg());
825     assert(isRegToSpill(SnipLI.reg) && "Unexpected register in copy");
826     VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getRegSlot(true));
827     assert(SnipVNI && "Snippet undefined before copy");
828     WorkList.push_back(std::make_pair(&SnipLI, SnipVNI));
829   } while (!WorkList.empty());
830 }
831
832 /// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
833 bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg,
834                                      MachineBasicBlock::iterator MI) {
835   SlotIndex UseIdx = LIS.getInstructionIndex(MI).getRegSlot(true);
836   VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx.getBaseIndex());
837
838   if (!ParentVNI) {
839     DEBUG(dbgs() << "\tadding <undef> flags: ");
840     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
841       MachineOperand &MO = MI->getOperand(i);
842       if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg)
843         MO.setIsUndef();
844     }
845     DEBUG(dbgs() << UseIdx << '\t' << *MI);
846     return true;
847   }
848
849   if (SnippetCopies.count(MI))
850     return false;
851
852   // Use an OrigVNI from traceSiblingValue when ParentVNI is a sibling copy.
853   LiveRangeEdit::Remat RM(ParentVNI);
854   SibValueMap::const_iterator SibI = SibValues.find(ParentVNI);
855   if (SibI != SibValues.end())
856     RM.OrigMI = SibI->second.DefMI;
857   if (!Edit->canRematerializeAt(RM, UseIdx, false)) {
858     markValueUsed(&VirtReg, ParentVNI);
859     DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << *MI);
860     return false;
861   }
862
863   // If the instruction also writes VirtReg.reg, it had better not require the
864   // same register for uses and defs.
865   SmallVector<std::pair<MachineInstr*, unsigned>, 8> Ops;
866   MIBundleOperands::VirtRegInfo RI =
867     MIBundleOperands(MI).analyzeVirtReg(VirtReg.reg, &Ops);
868   if (RI.Tied) {
869     markValueUsed(&VirtReg, ParentVNI);
870     DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << *MI);
871     return false;
872   }
873
874   // Before rematerializing into a register for a single instruction, try to
875   // fold a load into the instruction. That avoids allocating a new register.
876   if (RM.OrigMI->canFoldAsLoad() &&
877       foldMemoryOperand(Ops, RM.OrigMI)) {
878     Edit->markRematerialized(RM.ParentVNI);
879     ++NumFoldedLoads;
880     return true;
881   }
882
883   // Alocate a new register for the remat.
884   LiveInterval &NewLI = Edit->createFrom(Original);
885   NewLI.markNotSpillable();
886
887   // Finally we can rematerialize OrigMI before MI.
888   SlotIndex DefIdx = Edit->rematerializeAt(*MI->getParent(), MI, NewLI.reg, RM,
889                                            TRI);
890   DEBUG(dbgs() << "\tremat:  " << DefIdx << '\t'
891                << *LIS.getInstructionFromIndex(DefIdx));
892
893   // Replace operands
894   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
895     MachineOperand &MO = MI->getOperand(Ops[i].second);
896     if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg) {
897       MO.setReg(NewLI.reg);
898       MO.setIsKill();
899     }
900   }
901   DEBUG(dbgs() << "\t        " << UseIdx << '\t' << *MI);
902
903   VNInfo *DefVNI = NewLI.getNextValue(DefIdx, LIS.getVNInfoAllocator());
904   NewLI.addRange(LiveRange(DefIdx, UseIdx.getRegSlot(), DefVNI));
905   DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
906   ++NumRemats;
907   return true;
908 }
909
910 /// reMaterializeAll - Try to rematerialize as many uses as possible,
911 /// and trim the live ranges after.
912 void InlineSpiller::reMaterializeAll() {
913   // analyzeSiblingValues has already tested all relevant defining instructions.
914   if (!Edit->anyRematerializable(AA))
915     return;
916
917   UsedValues.clear();
918
919   // Try to remat before all uses of snippets.
920   bool anyRemat = false;
921   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
922     unsigned Reg = RegsToSpill[i];
923     LiveInterval &LI = LIS.getInterval(Reg);
924     for (MachineRegisterInfo::use_nodbg_iterator
925          RI = MRI.use_nodbg_begin(Reg);
926          MachineInstr *MI = RI.skipBundle();)
927       anyRemat |= reMaterializeFor(LI, MI);
928   }
929   if (!anyRemat)
930     return;
931
932   // Remove any values that were completely rematted.
933   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
934     unsigned Reg = RegsToSpill[i];
935     LiveInterval &LI = LIS.getInterval(Reg);
936     for (LiveInterval::vni_iterator I = LI.vni_begin(), E = LI.vni_end();
937          I != E; ++I) {
938       VNInfo *VNI = *I;
939       if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI))
940         continue;
941       MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
942       MI->addRegisterDead(Reg, &TRI);
943       if (!MI->allDefsAreDead())
944         continue;
945       DEBUG(dbgs() << "All defs dead: " << *MI);
946       DeadDefs.push_back(MI);
947     }
948   }
949
950   // Eliminate dead code after remat. Note that some snippet copies may be
951   // deleted here.
952   if (DeadDefs.empty())
953     return;
954   DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n");
955   Edit->eliminateDeadDefs(DeadDefs, RegsToSpill);
956
957   // Get rid of deleted and empty intervals.
958   unsigned ResultPos = 0;
959   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
960     unsigned Reg = RegsToSpill[i];
961     if (!LIS.hasInterval(Reg))
962       continue;
963
964     LiveInterval &LI = LIS.getInterval(Reg);
965     if (LI.empty()) {
966       Edit->eraseVirtReg(Reg);
967       continue;
968     }
969
970     RegsToSpill[ResultPos++] = Reg;
971   }
972   RegsToSpill.erase(RegsToSpill.begin() + ResultPos, RegsToSpill.end());
973   DEBUG(dbgs() << RegsToSpill.size() << " registers to spill after remat.\n");
974 }
975
976
977 //===----------------------------------------------------------------------===//
978 //                                 Spilling
979 //===----------------------------------------------------------------------===//
980
981 /// If MI is a load or store of StackSlot, it can be removed.
982 bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, unsigned Reg) {
983   int FI = 0;
984   unsigned InstrReg = TII.isLoadFromStackSlot(MI, FI);
985   bool IsLoad = InstrReg;
986   if (!IsLoad)
987     InstrReg = TII.isStoreToStackSlot(MI, FI);
988
989   // We have a stack access. Is it the right register and slot?
990   if (InstrReg != Reg || FI != StackSlot)
991     return false;
992
993   DEBUG(dbgs() << "Coalescing stack access: " << *MI);
994   LIS.RemoveMachineInstrFromMaps(MI);
995   MI->eraseFromParent();
996
997   if (IsLoad) {
998     ++NumReloadsRemoved;
999     --NumReloads;
1000   } else {
1001     ++NumSpillsRemoved;
1002     --NumSpills;
1003   }
1004
1005   return true;
1006 }
1007
1008 /// foldMemoryOperand - Try folding stack slot references in Ops into their
1009 /// instructions.
1010 ///
1011 /// @param Ops    Operand indices from analyzeVirtReg().
1012 /// @param LoadMI Load instruction to use instead of stack slot when non-null.
1013 /// @return       True on success.
1014 bool InlineSpiller::
1015 foldMemoryOperand(ArrayRef<std::pair<MachineInstr*, unsigned> > Ops,
1016                   MachineInstr *LoadMI) {
1017   if (Ops.empty())
1018     return false;
1019   // Don't attempt folding in bundles.
1020   MachineInstr *MI = Ops.front().first;
1021   if (Ops.back().first != MI || MI->isBundled())
1022     return false;
1023
1024   bool WasCopy = MI->isCopy();
1025   unsigned ImpReg = 0;
1026
1027   // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
1028   // operands.
1029   SmallVector<unsigned, 8> FoldOps;
1030   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1031     unsigned Idx = Ops[i].second;
1032     MachineOperand &MO = MI->getOperand(Idx);
1033     if (MO.isImplicit()) {
1034       ImpReg = MO.getReg();
1035       continue;
1036     }
1037     // FIXME: Teach targets to deal with subregs.
1038     if (MO.getSubReg())
1039       return false;
1040     // We cannot fold a load instruction into a def.
1041     if (LoadMI && MO.isDef())
1042       return false;
1043     // Tied use operands should not be passed to foldMemoryOperand.
1044     if (!MI->isRegTiedToDefOperand(Idx))
1045       FoldOps.push_back(Idx);
1046   }
1047
1048   MachineInstr *FoldMI =
1049                 LoadMI ? TII.foldMemoryOperand(MI, FoldOps, LoadMI)
1050                        : TII.foldMemoryOperand(MI, FoldOps, StackSlot);
1051   if (!FoldMI)
1052     return false;
1053   LIS.ReplaceMachineInstrInMaps(MI, FoldMI);
1054   MI->eraseFromParent();
1055
1056   // TII.foldMemoryOperand may have left some implicit operands on the
1057   // instruction.  Strip them.
1058   if (ImpReg)
1059     for (unsigned i = FoldMI->getNumOperands(); i; --i) {
1060       MachineOperand &MO = FoldMI->getOperand(i - 1);
1061       if (!MO.isReg() || !MO.isImplicit())
1062         break;
1063       if (MO.getReg() == ImpReg)
1064         FoldMI->RemoveOperand(i - 1);
1065     }
1066
1067   DEBUG(dbgs() << "\tfolded:  " << LIS.getInstructionIndex(FoldMI) << '\t'
1068                << *FoldMI);
1069   if (!WasCopy)
1070     ++NumFolded;
1071   else if (Ops.front().second == 0)
1072     ++NumSpills;
1073   else
1074     ++NumReloads;
1075   return true;
1076 }
1077
1078 /// insertReload - Insert a reload of NewLI.reg before MI.
1079 void InlineSpiller::insertReload(LiveInterval &NewLI,
1080                                  SlotIndex Idx,
1081                                  MachineBasicBlock::iterator MI) {
1082   MachineBasicBlock &MBB = *MI->getParent();
1083   TII.loadRegFromStackSlot(MBB, MI, NewLI.reg, StackSlot,
1084                            MRI.getRegClass(NewLI.reg), &TRI);
1085   --MI; // Point to load instruction.
1086   SlotIndex LoadIdx = LIS.InsertMachineInstrInMaps(MI).getRegSlot();
1087   // Some (out-of-tree) targets have EC reload instructions.
1088   if (MachineOperand *MO = MI->findRegisterDefOperand(NewLI.reg))
1089     if (MO->isEarlyClobber())
1090       LoadIdx = LoadIdx.getRegSlot(true);
1091   DEBUG(dbgs() << "\treload:  " << LoadIdx << '\t' << *MI);
1092   VNInfo *LoadVNI = NewLI.getNextValue(LoadIdx, LIS.getVNInfoAllocator());
1093   NewLI.addRange(LiveRange(LoadIdx, Idx, LoadVNI));
1094   ++NumReloads;
1095 }
1096
1097 /// insertSpill - Insert a spill of NewLI.reg after MI.
1098 void InlineSpiller::insertSpill(LiveInterval &NewLI, const LiveInterval &OldLI,
1099                                 SlotIndex Idx, MachineBasicBlock::iterator MI) {
1100   MachineBasicBlock &MBB = *MI->getParent();
1101   TII.storeRegToStackSlot(MBB, ++MI, NewLI.reg, true, StackSlot,
1102                           MRI.getRegClass(NewLI.reg), &TRI);
1103   --MI; // Point to store instruction.
1104   SlotIndex StoreIdx = LIS.InsertMachineInstrInMaps(MI).getRegSlot();
1105   DEBUG(dbgs() << "\tspilled: " << StoreIdx << '\t' << *MI);
1106   VNInfo *StoreVNI = NewLI.getNextValue(Idx, LIS.getVNInfoAllocator());
1107   NewLI.addRange(LiveRange(Idx, StoreIdx, StoreVNI));
1108   ++NumSpills;
1109 }
1110
1111 /// spillAroundUses - insert spill code around each use of Reg.
1112 void InlineSpiller::spillAroundUses(unsigned Reg) {
1113   DEBUG(dbgs() << "spillAroundUses " << PrintReg(Reg) << '\n');
1114   LiveInterval &OldLI = LIS.getInterval(Reg);
1115
1116   // Iterate over instructions using Reg.
1117   for (MachineRegisterInfo::reg_iterator RegI = MRI.reg_begin(Reg);
1118        MachineInstr *MI = RegI.skipBundle();) {
1119
1120     // Debug values are not allowed to affect codegen.
1121     if (MI->isDebugValue()) {
1122       // Modify DBG_VALUE now that the value is in a spill slot.
1123       uint64_t Offset = MI->getOperand(1).getImm();
1124       const MDNode *MDPtr = MI->getOperand(2).getMetadata();
1125       DebugLoc DL = MI->getDebugLoc();
1126       if (MachineInstr *NewDV = TII.emitFrameIndexDebugValue(MF, StackSlot,
1127                                                            Offset, MDPtr, DL)) {
1128         DEBUG(dbgs() << "Modifying debug info due to spill:" << "\t" << *MI);
1129         MachineBasicBlock *MBB = MI->getParent();
1130         MBB->insert(MBB->erase(MI), NewDV);
1131       } else {
1132         DEBUG(dbgs() << "Removing debug info due to spill:" << "\t" << *MI);
1133         MI->eraseFromParent();
1134       }
1135       continue;
1136     }
1137
1138     // Ignore copies to/from snippets. We'll delete them.
1139     if (SnippetCopies.count(MI))
1140       continue;
1141
1142     // Stack slot accesses may coalesce away.
1143     if (coalesceStackAccess(MI, Reg))
1144       continue;
1145
1146     // Analyze instruction.
1147     SmallVector<std::pair<MachineInstr*, unsigned>, 8> Ops;
1148     MIBundleOperands::VirtRegInfo RI =
1149       MIBundleOperands(MI).analyzeVirtReg(Reg, &Ops);
1150
1151     // Find the slot index where this instruction reads and writes OldLI.
1152     // This is usually the def slot, except for tied early clobbers.
1153     SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
1154     if (VNInfo *VNI = OldLI.getVNInfoAt(Idx.getRegSlot(true)))
1155       if (SlotIndex::isSameInstr(Idx, VNI->def))
1156         Idx = VNI->def;
1157
1158     // Check for a sibling copy.
1159     unsigned SibReg = isFullCopyOf(MI, Reg);
1160     if (SibReg && isSibling(SibReg)) {
1161       // This may actually be a copy between snippets.
1162       if (isRegToSpill(SibReg)) {
1163         DEBUG(dbgs() << "Found new snippet copy: " << *MI);
1164         SnippetCopies.insert(MI);
1165         continue;
1166       }
1167       if (RI.Writes) {
1168         // Hoist the spill of a sib-reg copy.
1169         if (hoistSpill(OldLI, MI)) {
1170           // This COPY is now dead, the value is already in the stack slot.
1171           MI->getOperand(0).setIsDead();
1172           DeadDefs.push_back(MI);
1173           continue;
1174         }
1175       } else {
1176         // This is a reload for a sib-reg copy. Drop spills downstream.
1177         LiveInterval &SibLI = LIS.getInterval(SibReg);
1178         eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx));
1179         // The COPY will fold to a reload below.
1180       }
1181     }
1182
1183     // Attempt to fold memory ops.
1184     if (foldMemoryOperand(Ops))
1185       continue;
1186
1187     // Allocate interval around instruction.
1188     // FIXME: Infer regclass from instruction alone.
1189     LiveInterval &NewLI = Edit->createFrom(Reg);
1190     NewLI.markNotSpillable();
1191
1192     if (RI.Reads)
1193       insertReload(NewLI, Idx, MI);
1194
1195     // Rewrite instruction operands.
1196     bool hasLiveDef = false;
1197     for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1198       MachineOperand &MO = Ops[i].first->getOperand(Ops[i].second);
1199       MO.setReg(NewLI.reg);
1200       if (MO.isUse()) {
1201         if (!Ops[i].first->isRegTiedToDefOperand(Ops[i].second))
1202           MO.setIsKill();
1203       } else {
1204         if (!MO.isDead())
1205           hasLiveDef = true;
1206       }
1207     }
1208     DEBUG(dbgs() << "\trewrite: " << Idx << '\t' << *MI);
1209
1210     // FIXME: Use a second vreg if instruction has no tied ops.
1211     if (RI.Writes) {
1212       if (hasLiveDef)
1213         insertSpill(NewLI, OldLI, Idx, MI);
1214       else {
1215         // This instruction defines a dead value.  We don't need to spill it,
1216         // but do create a live range for the dead value.
1217         VNInfo *VNI = NewLI.getNextValue(Idx, LIS.getVNInfoAllocator());
1218         NewLI.addRange(LiveRange(Idx, Idx.getDeadSlot(), VNI));
1219       }
1220     }
1221
1222     DEBUG(dbgs() << "\tinterval: " << NewLI << '\n');
1223   }
1224 }
1225
1226 /// spillAll - Spill all registers remaining after rematerialization.
1227 void InlineSpiller::spillAll() {
1228   // Update LiveStacks now that we are committed to spilling.
1229   if (StackSlot == VirtRegMap::NO_STACK_SLOT) {
1230     StackSlot = VRM.assignVirt2StackSlot(Original);
1231     StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original));
1232     StackInt->getNextValue(SlotIndex(), LSS.getVNInfoAllocator());
1233   } else
1234     StackInt = &LSS.getInterval(StackSlot);
1235
1236   if (Original != Edit->getReg())
1237     VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot);
1238
1239   assert(StackInt->getNumValNums() == 1 && "Bad stack interval values");
1240   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1241     StackInt->MergeRangesInAsValue(LIS.getInterval(RegsToSpill[i]),
1242                                    StackInt->getValNumInfo(0));
1243   DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n');
1244
1245   // Spill around uses of all RegsToSpill.
1246   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1247     spillAroundUses(RegsToSpill[i]);
1248
1249   // Hoisted spills may cause dead code.
1250   if (!DeadDefs.empty()) {
1251     DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n");
1252     Edit->eliminateDeadDefs(DeadDefs, RegsToSpill);
1253   }
1254
1255   // Finally delete the SnippetCopies.
1256   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i) {
1257     for (MachineRegisterInfo::reg_iterator RI = MRI.reg_begin(RegsToSpill[i]);
1258          MachineInstr *MI = RI.skipInstruction();) {
1259       assert(SnippetCopies.count(MI) && "Remaining use wasn't a snippet copy");
1260       // FIXME: Do this with a LiveRangeEdit callback.
1261       LIS.RemoveMachineInstrFromMaps(MI);
1262       MI->eraseFromParent();
1263     }
1264   }
1265
1266   // Delete all spilled registers.
1267   for (unsigned i = 0, e = RegsToSpill.size(); i != e; ++i)
1268     Edit->eraseVirtReg(RegsToSpill[i]);
1269 }
1270
1271 void InlineSpiller::spill(LiveRangeEdit &edit) {
1272   ++NumSpilledRanges;
1273   Edit = &edit;
1274   assert(!TargetRegisterInfo::isStackSlot(edit.getReg())
1275          && "Trying to spill a stack slot.");
1276   // Share a stack slot among all descendants of Original.
1277   Original = VRM.getOriginal(edit.getReg());
1278   StackSlot = VRM.getStackSlot(Original);
1279   StackInt = 0;
1280
1281   DEBUG(dbgs() << "Inline spilling "
1282                << MRI.getRegClass(edit.getReg())->getName()
1283                << ':' << PrintReg(edit.getReg()) << ' ' << edit.getParent()
1284                << "\nFrom original " << LIS.getInterval(Original) << '\n');
1285   assert(edit.getParent().isSpillable() &&
1286          "Attempting to spill already spilled value.");
1287   assert(DeadDefs.empty() && "Previous spill didn't remove dead defs");
1288
1289   collectRegsToSpill();
1290   analyzeSiblingValues();
1291   reMaterializeAll();
1292
1293   // Remat may handle everything.
1294   if (!RegsToSpill.empty())
1295     spillAll();
1296
1297   Edit->calculateRegClassAndHint(MF, Loops);
1298 }