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