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