1 //===- InlineSpiller.cpp - Insert spills and restores inline --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // The inline spiller modifies the machine function directly instead of
10 // inserting spills and restores in VirtRegMap.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "SplitKit.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/MapVector.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/LiveInterval.h"
26 #include "llvm/CodeGen/LiveIntervalCalc.h"
27 #include "llvm/CodeGen/LiveIntervals.h"
28 #include "llvm/CodeGen/LiveRangeEdit.h"
29 #include "llvm/CodeGen/LiveStacks.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
32 #include "llvm/CodeGen/MachineDominators.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineFunctionPass.h"
35 #include "llvm/CodeGen/MachineInstr.h"
36 #include "llvm/CodeGen/MachineInstrBuilder.h"
37 #include "llvm/CodeGen/MachineInstrBundle.h"
38 #include "llvm/CodeGen/MachineLoopInfo.h"
39 #include "llvm/CodeGen/MachineOperand.h"
40 #include "llvm/CodeGen/MachineRegisterInfo.h"
41 #include "llvm/CodeGen/SlotIndexes.h"
42 #include "llvm/CodeGen/Spiller.h"
43 #include "llvm/CodeGen/StackMaps.h"
44 #include "llvm/CodeGen/TargetInstrInfo.h"
45 #include "llvm/CodeGen/TargetOpcodes.h"
46 #include "llvm/CodeGen/TargetRegisterInfo.h"
47 #include "llvm/CodeGen/TargetSubtargetInfo.h"
48 #include "llvm/CodeGen/VirtRegMap.h"
49 #include "llvm/Config/llvm-config.h"
50 #include "llvm/Support/BlockFrequency.h"
51 #include "llvm/Support/BranchProbability.h"
52 #include "llvm/Support/CommandLine.h"
53 #include "llvm/Support/Compiler.h"
54 #include "llvm/Support/Debug.h"
55 #include "llvm/Support/ErrorHandling.h"
56 #include "llvm/Support/raw_ostream.h"
57 #include <cassert>
58 #include <iterator>
59 #include <tuple>
60 #include <utility>
61 #include <vector>
62 
63 using namespace llvm;
64 
65 #define DEBUG_TYPE "regalloc"
66 
67 STATISTIC(NumSpilledRanges,   "Number of spilled live ranges");
68 STATISTIC(NumSnippets,        "Number of spilled snippets");
69 STATISTIC(NumSpills,          "Number of spills inserted");
70 STATISTIC(NumSpillsRemoved,   "Number of spills removed");
71 STATISTIC(NumReloads,         "Number of reloads inserted");
72 STATISTIC(NumReloadsRemoved,  "Number of reloads removed");
73 STATISTIC(NumFolded,          "Number of folded stack accesses");
74 STATISTIC(NumFoldedLoads,     "Number of folded loads");
75 STATISTIC(NumRemats,          "Number of rematerialized defs for spilling");
76 
77 static cl::opt<bool> DisableHoisting("disable-spill-hoist", cl::Hidden,
78                                      cl::desc("Disable inline spill hoisting"));
79 static cl::opt<bool>
80 RestrictStatepointRemat("restrict-statepoint-remat",
81                        cl::init(false), cl::Hidden,
82                        cl::desc("Restrict remat for statepoint operands"));
83 
84 namespace {
85 
86 class HoistSpillHelper : private LiveRangeEdit::Delegate {
87   MachineFunction &MF;
88   LiveIntervals &LIS;
89   LiveStacks &LSS;
90   AliasAnalysis *AA;
91   MachineDominatorTree &MDT;
92   MachineLoopInfo &Loops;
93   VirtRegMap &VRM;
94   MachineRegisterInfo &MRI;
95   const TargetInstrInfo &TII;
96   const TargetRegisterInfo &TRI;
97   const MachineBlockFrequencyInfo &MBFI;
98 
99   InsertPointAnalysis IPA;
100 
101   // Map from StackSlot to the LiveInterval of the original register.
102   // Note the LiveInterval of the original register may have been deleted
103   // after it is spilled. We keep a copy here to track the range where
104   // spills can be moved.
105   DenseMap<int, std::unique_ptr<LiveInterval>> StackSlotToOrigLI;
106 
107   // Map from pair of (StackSlot and Original VNI) to a set of spills which
108   // have the same stackslot and have equal values defined by Original VNI.
109   // These spills are mergeable and are hoist candiates.
110   using MergeableSpillsMap =
111       MapVector<std::pair<int, VNInfo *>, SmallPtrSet<MachineInstr *, 16>>;
112   MergeableSpillsMap MergeableSpills;
113 
114   /// This is the map from original register to a set containing all its
115   /// siblings. To hoist a spill to another BB, we need to find out a live
116   /// sibling there and use it as the source of the new spill.
117   DenseMap<Register, SmallSetVector<Register, 16>> Virt2SiblingsMap;
118 
119   bool isSpillCandBB(LiveInterval &OrigLI, VNInfo &OrigVNI,
120                      MachineBasicBlock &BB, Register &LiveReg);
121 
122   void rmRedundantSpills(
123       SmallPtrSet<MachineInstr *, 16> &Spills,
124       SmallVectorImpl<MachineInstr *> &SpillsToRm,
125       DenseMap<MachineDomTreeNode *, MachineInstr *> &SpillBBToSpill);
126 
127   void getVisitOrders(
128       MachineBasicBlock *Root, SmallPtrSet<MachineInstr *, 16> &Spills,
129       SmallVectorImpl<MachineDomTreeNode *> &Orders,
130       SmallVectorImpl<MachineInstr *> &SpillsToRm,
131       DenseMap<MachineDomTreeNode *, unsigned> &SpillsToKeep,
132       DenseMap<MachineDomTreeNode *, MachineInstr *> &SpillBBToSpill);
133 
134   void runHoistSpills(LiveInterval &OrigLI, VNInfo &OrigVNI,
135                       SmallPtrSet<MachineInstr *, 16> &Spills,
136                       SmallVectorImpl<MachineInstr *> &SpillsToRm,
137                       DenseMap<MachineBasicBlock *, unsigned> &SpillsToIns);
138 
139 public:
140   HoistSpillHelper(MachineFunctionPass &pass, MachineFunction &mf,
141                    VirtRegMap &vrm)
142       : MF(mf), LIS(pass.getAnalysis<LiveIntervals>()),
143         LSS(pass.getAnalysis<LiveStacks>()),
144         AA(&pass.getAnalysis<AAResultsWrapperPass>().getAAResults()),
145         MDT(pass.getAnalysis<MachineDominatorTree>()),
146         Loops(pass.getAnalysis<MachineLoopInfo>()), VRM(vrm),
147         MRI(mf.getRegInfo()), TII(*mf.getSubtarget().getInstrInfo()),
148         TRI(*mf.getSubtarget().getRegisterInfo()),
149         MBFI(pass.getAnalysis<MachineBlockFrequencyInfo>()),
150         IPA(LIS, mf.getNumBlockIDs()) {}
151 
152   void addToMergeableSpills(MachineInstr &Spill, int StackSlot,
153                             unsigned Original);
154   bool rmFromMergeableSpills(MachineInstr &Spill, int StackSlot);
155   void hoistAllSpills();
156   void LRE_DidCloneVirtReg(unsigned, unsigned) override;
157 };
158 
159 class InlineSpiller : public Spiller {
160   MachineFunction &MF;
161   LiveIntervals &LIS;
162   LiveStacks &LSS;
163   AliasAnalysis *AA;
164   MachineDominatorTree &MDT;
165   MachineLoopInfo &Loops;
166   VirtRegMap &VRM;
167   MachineRegisterInfo &MRI;
168   const TargetInstrInfo &TII;
169   const TargetRegisterInfo &TRI;
170   const MachineBlockFrequencyInfo &MBFI;
171 
172   // Variables that are valid during spill(), but used by multiple methods.
173   LiveRangeEdit *Edit;
174   LiveInterval *StackInt;
175   int StackSlot;
176   unsigned Original;
177 
178   // All registers to spill to StackSlot, including the main register.
179   SmallVector<Register, 8> RegsToSpill;
180 
181   // All COPY instructions to/from snippets.
182   // They are ignored since both operands refer to the same stack slot.
183   SmallPtrSet<MachineInstr*, 8> SnippetCopies;
184 
185   // Values that failed to remat at some point.
186   SmallPtrSet<VNInfo*, 8> UsedValues;
187 
188   // Dead defs generated during spilling.
189   SmallVector<MachineInstr*, 8> DeadDefs;
190 
191   // Object records spills information and does the hoisting.
192   HoistSpillHelper HSpiller;
193 
194   ~InlineSpiller() override = default;
195 
196 public:
197   InlineSpiller(MachineFunctionPass &pass, MachineFunction &mf, VirtRegMap &vrm)
198       : MF(mf), LIS(pass.getAnalysis<LiveIntervals>()),
199         LSS(pass.getAnalysis<LiveStacks>()),
200         AA(&pass.getAnalysis<AAResultsWrapperPass>().getAAResults()),
201         MDT(pass.getAnalysis<MachineDominatorTree>()),
202         Loops(pass.getAnalysis<MachineLoopInfo>()), VRM(vrm),
203         MRI(mf.getRegInfo()), TII(*mf.getSubtarget().getInstrInfo()),
204         TRI(*mf.getSubtarget().getRegisterInfo()),
205         MBFI(pass.getAnalysis<MachineBlockFrequencyInfo>()),
206         HSpiller(pass, mf, vrm) {}
207 
208   void spill(LiveRangeEdit &) override;
209   void postOptimization() override;
210 
211 private:
212   bool isSnippet(const LiveInterval &SnipLI);
213   void collectRegsToSpill();
214 
215   bool isRegToSpill(Register Reg) { return is_contained(RegsToSpill, Reg); }
216 
217   bool isSibling(Register Reg);
218   bool hoistSpillInsideBB(LiveInterval &SpillLI, MachineInstr &CopyMI);
219   void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI);
220 
221   void markValueUsed(LiveInterval*, VNInfo*);
222   bool canGuaranteeAssignmentAfterRemat(Register VReg, MachineInstr &MI);
223   bool reMaterializeFor(LiveInterval &, MachineInstr &MI);
224   void reMaterializeAll();
225 
226   bool coalesceStackAccess(MachineInstr *MI, Register Reg);
227   bool foldMemoryOperand(ArrayRef<std::pair<MachineInstr *, unsigned>>,
228                          MachineInstr *LoadMI = nullptr);
229   void insertReload(Register VReg, SlotIndex, MachineBasicBlock::iterator MI);
230   void insertSpill(Register VReg, bool isKill, MachineBasicBlock::iterator MI);
231 
232   void spillAroundUses(Register Reg);
233   void spillAll();
234 };
235 
236 } // end anonymous namespace
237 
238 Spiller::~Spiller() = default;
239 
240 void Spiller::anchor() {}
241 
242 Spiller *llvm::createInlineSpiller(MachineFunctionPass &pass,
243                                    MachineFunction &mf,
244                                    VirtRegMap &vrm) {
245   return new InlineSpiller(pass, mf, vrm);
246 }
247 
248 //===----------------------------------------------------------------------===//
249 //                                Snippets
250 //===----------------------------------------------------------------------===//
251 
252 // When spilling a virtual register, we also spill any snippets it is connected
253 // to. The snippets are small live ranges that only have a single real use,
254 // leftovers from live range splitting. Spilling them enables memory operand
255 // folding or tightens the live range around the single use.
256 //
257 // This minimizes register pressure and maximizes the store-to-load distance for
258 // spill slots which can be important in tight loops.
259 
260 /// isFullCopyOf - If MI is a COPY to or from Reg, return the other register,
261 /// otherwise return 0.
262 static Register isFullCopyOf(const MachineInstr &MI, Register Reg) {
263   if (!MI.isFullCopy())
264     return Register();
265   if (MI.getOperand(0).getReg() == Reg)
266     return MI.getOperand(1).getReg();
267   if (MI.getOperand(1).getReg() == Reg)
268     return MI.getOperand(0).getReg();
269   return Register();
270 }
271 
272 /// isSnippet - Identify if a live interval is a snippet that should be spilled.
273 /// It is assumed that SnipLI is a virtual register with the same original as
274 /// Edit->getReg().
275 bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
276   Register Reg = Edit->getReg();
277 
278   // A snippet is a tiny live range with only a single instruction using it
279   // besides copies to/from Reg or spills/fills. We accept:
280   //
281   //   %snip = COPY %Reg / FILL fi#
282   //   %snip = USE %snip
283   //   %Reg = COPY %snip / SPILL %snip, fi#
284   //
285   if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI))
286     return false;
287 
288   MachineInstr *UseMI = nullptr;
289 
290   // Check that all uses satisfy our criteria.
291   for (MachineRegisterInfo::reg_instr_nodbg_iterator
292            RI = MRI.reg_instr_nodbg_begin(SnipLI.reg()),
293            E = MRI.reg_instr_nodbg_end();
294        RI != E;) {
295     MachineInstr &MI = *RI++;
296 
297     // Allow copies to/from Reg.
298     if (isFullCopyOf(MI, Reg))
299       continue;
300 
301     // Allow stack slot loads.
302     int FI;
303     if (SnipLI.reg() == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
304       continue;
305 
306     // Allow stack slot stores.
307     if (SnipLI.reg() == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
308       continue;
309 
310     // Allow a single additional instruction.
311     if (UseMI && &MI != UseMI)
312       return false;
313     UseMI = &MI;
314   }
315   return true;
316 }
317 
318 /// collectRegsToSpill - Collect live range snippets that only have a single
319 /// real use.
320 void InlineSpiller::collectRegsToSpill() {
321   Register Reg = Edit->getReg();
322 
323   // Main register always spills.
324   RegsToSpill.assign(1, Reg);
325   SnippetCopies.clear();
326 
327   // Snippets all have the same original, so there can't be any for an original
328   // register.
329   if (Original == Reg)
330     return;
331 
332   for (MachineRegisterInfo::reg_instr_iterator
333        RI = MRI.reg_instr_begin(Reg), E = MRI.reg_instr_end(); RI != E; ) {
334     MachineInstr &MI = *RI++;
335     Register SnipReg = isFullCopyOf(MI, Reg);
336     if (!isSibling(SnipReg))
337       continue;
338     LiveInterval &SnipLI = LIS.getInterval(SnipReg);
339     if (!isSnippet(SnipLI))
340       continue;
341     SnippetCopies.insert(&MI);
342     if (isRegToSpill(SnipReg))
343       continue;
344     RegsToSpill.push_back(SnipReg);
345     LLVM_DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n');
346     ++NumSnippets;
347   }
348 }
349 
350 bool InlineSpiller::isSibling(Register Reg) {
351   return Reg.isVirtual() && VRM.getOriginal(Reg) == Original;
352 }
353 
354 /// It is beneficial to spill to earlier place in the same BB in case
355 /// as follows:
356 /// There is an alternative def earlier in the same MBB.
357 /// Hoist the spill as far as possible in SpillMBB. This can ease
358 /// register pressure:
359 ///
360 ///   x = def
361 ///   y = use x
362 ///   s = copy x
363 ///
364 /// Hoisting the spill of s to immediately after the def removes the
365 /// interference between x and y:
366 ///
367 ///   x = def
368 ///   spill x
369 ///   y = use killed x
370 ///
371 /// This hoist only helps when the copy kills its source.
372 ///
373 bool InlineSpiller::hoistSpillInsideBB(LiveInterval &SpillLI,
374                                        MachineInstr &CopyMI) {
375   SlotIndex Idx = LIS.getInstructionIndex(CopyMI);
376 #ifndef NDEBUG
377   VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getRegSlot());
378   assert(VNI && VNI->def == Idx.getRegSlot() && "Not defined by copy");
379 #endif
380 
381   Register SrcReg = CopyMI.getOperand(1).getReg();
382   LiveInterval &SrcLI = LIS.getInterval(SrcReg);
383   VNInfo *SrcVNI = SrcLI.getVNInfoAt(Idx);
384   LiveQueryResult SrcQ = SrcLI.Query(Idx);
385   MachineBasicBlock *DefMBB = LIS.getMBBFromIndex(SrcVNI->def);
386   if (DefMBB != CopyMI.getParent() || !SrcQ.isKill())
387     return false;
388 
389   // Conservatively extend the stack slot range to the range of the original
390   // value. We may be able to do better with stack slot coloring by being more
391   // careful here.
392   assert(StackInt && "No stack slot assigned yet.");
393   LiveInterval &OrigLI = LIS.getInterval(Original);
394   VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
395   StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0));
396   LLVM_DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
397                     << *StackInt << '\n');
398 
399   // We are going to spill SrcVNI immediately after its def, so clear out
400   // any later spills of the same value.
401   eliminateRedundantSpills(SrcLI, SrcVNI);
402 
403   MachineBasicBlock *MBB = LIS.getMBBFromIndex(SrcVNI->def);
404   MachineBasicBlock::iterator MII;
405   if (SrcVNI->isPHIDef())
406     MII = MBB->SkipPHIsLabelsAndDebug(MBB->begin());
407   else {
408     MachineInstr *DefMI = LIS.getInstructionFromIndex(SrcVNI->def);
409     assert(DefMI && "Defining instruction disappeared");
410     MII = DefMI;
411     ++MII;
412   }
413   // Insert spill without kill flag immediately after def.
414   TII.storeRegToStackSlot(*MBB, MII, SrcReg, false, StackSlot,
415                           MRI.getRegClass(SrcReg), &TRI);
416   --MII; // Point to store instruction.
417   LIS.InsertMachineInstrInMaps(*MII);
418   LLVM_DEBUG(dbgs() << "\thoisted: " << SrcVNI->def << '\t' << *MII);
419 
420   HSpiller.addToMergeableSpills(*MII, StackSlot, Original);
421   ++NumSpills;
422   return true;
423 }
424 
425 /// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any
426 /// redundant spills of this value in SLI.reg and sibling copies.
427 void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
428   assert(VNI && "Missing value");
429   SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
430   WorkList.push_back(std::make_pair(&SLI, VNI));
431   assert(StackInt && "No stack slot assigned yet.");
432 
433   do {
434     LiveInterval *LI;
435     std::tie(LI, VNI) = WorkList.pop_back_val();
436     Register Reg = LI->reg();
437     LLVM_DEBUG(dbgs() << "Checking redundant spills for " << VNI->id << '@'
438                       << VNI->def << " in " << *LI << '\n');
439 
440     // Regs to spill are taken care of.
441     if (isRegToSpill(Reg))
442       continue;
443 
444     // Add all of VNI's live range to StackInt.
445     StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0));
446     LLVM_DEBUG(dbgs() << "Merged to stack int: " << *StackInt << '\n');
447 
448     // Find all spills and copies of VNI.
449     for (MachineRegisterInfo::use_instr_nodbg_iterator
450          UI = MRI.use_instr_nodbg_begin(Reg), E = MRI.use_instr_nodbg_end();
451          UI != E; ) {
452       MachineInstr &MI = *UI++;
453       if (!MI.isCopy() && !MI.mayStore())
454         continue;
455       SlotIndex Idx = LIS.getInstructionIndex(MI);
456       if (LI->getVNInfoAt(Idx) != VNI)
457         continue;
458 
459       // Follow sibling copies down the dominator tree.
460       if (Register DstReg = isFullCopyOf(MI, Reg)) {
461         if (isSibling(DstReg)) {
462            LiveInterval &DstLI = LIS.getInterval(DstReg);
463            VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getRegSlot());
464            assert(DstVNI && "Missing defined value");
465            assert(DstVNI->def == Idx.getRegSlot() && "Wrong copy def slot");
466            WorkList.push_back(std::make_pair(&DstLI, DstVNI));
467         }
468         continue;
469       }
470 
471       // Erase spills.
472       int FI;
473       if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) {
474         LLVM_DEBUG(dbgs() << "Redundant spill " << Idx << '\t' << MI);
475         // eliminateDeadDefs won't normally remove stores, so switch opcode.
476         MI.setDesc(TII.get(TargetOpcode::KILL));
477         DeadDefs.push_back(&MI);
478         ++NumSpillsRemoved;
479         if (HSpiller.rmFromMergeableSpills(MI, StackSlot))
480           --NumSpills;
481       }
482     }
483   } while (!WorkList.empty());
484 }
485 
486 //===----------------------------------------------------------------------===//
487 //                            Rematerialization
488 //===----------------------------------------------------------------------===//
489 
490 /// markValueUsed - Remember that VNI failed to rematerialize, so its defining
491 /// instruction cannot be eliminated. See through snippet copies
492 void InlineSpiller::markValueUsed(LiveInterval *LI, VNInfo *VNI) {
493   SmallVector<std::pair<LiveInterval*, VNInfo*>, 8> WorkList;
494   WorkList.push_back(std::make_pair(LI, VNI));
495   do {
496     std::tie(LI, VNI) = WorkList.pop_back_val();
497     if (!UsedValues.insert(VNI).second)
498       continue;
499 
500     if (VNI->isPHIDef()) {
501       MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
502       for (MachineBasicBlock *P : MBB->predecessors()) {
503         VNInfo *PVNI = LI->getVNInfoBefore(LIS.getMBBEndIdx(P));
504         if (PVNI)
505           WorkList.push_back(std::make_pair(LI, PVNI));
506       }
507       continue;
508     }
509 
510     // Follow snippet copies.
511     MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
512     if (!SnippetCopies.count(MI))
513       continue;
514     LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg());
515     assert(isRegToSpill(SnipLI.reg()) && "Unexpected register in copy");
516     VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getRegSlot(true));
517     assert(SnipVNI && "Snippet undefined before copy");
518     WorkList.push_back(std::make_pair(&SnipLI, SnipVNI));
519   } while (!WorkList.empty());
520 }
521 
522 bool InlineSpiller::canGuaranteeAssignmentAfterRemat(Register VReg,
523                                                      MachineInstr &MI) {
524   if (!RestrictStatepointRemat)
525     return true;
526   // Here's a quick explanation of the problem we're trying to handle here:
527   // * There are some pseudo instructions with more vreg uses than there are
528   //   physical registers on the machine.
529   // * This is normally handled by spilling the vreg, and folding the reload
530   //   into the user instruction.  (Thus decreasing the number of used vregs
531   //   until the remainder can be assigned to physregs.)
532   // * However, since we may try to spill vregs in any order, we can end up
533   //   trying to spill each operand to the instruction, and then rematting it
534   //   instead.  When that happens, the new live intervals (for the remats) are
535   //   expected to be trivially assignable (i.e. RS_Done).  However, since we
536   //   may have more remats than physregs, we're guaranteed to fail to assign
537   //   one.
538   // At the moment, we only handle this for STATEPOINTs since they're the only
539   // pseudo op where we've seen this.  If we start seeing other instructions
540   // with the same problem, we need to revisit this.
541   if (MI.getOpcode() != TargetOpcode::STATEPOINT)
542     return true;
543   // For STATEPOINTs we allow re-materialization for fixed arguments only hoping
544   // that number of physical registers is enough to cover all fixed arguments.
545   // If it is not true we need to revisit it.
546   for (unsigned Idx = StatepointOpers(&MI).getVarIdx(),
547                 EndIdx = MI.getNumOperands();
548        Idx < EndIdx; ++Idx) {
549     MachineOperand &MO = MI.getOperand(Idx);
550     if (MO.isReg() && MO.getReg() == VReg)
551       return false;
552   }
553   return true;
554 }
555 
556 /// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
557 bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg, MachineInstr &MI) {
558   // Analyze instruction
559   SmallVector<std::pair<MachineInstr *, unsigned>, 8> Ops;
560   VirtRegInfo RI = AnalyzeVirtRegInBundle(MI, VirtReg.reg(), &Ops);
561 
562   if (!RI.Reads)
563     return false;
564 
565   SlotIndex UseIdx = LIS.getInstructionIndex(MI).getRegSlot(true);
566   VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx.getBaseIndex());
567 
568   if (!ParentVNI) {
569     LLVM_DEBUG(dbgs() << "\tadding <undef> flags: ");
570     for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
571       MachineOperand &MO = MI.getOperand(i);
572       if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg())
573         MO.setIsUndef();
574     }
575     LLVM_DEBUG(dbgs() << UseIdx << '\t' << MI);
576     return true;
577   }
578 
579   if (SnippetCopies.count(&MI))
580     return false;
581 
582   LiveInterval &OrigLI = LIS.getInterval(Original);
583   VNInfo *OrigVNI = OrigLI.getVNInfoAt(UseIdx);
584   LiveRangeEdit::Remat RM(ParentVNI);
585   RM.OrigMI = LIS.getInstructionFromIndex(OrigVNI->def);
586 
587   if (!Edit->canRematerializeAt(RM, OrigVNI, UseIdx, false)) {
588     markValueUsed(&VirtReg, ParentVNI);
589     LLVM_DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << MI);
590     return false;
591   }
592 
593   // If the instruction also writes VirtReg.reg, it had better not require the
594   // same register for uses and defs.
595   if (RI.Tied) {
596     markValueUsed(&VirtReg, ParentVNI);
597     LLVM_DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << MI);
598     return false;
599   }
600 
601   // Before rematerializing into a register for a single instruction, try to
602   // fold a load into the instruction. That avoids allocating a new register.
603   if (RM.OrigMI->canFoldAsLoad() &&
604       foldMemoryOperand(Ops, RM.OrigMI)) {
605     Edit->markRematerialized(RM.ParentVNI);
606     ++NumFoldedLoads;
607     return true;
608   }
609 
610   // If we can't guarantee that we'll be able to actually assign the new vreg,
611   // we can't remat.
612   if (!canGuaranteeAssignmentAfterRemat(VirtReg.reg(), MI)) {
613     markValueUsed(&VirtReg, ParentVNI);
614     LLVM_DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << MI);
615     return false;
616   }
617 
618   // Allocate a new register for the remat.
619   Register NewVReg = Edit->createFrom(Original);
620 
621   // Finally we can rematerialize OrigMI before MI.
622   SlotIndex DefIdx =
623       Edit->rematerializeAt(*MI.getParent(), MI, NewVReg, RM, TRI);
624 
625   // We take the DebugLoc from MI, since OrigMI may be attributed to a
626   // different source location.
627   auto *NewMI = LIS.getInstructionFromIndex(DefIdx);
628   NewMI->setDebugLoc(MI.getDebugLoc());
629 
630   (void)DefIdx;
631   LLVM_DEBUG(dbgs() << "\tremat:  " << DefIdx << '\t'
632                     << *LIS.getInstructionFromIndex(DefIdx));
633 
634   // Replace operands
635   for (const auto &OpPair : Ops) {
636     MachineOperand &MO = OpPair.first->getOperand(OpPair.second);
637     if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg()) {
638       MO.setReg(NewVReg);
639       MO.setIsKill();
640     }
641   }
642   LLVM_DEBUG(dbgs() << "\t        " << UseIdx << '\t' << MI << '\n');
643 
644   ++NumRemats;
645   return true;
646 }
647 
648 /// reMaterializeAll - Try to rematerialize as many uses as possible,
649 /// and trim the live ranges after.
650 void InlineSpiller::reMaterializeAll() {
651   if (!Edit->anyRematerializable(AA))
652     return;
653 
654   UsedValues.clear();
655 
656   // Try to remat before all uses of snippets.
657   bool anyRemat = false;
658   for (Register Reg : RegsToSpill) {
659     LiveInterval &LI = LIS.getInterval(Reg);
660     for (MachineRegisterInfo::reg_bundle_iterator
661            RegI = MRI.reg_bundle_begin(Reg), E = MRI.reg_bundle_end();
662          RegI != E; ) {
663       MachineInstr &MI = *RegI++;
664 
665       // Debug values are not allowed to affect codegen.
666       if (MI.isDebugValue())
667         continue;
668 
669       assert(!MI.isDebugInstr() && "Did not expect to find a use in debug "
670              "instruction that isn't a DBG_VALUE");
671 
672       anyRemat |= reMaterializeFor(LI, MI);
673     }
674   }
675   if (!anyRemat)
676     return;
677 
678   // Remove any values that were completely rematted.
679   for (Register Reg : RegsToSpill) {
680     LiveInterval &LI = LIS.getInterval(Reg);
681     for (LiveInterval::vni_iterator I = LI.vni_begin(), E = LI.vni_end();
682          I != E; ++I) {
683       VNInfo *VNI = *I;
684       if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI))
685         continue;
686       MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
687       MI->addRegisterDead(Reg, &TRI);
688       if (!MI->allDefsAreDead())
689         continue;
690       LLVM_DEBUG(dbgs() << "All defs dead: " << *MI);
691       DeadDefs.push_back(MI);
692     }
693   }
694 
695   // Eliminate dead code after remat. Note that some snippet copies may be
696   // deleted here.
697   if (DeadDefs.empty())
698     return;
699   LLVM_DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n");
700   Edit->eliminateDeadDefs(DeadDefs, RegsToSpill, AA);
701 
702   // LiveRangeEdit::eliminateDeadDef is used to remove dead define instructions
703   // after rematerialization.  To remove a VNI for a vreg from its LiveInterval,
704   // LiveIntervals::removeVRegDefAt is used. However, after non-PHI VNIs are all
705   // removed, PHI VNI are still left in the LiveInterval.
706   // So to get rid of unused reg, we need to check whether it has non-dbg
707   // reference instead of whether it has non-empty interval.
708   unsigned ResultPos = 0;
709   for (Register Reg : RegsToSpill) {
710     if (MRI.reg_nodbg_empty(Reg)) {
711       Edit->eraseVirtReg(Reg);
712       continue;
713     }
714 
715     assert(LIS.hasInterval(Reg) &&
716            (!LIS.getInterval(Reg).empty() || !MRI.reg_nodbg_empty(Reg)) &&
717            "Empty and not used live-range?!");
718 
719     RegsToSpill[ResultPos++] = Reg;
720   }
721   RegsToSpill.erase(RegsToSpill.begin() + ResultPos, RegsToSpill.end());
722   LLVM_DEBUG(dbgs() << RegsToSpill.size()
723                     << " registers to spill after remat.\n");
724 }
725 
726 //===----------------------------------------------------------------------===//
727 //                                 Spilling
728 //===----------------------------------------------------------------------===//
729 
730 /// If MI is a load or store of StackSlot, it can be removed.
731 bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, Register Reg) {
732   int FI = 0;
733   Register InstrReg = TII.isLoadFromStackSlot(*MI, FI);
734   bool IsLoad = InstrReg;
735   if (!IsLoad)
736     InstrReg = TII.isStoreToStackSlot(*MI, FI);
737 
738   // We have a stack access. Is it the right register and slot?
739   if (InstrReg != Reg || FI != StackSlot)
740     return false;
741 
742   if (!IsLoad)
743     HSpiller.rmFromMergeableSpills(*MI, StackSlot);
744 
745   LLVM_DEBUG(dbgs() << "Coalescing stack access: " << *MI);
746   LIS.RemoveMachineInstrFromMaps(*MI);
747   MI->eraseFromParent();
748 
749   if (IsLoad) {
750     ++NumReloadsRemoved;
751     --NumReloads;
752   } else {
753     ++NumSpillsRemoved;
754     --NumSpills;
755   }
756 
757   return true;
758 }
759 
760 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
761 LLVM_DUMP_METHOD
762 // Dump the range of instructions from B to E with their slot indexes.
763 static void dumpMachineInstrRangeWithSlotIndex(MachineBasicBlock::iterator B,
764                                                MachineBasicBlock::iterator E,
765                                                LiveIntervals const &LIS,
766                                                const char *const header,
767                                                Register VReg = Register()) {
768   char NextLine = '\n';
769   char SlotIndent = '\t';
770 
771   if (std::next(B) == E) {
772     NextLine = ' ';
773     SlotIndent = ' ';
774   }
775 
776   dbgs() << '\t' << header << ": " << NextLine;
777 
778   for (MachineBasicBlock::iterator I = B; I != E; ++I) {
779     SlotIndex Idx = LIS.getInstructionIndex(*I).getRegSlot();
780 
781     // If a register was passed in and this instruction has it as a
782     // destination that is marked as an early clobber, print the
783     // early-clobber slot index.
784     if (VReg) {
785       MachineOperand *MO = I->findRegisterDefOperand(VReg);
786       if (MO && MO->isEarlyClobber())
787         Idx = Idx.getRegSlot(true);
788     }
789 
790     dbgs() << SlotIndent << Idx << '\t' << *I;
791   }
792 }
793 #endif
794 
795 /// foldMemoryOperand - Try folding stack slot references in Ops into their
796 /// instructions.
797 ///
798 /// @param Ops    Operand indices from AnalyzeVirtRegInBundle().
799 /// @param LoadMI Load instruction to use instead of stack slot when non-null.
800 /// @return       True on success.
801 bool InlineSpiller::
802 foldMemoryOperand(ArrayRef<std::pair<MachineInstr *, unsigned>> Ops,
803                   MachineInstr *LoadMI) {
804   if (Ops.empty())
805     return false;
806   // Don't attempt folding in bundles.
807   MachineInstr *MI = Ops.front().first;
808   if (Ops.back().first != MI || MI->isBundled())
809     return false;
810 
811   bool WasCopy = MI->isCopy();
812   Register ImpReg;
813 
814   // TII::foldMemoryOperand will do what we need here for statepoint
815   // (fold load into use and remove corresponding def). We will replace
816   // uses of removed def with loads (spillAroundUses).
817   // For that to work we need to untie def and use to pass it through
818   // foldMemoryOperand and signal foldPatchpoint that it is allowed to
819   // fold them.
820   bool UntieRegs = MI->getOpcode() == TargetOpcode::STATEPOINT;
821 
822   // Spill subregs if the target allows it.
823   // We always want to spill subregs for stackmap/patchpoint pseudos.
824   bool SpillSubRegs = TII.isSubregFoldable() ||
825                       MI->getOpcode() == TargetOpcode::STATEPOINT ||
826                       MI->getOpcode() == TargetOpcode::PATCHPOINT ||
827                       MI->getOpcode() == TargetOpcode::STACKMAP;
828 
829   // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
830   // operands.
831   SmallVector<unsigned, 8> FoldOps;
832   for (const auto &OpPair : Ops) {
833     unsigned Idx = OpPair.second;
834     assert(MI == OpPair.first && "Instruction conflict during operand folding");
835     MachineOperand &MO = MI->getOperand(Idx);
836     if (MO.isImplicit()) {
837       ImpReg = MO.getReg();
838       continue;
839     }
840 
841     if (UntieRegs && MO.isTied())
842       MI->untieRegOperand(Idx);
843 
844     if (!SpillSubRegs && MO.getSubReg())
845       return false;
846     // We cannot fold a load instruction into a def.
847     if (LoadMI && MO.isDef())
848       return false;
849     // Tied use operands should not be passed to foldMemoryOperand.
850     if (!MI->isRegTiedToDefOperand(Idx))
851       FoldOps.push_back(Idx);
852   }
853 
854   // If we only have implicit uses, we won't be able to fold that.
855   // Moreover, TargetInstrInfo::foldMemoryOperand will assert if we try!
856   if (FoldOps.empty())
857     return false;
858 
859   MachineInstrSpan MIS(MI, MI->getParent());
860 
861   MachineInstr *FoldMI =
862       LoadMI ? TII.foldMemoryOperand(*MI, FoldOps, *LoadMI, &LIS)
863              : TII.foldMemoryOperand(*MI, FoldOps, StackSlot, &LIS, &VRM);
864   if (!FoldMI)
865     return false;
866 
867   // Remove LIS for any dead defs in the original MI not in FoldMI.
868   for (MIBundleOperands MO(*MI); MO.isValid(); ++MO) {
869     if (!MO->isReg())
870       continue;
871     Register Reg = MO->getReg();
872     if (!Reg || Register::isVirtualRegister(Reg) || MRI.isReserved(Reg)) {
873       continue;
874     }
875     // Skip non-Defs, including undef uses and internal reads.
876     if (MO->isUse())
877       continue;
878     PhysRegInfo RI = AnalyzePhysRegInBundle(*FoldMI, Reg, &TRI);
879     if (RI.FullyDefined)
880       continue;
881     // FoldMI does not define this physreg. Remove the LI segment.
882     assert(MO->isDead() && "Cannot fold physreg def");
883     SlotIndex Idx = LIS.getInstructionIndex(*MI).getRegSlot();
884     LIS.removePhysRegDefAt(Reg, Idx);
885   }
886 
887   int FI;
888   if (TII.isStoreToStackSlot(*MI, FI) &&
889       HSpiller.rmFromMergeableSpills(*MI, FI))
890     --NumSpills;
891   LIS.ReplaceMachineInstrInMaps(*MI, *FoldMI);
892   // Update the call site info.
893   if (MI->isCandidateForCallSiteEntry())
894     MI->getMF()->moveCallSiteInfo(MI, FoldMI);
895   MI->eraseFromParent();
896 
897   // Insert any new instructions other than FoldMI into the LIS maps.
898   assert(!MIS.empty() && "Unexpected empty span of instructions!");
899   for (MachineInstr &MI : MIS)
900     if (&MI != FoldMI)
901       LIS.InsertMachineInstrInMaps(MI);
902 
903   // TII.foldMemoryOperand may have left some implicit operands on the
904   // instruction.  Strip them.
905   if (ImpReg)
906     for (unsigned i = FoldMI->getNumOperands(); i; --i) {
907       MachineOperand &MO = FoldMI->getOperand(i - 1);
908       if (!MO.isReg() || !MO.isImplicit())
909         break;
910       if (MO.getReg() == ImpReg)
911         FoldMI->RemoveOperand(i - 1);
912     }
913 
914   LLVM_DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MIS.end(), LIS,
915                                                 "folded"));
916 
917   if (!WasCopy)
918     ++NumFolded;
919   else if (Ops.front().second == 0) {
920     ++NumSpills;
921     HSpiller.addToMergeableSpills(*FoldMI, StackSlot, Original);
922   } else
923     ++NumReloads;
924   return true;
925 }
926 
927 void InlineSpiller::insertReload(Register NewVReg,
928                                  SlotIndex Idx,
929                                  MachineBasicBlock::iterator MI) {
930   MachineBasicBlock &MBB = *MI->getParent();
931 
932   MachineInstrSpan MIS(MI, &MBB);
933   TII.loadRegFromStackSlot(MBB, MI, NewVReg, StackSlot,
934                            MRI.getRegClass(NewVReg), &TRI);
935 
936   LIS.InsertMachineInstrRangeInMaps(MIS.begin(), MI);
937 
938   LLVM_DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MI, LIS, "reload",
939                                                 NewVReg));
940   ++NumReloads;
941 }
942 
943 /// Check if \p Def fully defines a VReg with an undefined value.
944 /// If that's the case, that means the value of VReg is actually
945 /// not relevant.
946 static bool isRealSpill(const MachineInstr &Def) {
947   if (!Def.isImplicitDef())
948     return true;
949   assert(Def.getNumOperands() == 1 &&
950          "Implicit def with more than one definition");
951   // We can say that the VReg defined by Def is undef, only if it is
952   // fully defined by Def. Otherwise, some of the lanes may not be
953   // undef and the value of the VReg matters.
954   return Def.getOperand(0).getSubReg();
955 }
956 
957 /// insertSpill - Insert a spill of NewVReg after MI.
958 void InlineSpiller::insertSpill(Register NewVReg, bool isKill,
959                                  MachineBasicBlock::iterator MI) {
960   // Spill are not terminators, so inserting spills after terminators will
961   // violate invariants in MachineVerifier.
962   assert(!MI->isTerminator() && "Inserting a spill after a terminator");
963   MachineBasicBlock &MBB = *MI->getParent();
964 
965   MachineInstrSpan MIS(MI, &MBB);
966   MachineBasicBlock::iterator SpillBefore = std::next(MI);
967   bool IsRealSpill = isRealSpill(*MI);
968   if (IsRealSpill)
969     TII.storeRegToStackSlot(MBB, SpillBefore, NewVReg, isKill, StackSlot,
970                             MRI.getRegClass(NewVReg), &TRI);
971   else
972     // Don't spill undef value.
973     // Anything works for undef, in particular keeping the memory
974     // uninitialized is a viable option and it saves code size and
975     // run time.
976     BuildMI(MBB, SpillBefore, MI->getDebugLoc(), TII.get(TargetOpcode::KILL))
977         .addReg(NewVReg, getKillRegState(isKill));
978 
979   MachineBasicBlock::iterator Spill = std::next(MI);
980   LIS.InsertMachineInstrRangeInMaps(Spill, MIS.end());
981 
982   LLVM_DEBUG(
983       dumpMachineInstrRangeWithSlotIndex(Spill, MIS.end(), LIS, "spill"));
984   ++NumSpills;
985   if (IsRealSpill)
986     HSpiller.addToMergeableSpills(*Spill, StackSlot, Original);
987 }
988 
989 /// spillAroundUses - insert spill code around each use of Reg.
990 void InlineSpiller::spillAroundUses(Register Reg) {
991   LLVM_DEBUG(dbgs() << "spillAroundUses " << printReg(Reg) << '\n');
992   LiveInterval &OldLI = LIS.getInterval(Reg);
993 
994   // Iterate over instructions using Reg.
995   for (MachineRegisterInfo::reg_bundle_iterator
996        RegI = MRI.reg_bundle_begin(Reg), E = MRI.reg_bundle_end();
997        RegI != E; ) {
998     MachineInstr *MI = &*(RegI++);
999 
1000     // Debug values are not allowed to affect codegen.
1001     if (MI->isDebugValue()) {
1002       // Modify DBG_VALUE now that the value is in a spill slot.
1003       MachineBasicBlock *MBB = MI->getParent();
1004       LLVM_DEBUG(dbgs() << "Modifying debug info due to spill:\t" << *MI);
1005       buildDbgValueForSpill(*MBB, MI, *MI, StackSlot);
1006       MBB->erase(MI);
1007       continue;
1008     }
1009 
1010     assert(!MI->isDebugInstr() && "Did not expect to find a use in debug "
1011            "instruction that isn't a DBG_VALUE");
1012 
1013     // Ignore copies to/from snippets. We'll delete them.
1014     if (SnippetCopies.count(MI))
1015       continue;
1016 
1017     // Stack slot accesses may coalesce away.
1018     if (coalesceStackAccess(MI, Reg))
1019       continue;
1020 
1021     // Analyze instruction.
1022     SmallVector<std::pair<MachineInstr*, unsigned>, 8> Ops;
1023     VirtRegInfo RI = AnalyzeVirtRegInBundle(*MI, Reg, &Ops);
1024 
1025     // Find the slot index where this instruction reads and writes OldLI.
1026     // This is usually the def slot, except for tied early clobbers.
1027     SlotIndex Idx = LIS.getInstructionIndex(*MI).getRegSlot();
1028     if (VNInfo *VNI = OldLI.getVNInfoAt(Idx.getRegSlot(true)))
1029       if (SlotIndex::isSameInstr(Idx, VNI->def))
1030         Idx = VNI->def;
1031 
1032     // Check for a sibling copy.
1033     Register SibReg = isFullCopyOf(*MI, Reg);
1034     if (SibReg && isSibling(SibReg)) {
1035       // This may actually be a copy between snippets.
1036       if (isRegToSpill(SibReg)) {
1037         LLVM_DEBUG(dbgs() << "Found new snippet copy: " << *MI);
1038         SnippetCopies.insert(MI);
1039         continue;
1040       }
1041       if (RI.Writes) {
1042         if (hoistSpillInsideBB(OldLI, *MI)) {
1043           // This COPY is now dead, the value is already in the stack slot.
1044           MI->getOperand(0).setIsDead();
1045           DeadDefs.push_back(MI);
1046           continue;
1047         }
1048       } else {
1049         // This is a reload for a sib-reg copy. Drop spills downstream.
1050         LiveInterval &SibLI = LIS.getInterval(SibReg);
1051         eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx));
1052         // The COPY will fold to a reload below.
1053       }
1054     }
1055 
1056     // Attempt to fold memory ops.
1057     if (foldMemoryOperand(Ops))
1058       continue;
1059 
1060     // Create a new virtual register for spill/fill.
1061     // FIXME: Infer regclass from instruction alone.
1062     Register NewVReg = Edit->createFrom(Reg);
1063 
1064     if (RI.Reads)
1065       insertReload(NewVReg, Idx, MI);
1066 
1067     // Rewrite instruction operands.
1068     bool hasLiveDef = false;
1069     for (const auto &OpPair : Ops) {
1070       MachineOperand &MO = OpPair.first->getOperand(OpPair.second);
1071       MO.setReg(NewVReg);
1072       if (MO.isUse()) {
1073         if (!OpPair.first->isRegTiedToDefOperand(OpPair.second))
1074           MO.setIsKill();
1075       } else {
1076         if (!MO.isDead())
1077           hasLiveDef = true;
1078       }
1079     }
1080     LLVM_DEBUG(dbgs() << "\trewrite: " << Idx << '\t' << *MI << '\n');
1081 
1082     // FIXME: Use a second vreg if instruction has no tied ops.
1083     if (RI.Writes)
1084       if (hasLiveDef)
1085         insertSpill(NewVReg, true, MI);
1086   }
1087 }
1088 
1089 /// spillAll - Spill all registers remaining after rematerialization.
1090 void InlineSpiller::spillAll() {
1091   // Update LiveStacks now that we are committed to spilling.
1092   if (StackSlot == VirtRegMap::NO_STACK_SLOT) {
1093     StackSlot = VRM.assignVirt2StackSlot(Original);
1094     StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original));
1095     StackInt->getNextValue(SlotIndex(), LSS.getVNInfoAllocator());
1096   } else
1097     StackInt = &LSS.getInterval(StackSlot);
1098 
1099   if (Original != Edit->getReg())
1100     VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot);
1101 
1102   assert(StackInt->getNumValNums() == 1 && "Bad stack interval values");
1103   for (Register Reg : RegsToSpill)
1104     StackInt->MergeSegmentsInAsValue(LIS.getInterval(Reg),
1105                                      StackInt->getValNumInfo(0));
1106   LLVM_DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n');
1107 
1108   // Spill around uses of all RegsToSpill.
1109   for (Register Reg : RegsToSpill)
1110     spillAroundUses(Reg);
1111 
1112   // Hoisted spills may cause dead code.
1113   if (!DeadDefs.empty()) {
1114     LLVM_DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n");
1115     Edit->eliminateDeadDefs(DeadDefs, RegsToSpill, AA);
1116   }
1117 
1118   // Finally delete the SnippetCopies.
1119   for (Register Reg : RegsToSpill) {
1120     for (MachineRegisterInfo::reg_instr_iterator
1121          RI = MRI.reg_instr_begin(Reg), E = MRI.reg_instr_end();
1122          RI != E; ) {
1123       MachineInstr &MI = *(RI++);
1124       assert(SnippetCopies.count(&MI) && "Remaining use wasn't a snippet copy");
1125       // FIXME: Do this with a LiveRangeEdit callback.
1126       LIS.RemoveMachineInstrFromMaps(MI);
1127       MI.eraseFromParent();
1128     }
1129   }
1130 
1131   // Delete all spilled registers.
1132   for (Register Reg : RegsToSpill)
1133     Edit->eraseVirtReg(Reg);
1134 }
1135 
1136 void InlineSpiller::spill(LiveRangeEdit &edit) {
1137   ++NumSpilledRanges;
1138   Edit = &edit;
1139   assert(!Register::isStackSlot(edit.getReg()) &&
1140          "Trying to spill a stack slot.");
1141   // Share a stack slot among all descendants of Original.
1142   Original = VRM.getOriginal(edit.getReg());
1143   StackSlot = VRM.getStackSlot(Original);
1144   StackInt = nullptr;
1145 
1146   LLVM_DEBUG(dbgs() << "Inline spilling "
1147                     << TRI.getRegClassName(MRI.getRegClass(edit.getReg()))
1148                     << ':' << edit.getParent() << "\nFrom original "
1149                     << printReg(Original) << '\n');
1150   assert(edit.getParent().isSpillable() &&
1151          "Attempting to spill already spilled value.");
1152   assert(DeadDefs.empty() && "Previous spill didn't remove dead defs");
1153 
1154   collectRegsToSpill();
1155   reMaterializeAll();
1156 
1157   // Remat may handle everything.
1158   if (!RegsToSpill.empty())
1159     spillAll();
1160 
1161   Edit->calculateRegClassAndHint(MF, Loops, MBFI);
1162 }
1163 
1164 /// Optimizations after all the reg selections and spills are done.
1165 void InlineSpiller::postOptimization() { HSpiller.hoistAllSpills(); }
1166 
1167 /// When a spill is inserted, add the spill to MergeableSpills map.
1168 void HoistSpillHelper::addToMergeableSpills(MachineInstr &Spill, int StackSlot,
1169                                             unsigned Original) {
1170   BumpPtrAllocator &Allocator = LIS.getVNInfoAllocator();
1171   LiveInterval &OrigLI = LIS.getInterval(Original);
1172   // save a copy of LiveInterval in StackSlotToOrigLI because the original
1173   // LiveInterval may be cleared after all its references are spilled.
1174   if (StackSlotToOrigLI.find(StackSlot) == StackSlotToOrigLI.end()) {
1175     auto LI = std::make_unique<LiveInterval>(OrigLI.reg(), OrigLI.weight());
1176     LI->assign(OrigLI, Allocator);
1177     StackSlotToOrigLI[StackSlot] = std::move(LI);
1178   }
1179   SlotIndex Idx = LIS.getInstructionIndex(Spill);
1180   VNInfo *OrigVNI = StackSlotToOrigLI[StackSlot]->getVNInfoAt(Idx.getRegSlot());
1181   std::pair<int, VNInfo *> MIdx = std::make_pair(StackSlot, OrigVNI);
1182   MergeableSpills[MIdx].insert(&Spill);
1183 }
1184 
1185 /// When a spill is removed, remove the spill from MergeableSpills map.
1186 /// Return true if the spill is removed successfully.
1187 bool HoistSpillHelper::rmFromMergeableSpills(MachineInstr &Spill,
1188                                              int StackSlot) {
1189   auto It = StackSlotToOrigLI.find(StackSlot);
1190   if (It == StackSlotToOrigLI.end())
1191     return false;
1192   SlotIndex Idx = LIS.getInstructionIndex(Spill);
1193   VNInfo *OrigVNI = It->second->getVNInfoAt(Idx.getRegSlot());
1194   std::pair<int, VNInfo *> MIdx = std::make_pair(StackSlot, OrigVNI);
1195   return MergeableSpills[MIdx].erase(&Spill);
1196 }
1197 
1198 /// Check BB to see if it is a possible target BB to place a hoisted spill,
1199 /// i.e., there should be a living sibling of OrigReg at the insert point.
1200 bool HoistSpillHelper::isSpillCandBB(LiveInterval &OrigLI, VNInfo &OrigVNI,
1201                                      MachineBasicBlock &BB, Register &LiveReg) {
1202   SlotIndex Idx;
1203   Register OrigReg = OrigLI.reg();
1204   MachineBasicBlock::iterator MI = IPA.getLastInsertPointIter(OrigLI, BB);
1205   if (MI != BB.end())
1206     Idx = LIS.getInstructionIndex(*MI);
1207   else
1208     Idx = LIS.getMBBEndIdx(&BB).getPrevSlot();
1209   SmallSetVector<Register, 16> &Siblings = Virt2SiblingsMap[OrigReg];
1210   assert(OrigLI.getVNInfoAt(Idx) == &OrigVNI && "Unexpected VNI");
1211 
1212   for (const Register &SibReg : Siblings) {
1213     LiveInterval &LI = LIS.getInterval(SibReg);
1214     VNInfo *VNI = LI.getVNInfoAt(Idx);
1215     if (VNI) {
1216       LiveReg = SibReg;
1217       return true;
1218     }
1219   }
1220   return false;
1221 }
1222 
1223 /// Remove redundant spills in the same BB. Save those redundant spills in
1224 /// SpillsToRm, and save the spill to keep and its BB in SpillBBToSpill map.
1225 void HoistSpillHelper::rmRedundantSpills(
1226     SmallPtrSet<MachineInstr *, 16> &Spills,
1227     SmallVectorImpl<MachineInstr *> &SpillsToRm,
1228     DenseMap<MachineDomTreeNode *, MachineInstr *> &SpillBBToSpill) {
1229   // For each spill saw, check SpillBBToSpill[] and see if its BB already has
1230   // another spill inside. If a BB contains more than one spill, only keep the
1231   // earlier spill with smaller SlotIndex.
1232   for (const auto CurrentSpill : Spills) {
1233     MachineBasicBlock *Block = CurrentSpill->getParent();
1234     MachineDomTreeNode *Node = MDT.getBase().getNode(Block);
1235     MachineInstr *PrevSpill = SpillBBToSpill[Node];
1236     if (PrevSpill) {
1237       SlotIndex PIdx = LIS.getInstructionIndex(*PrevSpill);
1238       SlotIndex CIdx = LIS.getInstructionIndex(*CurrentSpill);
1239       MachineInstr *SpillToRm = (CIdx > PIdx) ? CurrentSpill : PrevSpill;
1240       MachineInstr *SpillToKeep = (CIdx > PIdx) ? PrevSpill : CurrentSpill;
1241       SpillsToRm.push_back(SpillToRm);
1242       SpillBBToSpill[MDT.getBase().getNode(Block)] = SpillToKeep;
1243     } else {
1244       SpillBBToSpill[MDT.getBase().getNode(Block)] = CurrentSpill;
1245     }
1246   }
1247   for (const auto SpillToRm : SpillsToRm)
1248     Spills.erase(SpillToRm);
1249 }
1250 
1251 /// Starting from \p Root find a top-down traversal order of the dominator
1252 /// tree to visit all basic blocks containing the elements of \p Spills.
1253 /// Redundant spills will be found and put into \p SpillsToRm at the same
1254 /// time. \p SpillBBToSpill will be populated as part of the process and
1255 /// maps a basic block to the first store occurring in the basic block.
1256 /// \post SpillsToRm.union(Spills\@post) == Spills\@pre
1257 void HoistSpillHelper::getVisitOrders(
1258     MachineBasicBlock *Root, SmallPtrSet<MachineInstr *, 16> &Spills,
1259     SmallVectorImpl<MachineDomTreeNode *> &Orders,
1260     SmallVectorImpl<MachineInstr *> &SpillsToRm,
1261     DenseMap<MachineDomTreeNode *, unsigned> &SpillsToKeep,
1262     DenseMap<MachineDomTreeNode *, MachineInstr *> &SpillBBToSpill) {
1263   // The set contains all the possible BB nodes to which we may hoist
1264   // original spills.
1265   SmallPtrSet<MachineDomTreeNode *, 8> WorkSet;
1266   // Save the BB nodes on the path from the first BB node containing
1267   // non-redundant spill to the Root node.
1268   SmallPtrSet<MachineDomTreeNode *, 8> NodesOnPath;
1269   // All the spills to be hoisted must originate from a single def instruction
1270   // to the OrigReg. It means the def instruction should dominate all the spills
1271   // to be hoisted. We choose the BB where the def instruction is located as
1272   // the Root.
1273   MachineDomTreeNode *RootIDomNode = MDT[Root]->getIDom();
1274   // For every node on the dominator tree with spill, walk up on the dominator
1275   // tree towards the Root node until it is reached. If there is other node
1276   // containing spill in the middle of the path, the previous spill saw will
1277   // be redundant and the node containing it will be removed. All the nodes on
1278   // the path starting from the first node with non-redundant spill to the Root
1279   // node will be added to the WorkSet, which will contain all the possible
1280   // locations where spills may be hoisted to after the loop below is done.
1281   for (const auto Spill : Spills) {
1282     MachineBasicBlock *Block = Spill->getParent();
1283     MachineDomTreeNode *Node = MDT[Block];
1284     MachineInstr *SpillToRm = nullptr;
1285     while (Node != RootIDomNode) {
1286       // If Node dominates Block, and it already contains a spill, the spill in
1287       // Block will be redundant.
1288       if (Node != MDT[Block] && SpillBBToSpill[Node]) {
1289         SpillToRm = SpillBBToSpill[MDT[Block]];
1290         break;
1291         /// If we see the Node already in WorkSet, the path from the Node to
1292         /// the Root node must already be traversed by another spill.
1293         /// Then no need to repeat.
1294       } else if (WorkSet.count(Node)) {
1295         break;
1296       } else {
1297         NodesOnPath.insert(Node);
1298       }
1299       Node = Node->getIDom();
1300     }
1301     if (SpillToRm) {
1302       SpillsToRm.push_back(SpillToRm);
1303     } else {
1304       // Add a BB containing the original spills to SpillsToKeep -- i.e.,
1305       // set the initial status before hoisting start. The value of BBs
1306       // containing original spills is set to 0, in order to descriminate
1307       // with BBs containing hoisted spills which will be inserted to
1308       // SpillsToKeep later during hoisting.
1309       SpillsToKeep[MDT[Block]] = 0;
1310       WorkSet.insert(NodesOnPath.begin(), NodesOnPath.end());
1311     }
1312     NodesOnPath.clear();
1313   }
1314 
1315   // Sort the nodes in WorkSet in top-down order and save the nodes
1316   // in Orders. Orders will be used for hoisting in runHoistSpills.
1317   unsigned idx = 0;
1318   Orders.push_back(MDT.getBase().getNode(Root));
1319   do {
1320     MachineDomTreeNode *Node = Orders[idx++];
1321     for (MachineDomTreeNode *Child : Node->children()) {
1322       if (WorkSet.count(Child))
1323         Orders.push_back(Child);
1324     }
1325   } while (idx != Orders.size());
1326   assert(Orders.size() == WorkSet.size() &&
1327          "Orders have different size with WorkSet");
1328 
1329 #ifndef NDEBUG
1330   LLVM_DEBUG(dbgs() << "Orders size is " << Orders.size() << "\n");
1331   SmallVector<MachineDomTreeNode *, 32>::reverse_iterator RIt = Orders.rbegin();
1332   for (; RIt != Orders.rend(); RIt++)
1333     LLVM_DEBUG(dbgs() << "BB" << (*RIt)->getBlock()->getNumber() << ",");
1334   LLVM_DEBUG(dbgs() << "\n");
1335 #endif
1336 }
1337 
1338 /// Try to hoist spills according to BB hotness. The spills to removed will
1339 /// be saved in \p SpillsToRm. The spills to be inserted will be saved in
1340 /// \p SpillsToIns.
1341 void HoistSpillHelper::runHoistSpills(
1342     LiveInterval &OrigLI, VNInfo &OrigVNI,
1343     SmallPtrSet<MachineInstr *, 16> &Spills,
1344     SmallVectorImpl<MachineInstr *> &SpillsToRm,
1345     DenseMap<MachineBasicBlock *, unsigned> &SpillsToIns) {
1346   // Visit order of dominator tree nodes.
1347   SmallVector<MachineDomTreeNode *, 32> Orders;
1348   // SpillsToKeep contains all the nodes where spills are to be inserted
1349   // during hoisting. If the spill to be inserted is an original spill
1350   // (not a hoisted one), the value of the map entry is 0. If the spill
1351   // is a hoisted spill, the value of the map entry is the VReg to be used
1352   // as the source of the spill.
1353   DenseMap<MachineDomTreeNode *, unsigned> SpillsToKeep;
1354   // Map from BB to the first spill inside of it.
1355   DenseMap<MachineDomTreeNode *, MachineInstr *> SpillBBToSpill;
1356 
1357   rmRedundantSpills(Spills, SpillsToRm, SpillBBToSpill);
1358 
1359   MachineBasicBlock *Root = LIS.getMBBFromIndex(OrigVNI.def);
1360   getVisitOrders(Root, Spills, Orders, SpillsToRm, SpillsToKeep,
1361                  SpillBBToSpill);
1362 
1363   // SpillsInSubTreeMap keeps the map from a dom tree node to a pair of
1364   // nodes set and the cost of all the spills inside those nodes.
1365   // The nodes set are the locations where spills are to be inserted
1366   // in the subtree of current node.
1367   using NodesCostPair =
1368       std::pair<SmallPtrSet<MachineDomTreeNode *, 16>, BlockFrequency>;
1369   DenseMap<MachineDomTreeNode *, NodesCostPair> SpillsInSubTreeMap;
1370 
1371   // Iterate Orders set in reverse order, which will be a bottom-up order
1372   // in the dominator tree. Once we visit a dom tree node, we know its
1373   // children have already been visited and the spill locations in the
1374   // subtrees of all the children have been determined.
1375   SmallVector<MachineDomTreeNode *, 32>::reverse_iterator RIt = Orders.rbegin();
1376   for (; RIt != Orders.rend(); RIt++) {
1377     MachineBasicBlock *Block = (*RIt)->getBlock();
1378 
1379     // If Block contains an original spill, simply continue.
1380     if (SpillsToKeep.find(*RIt) != SpillsToKeep.end() && !SpillsToKeep[*RIt]) {
1381       SpillsInSubTreeMap[*RIt].first.insert(*RIt);
1382       // SpillsInSubTreeMap[*RIt].second contains the cost of spill.
1383       SpillsInSubTreeMap[*RIt].second = MBFI.getBlockFreq(Block);
1384       continue;
1385     }
1386 
1387     // Collect spills in subtree of current node (*RIt) to
1388     // SpillsInSubTreeMap[*RIt].first.
1389     for (MachineDomTreeNode *Child : (*RIt)->children()) {
1390       if (SpillsInSubTreeMap.find(Child) == SpillsInSubTreeMap.end())
1391         continue;
1392       // The stmt "SpillsInSubTree = SpillsInSubTreeMap[*RIt].first" below
1393       // should be placed before getting the begin and end iterators of
1394       // SpillsInSubTreeMap[Child].first, or else the iterators may be
1395       // invalidated when SpillsInSubTreeMap[*RIt] is seen the first time
1396       // and the map grows and then the original buckets in the map are moved.
1397       SmallPtrSet<MachineDomTreeNode *, 16> &SpillsInSubTree =
1398           SpillsInSubTreeMap[*RIt].first;
1399       BlockFrequency &SubTreeCost = SpillsInSubTreeMap[*RIt].second;
1400       SubTreeCost += SpillsInSubTreeMap[Child].second;
1401       auto BI = SpillsInSubTreeMap[Child].first.begin();
1402       auto EI = SpillsInSubTreeMap[Child].first.end();
1403       SpillsInSubTree.insert(BI, EI);
1404       SpillsInSubTreeMap.erase(Child);
1405     }
1406 
1407     SmallPtrSet<MachineDomTreeNode *, 16> &SpillsInSubTree =
1408           SpillsInSubTreeMap[*RIt].first;
1409     BlockFrequency &SubTreeCost = SpillsInSubTreeMap[*RIt].second;
1410     // No spills in subtree, simply continue.
1411     if (SpillsInSubTree.empty())
1412       continue;
1413 
1414     // Check whether Block is a possible candidate to insert spill.
1415     Register LiveReg;
1416     if (!isSpillCandBB(OrigLI, OrigVNI, *Block, LiveReg))
1417       continue;
1418 
1419     // If there are multiple spills that could be merged, bias a little
1420     // to hoist the spill.
1421     BranchProbability MarginProb = (SpillsInSubTree.size() > 1)
1422                                        ? BranchProbability(9, 10)
1423                                        : BranchProbability(1, 1);
1424     if (SubTreeCost > MBFI.getBlockFreq(Block) * MarginProb) {
1425       // Hoist: Move spills to current Block.
1426       for (const auto SpillBB : SpillsInSubTree) {
1427         // When SpillBB is a BB contains original spill, insert the spill
1428         // to SpillsToRm.
1429         if (SpillsToKeep.find(SpillBB) != SpillsToKeep.end() &&
1430             !SpillsToKeep[SpillBB]) {
1431           MachineInstr *SpillToRm = SpillBBToSpill[SpillBB];
1432           SpillsToRm.push_back(SpillToRm);
1433         }
1434         // SpillBB will not contain spill anymore, remove it from SpillsToKeep.
1435         SpillsToKeep.erase(SpillBB);
1436       }
1437       // Current Block is the BB containing the new hoisted spill. Add it to
1438       // SpillsToKeep. LiveReg is the source of the new spill.
1439       SpillsToKeep[*RIt] = LiveReg;
1440       LLVM_DEBUG({
1441         dbgs() << "spills in BB: ";
1442         for (const auto Rspill : SpillsInSubTree)
1443           dbgs() << Rspill->getBlock()->getNumber() << " ";
1444         dbgs() << "were promoted to BB" << (*RIt)->getBlock()->getNumber()
1445                << "\n";
1446       });
1447       SpillsInSubTree.clear();
1448       SpillsInSubTree.insert(*RIt);
1449       SubTreeCost = MBFI.getBlockFreq(Block);
1450     }
1451   }
1452   // For spills in SpillsToKeep with LiveReg set (i.e., not original spill),
1453   // save them to SpillsToIns.
1454   for (const auto &Ent : SpillsToKeep) {
1455     if (Ent.second)
1456       SpillsToIns[Ent.first->getBlock()] = Ent.second;
1457   }
1458 }
1459 
1460 /// For spills with equal values, remove redundant spills and hoist those left
1461 /// to less hot spots.
1462 ///
1463 /// Spills with equal values will be collected into the same set in
1464 /// MergeableSpills when spill is inserted. These equal spills are originated
1465 /// from the same defining instruction and are dominated by the instruction.
1466 /// Before hoisting all the equal spills, redundant spills inside in the same
1467 /// BB are first marked to be deleted. Then starting from the spills left, walk
1468 /// up on the dominator tree towards the Root node where the define instruction
1469 /// is located, mark the dominated spills to be deleted along the way and
1470 /// collect the BB nodes on the path from non-dominated spills to the define
1471 /// instruction into a WorkSet. The nodes in WorkSet are the candidate places
1472 /// where we are considering to hoist the spills. We iterate the WorkSet in
1473 /// bottom-up order, and for each node, we will decide whether to hoist spills
1474 /// inside its subtree to that node. In this way, we can get benefit locally
1475 /// even if hoisting all the equal spills to one cold place is impossible.
1476 void HoistSpillHelper::hoistAllSpills() {
1477   SmallVector<Register, 4> NewVRegs;
1478   LiveRangeEdit Edit(nullptr, NewVRegs, MF, LIS, &VRM, this);
1479 
1480   for (unsigned i = 0, e = MRI.getNumVirtRegs(); i != e; ++i) {
1481     Register Reg = Register::index2VirtReg(i);
1482     Register Original = VRM.getPreSplitReg(Reg);
1483     if (!MRI.def_empty(Reg))
1484       Virt2SiblingsMap[Original].insert(Reg);
1485   }
1486 
1487   // Each entry in MergeableSpills contains a spill set with equal values.
1488   for (auto &Ent : MergeableSpills) {
1489     int Slot = Ent.first.first;
1490     LiveInterval &OrigLI = *StackSlotToOrigLI[Slot];
1491     VNInfo *OrigVNI = Ent.first.second;
1492     SmallPtrSet<MachineInstr *, 16> &EqValSpills = Ent.second;
1493     if (Ent.second.empty())
1494       continue;
1495 
1496     LLVM_DEBUG({
1497       dbgs() << "\nFor Slot" << Slot << " and VN" << OrigVNI->id << ":\n"
1498              << "Equal spills in BB: ";
1499       for (const auto spill : EqValSpills)
1500         dbgs() << spill->getParent()->getNumber() << " ";
1501       dbgs() << "\n";
1502     });
1503 
1504     // SpillsToRm is the spill set to be removed from EqValSpills.
1505     SmallVector<MachineInstr *, 16> SpillsToRm;
1506     // SpillsToIns is the spill set to be newly inserted after hoisting.
1507     DenseMap<MachineBasicBlock *, unsigned> SpillsToIns;
1508 
1509     runHoistSpills(OrigLI, *OrigVNI, EqValSpills, SpillsToRm, SpillsToIns);
1510 
1511     LLVM_DEBUG({
1512       dbgs() << "Finally inserted spills in BB: ";
1513       for (const auto &Ispill : SpillsToIns)
1514         dbgs() << Ispill.first->getNumber() << " ";
1515       dbgs() << "\nFinally removed spills in BB: ";
1516       for (const auto Rspill : SpillsToRm)
1517         dbgs() << Rspill->getParent()->getNumber() << " ";
1518       dbgs() << "\n";
1519     });
1520 
1521     // Stack live range update.
1522     LiveInterval &StackIntvl = LSS.getInterval(Slot);
1523     if (!SpillsToIns.empty() || !SpillsToRm.empty())
1524       StackIntvl.MergeValueInAsValue(OrigLI, OrigVNI,
1525                                      StackIntvl.getValNumInfo(0));
1526 
1527     // Insert hoisted spills.
1528     for (auto const &Insert : SpillsToIns) {
1529       MachineBasicBlock *BB = Insert.first;
1530       Register LiveReg = Insert.second;
1531       MachineBasicBlock::iterator MI = IPA.getLastInsertPointIter(OrigLI, *BB);
1532       TII.storeRegToStackSlot(*BB, MI, LiveReg, false, Slot,
1533                               MRI.getRegClass(LiveReg), &TRI);
1534       LIS.InsertMachineInstrRangeInMaps(std::prev(MI), MI);
1535       ++NumSpills;
1536     }
1537 
1538     // Remove redundant spills or change them to dead instructions.
1539     NumSpills -= SpillsToRm.size();
1540     for (auto const RMEnt : SpillsToRm) {
1541       RMEnt->setDesc(TII.get(TargetOpcode::KILL));
1542       for (unsigned i = RMEnt->getNumOperands(); i; --i) {
1543         MachineOperand &MO = RMEnt->getOperand(i - 1);
1544         if (MO.isReg() && MO.isImplicit() && MO.isDef() && !MO.isDead())
1545           RMEnt->RemoveOperand(i - 1);
1546       }
1547     }
1548     Edit.eliminateDeadDefs(SpillsToRm, None, AA);
1549   }
1550 }
1551 
1552 /// For VirtReg clone, the \p New register should have the same physreg or
1553 /// stackslot as the \p old register.
1554 void HoistSpillHelper::LRE_DidCloneVirtReg(unsigned New, unsigned Old) {
1555   if (VRM.hasPhys(Old))
1556     VRM.assignVirt2Phys(New, VRM.getPhys(Old));
1557   else if (VRM.getStackSlot(Old) != VirtRegMap::NO_STACK_SLOT)
1558     VRM.assignVirt2StackSlot(New, VRM.getStackSlot(Old));
1559   else
1560     llvm_unreachable("VReg should be assigned either physreg or stackslot");
1561 }
1562