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