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