LLVM 24.0.0git
InlineSpiller.cpp
Go to the documentation of this file.
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 "InlineSpiller.h"
15#include "AllocationOrder.h"
16#include "SplitKit.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/MapVector.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SetVector.h"
24#include "llvm/ADT/Statistic.h"
49#include "llvm/Config/llvm-config.h"
54#include "llvm/Support/Debug.h"
57#include <cassert>
58#include <iterator>
59#include <tuple>
60#include <utility>
61
62using namespace llvm;
63
64#define DEBUG_TYPE "regalloc"
65
66STATISTIC(NumSpilledRanges, "Number of spilled live ranges");
67STATISTIC(NumSnippets, "Number of spilled snippets");
68STATISTIC(NumSpills, "Number of spills inserted");
69STATISTIC(NumSpillsRemoved, "Number of spills removed");
70STATISTIC(NumReloads, "Number of reloads inserted");
71STATISTIC(NumReloadsRemoved, "Number of reloads removed");
72STATISTIC(NumFolded, "Number of folded stack accesses");
73STATISTIC(NumFoldedLoads, "Number of folded loads");
74STATISTIC(NumRemats, "Number of rematerialized defs for spilling");
75
76static cl::opt<bool>
77RestrictStatepointRemat("restrict-statepoint-remat",
78 cl::init(false), cl::Hidden,
79 cl::desc("Restrict remat for statepoint operands"));
80
81namespace {
82class HoistSpillHelper : private LiveRangeEdit::Delegate {
84 LiveIntervals &LIS;
85 LiveStacks &LSS;
87 VirtRegMap &VRM;
89 const TargetInstrInfo &TII;
90 const MachineBlockFrequencyInfo &MBFI;
92
94
95 // Map from StackSlot to the LiveInterval of the original register.
96 // Note the LiveInterval of the original register may have been deleted
97 // after it is spilled. We keep a copy here to track the range where
98 // spills can be moved.
100
101 // Map from pair of (StackSlot and Original VNI) to a set of spills which
102 // have the same stackslot and have equal values defined by Original VNI.
103 // These spills are mergeable and are hoist candidates.
104 using MergeableSpillsMap =
106 MergeableSpillsMap MergeableSpills;
107
108 // Original values whose saves may have become dead by restore forwarding.
109 SmallPtrSet<VNInfo *, 8> DeadSpillCandidates;
110
111 /// This is the map from original register to a set containing all its
112 /// siblings. To hoist a spill to another BB, we need to find out a live
113 /// sibling there and use it as the source of the new spill.
115
116 bool isSpillCandBB(LiveInterval &OrigLI, VNInfo &OrigVNI,
117 MachineBasicBlock &BB, Register &LiveReg);
118
119 void rmRedundantSpills(
123
124 void getVisitOrders(
130
131 void runHoistSpills(LiveInterval &OrigLI, VNInfo &OrigVNI,
135
136 bool isFullSlotStore(const MachineInstr &MI, int FI) const;
137 SmallPtrSet<VNInfo *, 8> collectUsedSpillValues() const;
138 void removeSlotsWithoutAccesses(const SmallSetVector<int, 8> &Slots);
139
140public:
141 HoistSpillHelper(const Spiller::RequiredAnalyses &Analyses,
142 MachineFunction &mf, VirtRegMap &vrm, LiveRegMatrix *matrix)
143 : MF(mf), LIS(Analyses.LIS), LSS(Analyses.LSS), MDT(Analyses.MDT),
144 VRM(vrm), MRI(mf.getRegInfo()), TII(*mf.getSubtarget().getInstrInfo()),
145 MBFI(Analyses.MBFI), Matrix(matrix), IPA(LIS, mf.getNumBlockIDs()) {}
146
147 void addToMergeableSpills(MachineInstr &Spill, int StackSlot,
148 Register Original);
149 bool rmFromMergeableSpills(MachineInstr &Spill, int StackSlot);
150 void addDeadSpillCandidate(const MachineInstr &Spill, int StackSlot);
151 void hoistAllSpills();
152 void LRE_WillShrinkVirtReg(Register) override;
153 bool LRE_CanEraseVirtReg(Register) override;
154 void LRE_DidCloneVirtReg(Register, Register) override;
155
156private:
157 // Vregs unassigned from the matrix during LRE_WillShrinkVirtReg, pending
158 // re-assignment after the interval is shrunk/split.
159 DenseMap<Register, MCRegister> PendingReassignments;
160};
161
162class InlineSpiller : public Spiller {
163 MachineFunction &MF;
164 LiveIntervals &LIS;
165 LiveStacks &LSS;
166 VirtRegMap &VRM;
167 MachineRegisterInfo &MRI;
168 const TargetInstrInfo &TII;
169 const TargetRegisterInfo &TRI;
170 LiveRegMatrix *Matrix = nullptr;
171 LiveDebugVariables *DebugVars = nullptr;
172
173 // Variables that are valid during spill(), but used by multiple methods.
174 LiveRangeEdit *Edit = nullptr;
175 LiveInterval *StackInt = nullptr;
176 int StackSlot;
177 Register Original;
178 AllocationOrder *Order = nullptr;
179
180 // All registers to spill to StackSlot, including the main register.
181 SmallVector<Register, 8> RegsToSpill;
182
183 // All registers that were replaced by the spiller through some other method,
184 // e.g. rematerialization.
185 SmallVector<Register, 8> RegsReplaced;
186
187 // All COPY instructions to/from snippets.
188 // They are ignored since both operands refer to the same stack slot.
189 // For bundled copies, this will only include the first header copy.
190 SmallPtrSet<MachineInstr*, 8> SnippetCopies;
191
192 // Values that failed to remat at some point.
193 SmallPtrSet<VNInfo*, 8> UsedValues;
194
195 // Dead defs generated during spilling.
196 SmallVector<MachineInstr*, 8> DeadDefs;
197
198 // Virtual registers whose saves were forwarded to restores, by stack slot.
199 DenseMap<int, SmallVector<Register, 4>> ForwardedStoreRegs;
200
201 // Object records spills information and does the hoisting.
202 HoistSpillHelper HSpiller;
203
204 // Live range weight calculator.
205 VirtRegAuxInfo &VRAI;
206
207 ~InlineSpiller() override = default;
208
209public:
210 InlineSpiller(const Spiller::RequiredAnalyses &Analyses, MachineFunction &MF,
211 VirtRegMap &VRM, VirtRegAuxInfo &VRAI, LiveRegMatrix *Matrix)
212 : MF(MF), LIS(Analyses.LIS), LSS(Analyses.LSS), VRM(VRM),
213 MRI(MF.getRegInfo()), TII(*MF.getSubtarget().getInstrInfo()),
214 TRI(*MF.getSubtarget().getRegisterInfo()), Matrix(Matrix),
215 DebugVars(Analyses.DebugVars), HSpiller(Analyses, MF, VRM, Matrix),
216 VRAI(VRAI) {}
217
218 void spill(LiveRangeEdit &, AllocationOrder *Order = nullptr) override;
219 ArrayRef<Register> getSpilledRegs() override { return RegsToSpill; }
220 ArrayRef<Register> getReplacedRegs() override { return RegsReplaced; }
221 void postOptimization() override;
222
223private:
224 bool isSnippet(const LiveInterval &SnipLI);
225 void collectRegsToSpill();
226
227 bool isRegToSpill(Register Reg) { return is_contained(RegsToSpill, Reg); }
228
229 bool isSibling(Register Reg);
230 bool hoistSpillInsideBB(LiveInterval &SpillLI, MachineInstr &CopyMI);
231 void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI);
232 void eliminateRedundantRestores();
233 bool tryForwardFromStoreToRestore(MachineInstr &Store, MachineInstr &Restore);
234
235 void markValueUsed(LiveInterval *, VNInfo *);
236 bool hasPhysRegAvailable(const MachineInstr &MI);
237 bool reMaterializeFor(LiveInterval &, MachineInstr &MI);
238 void reMaterializeAll();
239
240 bool coalesceStackAccess(MachineInstr *MI, Register Reg);
241 bool foldMemoryOperand(ArrayRef<std::pair<MachineInstr *, unsigned>>,
242 MachineInstr *LoadMI = nullptr);
243 void insertReload(Register VReg, SlotIndex, MachineBasicBlock::iterator MI);
244 void insertSpill(Register VReg, MachineBasicBlock::iterator MI);
245
246 void spillAroundUses(Register Reg);
247 void spillAll();
248};
249
250} // end anonymous namespace
251
252Spiller::~Spiller() = default;
253
254void Spiller::anchor() {}
255
256Spiller *
257llvm::createInlineSpiller(const InlineSpiller::RequiredAnalyses &Analyses,
258 MachineFunction &MF, VirtRegMap &VRM,
260 return new InlineSpiller(Analyses, MF, VRM, VRAI, Matrix);
261}
262
263//===----------------------------------------------------------------------===//
264// Snippets
265//===----------------------------------------------------------------------===//
266
267// When spilling a virtual register, we also spill any snippets it is connected
268// to. The snippets are small live ranges that only have a single real use,
269// leftovers from live range splitting. Spilling them enables memory operand
270// folding or tightens the live range around the single use.
271//
272// This minimizes register pressure and maximizes the store-to-load distance for
273// spill slots which can be important in tight loops.
274
275/// isFullCopyOf - If MI is a COPY to or from Reg, return the other register,
276/// otherwise return 0.
278 const TargetInstrInfo &TII) {
279 if (!TII.isCopyInstr(MI))
280 return Register();
281
282 const MachineOperand &DstOp = MI.getOperand(0);
283 const MachineOperand &SrcOp = MI.getOperand(1);
284
285 // TODO: Probably only worth allowing subreg copies with undef dests.
286 if (DstOp.getSubReg() != SrcOp.getSubReg())
287 return Register();
288 if (DstOp.getReg() == Reg)
289 return SrcOp.getReg();
290 if (SrcOp.getReg() == Reg)
291 return DstOp.getReg();
292 return Register();
293}
294
295/// Check for a copy bundle as formed by SplitKit.
297 const TargetInstrInfo &TII) {
298 if (!FirstMI.isBundled())
299 return isCopyOf(FirstMI, Reg, TII);
300
301 assert(!FirstMI.isBundledWithPred() && FirstMI.isBundledWithSucc() &&
302 "expected to see first instruction in bundle");
303
304 Register SnipReg;
306 while (I->isBundledWithSucc()) {
307 const MachineInstr &MI = *I;
308 auto CopyInst = TII.isCopyInstr(MI);
309 if (!CopyInst)
310 return Register();
311
312 const MachineOperand &DstOp = *CopyInst->Destination;
313 const MachineOperand &SrcOp = *CopyInst->Source;
314 if (DstOp.getReg() == Reg) {
315 if (!SnipReg)
316 SnipReg = SrcOp.getReg();
317 else if (SnipReg != SrcOp.getReg())
318 return Register();
319 } else if (SrcOp.getReg() == Reg) {
320 if (!SnipReg)
321 SnipReg = DstOp.getReg();
322 else if (SnipReg != DstOp.getReg())
323 return Register();
324 }
325
326 ++I;
327 }
328
329 return Register();
330}
331
332static void getVDefInterval(const MachineInstr &MI, LiveIntervals &LIS) {
333 for (const MachineOperand &MO : MI.all_defs())
334 if (MO.getReg().isVirtual())
335 LIS.getInterval(MO.getReg());
336}
337
338/// isSnippet - Identify if a live interval is a snippet that should be spilled.
339/// It is assumed that SnipLI is a virtual register with the same original as
340/// Edit->getReg().
341bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) {
342 Register Reg = Edit->getReg();
343
344 // A snippet is a tiny live range with only a single instruction using it
345 // besides copies to/from Reg or spills/fills.
346 // Exception is done for statepoint instructions which will fold fills
347 // into their operands.
348 // We accept:
349 //
350 // %snip = COPY %Reg / FILL fi#
351 // %snip = USE %snip
352 // %snip = STATEPOINT %snip in var arg area
353 // %Reg = COPY %snip / SPILL %snip, fi#
354 //
355 if (!LIS.intervalIsInOneMBB(SnipLI))
356 return false;
357
358 // Number of defs should not exceed 2 not accounting defs coming from
359 // statepoint instructions.
360 unsigned NumValNums = SnipLI.getNumValNums();
361 for (auto *VNI : SnipLI.vnis()) {
362 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
363 if (MI->getOpcode() == TargetOpcode::STATEPOINT)
364 --NumValNums;
365 }
366 if (NumValNums > 2)
367 return false;
368
369 MachineInstr *UseMI = nullptr;
370
371 // Check that all uses satisfy our criteria.
373 RI = MRI.reg_bundle_nodbg_begin(SnipLI.reg()),
375 RI != E;) {
376 MachineInstr &MI = *RI++;
377
378 // Allow copies to/from Reg.
379 if (isCopyOfBundle(MI, Reg, TII))
380 continue;
381
382 // Allow stack slot loads.
383 int FI;
384 if (SnipLI.reg() == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot)
385 continue;
386
387 // Allow stack slot stores.
388 if (SnipLI.reg() == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot)
389 continue;
390
391 if (StatepointOpers::isFoldableReg(&MI, SnipLI.reg()))
392 continue;
393
394 // Allow a single additional instruction.
395 if (UseMI && &MI != UseMI)
396 return false;
397 UseMI = &MI;
398 }
399 return true;
400}
401
402/// collectRegsToSpill - Collect live range snippets that only have a single
403/// real use.
404void InlineSpiller::collectRegsToSpill() {
405 Register Reg = Edit->getReg();
406
407 // Main register always spills.
408 RegsToSpill.assign(1, Reg);
409 SnippetCopies.clear();
410 RegsReplaced.clear();
411
412 // Snippets all have the same original, so there can't be any for an original
413 // register.
414 if (Original == Reg)
415 return;
416
418 Register SnipReg = isCopyOfBundle(MI, Reg, TII);
419 if (!isSibling(SnipReg))
420 continue;
421 LiveInterval &SnipLI = LIS.getInterval(SnipReg);
422 if (!isSnippet(SnipLI))
423 continue;
424 SnippetCopies.insert(&MI);
425 if (isRegToSpill(SnipReg))
426 continue;
427 RegsToSpill.push_back(SnipReg);
428 LLVM_DEBUG(dbgs() << "\talso spill snippet " << SnipLI << '\n');
429 ++NumSnippets;
430 }
431}
432
433bool InlineSpiller::isSibling(Register Reg) {
434 return Reg.isVirtual() && VRM.getOriginal(Reg) == Original;
435}
436
437/// It is beneficial to spill to earlier place in the same BB in case
438/// as follows:
439/// There is an alternative def earlier in the same MBB.
440/// Hoist the spill as far as possible in SpillMBB. This can ease
441/// register pressure:
442///
443/// x = def
444/// y = use x
445/// s = copy x
446///
447/// Hoisting the spill of s to immediately after the def removes the
448/// interference between x and y:
449///
450/// x = def
451/// spill x
452/// y = use killed x
453///
454/// This hoist only helps when the copy kills its source.
455///
456bool InlineSpiller::hoistSpillInsideBB(LiveInterval &SpillLI,
457 MachineInstr &CopyMI) {
458 SlotIndex Idx = LIS.getInstructionIndex(CopyMI);
459#ifndef NDEBUG
460 VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getRegSlot());
461 assert(VNI && VNI->def == Idx.getRegSlot() && "Not defined by copy");
462#endif
463
464 Register SrcReg = CopyMI.getOperand(1).getReg();
465 LiveInterval &SrcLI = LIS.getInterval(SrcReg);
466 VNInfo *SrcVNI = SrcLI.getVNInfoAt(Idx);
467 LiveQueryResult SrcQ = SrcLI.Query(Idx);
468 MachineBasicBlock *DefMBB = LIS.getMBBFromIndex(SrcVNI->def);
469 if (DefMBB != CopyMI.getParent() || !SrcQ.isKill())
470 return false;
471
472 MachineBasicBlock *MBB = DefMBB;
474 if (SrcVNI->isPHIDef())
475 MII = MBB->SkipPHIsLabelsAndDebug(MBB->begin(), SrcReg);
476 else {
477 MachineInstr *DefMI = LIS.getInstructionFromIndex(SrcVNI->def);
478 assert(DefMI && "Defining instruction disappeared");
479 MII = DefMI;
480 ++MII;
481 }
482
483 // When the def is a PHI, the store may be inserted after the prologue
484 // instructions. In that case, the segment may need to be extended to the
485 // store (see below). Do not hoist if there is an interference between the end
486 // of the segment and the insertion point.
487 if (SrcVNI->isPHIDef() && Matrix && VRM.hasPhys(SrcReg)) {
488 // Here, MII points to the instruction before which the store will be
489 // inserted. Using that instruction's base index is a safe upper bound for
490 // the interference check.
491 SlotIndex InsertIdx = MII == MBB->end()
492 ? LIS.getMBBEndIdx(MBB)
493 : LIS.getInstructionIndex(*MII).getBaseIndex();
494 if (SrcQ.endPoint() < InsertIdx &&
495 Matrix->checkInterference(SrcQ.endPoint(), InsertIdx,
496 VRM.getPhys(SrcReg)))
497 return false;
498 }
499
500 // Conservatively extend the stack slot range to the range of the original
501 // value. We may be able to do better with stack slot coloring by being more
502 // careful here.
503 assert(StackInt && "No stack slot assigned yet.");
504 LiveInterval &OrigLI = LIS.getInterval(Original);
505 VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx);
506 StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0));
507 LLVM_DEBUG(dbgs() << "\tmerged orig valno " << OrigVNI->id << ": "
508 << *StackInt << '\n');
509
510 // We are going to spill SrcVNI immediately after its def, so clear out
511 // any later spills of the same value.
512 eliminateRedundantSpills(SrcLI, SrcVNI);
513
514 MachineInstrSpan MIS(MII, MBB);
515 // Insert spill without kill flag immediately after def.
516 TII.storeRegToStackSlot(*MBB, MII, SrcReg, false, StackSlot,
517 MRI.getRegClass(SrcReg), Register());
518 LIS.InsertMachineInstrRangeInMaps(MIS.begin(), MII);
519 for (const MachineInstr &MI : make_range(MIS.begin(), MII))
520 getVDefInterval(MI, LIS);
521 --MII; // Point to store instruction.
522 LLVM_DEBUG(dbgs() << "\thoisted: " << SrcVNI->def << '\t' << *MII);
523
524 // When the def is a PHI, SkipPHIsLabelsAndDebug may place the store past
525 // prologue instructions. Therefore if that copy was the end of a segment
526 // we need to extend it to the store.
527 if (SrcVNI->isPHIDef()) {
528 SlotIndex StoreUseIdx = LIS.getInstructionIndex(*MII).getRegSlot(true);
529 SrcLI.extendInBlock(LIS.getMBBStartIdx(MBB), StoreUseIdx);
530 }
531
532 // If there is only 1 store instruction is required for spill, add it
533 // to mergeable list. In X86 AMX, 2 instructions are required to store.
534 // We disable the merge for this case.
535 if (MIS.begin() == MII)
536 HSpiller.addToMergeableSpills(*MII, StackSlot, Original);
537 ++NumSpills;
538 return true;
539}
540
542 return Reg.isVirtual() ? Register(VRM.getPhys(Reg)) : Reg;
543}
544
545/// Return true if \p Other reads every physical register that \p MI reads,
546/// except \p Ignore.
549 return all_of(MI.all_uses(), [&](const MachineOperand &MO) {
550 Register Reg = MO.getReg();
551 return !Reg.isPhysical() || Reg == Ignore ||
552 Other.readsRegister(Reg, /*TRI=*/nullptr);
553 });
554}
555
556/// Replace \p Restore with a copy to forward the value if \p Store saved the
557/// same physical register to the same slot and that register still holds the
558/// value. Returns true if the forwarding was successful, false otherwise.
559bool InlineSpiller::tryForwardFromStoreToRestore(MachineInstr &Store,
560 MachineInstr &Restore) {
561 // Establish that Restore and Store are both eligible for forwarding check
562 // that physical register, store/load size and stack slot match.
563 int LoadFI;
564 TypeSize LoadSize = TypeSize::getZero();
565 Register LoadReg = TII.isLoadFromStackSlot(Restore, LoadFI, LoadSize);
566 if (!LoadReg)
567 return false;
568
569 MachineOperand *LoadOperand = Restore.findRegisterDefOperand(LoadReg, &TRI);
570 if (!LoadOperand || LoadOperand->getSubReg())
571 return false;
572
573 int StoreFI;
574 TypeSize StoreSize = TypeSize::getZero();
575 Register StoreReg = TII.isStoreToStackSlot(Store, StoreFI, StoreSize);
576 if (!StoreReg)
577 return false;
578
579 MachineOperand *StoreOperand = Store.findRegisterUseOperand(StoreReg, &TRI);
580 if (!StoreOperand || StoreOperand->getSubReg() || StoreOperand->isUndef())
581 return false;
582
583 if (StoreFI != LoadFI || !MF.getFrameInfo().isSpillSlotObjectIndex(LoadFI))
584 return false;
585
586 if (StoreSize.isZero() || StoreSize != LoadSize)
587 return false;
588 if (StoreSize * 8 != TRI.getRegSizeInBits(StoreReg, MRI) ||
589 LoadSize * 8 != TRI.getRegSizeInBits(LoadReg, MRI))
590 return false;
591
592 Register PhysReg = getAssignedReg(VRM, LoadReg);
593 if (!PhysReg || PhysReg != getAssignedReg(VRM, StoreReg))
594 return false;
595
596 // Both accesses must read the same physical registers.
597 if (!readsPhysRegsOf(Store, Restore, StoreReg) ||
598 !readsPhysRegsOf(Restore, Store, StoreReg))
599 return false;
600
601 MachineBasicBlock &MBB = *Restore.getParent();
602 auto Gap = make_range(std::next(Store.getIterator()), Restore.getIterator());
603 bool Adjacent = all_of(
604 Gap, [](const MachineInstr &GapMI) { return GapMI.isDebugInstr(); });
605 SlotIndex StoreIdx = LIS.getInstructionIndex(Store).getRegSlot();
606 SlotIndex Use = LIS.getInstructionIndex(Restore).getRegSlot();
607 LiveInterval *StoreLI =
608 StoreReg.isVirtual() ? &LIS.getInterval(StoreReg) : nullptr;
609 // If Restore and Store are not directly adjacent, we need to make sure that
610 // the forwarded register or the inputs of restore and store are not modified
611 // between the two instructions.
612 if (!Adjacent) {
613 if (!Matrix)
614 return false;
615 for (const MachineInstr &GapMI : Gap)
616 for (const MachineOperand &Def : GapMI.all_defs()) {
617 Register DefReg = getAssignedReg(VRM, Def.getReg());
618 if (DefReg && (TRI.regsOverlap(DefReg, PhysReg) ||
619 Store.readsRegister(DefReg, &TRI)))
620 return false;
621 }
622 // The saved register must keep its value across the gap.
623 if (StoreLI && any_of(StoreLI->vnis(), [&](const VNInfo *VNI) {
624 return !VNI->isUnused() && StoreIdx < VNI->def && VNI->def < Use;
625 }))
626 return false;
627 if (StoreLI)
628 Matrix->unassign(*StoreLI);
629 bool Interferes =
630 Matrix->checkInterference(StoreIdx, Use, PhysReg.asMCReg());
631 if (StoreLI)
632 Matrix->assign(*StoreLI, PhysReg.asMCReg());
633 if (Interferes)
634 return false;
635 }
636
637 LLVM_DEBUG(dbgs() << "Forwarding restore " << Restore << " from save "
638 << Store);
639 // Forward by inserting a copy instruction.
640 MachineInstr *Copy = BuildMI(MBB, Restore, Restore.getDebugLoc(),
641 TII.get(TargetOpcode::COPY), LoadReg)
642 .addReg(StoreReg)
643 .getInstr();
644 Store.clearRegisterKills(StoreReg, &TRI);
645 // The copy doesn't read the other physical registers of the restore.
646 // Drop their outdated cached ranges to be recomputed on demand.
647 for (const MachineOperand &MO : Restore.all_uses())
648 if (MO.getReg().isPhysical())
649 for (MCRegUnit Unit : TRI.regunits(MO.getReg().asMCReg()))
650 if (!MRI.isReservedRegUnit(Unit))
651 LIS.removeRegUnit(Unit);
652 LIS.ReplaceMachineInstrInMaps(Restore, *Copy);
653 MF.substituteDebugValuesForInst(Restore, *Copy, /*MaxOperand=*/1);
654 Restore.eraseFromParent();
655 ++NumReloadsRemoved;
656 SlotIndex BlockStart = LIS.getMBBStartIdx(&MBB);
657 if (!StoreLI) {
658 // Store register is physical, extend the live range.
659 for (MCRegUnit Unit : TRI.regunits(StoreReg.asMCReg())) {
660 if (MRI.isReservedRegUnit(Unit))
661 continue;
662 if (LiveRange *LR = LIS.getCachedRegUnit(Unit))
663 LR->extendInBlock(BlockStart, Use);
664 }
665 return true;
666 }
667 // Saves can only be removed if LiveDebugVariables can be told that the value
668 // is in the forwarded register instead of the stack slot.
669 if (DebugVars) {
670 HSpiller.addDeadSpillCandidate(Store, StoreFI);
671 ForwardedStoreRegs[StoreFI].push_back(StoreReg);
672 }
673 // Store register is virtual, update liveness information and re-assign in the
674 // matrix.
675 if (Matrix)
676 Matrix->unassign(*StoreLI);
677 StoreLI->extendInBlock(BlockStart, Use);
678 for (LiveInterval::SubRange &SubLI : StoreLI->subranges())
679 if (SubLI.getVNInfoBefore(StoreIdx))
680 SubLI.extendInBlock(BlockStart, Use);
681 if (Matrix)
682 Matrix->assign(*StoreLI, PhysReg.asMCReg());
683 return true;
684}
685
686void InlineSpiller::eliminateRedundantRestores() {
687 for (MachineBasicBlock &MBB : MF) {
688 DenseMap<int, MachineInstr *> PreviousSlotAccess;
690 if (MI.isDebugInstr())
691 continue;
692 int FI;
694 if (TII.isLoadFromStackSlot(MI, FI, Size))
695 if (MachineInstr *Store = PreviousSlotAccess.lookup(FI))
696 if (tryForwardFromStoreToRestore(*Store, MI))
697 continue;
698 // Before frame index elimination, every stack slot access has a frame
699 // index operand.
700 for (const MachineOperand &MO : MI.operands())
701 if (MO.isFI())
702 PreviousSlotAccess[MO.getIndex()] = &MI;
703 }
704 }
705
706 if (ForwardedStoreRegs.empty())
707 return;
708 // Update LiveDebugVariables for forwarded registers.
709 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
711 auto It = ForwardedStoreRegs.find(VRM.getStackSlot(Reg));
712 if (It != ForwardedStoreRegs.end())
713 DebugVars->splitRegister(Reg, It->second, LIS);
714 }
715 ForwardedStoreRegs.clear();
716}
717
718/// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any
719/// redundant spills of this value in SLI.reg and sibling copies.
720void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) {
721 assert(VNI && "Missing value");
723 WorkList.push_back(std::make_pair(&SLI, VNI));
724 assert(StackInt && "No stack slot assigned yet.");
725
726 do {
727 LiveInterval *LI;
728 std::tie(LI, VNI) = WorkList.pop_back_val();
729 Register Reg = LI->reg();
730 LLVM_DEBUG(dbgs() << "Checking redundant spills for " << VNI->id << '@'
731 << VNI->def << " in " << *LI << '\n');
732
733 // Regs to spill are taken care of.
734 if (isRegToSpill(Reg))
735 continue;
736
737 // Add all of VNI's live range to StackInt.
738 StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0));
739 LLVM_DEBUG(dbgs() << "Merged to stack int: " << *StackInt << '\n');
740
741 // Find all spills and copies of VNI.
742 for (MachineInstr &MI :
744 if (!MI.mayStore() && !TII.isCopyInstr(MI))
745 continue;
746 SlotIndex Idx = LIS.getInstructionIndex(MI);
747 if (LI->getVNInfoAt(Idx) != VNI)
748 continue;
749
750 // Follow sibling copies down the dominator tree.
751 if (Register DstReg = isCopyOfBundle(MI, Reg, TII)) {
752 if (isSibling(DstReg)) {
753 LiveInterval &DstLI = LIS.getInterval(DstReg);
754 VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getRegSlot());
755 assert(DstVNI && "Missing defined value");
756 assert(DstVNI->def == Idx.getRegSlot() && "Wrong copy def slot");
757
758 WorkList.push_back(std::make_pair(&DstLI, DstVNI));
759 }
760 continue;
761 }
762
763 // Erase spills.
764 int FI;
765 if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) {
766 LLVM_DEBUG(dbgs() << "Redundant spill " << Idx << '\t' << MI);
767 // eliminateDeadDefs won't normally remove stores, so switch opcode.
768 MI.setDesc(TII.get(TargetOpcode::KILL));
769 DeadDefs.push_back(&MI);
770 ++NumSpillsRemoved;
771 if (HSpiller.rmFromMergeableSpills(MI, StackSlot))
772 --NumSpills;
773 }
774 }
775 } while (!WorkList.empty());
776}
777
778//===----------------------------------------------------------------------===//
779// Rematerialization
780//===----------------------------------------------------------------------===//
781
782/// markValueUsed - Remember that VNI failed to rematerialize, so its defining
783/// instruction cannot be eliminated. See through snippet copies
784void InlineSpiller::markValueUsed(LiveInterval *LI, VNInfo *VNI) {
786 WorkList.push_back(std::make_pair(LI, VNI));
787 do {
788 std::tie(LI, VNI) = WorkList.pop_back_val();
789 if (!UsedValues.insert(VNI).second)
790 continue;
791
792 if (VNI->isPHIDef()) {
793 MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def);
794 for (MachineBasicBlock *P : MBB->predecessors()) {
795 VNInfo *PVNI = LI->getVNInfoBefore(LIS.getMBBEndIdx(P));
796 if (PVNI)
797 WorkList.push_back(std::make_pair(LI, PVNI));
798 }
799 continue;
800 }
801
802 // Follow snippet copies.
803 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
804 if (!SnippetCopies.count(MI))
805 continue;
806 LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg());
807 assert(isRegToSpill(SnipLI.reg()) && "Unexpected register in copy");
808 VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getRegSlot(true));
809 assert(SnipVNI && "Snippet undefined before copy");
810 WorkList.push_back(std::make_pair(&SnipLI, SnipVNI));
811 } while (!WorkList.empty());
812}
813
815 const MachineInstr &MI) {
817 return true;
818 // Here's a quick explanation of the problem we're trying to handle here:
819 // * There are some pseudo instructions with more vreg uses than there are
820 // physical registers on the machine.
821 // * This is normally handled by spilling the vreg, and folding the reload
822 // into the user instruction. (Thus decreasing the number of used vregs
823 // until the remainder can be assigned to physregs.)
824 // * However, since we may try to spill vregs in any order, we can end up
825 // trying to spill each operand to the instruction, and then rematting it
826 // instead. When that happens, the new live intervals (for the remats) are
827 // expected to be trivially assignable (i.e. RS_Done). However, since we
828 // may have more remats than physregs, we're guaranteed to fail to assign
829 // one.
830 // At the moment, we only handle this for STATEPOINTs since they're the only
831 // pseudo op where we've seen this. If we start seeing other instructions
832 // with the same problem, we need to revisit this.
833 if (MI.getOpcode() != TargetOpcode::STATEPOINT)
834 return true;
835 // For STATEPOINTs we allow re-materialization for fixed arguments only hoping
836 // that number of physical registers is enough to cover all fixed arguments.
837 // If it is not true we need to revisit it.
838 for (unsigned Idx = StatepointOpers(&MI).getVarIdx(),
839 EndIdx = MI.getNumOperands();
840 Idx < EndIdx; ++Idx) {
841 const MachineOperand &MO = MI.getOperand(Idx);
842 if (MO.isReg() && MO.getReg() == VReg)
843 return false;
844 }
845 return true;
846}
847
848/// hasPhysRegAvailable - Check if there is an available physical register for
849/// rematerialization.
850bool InlineSpiller::hasPhysRegAvailable(const MachineInstr &MI) {
851 if (!Order || !Matrix)
852 return false;
853
854 SlotIndex UseIdx = LIS.getInstructionIndex(MI).getRegSlot(true);
855 SlotIndex PrevIdx = UseIdx.getPrevSlot();
856
857 for (MCPhysReg PhysReg : *Order) {
858 if (!Matrix->checkInterference(PrevIdx, UseIdx, PhysReg))
859 return true;
860 }
861
862 return false;
863}
864
865/// reMaterializeFor - Attempt to rematerialize before MI instead of reloading.
866bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg, MachineInstr &MI) {
867 // Analyze instruction
869 VirtRegInfo RI = AnalyzeVirtRegInBundle(MI, VirtReg.reg(), &Ops);
870
871 // Defs without reads will be deleted if unused after remat is
872 // completed for other users of the virtual register.
873 if (!RI.Reads) {
874 LLVM_DEBUG(dbgs() << "\tskipping remat of def " << MI);
875 return false;
876 }
877
878 SlotIndex UseIdx = LIS.getInstructionIndex(MI).getRegSlot(true);
879 VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx.getBaseIndex());
880
881 if (!ParentVNI) {
882 LLVM_DEBUG(dbgs() << "\tadding <undef> flags: ");
883 for (MachineOperand &MO : MI.all_uses())
884 if (MO.getReg() == VirtReg.reg())
885 MO.setIsUndef();
886 LLVM_DEBUG(dbgs() << UseIdx << '\t' << MI);
887 return true;
888 }
889
890 // Snippets copies are ignored for remat, and will be deleted if they
891 // don't feed a live user after rematerialization completes.
892 if (SnippetCopies.count(&MI)) {
893 LLVM_DEBUG(dbgs() << "\tskipping remat snippet copy for " << UseIdx << '\t'
894 << MI);
895 return false;
896 }
897
898 LiveInterval &OrigLI = LIS.getInterval(Original);
899 VNInfo *OrigVNI = OrigLI.getVNInfoAt(UseIdx);
900 assert(OrigVNI && "corrupted sub-interval");
901 MachineInstr *DefMI = LIS.getInstructionFromIndex(OrigVNI->def);
902 // This can happen if for two reasons: 1) This could be a phi valno,
903 // or 2) the remat def has already been removed from the original
904 // live interval; this happens if we rematted to all uses, and
905 // then further split one of those live ranges.
906 if (!DefMI) {
907 // Try to find the rematerializable definition by tracing through COPY
908 // chains.
909 LiveInterval &LI = LIS.getInterval(VirtReg.reg());
910 VNInfo *CurVNI = LI.getVNInfoAt(UseIdx);
911 MachineInstr *CurDef = nullptr;
912
913 LLVM_DEBUG(dbgs() << "\ttracing COPY chain from "
914 << printReg(VirtReg.reg(), &TRI) << "\n");
915
916 // Trace backwards through COPY chain using VNInfo
917 while (CurVNI) {
918 CurDef = LIS.getInstructionFromIndex(CurVNI->def);
919
920 LLVM_DEBUG(dbgs() << "\t -> def at " << CurVNI->def << ": "
921 << (CurDef ? TII.getName(CurDef->getOpcode()) : "null")
922 << "\n");
923
924 if (!CurDef || !CurDef->isFullCopy())
925 break;
926
927 Register SrcReg = CurDef->getOperand(1).getReg();
928 if (!SrcReg.isVirtual())
929 break;
930 LLVM_DEBUG(dbgs() << "\t -> tracing through COPY to "
931 << printReg(SrcReg, &TRI) << "\n");
932 LiveInterval &SrcLI = LIS.getInterval(SrcReg);
933 CurVNI = SrcLI.getVNInfoBefore(CurVNI->def);
934 }
935 if (CurDef && TII.isReMaterializable(*CurDef)) {
936 DefMI = CurDef;
937 LLVM_DEBUG(dbgs() << "\tFound remat possibility through COPY chain: "
938 << *DefMI);
939 }
940 if (!DefMI) {
941 markValueUsed(&VirtReg, ParentVNI);
942 LLVM_DEBUG(dbgs() << "\tcannot remat missing def for " << UseIdx << '\t'
943 << MI);
944 return false;
945 }
946 }
947
948 LiveRangeEdit::Remat RM(ParentVNI);
949 RM.OrigMI = DefMI;
950 if (!Edit->canRematerializeAt(RM, UseIdx)) {
951 markValueUsed(&VirtReg, ParentVNI);
952 LLVM_DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << MI);
953 return false;
954 }
955
956 // If the instruction also writes VirtReg.reg, it had better not require the
957 // same register for uses and defs.
958 if (RI.Tied) {
959 markValueUsed(&VirtReg, ParentVNI);
960 LLVM_DEBUG(dbgs() << "\tcannot remat tied reg: " << UseIdx << '\t' << MI);
961 return false;
962 }
963
964 // Before rematerializing into a register for a single instruction, try to
965 // fold a load into the instruction. That avoids allocating a new register.
966 if (RM.OrigMI->canFoldAsLoad() &&
967 (RM.OrigMI->mayLoad() || !hasPhysRegAvailable(MI)) &&
968 foldMemoryOperand(Ops, RM.OrigMI)) {
969 Edit->markRematerialized(RM.ParentVNI);
970 ++NumFoldedLoads;
971 return true;
972 }
973
974 // If we can't guarantee that we'll be able to actually assign the new vreg,
975 // we can't remat.
976 if (!canGuaranteeAssignmentAfterRemat(VirtReg.reg(), MI)) {
977 markValueUsed(&VirtReg, ParentVNI);
978 LLVM_DEBUG(dbgs() << "\tcannot remat for " << UseIdx << '\t' << MI);
979 return false;
980 }
981
982 // Allocate a new register for the remat.
983 Register NewVReg = Edit->createFrom(Original);
984
985 // Constrain it to the register class of MI.
986 MRI.constrainRegClass(NewVReg, MRI.getRegClass(VirtReg.reg()));
987
988 // Compute which lanes of the virtual register are live at the use point.
989 LaneBitmask UsedLanes = LaneBitmask::getAll();
990 if (VirtReg.hasSubRanges()) {
991 UsedLanes = LaneBitmask::getNone();
992 for (const LiveInterval::SubRange &SR : VirtReg.subranges())
993 if (SR.liveAt(UseIdx))
994 UsedLanes |= SR.LaneMask;
995 }
996
997 // Finally we can rematerialize OrigMI before MI.
998 SlotIndex DefIdx = Edit->rematerializeAt(*MI.getParent(), MI, NewVReg, RM,
999 TRI, false, 0, nullptr, UsedLanes);
1000
1001 // We take the DebugLoc from MI, since OrigMI may be attributed to a
1002 // different source location.
1003 auto *NewMI = LIS.getInstructionFromIndex(DefIdx);
1004 NewMI->setDebugLoc(MI.getDebugLoc());
1005
1006 (void)DefIdx;
1007 LLVM_DEBUG(dbgs() << "\tremat: " << DefIdx << '\t'
1008 << *LIS.getInstructionFromIndex(DefIdx));
1009
1010 // Replace operands
1011 for (const auto &OpPair : Ops) {
1012 MachineOperand &MO = OpPair.first->getOperand(OpPair.second);
1013 if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg())
1014 MO.setReg(NewVReg);
1015 }
1016 LLVM_DEBUG(dbgs() << "\t " << UseIdx << '\t' << MI << '\n');
1017
1018 ++NumRemats;
1019 return true;
1020}
1021
1022/// reMaterializeAll - Try to rematerialize as many uses as possible,
1023/// and trim the live ranges after.
1024void InlineSpiller::reMaterializeAll() {
1025 UsedValues.clear();
1026
1027 // Try to remat before all uses of snippets.
1028 bool anyRemat = false;
1029 for (Register Reg : RegsToSpill) {
1030 LiveInterval &LI = LIS.getInterval(Reg);
1032 // Debug values are not allowed to affect codegen.
1033 if (MI.isDebugValue())
1034 continue;
1035
1036 assert(!MI.isDebugInstr() && "Did not expect to find a use in debug "
1037 "instruction that isn't a DBG_VALUE");
1038
1039 anyRemat |= reMaterializeFor(LI, MI);
1040 }
1041 }
1042 if (!anyRemat)
1043 return;
1044
1045 // Remove any values that were completely rematted.
1046 for (Register Reg : RegsToSpill) {
1047 LiveInterval &LI = LIS.getInterval(Reg);
1048 for (VNInfo *VNI : LI.vnis()) {
1049 if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI))
1050 continue;
1051 MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def);
1053 if (!MI->allDefsAreDead())
1054 continue;
1055 LLVM_DEBUG(dbgs() << "All defs dead: " << *MI);
1056 DeadDefs.push_back(MI);
1057 // If MI is a bundle header, also try removing copies inside the bundle,
1058 // otherwise the verifier would complain "live range continues after dead
1059 // def flag".
1060 if (MI->isBundledWithSucc() && !MI->isBundledWithPred()) {
1061 MachineBasicBlock::instr_iterator BeginIt = MI->getIterator(),
1062 EndIt = MI->getParent()->instr_end();
1063 ++BeginIt; // Skip MI that was already handled.
1064
1065 bool OnlyDeadCopies = true;
1066 for (MachineBasicBlock::instr_iterator It = BeginIt;
1067 It != EndIt && It->isBundledWithPred(); ++It) {
1068
1069 auto DestSrc = TII.isCopyInstr(*It);
1070 bool IsCopyToDeadReg =
1071 DestSrc && DestSrc->Destination->getReg() == Reg;
1072 if (!IsCopyToDeadReg) {
1073 OnlyDeadCopies = false;
1074 break;
1075 }
1076 }
1077 if (OnlyDeadCopies) {
1078 for (MachineBasicBlock::instr_iterator It = BeginIt;
1079 It != EndIt && It->isBundledWithPred(); ++It) {
1080 It->addRegisterDead(Reg, &TRI);
1081 LLVM_DEBUG(dbgs() << "All defs dead: " << *It);
1082 DeadDefs.push_back(&*It);
1083 }
1084 }
1085 }
1086 }
1087 }
1088
1089 // Eliminate dead code after remat. Note that some snippet copies may be
1090 // deleted here.
1091 if (DeadDefs.empty())
1092 return;
1093 LLVM_DEBUG(dbgs() << "Remat created " << DeadDefs.size() << " dead defs.\n");
1094 Edit->eliminateDeadDefs(DeadDefs, RegsToSpill);
1095
1096 // LiveRangeEdit::eliminateDeadDef is used to remove dead define instructions
1097 // after rematerialization. To remove a VNI for a vreg from its LiveInterval,
1098 // LiveIntervals::removeVRegDefAt is used. However, after non-PHI VNIs are all
1099 // removed, PHI VNI are still left in the LiveInterval.
1100 // So to get rid of unused reg, we need to check whether it has non-dbg
1101 // reference instead of whether it has non-empty interval.
1102 unsigned ResultPos = 0;
1103 for (Register Reg : RegsToSpill) {
1104 if (MRI.reg_nodbg_empty(Reg)) {
1105 Edit->eraseVirtReg(Reg);
1106 RegsReplaced.push_back(Reg);
1107 continue;
1108 }
1109
1110 assert(LIS.hasInterval(Reg) &&
1111 (!LIS.getInterval(Reg).empty() || !MRI.reg_nodbg_empty(Reg)) &&
1112 "Empty and not used live-range?!");
1113
1114 RegsToSpill[ResultPos++] = Reg;
1115 }
1116 RegsToSpill.erase(RegsToSpill.begin() + ResultPos, RegsToSpill.end());
1117 LLVM_DEBUG(dbgs() << RegsToSpill.size()
1118 << " registers to spill after remat.\n");
1119}
1120
1121//===----------------------------------------------------------------------===//
1122// Spilling
1123//===----------------------------------------------------------------------===//
1124
1125/// If MI is a load or store of StackSlot, it can be removed.
1126bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, Register Reg) {
1127 int FI = 0;
1128 Register InstrReg = TII.isLoadFromStackSlot(*MI, FI);
1129 bool IsLoad = InstrReg.isValid();
1130 if (!IsLoad)
1131 InstrReg = TII.isStoreToStackSlot(*MI, FI);
1132
1133 // We have a stack access. Is it the right register and slot?
1134 if (InstrReg != Reg || FI != StackSlot)
1135 return false;
1136
1137 if (!IsLoad)
1138 HSpiller.rmFromMergeableSpills(*MI, StackSlot);
1139
1140 LLVM_DEBUG(dbgs() << "Coalescing stack access: " << *MI);
1141 LIS.RemoveMachineInstrFromMaps(*MI);
1142 MI->eraseFromParent();
1143
1144 if (IsLoad) {
1145 ++NumReloadsRemoved;
1146 --NumReloads;
1147 } else {
1148 ++NumSpillsRemoved;
1149 --NumSpills;
1150 }
1151
1152 return true;
1153}
1154
1155#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1157// Dump the range of instructions from B to E with their slot indexes.
1160 LiveIntervals const &LIS,
1161 const char *const header,
1162 Register VReg = Register()) {
1163 char NextLine = '\n';
1164 char SlotIndent = '\t';
1165
1166 if (std::next(B) == E) {
1167 NextLine = ' ';
1168 SlotIndent = ' ';
1169 }
1170
1171 dbgs() << '\t' << header << ": " << NextLine;
1172
1173 for (MachineBasicBlock::iterator I = B; I != E; ++I) {
1175
1176 // If a register was passed in and this instruction has it as a
1177 // destination that is marked as an early clobber, print the
1178 // early-clobber slot index.
1179 if (VReg) {
1180 MachineOperand *MO = I->findRegisterDefOperand(VReg, /*TRI=*/nullptr);
1181 if (MO && MO->isEarlyClobber())
1182 Idx = Idx.getRegSlot(true);
1183 }
1184
1185 dbgs() << SlotIndent << Idx << '\t' << *I;
1186 }
1187}
1188#endif
1189
1190/// foldMemoryOperand - Try folding stack slot references in Ops into their
1191/// instructions.
1192///
1193/// @param Ops Operand indices from AnalyzeVirtRegInBundle().
1194/// @param LoadMI Load instruction to use instead of stack slot when non-null.
1195/// @return True on success.
1196bool InlineSpiller::
1197foldMemoryOperand(ArrayRef<std::pair<MachineInstr *, unsigned>> Ops,
1198 MachineInstr *LoadMI) {
1199 if (Ops.empty())
1200 return false;
1201 // Don't attempt folding in bundles.
1202 MachineInstr *MI = Ops.front().first;
1203 if (Ops.back().first != MI || MI->isBundled())
1204 return false;
1205
1206 bool WasCopy = TII.isCopyInstr(*MI).has_value();
1207 Register ImpReg;
1208
1209 // TII::foldMemoryOperand will do what we need here for statepoint
1210 // (fold load into use and remove corresponding def). We will replace
1211 // uses of removed def with loads (spillAroundUses).
1212 // For that to work we need to untie def and use to pass it through
1213 // foldMemoryOperand and signal foldPatchpoint that it is allowed to
1214 // fold them.
1215 bool UntieRegs = MI->getOpcode() == TargetOpcode::STATEPOINT;
1216
1217 // Spill subregs if the target allows it.
1218 // We always want to spill subregs for stackmap/patchpoint pseudos.
1219 bool SpillSubRegs = TII.isSubregFoldable() ||
1220 MI->getOpcode() == TargetOpcode::STATEPOINT ||
1221 MI->getOpcode() == TargetOpcode::PATCHPOINT ||
1222 MI->getOpcode() == TargetOpcode::STACKMAP;
1223
1224 // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied
1225 // operands.
1227 for (const auto &OpPair : Ops) {
1228 unsigned Idx = OpPair.second;
1229 assert(MI == OpPair.first && "Instruction conflict during operand folding");
1230 MachineOperand &MO = MI->getOperand(Idx);
1231
1232 // No point restoring an undef read, and we'll produce an invalid live
1233 // interval.
1234 // TODO: Is this really the correct way to handle undef tied uses?
1235 if (MO.isUse() && !MO.readsReg() && !MO.isTied())
1236 continue;
1237
1238 if (MO.isImplicit()) {
1239 ImpReg = MO.getReg();
1240 continue;
1241 }
1242
1243 if (!SpillSubRegs && MO.getSubReg())
1244 return false;
1245 // We cannot fold a load instruction into a def.
1246 if (LoadMI && MO.isDef())
1247 return false;
1248 // Tied use operands should not be passed to foldMemoryOperand.
1249 if (UntieRegs || !MI->isRegTiedToDefOperand(Idx))
1250 FoldOps.push_back(Idx);
1251 }
1252
1253 // If we only have implicit uses, we won't be able to fold that.
1254 // Moreover, TargetInstrInfo::foldMemoryOperand will assert if we try!
1255 if (FoldOps.empty())
1256 return false;
1257
1258 MachineInstrSpan MIS(MI, MI->getParent());
1259
1261 if (UntieRegs)
1262 for (unsigned Idx : FoldOps) {
1263 MachineOperand &MO = MI->getOperand(Idx);
1264 if (!MO.isTied())
1265 continue;
1266 unsigned Tied = MI->findTiedOperandIdx(Idx);
1267 if (MO.isUse())
1268 TiedOps.emplace_back(Tied, Idx);
1269 else {
1270 assert(MO.isDef() && "Tied to not use and def?");
1271 TiedOps.emplace_back(Idx, Tied);
1272 }
1273 MI->untieRegOperand(Idx);
1274 }
1275
1276 MachineInstr *CopyMI = nullptr;
1277 MachineInstr *FoldMI =
1278 LoadMI
1279 ? TII.foldMemoryOperand(*MI, FoldOps, *LoadMI, CopyMI, &LIS, &VRM)
1280 : TII.foldMemoryOperand(*MI, FoldOps, StackSlot, CopyMI, &LIS, &VRM);
1281 if (!FoldMI) {
1282 // Re-tie operands.
1283 for (auto Tied : TiedOps)
1284 MI->tieOperands(Tied.first, Tied.second);
1285 return false;
1286 }
1287
1288 // Remove LIS for any dead defs in the original MI not in FoldMI.
1289 for (MIBundleOperands MO(*MI); MO.isValid(); ++MO) {
1290 if (!MO->isReg())
1291 continue;
1292 Register Reg = MO->getReg();
1293 if (!Reg || Reg.isVirtual() || MRI.isReserved(Reg)) {
1294 continue;
1295 }
1296 // Skip non-Defs, including undef uses and internal reads.
1297 if (MO->isUse())
1298 continue;
1299 PhysRegInfo RI = AnalyzePhysRegInBundle(*FoldMI, Reg, &TRI);
1300 if (RI.FullyDefined)
1301 continue;
1302 // FoldMI does not define this physreg. Remove the LI segment.
1303 assert(MO->isDead() && "Cannot fold physreg def");
1305 LIS.removePhysRegDefAt(Reg.asMCReg(), Idx);
1306 }
1307
1308 int FI;
1309 if (TII.isStoreToStackSlot(*MI, FI) &&
1310 HSpiller.rmFromMergeableSpills(*MI, FI))
1311 --NumSpills;
1312 SlotIndex FoldIdx = LIS.ReplaceMachineInstrInMaps(*MI, *FoldMI);
1313 if (CopyMI) {
1314 SlotIndex CopyIdx = LIS.InsertMachineInstrInMaps(*CopyMI).getRegSlot();
1315 if (!MRI.isSSA()) {
1316 Register CopyDstReg = CopyMI->getOperand(0).getReg();
1317 LiveInterval &LI = LIS.getInterval(CopyDstReg);
1318
1319 // The addSegment below extends CopyDstReg's LiveInterval with a new
1320 // segment for the copy. If CopyDstReg is already assigned in the
1321 // LiveRegMatrix, we must unassign before the modification and reassign
1322 // after, so the matrix stays consistent with the updated interval.
1323 // This can happen when the fold target creates a copy
1324 // to preserve a source operand, defining a vreg that was already
1325 // allocated to a physreg.
1326 bool NeedMatrixReassign =
1327 Matrix && CopyDstReg.isVirtual() && VRM.hasPhys(CopyDstReg);
1328 MCRegister PhysReg;
1329 if (NeedMatrixReassign) {
1330 PhysReg = VRM.getPhys(CopyDstReg);
1331 Matrix->unassign(LI);
1332 }
1333
1334 VNInfo *VNI = LI.getNextValue(CopyIdx, LIS.getVNInfoAllocator());
1335 LI.addSegment(LiveRange::Segment(CopyIdx, FoldIdx.getRegSlot(), VNI));
1336
1337 if (NeedMatrixReassign)
1338 Matrix->assign(LI, PhysReg);
1339
1340 // The fold target must not create a COPY into a register derived from
1341 // another one, since the COPY's range would not be covered by the
1342 // original register's live interval.
1343 assert(VRM.getOriginal(CopyDstReg) == CopyDstReg &&
1344 "COPY destination should be an original register");
1345 }
1346 }
1347 // Update the call info.
1348 if (MI->isCandidateForAdditionalCallInfo())
1349 MI->getMF()->moveAdditionalCallInfo(MI, FoldMI);
1350
1351 // If we've folded a store into an instruction labelled with debug-info,
1352 // record a substitution from the old operand to the memory operand. Handle
1353 // the simple common case where operand 0 is the one being folded, plus when
1354 // the destination operand is also a tied def. More values could be
1355 // substituted / preserved with more analysis.
1356 if (MI->peekDebugInstrNum() && Ops[0].second == 0) {
1357 // Helper lambda.
1358 auto MakeSubstitution = [this,FoldMI,MI,&Ops]() {
1359 // Substitute old operand zero to the new instructions memory operand.
1360 unsigned OldOperandNum = Ops[0].second;
1361 unsigned NewNum = FoldMI->getDebugInstrNum();
1362 unsigned OldNum = MI->getDebugInstrNum();
1363 MF.makeDebugValueSubstitution({OldNum, OldOperandNum},
1365 };
1366
1367 const MachineOperand &Op0 = MI->getOperand(Ops[0].second);
1368 if (Ops.size() == 1 && Op0.isDef()) {
1369 MakeSubstitution();
1370 } else if (Ops.size() == 2 && Op0.isDef() && MI->getOperand(1).isTied() &&
1371 Op0.getReg() == MI->getOperand(1).getReg()) {
1372 MakeSubstitution();
1373 }
1374 } else if (MI->peekDebugInstrNum()) {
1375 // This is a debug-labelled instruction, but the operand being folded isn't
1376 // at operand zero. Most likely this means it's a load being folded in.
1377 // Substitute any register defs from operand zero up to the one being
1378 // folded -- past that point, we don't know what the new operand indexes
1379 // will be.
1380 MF.substituteDebugValuesForInst(*MI, *FoldMI, Ops[0].second);
1381 }
1382
1383 MI->eraseFromParent();
1384
1385 // Insert any new instructions other than FoldMI into the LIS maps.
1386 assert(!MIS.empty() && "Unexpected empty span of instructions!");
1387 for (MachineInstr &MI : MIS)
1388 if (&MI != FoldMI && &MI != CopyMI)
1390
1391 if (CopyMI) {
1392 Register R = CopyMI->getOperand(1).getReg();
1393 if (R.isVirtual()) {
1394 LiveInterval &LI = LIS.getInterval(R);
1395 LIS.shrinkToUses(&LI);
1396 } else {
1397 assert(MRI.isReserved(R) && "Unexpected PhysReg in source operand!");
1398 }
1399 }
1400
1401 // TII.foldMemoryOperand may have left some implicit operands on the
1402 // instruction. Strip them.
1403 if (ImpReg)
1404 for (unsigned i = FoldMI->getNumOperands(); i; --i) {
1405 MachineOperand &MO = FoldMI->getOperand(i - 1);
1406 if (!MO.isReg() || !MO.isImplicit())
1407 break;
1408 if (MO.getReg() == ImpReg)
1409 FoldMI->removeOperand(i - 1);
1410 }
1411
1412 LLVM_DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MIS.end(), LIS,
1413 "folded"));
1414
1415 if (!WasCopy)
1416 ++NumFolded;
1417 else if (Ops.front().second == 0) {
1418 ++NumSpills;
1419 // If there is only 1 store instruction is required for spill, add it
1420 // to mergeable list. In X86 AMX, 2 instructions are required to store.
1421 // We disable the merge for this case.
1422 if (std::distance(MIS.begin(), MIS.end()) <= 1)
1423 HSpiller.addToMergeableSpills(*FoldMI, StackSlot, Original);
1424 } else
1425 ++NumReloads;
1426 return true;
1427}
1428
1429void InlineSpiller::insertReload(Register NewVReg,
1430 SlotIndex Idx,
1433
1434 MachineInstrSpan MIS(MI, &MBB);
1435 TII.loadRegFromStackSlot(MBB, MI, NewVReg, StackSlot,
1436 MRI.getRegClass(NewVReg), Register());
1437
1438 LIS.InsertMachineInstrRangeInMaps(MIS.begin(), MI);
1439
1440 LLVM_DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MI, LIS, "reload",
1441 NewVReg));
1442 ++NumReloads;
1443}
1444
1445/// Check if \p Def defines \p Reg with an undefined value.
1446/// If that's the case, that means the value of Reg is actually
1447/// not relevant.
1448static bool isRealSpill(const MachineInstr &Def, Register Reg) {
1449 if (!Def.isImplicitDef())
1450 return true;
1451
1452 // Reg is undef only if every def of it in Def is full or read-undef.
1453 // Otherwise, other lanes may hold live values.
1454 return any_of(Def.all_defs(), [&](const MachineOperand &MO) {
1455 return MO.getReg() == Reg && MO.readsReg();
1456 });
1457}
1458
1459/// insertSpill - Insert a spill of NewVReg after MI.
1460void InlineSpiller::insertSpill(Register NewVReg,
1462 // Spill are not terminators, so inserting spills after terminators will
1463 // violate invariants in MachineVerifier.
1464 assert(!MI->isTerminator() && "Inserting a spill after a terminator");
1466
1467 MachineInstrSpan MIS(MI, &MBB);
1468 MachineBasicBlock::iterator SpillBefore = std::next(MI);
1469 bool IsRealSpill = isRealSpill(*MI, NewVReg);
1470
1471 if (IsRealSpill)
1472 TII.storeRegToStackSlot(MBB, SpillBefore, NewVReg, false, StackSlot,
1473 MRI.getRegClass(NewVReg), Register());
1474 else
1475 // Don't spill undef value.
1476 // Anything works for undef, in particular keeping the memory
1477 // uninitialized is a viable option and it saves code size and
1478 // run time.
1479 BuildMI(MBB, SpillBefore, MI->getDebugLoc(), TII.get(TargetOpcode::KILL))
1480 .addReg(NewVReg);
1481
1483 LIS.InsertMachineInstrRangeInMaps(Spill, MIS.end());
1484 for (const MachineInstr &MI : make_range(Spill, MIS.end()))
1485 getVDefInterval(MI, LIS);
1486
1487 LLVM_DEBUG(
1488 dumpMachineInstrRangeWithSlotIndex(Spill, MIS.end(), LIS, "spill"));
1489 ++NumSpills;
1490 // If there is only 1 store instruction is required for spill, add it
1491 // to mergeable list. In X86 AMX, 2 instructions are required to store.
1492 // We disable the merge for this case.
1493 if (IsRealSpill && std::distance(Spill, MIS.end()) <= 1)
1494 HSpiller.addToMergeableSpills(*Spill, StackSlot, Original);
1495}
1496
1497/// spillAroundUses - insert spill code around each use of Reg.
1498void InlineSpiller::spillAroundUses(Register Reg) {
1499 LLVM_DEBUG(dbgs() << "spillAroundUses " << printReg(Reg) << '\n');
1500 LiveInterval &OldLI = LIS.getInterval(Reg);
1501
1502 // Iterate over instructions using Reg.
1504 // Debug values are not allowed to affect codegen.
1505 if (MI.isDebugValue()) {
1506 // Modify DBG_VALUE now that the value is in a spill slot.
1508 LLVM_DEBUG(dbgs() << "Modifying debug info due to spill:\t" << MI);
1509 buildDbgValueForSpill(*MBB, &MI, MI, StackSlot, Reg);
1510 MBB->erase(MI);
1511 continue;
1512 }
1513
1514 assert(!MI.isDebugInstr() && "Did not expect to find a use in debug "
1515 "instruction that isn't a DBG_VALUE");
1516
1517 // Ignore copies to/from snippets. We'll delete them.
1518 if (SnippetCopies.count(&MI))
1519 continue;
1520
1521 // Stack slot accesses may coalesce away.
1522 if (coalesceStackAccess(&MI, Reg))
1523 continue;
1524
1525 // Analyze instruction.
1528
1529 // Find the slot index where this instruction reads and writes OldLI.
1530 // This is usually the def slot, except for tied early clobbers.
1532 if (VNInfo *VNI = OldLI.getVNInfoAt(Idx.getRegSlot(true)))
1533 if (SlotIndex::isSameInstr(Idx, VNI->def))
1534 Idx = VNI->def;
1535
1536 // Check for a sibling copy.
1537 Register SibReg = isCopyOfBundle(MI, Reg, TII);
1538 if (SibReg && isSibling(SibReg)) {
1539 // This may actually be a copy between snippets.
1540 if (isRegToSpill(SibReg)) {
1541 LLVM_DEBUG(dbgs() << "Found new snippet copy: " << MI);
1542 SnippetCopies.insert(&MI);
1543 continue;
1544 }
1545 if (RI.Writes) {
1546 if (hoistSpillInsideBB(OldLI, MI)) {
1547 // This COPY is now dead, the value is already in the stack slot.
1548 MI.getOperand(0).setIsDead();
1549 DeadDefs.push_back(&MI);
1550 continue;
1551 }
1552 } else {
1553 // This is a reload for a sib-reg copy. Drop spills downstream.
1554 LiveInterval &SibLI = LIS.getInterval(SibReg);
1555 eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx));
1556 // The COPY will fold to a reload below.
1557 }
1558 }
1559
1560 // Attempt to fold memory ops.
1561 if (foldMemoryOperand(Ops))
1562 continue;
1563
1564 // Create a new virtual register for spill/fill.
1565 // FIXME: Infer regclass from instruction alone.
1566 Register NewVReg = Edit->createFrom(Reg);
1567
1568 if (RI.Reads)
1569 insertReload(NewVReg, Idx, &MI);
1570
1571 // Rewrite instruction operands.
1572 bool hasLiveDef = false;
1573 for (const auto &OpPair : Ops) {
1574 MachineOperand &MO = OpPair.first->getOperand(OpPair.second);
1575 MO.setReg(NewVReg);
1576 if (MO.isDef() && !MO.isDead())
1577 hasLiveDef = true;
1578 }
1579 LLVM_DEBUG(dbgs() << "\trewrite: " << Idx << '\t' << MI << '\n');
1580
1581 // FIXME: Use a second vreg if instruction has no tied ops.
1582 if (RI.Writes)
1583 if (hasLiveDef)
1584 insertSpill(NewVReg, &MI);
1585 }
1586}
1587
1588/// spillAll - Spill all registers remaining after rematerialization.
1589void InlineSpiller::spillAll() {
1590 // Update LiveStacks now that we are committed to spilling.
1591 if (StackSlot == VirtRegMap::NO_STACK_SLOT) {
1592 StackSlot = VRM.assignVirt2StackSlot(Original);
1593 StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original));
1594 StackInt->getNextValue(SlotIndex(), LSS.getVNInfoAllocator());
1595 } else
1596 StackInt = &LSS.getInterval(StackSlot);
1597
1598 if (Original != Edit->getReg())
1599 VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot);
1600
1601 assert(StackInt->getNumValNums() == 1 && "Bad stack interval values");
1602 for (Register Reg : RegsToSpill)
1603 StackInt->MergeSegmentsInAsValue(LIS.getInterval(Reg),
1604 StackInt->getValNumInfo(0));
1605 LLVM_DEBUG(dbgs() << "Merged spilled regs: " << *StackInt << '\n');
1606
1607 // Spill around uses of all RegsToSpill.
1608 for (Register Reg : RegsToSpill) {
1609 spillAroundUses(Reg);
1610 // Assign all of the spilled registers to the slot so that
1611 // LiveDebugVariables knows about these locations later on.
1612 if (VRM.getStackSlot(Reg) == VirtRegMap::NO_STACK_SLOT)
1613 VRM.assignVirt2StackSlot(Reg, StackSlot);
1614 }
1615
1616 // Hoisted spills may cause dead code.
1617 if (!DeadDefs.empty()) {
1618 LLVM_DEBUG(dbgs() << "Eliminating " << DeadDefs.size() << " dead defs\n");
1619 Edit->eliminateDeadDefs(DeadDefs, RegsToSpill);
1620 }
1621
1622 // Finally delete the SnippetCopies.
1623 for (Register Reg : RegsToSpill) {
1624 for (MachineInstr &MI :
1626 assert(SnippetCopies.count(&MI) && "Remaining use wasn't a snippet copy");
1627 // FIXME: Do this with a LiveRangeEdit callback.
1629 MI.eraseFromBundle();
1630 }
1631 }
1632
1633 // Delete all spilled registers.
1634 for (Register Reg : RegsToSpill)
1635 Edit->eraseVirtReg(Reg);
1636}
1637
1638void InlineSpiller::spill(LiveRangeEdit &edit, AllocationOrder *order) {
1639 ++NumSpilledRanges;
1640 Edit = &edit;
1641 Order = order;
1642 assert(!edit.getReg().isStack() && "Trying to spill a stack slot.");
1643 // Share a stack slot among all descendants of Original.
1644 Original = VRM.getOriginal(edit.getReg());
1645 StackSlot = VRM.getStackSlot(Original);
1646 StackInt = nullptr;
1647
1648 LLVM_DEBUG(dbgs() << "Inline spilling "
1649 << TRI.getRegClassName(MRI.getRegClass(edit.getReg()))
1650 << ':' << edit.getParent() << "\nFrom original "
1651 << printReg(Original) << '\n');
1652 assert(edit.getParent().isSpillable() &&
1653 "Attempting to spill already spilled value.");
1654 assert(DeadDefs.empty() && "Previous spill didn't remove dead defs");
1655
1656 collectRegsToSpill();
1657 reMaterializeAll();
1658
1659 // Remat may handle everything.
1660 if (!RegsToSpill.empty())
1661 spillAll();
1662
1663 Edit->calculateRegClassAndHint(MF, VRAI);
1664}
1665
1666/// Optimizations after all the reg selections and spills are done.
1667void InlineSpiller::postOptimization() {
1668 eliminateRedundantRestores();
1669 HSpiller.hoistAllSpills();
1670}
1671
1672/// When a spill is inserted, add the spill to MergeableSpills map.
1673void HoistSpillHelper::addToMergeableSpills(MachineInstr &Spill, int StackSlot,
1674 Register Original) {
1676 LiveInterval &OrigLI = LIS.getInterval(Original);
1677 // save a copy of LiveInterval in StackSlotToOrigLI because the original
1678 // LiveInterval may be cleared after all its references are spilled.
1679
1680 auto [Place, Inserted] = StackSlotToOrigLI.try_emplace(StackSlot);
1681 if (Inserted) {
1682 auto LI = std::make_unique<LiveInterval>(OrigLI.reg(), OrigLI.weight());
1683 LI->assign(OrigLI, Allocator);
1684 Place->second = std::move(LI);
1685 }
1686
1687 SlotIndex Idx = LIS.getInstructionIndex(Spill);
1688 VNInfo *OrigVNI = Place->second->getVNInfoAt(Idx.getRegSlot());
1689 std::pair<int, VNInfo *> MIdx = std::make_pair(StackSlot, OrigVNI);
1690 MergeableSpills[MIdx].insert(&Spill);
1691}
1692
1693/// When a spill is removed, remove the spill from MergeableSpills map.
1694/// Return true if the spill is removed successfully.
1695bool HoistSpillHelper::rmFromMergeableSpills(MachineInstr &Spill,
1696 int StackSlot) {
1697 auto It = StackSlotToOrigLI.find(StackSlot);
1698 if (It == StackSlotToOrigLI.end())
1699 return false;
1700 SlotIndex Idx = LIS.getInstructionIndex(Spill);
1701 VNInfo *OrigVNI = It->second->getVNInfoAt(Idx.getRegSlot());
1702 std::pair<int, VNInfo *> MIdx = std::make_pair(StackSlot, OrigVNI);
1703 return MergeableSpills[MIdx].erase(&Spill);
1704}
1705
1706/// Record that the save \p Spill may be dead because a restore of the value it
1707/// saves was forwarded. Only saves into slots created by this spiller qualify.
1708void HoistSpillHelper::addDeadSpillCandidate(const MachineInstr &Spill,
1709 int StackSlot) {
1710 auto It = StackSlotToOrigLI.find(StackSlot);
1711 if (It == StackSlotToOrigLI.end())
1712 return;
1714 if (VNInfo *OrigVNI = It->second->getVNInfoAt(Idx))
1715 DeadSpillCandidates.insert(OrigVNI);
1716}
1717
1718/// Return true if \p MI unconditionally overwrites all of stack slot \p FI.
1719bool HoistSpillHelper::isFullSlotStore(const MachineInstr &MI, int FI) const {
1720 if (MI.peekDebugInstrNum() || MI.mayLoad() || !MI.all_defs().empty())
1721 return false;
1722 int StoreFI;
1725 if (!Reg || StoreFI != FI || Size.isScalable() || Size.isZero() ||
1726 Size.getFixedValue() != uint64_t(MF.getFrameInfo().getObjectSize(FI)))
1727 return false;
1728 // Implicit inputs may predicate a spill, as EXEC does on AMDGPU.
1729 // Call regmasks don't model reserved registers, so like MachineCSE, assume
1730 // calls preserve constant physical registers.
1731 return all_of(MI.all_uses(), [&](const MachineOperand &MO) {
1732 Register Use = MO.getReg();
1733 return !Use || Use == Reg ||
1734 (Use.isPhysical() && MRI.isConstantPhysReg(Use.asMCReg()));
1735 });
1736}
1737
1738/// Remove the frame objects of \p Slots that no instruction accesses any more
1739/// and drop every debug location that still refers to them.
1740void HoistSpillHelper::removeSlotsWithoutAccesses(
1741 const SmallSetVector<int, 8> &Slots) {
1742 SmallSetVector<int, 8> DeadSlots = Slots;
1744 for (MachineBasicBlock &MBB : MF) {
1745 for (MachineInstr &MI : MBB.instrs()) {
1746 for (MachineOperand &MO : MI.operands()) {
1747 if (!MO.isFI() || !DeadSlots.contains(MO.getIndex()))
1748 continue;
1749 if (MI.isDebugValue())
1750 DebugOps.push_back(&MO);
1751 else
1752 DeadSlots.remove(MO.getIndex());
1753 }
1754 }
1755 }
1756 if (DeadSlots.empty())
1757 return;
1758
1759 // Mark dead slots as optimized out in debug info.
1760 for (MachineOperand *MO : DebugOps)
1761 if (DeadSlots.contains(MO->getIndex()))
1762 MO->ChangeToRegister(Register(), /*isDef=*/false);
1763
1764 // LiveDebugVariables places debug ranges of a spilled register without a
1765 // physical register in its stack slot. Forwarding already updates most of
1766 // those ranges, clearing here makes sure any left over ranges do not refer to
1767 // removed frame objects.
1768 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
1770 int Slot = VRM.getStackSlot(Reg);
1771 if (Slot != VirtRegMap::NO_STACK_SLOT && DeadSlots.contains(Slot))
1772 VRM.clearStackSlot(Reg);
1773 }
1774
1775 MachineFrameInfo &MFI = MF.getFrameInfo();
1776 for (int Slot : DeadSlots) {
1777 MFI.RemoveStackObject(Slot);
1778 }
1779}
1780
1781/// Collect the original values that stack accesses may read from slots
1782/// created by this spiller. Only spill code accesses those slots, and a full
1783/// store writes the original value live at that point.
1784SmallPtrSet<VNInfo *, 8> HoistSpillHelper::collectUsedSpillValues() const {
1787 for (const MachineBasicBlock &MBB : MF) {
1788 for (const MachineInstr &MI : MBB.instrs()) {
1789 if (MI.isDebugInstr())
1790 continue;
1791 for (const MachineOperand &MO : MI.operands()) {
1792 if (!MO.isFI())
1793 continue;
1794 int FI = MO.getIndex();
1795 auto It = StackSlotToOrigLI.find(FI);
1796 if (It == StackSlotToOrigLI.end() || isFullSlotStore(MI, FI))
1797 continue;
1798 LiveInterval &OrigLI = *It->second;
1800 if (VNInfo *VNI =
1801 MI.mayLoad() ? OrigLI.getVNInfoBefore(Idx) : nullptr) {
1802 Worklist.emplace_back(&OrigLI, VNI);
1803 } else {
1804 // Other accesses, such as partial or predicated stores, may leave
1805 // any value visible.
1806 for (VNInfo *VNI : OrigLI.vnis())
1807 Used.insert(VNI);
1808 }
1809 }
1810 }
1811 }
1812
1813 // A value merged at a block entry reads the values incoming from the
1814 // predecessors.
1815 while (!Worklist.empty()) {
1816 auto [OrigLI, VNI] = Worklist.pop_back_val();
1817 if (!Used.insert(VNI).second || !VNI->isPHIDef())
1818 continue;
1819 for (MachineBasicBlock *Pred :
1820 LIS.getMBBFromIndex(VNI->def)->predecessors())
1821 if (VNInfo *PredVNI = OrigLI->getVNInfoBefore(LIS.getMBBEndIdx(Pred)))
1822 Worklist.emplace_back(OrigLI, PredVNI);
1823 }
1824 return Used;
1825}
1826
1827/// Check BB to see if it is a possible target BB to place a hoisted spill,
1828/// i.e., there should be a living sibling of OrigReg at the insert point.
1829bool HoistSpillHelper::isSpillCandBB(LiveInterval &OrigLI, VNInfo &OrigVNI,
1830 MachineBasicBlock &BB, Register &LiveReg) {
1831 SlotIndex Idx = IPA.getLastInsertPoint(OrigLI, BB);
1832 // The original def could be after the last insert point in the root block,
1833 // we can't hoist to here.
1834 if (Idx < OrigVNI.def) {
1835 // TODO: We could be better here. If LI is not alive in landing pad
1836 // we could hoist spill after LIP.
1837 LLVM_DEBUG(dbgs() << "can't spill in root block - def after LIP\n");
1838 return false;
1839 }
1840 Register OrigReg = OrigLI.reg();
1841 SmallSetVector<Register, 16> &Siblings = Virt2SiblingsMap[OrigReg];
1842 assert(OrigLI.getVNInfoAt(Idx) == &OrigVNI && "Unexpected VNI");
1843
1844 for (const Register &SibReg : Siblings) {
1845 LiveInterval &LI = LIS.getInterval(SibReg);
1846 if (!LI.getVNInfoAt(Idx))
1847 continue;
1848 // All of the sub-ranges should be alive at the prospective slot index.
1849 // Otherwise, we might risk storing unrelated / compromised values from some
1850 // sub-registers to the spill slot.
1851 if (all_of(LI.subranges(), [&](const LiveInterval::SubRange &SR) {
1852 return SR.getVNInfoAt(Idx) != nullptr;
1853 })) {
1854 LiveReg = SibReg;
1855 return true;
1856 }
1857 }
1858 return false;
1859}
1860
1861/// Remove redundant spills in the same BB. Save those redundant spills in
1862/// SpillsToRm, and save the spill to keep and its BB in SpillBBToSpill map.
1863void HoistSpillHelper::rmRedundantSpills(
1867 // For each spill saw, check SpillBBToSpill[] and see if its BB already has
1868 // another spill inside. If a BB contains more than one spill, only keep the
1869 // earlier spill with smaller SlotIndex.
1870 for (auto *const CurrentSpill : Spills) {
1871 MachineBasicBlock *Block = CurrentSpill->getParent();
1872 MachineDomTreeNode *Node = MDT.getNode(Block);
1873 MachineInstr *PrevSpill = SpillBBToSpill[Node];
1874 if (PrevSpill) {
1875 SlotIndex PIdx = LIS.getInstructionIndex(*PrevSpill);
1876 SlotIndex CIdx = LIS.getInstructionIndex(*CurrentSpill);
1877 MachineInstr *SpillToRm = (CIdx > PIdx) ? CurrentSpill : PrevSpill;
1878 MachineInstr *SpillToKeep = (CIdx > PIdx) ? PrevSpill : CurrentSpill;
1879 SpillsToRm.push_back(SpillToRm);
1880 SpillBBToSpill[MDT.getNode(Block)] = SpillToKeep;
1881 } else {
1882 SpillBBToSpill[MDT.getNode(Block)] = CurrentSpill;
1883 }
1884 }
1885 for (auto *const SpillToRm : SpillsToRm)
1886 Spills.erase(SpillToRm);
1887}
1888
1889/// Starting from \p Root find a top-down traversal order of the dominator
1890/// tree to visit all basic blocks containing the elements of \p Spills.
1891/// Redundant spills will be found and put into \p SpillsToRm at the same
1892/// time. \p SpillBBToSpill will be populated as part of the process and
1893/// maps a basic block to the first store occurring in the basic block.
1894/// \post SpillsToRm.union(Spills\@post) == Spills\@pre
1895void HoistSpillHelper::getVisitOrders(
1901 // The set contains all the possible BB nodes to which we may hoist
1902 // original spills.
1904 // Save the BB nodes on the path from the first BB node containing
1905 // non-redundant spill to the Root node.
1907 // All the spills to be hoisted must originate from a single def instruction
1908 // to the OrigReg. It means the def instruction should dominate all the spills
1909 // to be hoisted. We choose the BB where the def instruction is located as
1910 // the Root.
1911 MachineDomTreeNode *RootIDomNode = MDT[Root]->getIDom();
1912 // For every node on the dominator tree with spill, walk up on the dominator
1913 // tree towards the Root node until it is reached. If there is other node
1914 // containing spill in the middle of the path, the previous spill saw will
1915 // be redundant and the node containing it will be removed. All the nodes on
1916 // the path starting from the first node with non-redundant spill to the Root
1917 // node will be added to the WorkSet, which will contain all the possible
1918 // locations where spills may be hoisted to after the loop below is done.
1919 for (auto *const Spill : Spills) {
1920 MachineBasicBlock *Block = Spill->getParent();
1922 MachineInstr *SpillToRm = nullptr;
1923 while (Node != RootIDomNode) {
1924 // If Node dominates Block, and it already contains a spill, the spill in
1925 // Block will be redundant.
1926 if (Node != MDT[Block] && SpillBBToSpill[Node]) {
1927 SpillToRm = SpillBBToSpill[MDT[Block]];
1928 break;
1929 /// If we see the Node already in WorkSet, the path from the Node to
1930 /// the Root node must already be traversed by another spill.
1931 /// Then no need to repeat.
1932 } else if (WorkSet.count(Node)) {
1933 break;
1934 } else {
1935 NodesOnPath.insert(Node);
1936 }
1937 Node = Node->getIDom();
1938 }
1939 if (SpillToRm) {
1940 SpillsToRm.push_back(SpillToRm);
1941 } else {
1942 // Add a BB containing the original spills to SpillsToKeep -- i.e.,
1943 // set the initial status before hoisting start. The value of BBs
1944 // containing original spills is set to 0, in order to descriminate
1945 // with BBs containing hoisted spills which will be inserted to
1946 // SpillsToKeep later during hoisting.
1947 SpillsToKeep[MDT[Block]] = Register();
1948 WorkSet.insert_range(NodesOnPath);
1949 }
1950 NodesOnPath.clear();
1951 }
1952
1953 // Sort the nodes in WorkSet in top-down order and save the nodes
1954 // in Orders. Orders will be used for hoisting in runHoistSpills.
1955 unsigned idx = 0;
1956 Orders.push_back(MDT.getNode(Root));
1957 do {
1958 MachineDomTreeNode *Node = Orders[idx++];
1959 for (MachineDomTreeNode *Child : Node->children()) {
1960 if (WorkSet.count(Child))
1961 Orders.push_back(Child);
1962 }
1963 } while (idx != Orders.size());
1964 assert(Orders.size() == WorkSet.size() &&
1965 "Orders have different size with WorkSet");
1966
1967#ifndef NDEBUG
1968 LLVM_DEBUG(dbgs() << "Orders size is " << Orders.size() << "\n");
1970 for (; RIt != Orders.rend(); RIt++)
1971 LLVM_DEBUG(dbgs() << "BB" << (*RIt)->getBlock()->getNumber() << ",");
1972 LLVM_DEBUG(dbgs() << "\n");
1973#endif
1974}
1975
1976/// Try to hoist spills according to BB hotness. The spills to removed will
1977/// be saved in \p SpillsToRm. The spills to be inserted will be saved in
1978/// \p SpillsToIns.
1979void HoistSpillHelper::runHoistSpills(
1980 LiveInterval &OrigLI, VNInfo &OrigVNI,
1984 // Visit order of dominator tree nodes.
1986 // SpillsToKeep contains all the nodes where spills are to be inserted
1987 // during hoisting. If the spill to be inserted is an original spill
1988 // (not a hoisted one), the value of the map entry is 0. If the spill
1989 // is a hoisted spill, the value of the map entry is the VReg to be used
1990 // as the source of the spill.
1992 // Map from BB to the first spill inside of it.
1994
1995 rmRedundantSpills(Spills, SpillsToRm, SpillBBToSpill);
1996
1997 MachineBasicBlock *Root = LIS.getMBBFromIndex(OrigVNI.def);
1998 getVisitOrders(Root, Spills, Orders, SpillsToRm, SpillsToKeep,
1999 SpillBBToSpill);
2000
2001 // SpillsInSubTreeMap keeps the map from a dom tree node to a pair of
2002 // nodes set and the cost of all the spills inside those nodes.
2003 // The nodes set are the locations where spills are to be inserted
2004 // in the subtree of current node.
2005 using NodesCostPair =
2006 std::pair<SmallPtrSet<MachineDomTreeNode *, 16>, BlockFrequency>;
2008
2009 // Iterate Orders set in reverse order, which will be a bottom-up order
2010 // in the dominator tree. Once we visit a dom tree node, we know its
2011 // children have already been visited and the spill locations in the
2012 // subtrees of all the children have been determined.
2014 for (; RIt != Orders.rend(); RIt++) {
2015 MachineBasicBlock *Block = (*RIt)->getBlock();
2016
2017 // If Block contains an original spill, simply continue.
2018 if (auto It = SpillsToKeep.find(*RIt);
2019 It != SpillsToKeep.end() && !It->second) {
2020 auto &SIt = SpillsInSubTreeMap[*RIt];
2021 SIt.first.insert(*RIt);
2022 // Sit.second contains the cost of spill.
2023 SIt.second = MBFI.getBlockFreq(Block);
2024 continue;
2025 }
2026
2027 // Collect spills in subtree of current node (*RIt) to
2028 // SpillsInSubTreeMap[*RIt].first.
2029 for (MachineDomTreeNode *Child : (*RIt)->children()) {
2030 if (!SpillsInSubTreeMap.contains(Child))
2031 continue;
2032 // The stmt:
2033 // "auto &[SpillsInSubTree, SubTreeCost] = SpillsInSubTreeMap[*RIt]"
2034 // below should be placed before getting the begin and end iterators of
2035 // SpillsInSubTreeMap[Child].first, or else the iterators may be
2036 // invalidated when SpillsInSubTreeMap[*RIt] is seen the first time
2037 // and the map grows and then the original buckets in the map are moved.
2038 auto &[SpillsInSubTree, SubTreeCost] = SpillsInSubTreeMap[*RIt];
2039 auto ChildIt = SpillsInSubTreeMap.find(Child);
2040 SubTreeCost += ChildIt->second.second;
2041 auto BI = ChildIt->second.first.begin();
2042 auto EI = ChildIt->second.first.end();
2043 SpillsInSubTree.insert(BI, EI);
2044 SpillsInSubTreeMap.erase(ChildIt);
2045 }
2046
2047 auto &[SpillsInSubTree, SubTreeCost] = SpillsInSubTreeMap[*RIt];
2048 // No spills in subtree, simply continue.
2049 if (SpillsInSubTree.empty())
2050 continue;
2051
2052 // Check whether Block is a possible candidate to insert spill.
2053 Register LiveReg;
2054 if (!isSpillCandBB(OrigLI, OrigVNI, *Block, LiveReg))
2055 continue;
2056
2057 // If there are multiple spills that could be merged, bias a little
2058 // to hoist the spill.
2059 BranchProbability MarginProb = (SpillsInSubTree.size() > 1)
2060 ? BranchProbability(9, 10)
2061 : BranchProbability(1, 1);
2062 if (SubTreeCost > MBFI.getBlockFreq(Block) * MarginProb) {
2063 // Hoist: Move spills to current Block.
2064 for (auto *const SpillBB : SpillsInSubTree) {
2065 // When SpillBB is a BB contains original spill, insert the spill
2066 // to SpillsToRm.
2067 if (auto It = SpillsToKeep.find(SpillBB);
2068 It != SpillsToKeep.end() && !It->second) {
2069 MachineInstr *SpillToRm = SpillBBToSpill[SpillBB];
2070 SpillsToRm.push_back(SpillToRm);
2071 }
2072 // SpillBB will not contain spill anymore, remove it from SpillsToKeep.
2073 SpillsToKeep.erase(SpillBB);
2074 }
2075 // Current Block is the BB containing the new hoisted spill. Add it to
2076 // SpillsToKeep. LiveReg is the source of the new spill.
2077 SpillsToKeep[*RIt] = LiveReg;
2078 LLVM_DEBUG({
2079 dbgs() << "spills in BB: ";
2080 for (const auto Rspill : SpillsInSubTree)
2081 dbgs() << Rspill->getBlock()->getNumber() << " ";
2082 dbgs() << "were promoted to BB" << (*RIt)->getBlock()->getNumber()
2083 << "\n";
2084 });
2085 SpillsInSubTree.clear();
2086 SpillsInSubTree.insert(*RIt);
2087 SubTreeCost = MBFI.getBlockFreq(Block);
2088 }
2089 }
2090 // For spills in SpillsToKeep with LiveReg set (i.e., not original spill),
2091 // save them to SpillsToIns.
2092 for (const auto &Ent : SpillsToKeep) {
2093 if (Ent.second)
2094 SpillsToIns[Ent.first->getBlock()] = Ent.second;
2095 }
2096}
2097
2098/// For spills with equal values, remove redundant spills and hoist those left
2099/// to less hot spots.
2100///
2101/// Spills with equal values will be collected into the same set in
2102/// MergeableSpills when spill is inserted. These equal spills are originated
2103/// from the same defining instruction and are dominated by the instruction.
2104/// Before hoisting all the equal spills, redundant spills inside in the same
2105/// BB are first marked to be deleted. Then starting from the spills left, walk
2106/// up on the dominator tree towards the Root node where the define instruction
2107/// is located, mark the dominated spills to be deleted along the way and
2108/// collect the BB nodes on the path from non-dominated spills to the define
2109/// instruction into a WorkSet. The nodes in WorkSet are the candidate places
2110/// where we are considering to hoist the spills. We iterate the WorkSet in
2111/// bottom-up order, and for each node, we will decide whether to hoist spills
2112/// inside its subtree to that node. In this way, we can get benefit locally
2113/// even if hoisting all the equal spills to one cold place is impossible.
2114void HoistSpillHelper::hoistAllSpills() {
2115 SmallVector<Register, 4> NewVRegs;
2116 LiveRangeEdit Edit(nullptr, NewVRegs, MF, LIS, &VRM, this);
2117
2118 for (unsigned i = 0, e = MRI.getNumVirtRegs(); i != e; ++i) {
2120 Register Original = VRM.getPreSplitReg(Reg);
2121 if (!MRI.def_empty(Reg) && Original.isValid())
2122 Virt2SiblingsMap[Original].insert(Reg);
2123 }
2124
2125 SmallPtrSet<VNInfo *, 8> UsedValues;
2126 if (!DeadSpillCandidates.empty())
2127 UsedValues = collectUsedSpillValues();
2128
2129 SmallSetVector<int, 8> SlotsWithRemovedSpills;
2130
2131 // Each entry in MergeableSpills contains a spill set with equal values.
2132 for (auto &Ent : MergeableSpills) {
2133 int Slot = Ent.first.first;
2134 LiveInterval &OrigLI = *StackSlotToOrigLI[Slot];
2135 VNInfo *OrigVNI = Ent.first.second;
2136 SmallPtrSet<MachineInstr *, 16> &EqValSpills = Ent.second;
2137 if (Ent.second.empty())
2138 continue;
2139
2140 LLVM_DEBUG({
2141 dbgs() << "\nFor Slot" << Slot << " and VN" << OrigVNI->id << ":\n"
2142 << "Equal spills in BB: ";
2143 for (const auto spill : EqValSpills)
2144 dbgs() << spill->getParent()->getNumber() << " ";
2145 dbgs() << "\n";
2146 });
2147
2148 // SpillsToRm is the spill set to be removed from EqValSpills.
2150 // SpillsToIns is the spill set to be newly inserted after hoisting.
2152
2153 if (DeadSpillCandidates.contains(OrigVNI) &&
2154 !UsedValues.contains(OrigVNI)) {
2155 // Restore forwarding removed every read of this value.
2156 LLVM_DEBUG(dbgs() << "Removing unread spills of VN" << OrigVNI->id
2157 << '\n');
2158 SpillsToRm.append(EqValSpills.begin(), EqValSpills.end());
2159 EqValSpills.clear();
2160 NumSpillsRemoved += SpillsToRm.size();
2161 SlotsWithRemovedSpills.insert(Slot);
2162 } else {
2163 runHoistSpills(OrigLI, *OrigVNI, EqValSpills, SpillsToRm, SpillsToIns);
2164 }
2165
2166 LLVM_DEBUG({
2167 dbgs() << "Finally inserted spills in BB: ";
2168 for (const auto &Ispill : SpillsToIns)
2169 dbgs() << Ispill.first->getNumber() << " ";
2170 dbgs() << "\nFinally removed spills in BB: ";
2171 for (const auto Rspill : SpillsToRm)
2172 dbgs() << Rspill->getParent()->getNumber() << " ";
2173 dbgs() << "\n";
2174 });
2175
2176 // Stack live range update.
2177 LiveInterval &StackIntvl = LSS.getInterval(Slot);
2178 if (!SpillsToIns.empty() || !SpillsToRm.empty())
2179 StackIntvl.MergeValueInAsValue(OrigLI, OrigVNI,
2180 StackIntvl.getValNumInfo(0));
2181
2182 // Insert hoisted spills.
2183 for (auto const &Insert : SpillsToIns) {
2184 MachineBasicBlock *BB = Insert.first;
2185 Register LiveReg = Insert.second;
2186 MachineBasicBlock::iterator MII = IPA.getLastInsertPointIter(OrigLI, *BB);
2187 MachineInstrSpan MIS(MII, BB);
2188 TII.storeRegToStackSlot(*BB, MII, LiveReg, false, Slot,
2189 MRI.getRegClass(LiveReg), Register());
2190 LIS.InsertMachineInstrRangeInMaps(MIS.begin(), MII);
2191 for (const MachineInstr &MI : make_range(MIS.begin(), MII))
2192 getVDefInterval(MI, LIS);
2193 ++NumSpills;
2194 }
2195
2196 // Remove redundant spills or change them to dead instructions.
2197 NumSpills -= SpillsToRm.size();
2198 for (auto *const RMEnt : SpillsToRm) {
2199 RMEnt->setDesc(TII.get(TargetOpcode::KILL));
2200 for (unsigned i = RMEnt->getNumOperands(); i; --i) {
2201 MachineOperand &MO = RMEnt->getOperand(i - 1);
2202 if (MO.isReg() && MO.isImplicit() && MO.isDef() && !MO.isDead())
2203 RMEnt->removeOperand(i - 1);
2204 }
2205 }
2206 Edit.eliminateDeadDefs(SpillsToRm, {});
2207 }
2208
2209 if (!SlotsWithRemovedSpills.empty())
2210 removeSlotsWithoutAccesses(SlotsWithRemovedSpills);
2211
2212 // Flush vregs that were unassigned from the matrix during shrinking but
2213 // were not split (so LRE_DidCloneVirtReg never re-assigned them).
2214 for (auto &[VReg, PhysReg] : PendingReassignments) {
2215 assert(Matrix && LIS.hasInterval(VReg) &&
2216 "Pending reassignment without matrix or live interval");
2217 Matrix->assign(LIS.getInterval(VReg), PhysReg);
2218 }
2219 PendingReassignments.clear();
2220}
2221
2222/// Called when a virtual register's live interval is about to be shrunk.
2223/// Unassign from the matrix so the shrunk interval can be re-assigned by a
2224/// later LRE_DidCloneVirtReg or by hoistAllSpills' flush, and stash the
2225/// physreg in PendingReassignments since the unassign clears VRM.
2226void HoistSpillHelper::LRE_WillShrinkVirtReg(Register VirtReg) {
2227 if (!Matrix || !VRM.hasPhys(VirtReg) || !LIS.hasInterval(VirtReg))
2228 return;
2229
2230 MCRegister PhysReg = VRM.getPhys(VirtReg);
2231 LiveInterval &LI = LIS.getInterval(VirtReg);
2232 Matrix->unassign(LI, /*ClearAllReferencingSegments=*/true);
2233 PendingReassignments[VirtReg] = PhysReg;
2234}
2235
2236/// Called before a virtual register is erased from LiveIntervals.
2237/// Forcibly remove the register from LiveRegMatrix before it's deleted,
2238/// preventing dangling pointers.
2239bool HoistSpillHelper::LRE_CanEraseVirtReg(Register VirtReg) {
2240 PendingReassignments.erase(VirtReg);
2241 if (Matrix && VRM.hasPhys(VirtReg)) {
2242 const LiveInterval &LI = LIS.getInterval(VirtReg);
2243 Matrix->unassign(LI, /*ClearAllReferencingSegments=*/true);
2244 }
2245 return true; // Allow deletion to proceed
2246}
2247
2248/// For VirtReg clone, the \p New register should have the same physreg or
2249/// stackslot as the \p old register.
2250void HoistSpillHelper::LRE_DidCloneVirtReg(Register New, Register Old) {
2251 // New is freshly created by LiveRangeEdit::eliminateDeadDefs and its interval
2252 // is guaranteed to exist on every path below.
2253 assert(LIS.hasInterval(New) && "Cloned vreg without live interval");
2254
2255 auto PendingIt = PendingReassignments.find(Old);
2256 if (PendingIt != PendingReassignments.end()) {
2257 // Old was already unassigned in LRE_WillShrinkVirtReg, which only
2258 // enrolls vregs when Matrix is non-null and the interval exists.
2259 assert(Matrix && LIS.hasInterval(Old) &&
2260 "Pending reassignment without matrix or live interval");
2261 MCRegister PhysReg = PendingIt->second;
2262 PendingReassignments.erase(PendingIt);
2263
2264 // Reassign both Old (with its shrunk interval) and New to the matrix.
2265 Matrix->assign(LIS.getInterval(Old), PhysReg);
2266 Matrix->assign(LIS.getInterval(New), PhysReg);
2267 } else if (VRM.hasPhys(Old)) {
2268 MCRegister PhysReg = VRM.getPhys(Old);
2269 if (Matrix) {
2270 if (LIS.hasInterval(Old)) {
2271 const LiveInterval &LI = LIS.getInterval(Old);
2272 // Drop stale pre-clone segments before reassigning Old's current LI.
2273 Matrix->unassign(LI, /*ClearAllReferencingSegments=*/true);
2274 Matrix->assign(LI, PhysReg);
2275 }
2276 Matrix->assign(LIS.getInterval(New), PhysReg);
2277 } else {
2278 VRM.assignVirt2Phys(New, PhysReg);
2279 }
2280 } else if (VRM.getStackSlot(Old) != VirtRegMap::NO_STACK_SLOT) {
2281 VRM.assignVirt2StackSlot(New, VRM.getStackSlot(Old));
2282 } else {
2283 llvm_unreachable("VReg should be assigned either physreg or stackslot");
2284 }
2285 if (VRM.hasShape(Old))
2286 VRM.assignVirt2Shape(New, VRM.getShape(Old));
2287}
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
uint64_t uint64_t
ReachingDefInfo InstSet InstSet & Ignore
MachineBasicBlock & MBB
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:702
This file defines the DenseMap class.
IRTranslator LLVM IR MI
static LLVM_DUMP_METHOD void dumpMachineInstrRangeWithSlotIndex(MachineBasicBlock::iterator B, MachineBasicBlock::iterator E, LiveIntervals const &LIS, const char *const header, Register VReg=Register())
static Register isCopyOfBundle(const MachineInstr &FirstMI, Register Reg, const TargetInstrInfo &TII)
Check for a copy bundle as formed by SplitKit.
static bool isRealSpill(const MachineInstr &Def, Register Reg)
Check if Def defines Reg with an undefined value.
static bool readsPhysRegsOf(const MachineInstr &Other, const MachineInstr &MI, Register Ignore)
Return true if Other reads every physical register that MI reads, except Ignore.
static cl::opt< bool > RestrictStatepointRemat("restrict-statepoint-remat", cl::init(false), cl::Hidden, cl::desc("Restrict remat for statepoint operands"))
static Register isCopyOf(const MachineInstr &MI, Register Reg, const TargetInstrInfo &TII)
isFullCopyOf - If MI is a COPY to or from Reg, return the other register, otherwise return 0.
static void getVDefInterval(const MachineInstr &MI, LiveIntervals &LIS)
static Register getAssignedReg(const VirtRegMap &VRM, Register Reg)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
Live Register Matrix
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
This file implements a map that provides insertion order iteration.
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define P(N)
MachineRegisterInfo & MRI
Basic Register Allocator
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
bool isSubregFoldable() const override
void loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register DestReg, int FrameIndex, const TargetRegisterClass *RC, Register VReg, unsigned SubReg=0, MachineInstr::MIFlag Flags=MachineInstr::NoFlags) const override
void storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register SrcReg, bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg, MachineInstr::MIFlag Flags=MachineInstr::NoFlags) const override
Register isLoadFromStackSlot(const MachineInstr &MI, int &FrameIndex) const override
Register isStoreToStackSlot(const MachineInstr &MI, int &FrameIndex) const override
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:757
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
bool erase(const KeyT &Val)
Definition DenseMap.h:930
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
Register getReg() const
Determines the latest safe point in a block in which we can insert a split, spill or other instructio...
Definition SplitKit.h:50
A live range for subregisters.
LiveInterval - This class represents the liveness of a register, or stack slot.
float weight() const
Register reg() const
bool isSpillable() const
isSpillable - Can this interval be spilled?
bool hasSubRanges() const
Returns true if subregister liveness information is available.
iterator_range< subrange_iterator > subranges()
bool hasInterval(Register Reg) const
SlotIndex InsertMachineInstrInMaps(MachineInstr &MI)
SlotIndexes * getSlotIndexes() const
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
VNInfo::Allocator & getVNInfoAllocator()
SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const
Return the last index in the given basic block.
LiveInterval & getInterval(Register Reg)
void InsertMachineInstrRangeInMaps(MachineBasicBlock::iterator B, MachineBasicBlock::iterator E)
LLVM_ABI bool shrinkToUses(LiveInterval *li, SmallVectorImpl< MachineInstr * > *dead=nullptr, LaneBitmask SubRangeMask=LaneBitmask::getAll())
After removing some uses of a register, shrink its live range to just the remaining uses.
LLVM_ABI void removePhysRegDefAt(MCRegister Reg, SlotIndex Pos)
Remove value numbers and related live segments starting at position Pos that are part of any liverang...
MachineBasicBlock * getMBBFromIndex(SlotIndex index) const
SlotIndex ReplaceMachineInstrInMaps(MachineInstr &MI, MachineInstr &NewMI)
Result of a LiveRange query.
SlotIndex endPoint() const
Return the end point of the last live range segment to interact with the instruction,...
bool isKill() const
Return true if the live-in value is killed by this instruction.
Callback methods for LiveRangeEdit owners.
const LiveInterval & getParent() const
Register getReg() const
This class represents the liveness of a register, stack slot, etc.
VNInfo * getValNumInfo(unsigned ValNo)
getValNumInfo - Returns pointer to the specified val#.
LLVM_ABI iterator addSegment(Segment S)
Add the specified Segment to this range, merging segments as appropriate.
LLVM_ABI void MergeValueInAsValue(const LiveRange &RHS, const VNInfo *RHSValNo, VNInfo *LHSValNo)
MergeValueInAsValue - Merge all of the segments of a specific val# in RHS into this live range as the...
iterator_range< vni_iterator > vnis()
LiveQueryResult Query(SlotIndex Idx) const
Query Liveness at Idx.
VNInfo * getVNInfoBefore(SlotIndex Idx) const
getVNInfoBefore - Return the VNInfo that is live up to but not necessarily including Idx,...
LLVM_ABI std::pair< VNInfo *, bool > extendInBlock(ArrayRef< SlotIndex > Undefs, SlotIndex StartIdx, SlotIndex Kill)
Attempt to extend a value defined after StartIdx to include Use.
unsigned getNumValNums() const
VNInfo * getNextValue(SlotIndex Def, VNInfo::Allocator &VNInfoAllocator)
getNextValue - Create a new value number and return it.
void assign(const LiveRange &Other, BumpPtrAllocator &Allocator)
Copies values numbers and live segments from Other into this range.
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
Wrapper class representing physical registers and target specific virtual registers.
Definition MCRegister.h:42
MIBundleOperands - Iterate over all operands in a bundle of machine instructions.
LLVM_ABI iterator SkipPHIsLabelsAndDebug(iterator I, Register Reg=Register(), bool SkipPseudoOp=true)
Return the first instruction in MBB after I that is not a PHI, label or debug.
Instructions::iterator instr_iterator
Instructions::const_iterator const_instr_iterator
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
iterator_range< pred_iterator > predecessors()
MachineInstrBundleIterator< MachineInstr > iterator
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
void RemoveStackObject(int ObjectIdx)
Remove or mark dead a statically sized stack object.
static const unsigned int DebugOperandMemNumber
A reserved operand number representing the instructions memory operand, for instructions that have a ...
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
MachineInstrSpan provides an interface to get an iteration range containing the instruction it was in...
Representation of each machine instruction.
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
filtered_mop_range all_defs()
Returns an iterator range over all operands that are (explicit or implicit) register defs.
bool isDebugInstr() const
unsigned getNumOperands() const
Retuns the total number of operands.
bool isBundledWithPred() const
Return true if this instruction is part of a bundle, and it is not the first instruction in the bundl...
bool isFullCopy() const
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
LLVM_ABI void removeOperand(unsigned OpNo)
Erase an operand from an instruction, leaving it with one fewer operand than it started with.
filtered_mop_range all_uses()
Returns an iterator range over all operands that are (explicit or implicit) register uses.
bool isBundledWithSucc() const
Return true if this instruction is part of a bundle, and it is not the last instruction in the bundle...
LLVM_ABI unsigned getDebugInstrNum()
Fetch the instruction number of this MachineInstr.
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
MachineOperand * findRegisterDefOperand(Register Reg, const TargetRegisterInfo *TRI, bool isDead=false, bool Overlap=false)
Wrapper for findRegisterDefOperandIdx, it returns a pointer to the MachineOperand rather than an inde...
bool isBundled() const
Return true if this instruction part of a bundle.
LLVM_ABI bool addRegisterDead(Register Reg, const TargetRegisterInfo *RegInfo, bool AddIfNotFound=false)
We have determined MI defined a register without a use.
MachineOperand class - Representation of each machine instruction operand.
unsigned getSubReg() const
bool readsReg() const
readsReg - Returns true if this operand reads the previous value of its register.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
LLVM_ABI void ChangeToRegister(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isDebug=false)
ChangeToRegister - Replace this operand with a new register operand of the specified value.
bool isEarlyClobber() const
Register getReg() const
getReg - Returns the register number.
bool isFI() const
isFI - Tests if this is a MO_FrameIndex operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
iterator_range< reg_bundle_iterator > reg_bundles(Register Reg) const
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
reg_bundle_nodbg_iterator reg_bundle_nodbg_begin(Register RegNo) const
defusechain_instr_iterator< true, true, true, false > reg_bundle_nodbg_iterator
reg_bundle_nodbg_iterator/reg_bundle_nodbg_begin/reg_bundle_nodbg_end - Walk all defs and uses of the...
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
iterator_range< use_bundle_nodbg_iterator > use_nodbg_bundles(Register Reg) const
bool def_empty(Register RegNo) const
def_empty - Return true if there are no instructions defining the specified register (it may be live-...
bool reg_nodbg_empty(Register RegNo) const
reg_nodbg_empty - Return true if the only instructions using or defining Reg are Debug instructions.
static reg_bundle_nodbg_iterator reg_bundle_nodbg_end()
LLVM_ABI bool isReservedRegUnit(MCRegUnit Unit) const
Returns true when the given register unit is considered reserved.
iterator_range< reg_instr_iterator > reg_instructions(Register Reg) const
LLVM_ABI const TargetRegisterClass * constrainRegClass(Register Reg, const TargetRegisterClass *RC, unsigned MinNumRegs=0)
constrainRegClass - Constrain the register class of the specified virtual register to be a common sub...
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:39
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isStack() const
Return true if this is a stack slot.
Definition Register.h:46
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
Definition Register.h:72
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
constexpr bool isValid() const
Definition Register.h:109
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
bool remove(const value_type &X)
Remove an item from the set vector.
Definition SetVector.h:187
bool contains(const_arg_type key) const
Check if the SetVector contains the given key.
Definition SetVector.h:258
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
SlotIndex - An opaque wrapper around machine indexes.
Definition SlotIndexes.h:70
static bool isSameInstr(SlotIndex A, SlotIndex B)
isSameInstr - Return true if A and B refer to the same instruction.
SlotIndex getBaseIndex() const
Returns the base index for associated with this index.
SlotIndex getPrevSlot() const
Returns the previous slot in the index list.
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def.
LLVM_ABI void removeSingleMachineInstrFromMaps(MachineInstr &MI)
Removes a single machine instruction MI from the mapping.
size_type size() const
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:346
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
std::reverse_iterator< iterator > reverse_iterator
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Spiller interface.
Definition Spiller.h:33
virtual ~Spiller()=0
Register getReg() const
MI-level Statepoint operands.
Definition StackMaps.h:159
LLVM_ABI bool isFoldableReg(Register Reg) const
Return true if Reg is used only in operands which can be folded to stack usage.
TargetInstrInfo - Interface to description of machine instruction set.
static constexpr TypeSize getZero()
Definition TypeSize.h:358
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
VNInfo - Value Number Information.
bool isUnused() const
Returns true if this value is unused.
unsigned id
The ID number of this value.
SlotIndex def
The index of the defining instruction.
bool isPHIDef() const
Returns true if this value is defined by a PHI instruction (or was, PHI instructions may have been el...
Calculate auxiliary information for a virtual register such as its spill weight and allocation hint.
MCRegister getPhys(Register virtReg) const
returns the physical register mapped to the specified virtual register
Definition VirtRegMap.h:89
static constexpr int NO_STACK_SLOT
Definition VirtRegMap.h:64
constexpr bool isZero() const
Definition TypeSize.h:154
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
initializer< Ty > init(const Ty &Val)
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
@ Store
The extracted value is stored (ExtractElement only).
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI PhysRegInfo AnalyzePhysRegInBundle(const MachineInstr &MI, Register Reg, const TargetRegisterInfo *TRI)
AnalyzePhysRegInBundle - Analyze how the current instruction or bundle uses a physical register.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI Spiller * createInlineSpiller(const Spiller::RequiredAnalyses &Analyses, MachineFunction &MF, VirtRegMap &VRM, VirtRegAuxInfo &VRAI, LiveRegMatrix *Matrix=nullptr)
Create and return a spiller that will insert spill code directly instead of deferring though VirtRegM...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI VirtRegInfo AnalyzeVirtRegInBundle(MachineInstr &MI, Register Reg, SmallVectorImpl< std::pair< MachineInstr *, unsigned > > *Ops=nullptr)
AnalyzeVirtRegInBundle - Analyze how the current instruction or bundle uses a virtual register.
DomTreeNodeBase< MachineBasicBlock > MachineDomTreeNode
@ Other
Any other memory.
Definition ModRef.h:68
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
ArrayRef(const T &OneElt) -> ArrayRef< T >
bool canGuaranteeAssignmentAfterRemat(Register VReg, const MachineInstr &MI)
Return whether we can guarantee physical register assignment if VReg's value is rematerialized immedi...
LLVM_ABI MachineInstr * buildDbgValueForSpill(MachineBasicBlock &BB, MachineBasicBlock::iterator I, const MachineInstr &Orig, int FrameIndex, Register SpillReg)
Clone a DBG_VALUE whose value has been spilled to FrameIndex.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:391
LLVM_ABI Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
static constexpr LaneBitmask getAll()
Definition LaneBitmask.h:82
static constexpr LaneBitmask getNone()
Definition LaneBitmask.h:81
Remat - Information needed to rematerialize at a specific location.
This represents a simple continuous liveness interval for a value.
Information about how a physical register Reg is used by a set of operands.
bool FullyDefined
Reg or a super-register is defined.
VirtRegInfo - Information about a virtual register used by a set of operands.
bool Reads
Reads - One of the operands read the virtual register.
bool Tied
Tied - Uses and defs must use the same register.
bool Writes
Writes - One of the operands writes the virtual register.