LLVM 23.0.0git
SILowerSGPRSpills.cpp
Go to the documentation of this file.
1//===-- SILowerSGPRSPills.cpp ---------------------------------------------===//
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// Handle SGPR spills. This pass takes the place of PrologEpilogInserter for all
10// SGPR spills, so must insert CSR SGPR spills as well as expand them.
11//
12// This pass must never create new SGPR virtual registers.
13//
14// FIXME: Must stop RegScavenger spills in later passes.
15//
16//===----------------------------------------------------------------------===//
17
18#include "SILowerSGPRSpills.h"
19#include "AMDGPU.h"
20#include "GCNSubtarget.h"
23#include "SISpillUtils.h"
30
31using namespace llvm;
32
33#define DEBUG_TYPE "si-lower-sgpr-spills"
34
36
37namespace {
38
39/// Insertion point for IMPLICIT_DEF: iterator may be MBB::end() and can't be
40/// dereferenced so the parent block is stored explicitly.
41struct LaneVGPRInsertPt {
44};
45
46static LaneVGPRInsertPt insertPt(MachineBasicBlock *MBB,
48 return {MBB, It};
49}
50
51static cl::opt<unsigned> MaxNumVGPRsForWwmAllocation(
52 "amdgpu-num-vgprs-for-wwm-alloc",
53 cl::desc("Max num VGPRs for whole-wave register allocation."),
55
56class SILowerSGPRSpills {
57private:
58 const SIRegisterInfo *TRI = nullptr;
59 const SIInstrInfo *TII = nullptr;
60 LiveIntervals *LIS = nullptr;
61 SlotIndexes *Indexes = nullptr;
62 MachineDominatorTree *MDT = nullptr;
63 MachineCycleInfo *MCI = nullptr;
64
65 // Save and Restore blocks of the current function. Typically there is a
66 // single save block, unless Windows EH funclets are involved.
67 MBBVector SaveBlocks;
68 MBBVector RestoreBlocks;
69
70 MachineBasicBlock *getCycleDomBB(MachineCycle *C);
71
72public:
73 SILowerSGPRSpills(LiveIntervals *LIS, SlotIndexes *Indexes,
75 : LIS(LIS), Indexes(Indexes), MDT(MDT), MCI(MCI) {}
76 bool run(MachineFunction &MF);
77 void calculateSaveRestoreBlocks(MachineFunction &MF);
78 bool spillCalleeSavedRegs(MachineFunction &MF,
79 SmallVectorImpl<int> &CalleeSavedFIs);
80 void updateLaneVGPRDomInstr(
82 DenseMap<Register, LaneVGPRInsertPt> &LaneVGPRDomInstr);
83 void determineRegsForWWMAllocation(MachineFunction &MF, BitVector &RegMask);
84};
85
86class SILowerSGPRSpillsLegacy : public MachineFunctionPass {
87public:
88 static char ID;
89
90 SILowerSGPRSpillsLegacy() : MachineFunctionPass(ID) {}
91
92 bool runOnMachineFunction(MachineFunction &MF) override;
93
94 void getAnalysisUsage(AnalysisUsage &AU) const override {
97 AU.setPreservesAll();
99 }
100
101 MachineFunctionProperties getClearedProperties() const override {
102 // SILowerSGPRSpills introduces new Virtual VGPRs for spilling SGPRs.
103 return MachineFunctionProperties().setIsSSA().setNoVRegs();
104 }
105};
106
107} // end anonymous namespace
108
109char SILowerSGPRSpillsLegacy::ID = 0;
110
111INITIALIZE_PASS_BEGIN(SILowerSGPRSpillsLegacy, DEBUG_TYPE,
112 "SI lower SGPR spill instructions", false, false)
117INITIALIZE_PASS_END(SILowerSGPRSpillsLegacy, DEBUG_TYPE,
118 "SI lower SGPR spill instructions", false, false)
119
120char &llvm::SILowerSGPRSpillsLegacyID = SILowerSGPRSpillsLegacy::ID;
121
124 for (MCRegAliasIterator R(Reg, TRI, true); R.isValid(); ++R) {
125 if (MBB.isLiveIn(*R)) {
126 return true;
127 }
128 }
129 return false;
130}
131
132/// Insert spill code for the callee-saved registers used in the function.
133static void insertCSRSaves(MachineBasicBlock &SaveBlock,
135 LiveIntervals *LIS) {
136 MachineFunction &MF = *SaveBlock.getParent();
139 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
140 const SIRegisterInfo *RI = ST.getRegisterInfo();
141
142 MachineBasicBlock::iterator I = SaveBlock.begin();
143 if (!TFI->spillCalleeSavedRegisters(SaveBlock, I, CSI, RI)) {
144 for (const CalleeSavedInfo &CS : CSI) {
145 // Insert the spill to the stack frame.
146 MCRegister Reg = CS.getReg();
147
148 MachineInstrSpan MIS(I, &SaveBlock);
149 const TargetRegisterClass *RC = RI->getMinimalPhysRegClass(Reg);
150
151 // If this value was already livein, we probably have a direct use of the
152 // incoming register value, so don't kill at the spill point. This happens
153 // since we pass some special inputs (workgroup IDs) in the callee saved
154 // range.
155 const bool IsLiveIn = isLiveIntoMBB(Reg, SaveBlock, RI);
156 TII.storeRegToStackSlot(SaveBlock, I, Reg, !IsLiveIn, CS.getFrameIdx(),
157 RC, Register());
158
159 if (Indexes) {
160 assert(std::distance(MIS.begin(), I) == 1);
161 MachineInstr &Inst = *std::prev(I);
162 Indexes->insertMachineInstrInMaps(Inst);
163 }
164
165 if (LIS)
167 }
168 } else {
169 // TFI doesn't update Indexes and LIS, so we have to do it separately.
170 if (Indexes)
171 Indexes->repairIndexesInRange(&SaveBlock, SaveBlock.begin(), I);
172
173 if (LIS)
174 for (const CalleeSavedInfo &CS : CSI)
175 LIS->removeAllRegUnitsForPhysReg(CS.getReg());
176 }
177}
178
179/// Insert restore code for the callee-saved registers used in the function.
180static void insertCSRRestores(MachineBasicBlock &RestoreBlock,
182 SlotIndexes *Indexes, LiveIntervals *LIS) {
183 MachineFunction &MF = *RestoreBlock.getParent();
187 // Restore all registers immediately before the return and any
188 // terminators that precede it.
190 const MachineBasicBlock::iterator BeforeRestoresI =
191 I == RestoreBlock.begin() ? I : std::prev(I);
192
193 // FIXME: Just emit the readlane/writelane directly
194 if (!TFI->restoreCalleeSavedRegisters(RestoreBlock, I, CSI, TRI)) {
195 for (const CalleeSavedInfo &CI : reverse(CSI)) {
196 // Insert in reverse order. loadRegFromStackSlot can insert
197 // multiple instructions.
198 TFI->restoreCalleeSavedRegister(RestoreBlock, I, CI, &TII, TRI);
199
200 if (Indexes) {
201 MachineInstr &Inst = *std::prev(I);
202 Indexes->insertMachineInstrInMaps(Inst);
203 }
204
205 if (LIS)
206 LIS->removeAllRegUnitsForPhysReg(CI.getReg());
207 }
208 } else {
209 // TFI doesn't update Indexes and LIS, so we have to do it separately.
210 if (Indexes)
211 Indexes->repairIndexesInRange(&RestoreBlock, BeforeRestoresI,
212 RestoreBlock.getFirstTerminator());
213
214 if (LIS)
215 for (const CalleeSavedInfo &CS : CSI)
216 LIS->removeAllRegUnitsForPhysReg(CS.getReg());
217 }
218}
219
220/// Compute the sets of entry and return blocks for saving and restoring
221/// callee-saved registers, and placing prolog and epilog code.
222void SILowerSGPRSpills::calculateSaveRestoreBlocks(MachineFunction &MF) {
223 const MachineFrameInfo &MFI = MF.getFrameInfo();
224
225 // Even when we do not change any CSR, we still want to insert the
226 // prologue and epilogue of the function.
227 // So set the save points for those.
228
229 // Use the points found by shrink-wrapping, if any.
230 if (!MFI.getSavePoints().empty()) {
231 assert(MFI.getSavePoints().size() == 1 &&
232 "Multiple save points not yet supported!");
233 const auto &SavePoint = *MFI.getSavePoints().begin();
234 SaveBlocks.push_back(SavePoint.first);
235 assert(MFI.getRestorePoints().size() == 1 &&
236 "Multiple restore points not yet supported!");
237 const auto &RestorePoint = *MFI.getRestorePoints().begin();
238 MachineBasicBlock *RestoreBlock = RestorePoint.first;
239 // If RestoreBlock does not have any successor and is not a return block
240 // then the end point is unreachable and we do not need to insert any
241 // epilogue.
242 if (!RestoreBlock->succ_empty() || RestoreBlock->isReturnBlock())
243 RestoreBlocks.push_back(RestoreBlock);
244 return;
245 }
246
247 // Save refs to entry and return blocks.
248 SaveBlocks.push_back(&MF.front());
249 for (MachineBasicBlock &MBB : MF) {
250 if (MBB.isEHFuncletEntry())
251 SaveBlocks.push_back(&MBB);
252 if (MBB.isReturnBlock())
253 RestoreBlocks.push_back(&MBB);
254 }
255}
256
257// TODO: To support shrink wrapping, this would need to copy
258// PrologEpilogInserter's updateLiveness.
260 MachineBasicBlock &EntryBB = MF.front();
261
262 for (const CalleeSavedInfo &CSIReg : CSI)
263 EntryBB.addLiveIn(CSIReg.getReg());
264 EntryBB.sortUniqueLiveIns();
265}
266
267bool SILowerSGPRSpills::spillCalleeSavedRegs(
268 MachineFunction &MF, SmallVectorImpl<int> &CalleeSavedFIs) {
269 MachineRegisterInfo &MRI = MF.getRegInfo();
270 const Function &F = MF.getFunction();
271 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
272 const SIFrameLowering *TFI = ST.getFrameLowering();
273 MachineFrameInfo &MFI = MF.getFrameInfo();
274 RegScavenger *RS = nullptr;
275
276 // Determine which of the registers in the callee save list should be saved.
277 BitVector SavedRegs;
278 TFI->determineCalleeSavesSGPR(MF, SavedRegs, RS);
279
280 // Add the code to save and restore the callee saved registers.
281 if (!F.hasFnAttribute(Attribute::Naked)) {
282 // FIXME: This is a lie. The CalleeSavedInfo is incomplete, but this is
283 // necessary for verifier liveness checks.
284 MFI.setCalleeSavedInfoValid(true);
285
286 std::vector<CalleeSavedInfo> CSI;
287 const MCPhysReg *CSRegs = MRI.getCalleeSavedRegs();
288
289 for (unsigned I = 0; CSRegs[I]; ++I) {
290 MCRegister Reg = CSRegs[I];
291
292 if (SavedRegs.test(Reg)) {
293 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
294 int JunkFI = MFI.CreateStackObject(TRI->getSpillSize(*RC),
295 TRI->getSpillAlign(*RC), true);
296
297 CSI.emplace_back(Reg, JunkFI);
298 CalleeSavedFIs.push_back(JunkFI);
299 }
300 }
301
302 if (!CSI.empty()) {
303 for (MachineBasicBlock *SaveBlock : SaveBlocks)
304 insertCSRSaves(*SaveBlock, CSI, Indexes, LIS);
305
306 // Add live ins to save blocks.
307 assert(SaveBlocks.size() == 1 && "shrink wrapping not fully implemented");
308 updateLiveness(MF, CSI);
309
310 for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
311 insertCSRRestores(*RestoreBlock, CSI, Indexes, LIS);
312 return true;
313 }
314 }
315
316 return false;
317}
318
319MachineBasicBlock *SILowerSGPRSpills::getCycleDomBB(MachineCycle *C) {
320 // If the insertion point lands on a cycle entry, move it to a block that
321 // dominates all entries.
322 if (C->isReducible()) {
323 if (auto *IDom = MDT->getNode(C->getHeader())->getIDom())
324 return IDom->getBlock();
325 llvm_unreachable("Expected cycle to have an IDom.");
326 return nullptr;
327 }
328
329 const SmallVectorImpl<MachineBasicBlock *> &Entries = C->getEntries();
330 assert(!Entries.empty() && "Expected cycle to have at least one entry.");
331 MachineBasicBlock *EntryBB = Entries[0];
332 for (unsigned I = 1; I < Entries.size(); ++I)
333 EntryBB = MDT->findNearestCommonDominator(EntryBB, Entries[I]);
334 return EntryBB;
335}
336
337void SILowerSGPRSpills::updateLaneVGPRDomInstr(
338 int FI, MachineBasicBlock *MBB, MachineBasicBlock::iterator InsertPt,
339 DenseMap<Register, LaneVGPRInsertPt> &LaneVGPRDomInstr) {
340 // For the Def of a virtual LaneVGPR to dominate all its uses, we should
341 // insert an IMPLICIT_DEF before the dominating spill. Switching to a
342 // depth first order doesn't really help since the machine function can be in
343 // the unstructured control flow post-SSA. For each virtual register, hence
344 // finding the common dominator to get either the dominating spill or a block
345 // dominating all spills.
346 SIMachineFunctionInfo *FuncInfo =
347 MBB->getParent()->getInfo<SIMachineFunctionInfo>();
349 FuncInfo->getSGPRSpillToVirtualVGPRLanes(FI);
350 Register PrevLaneVGPR;
351 for (auto &Spill : VGPRSpills) {
352 if (PrevLaneVGPR == Spill.VGPR)
353 continue;
354
355 PrevLaneVGPR = Spill.VGPR;
356 auto I = LaneVGPRDomInstr.find(Spill.VGPR);
357 if (Spill.Lane == 0 && I == LaneVGPRDomInstr.end()) {
358 LaneVGPRDomInstr[Spill.VGPR] = insertPt(MBB, InsertPt);
359 } else {
360 assert(I != LaneVGPRDomInstr.end());
361 LaneVGPRInsertPt Prev = I->second;
362 MachineBasicBlock *PrevInsertMBB = Prev.MBB;
363 MachineBasicBlock::iterator PrevInsertPt = Prev.It;
364 MachineBasicBlock *DomMBB = PrevInsertMBB;
365 if (DomMBB == MBB) {
366 // The insertion point earlier selected in a predecessor block whose
367 // spills are currently being lowered. The earlier InsertPt would be
368 // the one just before the block terminator and it should be changed
369 // if we insert any new spill in it.
370 if (PrevInsertPt == MBB->end() ||
371 MDT->dominates(&*InsertPt, &*PrevInsertPt))
372 I->second = insertPt(MBB, InsertPt);
373
374 continue;
375 }
376
377 // Find the common dominator block between PrevInsertPt and the
378 // current spill.
379 DomMBB = MDT->findNearestCommonDominator(DomMBB, MBB);
380
381 if (DomMBB == MBB)
382 I->second = insertPt(MBB, InsertPt);
383 else if (DomMBB != PrevInsertMBB)
384 I->second = insertPt(DomMBB, DomMBB->getFirstTerminator());
385 }
386 }
387}
388
389void SILowerSGPRSpills::determineRegsForWWMAllocation(MachineFunction &MF,
390 BitVector &RegMask) {
391 // Determine an optimal number of VGPRs for WWM allocation. The complement
392 // list will be available for allocating other VGPR virtual registers.
393 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
394 MachineRegisterInfo &MRI = MF.getRegInfo();
395 BitVector ReservedRegs = TRI->getReservedRegs(MF);
396 BitVector NonWwmAllocMask(TRI->getNumRegs());
397 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
398
399 // FIXME: MaxNumVGPRsForWwmAllocation might need to be adjusted in the future
400 // to have a balanced allocation between WWM values and per-thread vector
401 // register operands.
402 unsigned NumRegs = MaxNumVGPRsForWwmAllocation;
403 NumRegs =
404 std::min(static_cast<unsigned>(MFI->getSGPRSpillVGPRs().size()), NumRegs);
405
406 auto [MaxNumVGPRs, MaxNumAGPRs] = ST.getMaxNumVectorRegs(MF.getFunction());
407 // Try to use the highest available registers for now. Later after
408 // vgpr-regalloc, they can be shifted to the lowest range.
409 unsigned I = 0;
410 for (unsigned Reg = AMDGPU::VGPR0 + MaxNumVGPRs - 1;
411 (I < NumRegs) && (Reg >= AMDGPU::VGPR0); --Reg) {
412 if (!ReservedRegs.test(Reg) &&
413 !MRI.isPhysRegUsed(Reg, /*SkipRegMaskTest=*/true)) {
414 TRI->markSuperRegs(RegMask, Reg);
415 ++I;
416 }
417 }
418
419 if (I != NumRegs) {
420 // Reserve an arbitrary register and report the error.
421 TRI->markSuperRegs(RegMask, AMDGPU::VGPR0);
423 "cannot find enough VGPRs for wwm-regalloc");
424 }
425}
426
427bool SILowerSGPRSpillsLegacy::runOnMachineFunction(MachineFunction &MF) {
428 auto *LISWrapper = getAnalysisIfAvailable<LiveIntervalsWrapperPass>();
429 LiveIntervals *LIS = LISWrapper ? &LISWrapper->getLIS() : nullptr;
430 auto *SIWrapper = getAnalysisIfAvailable<SlotIndexesWrapperPass>();
431 SlotIndexes *Indexes = SIWrapper ? &SIWrapper->getSI() : nullptr;
432 MachineDominatorTree *MDT =
433 &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
434 MachineCycleInfo *MCI =
435 &getAnalysis<MachineCycleInfoWrapperPass>().getCycleInfo();
436 return SILowerSGPRSpills(LIS, Indexes, MDT, MCI).run(MF);
437}
438
439bool SILowerSGPRSpills::run(MachineFunction &MF) {
440 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
441 TII = ST.getInstrInfo();
442 TRI = &TII->getRegisterInfo();
443
444 assert(SaveBlocks.empty() && RestoreBlocks.empty());
445
446 // First, expose any CSR SGPR spills. This is mostly the same as what PEI
447 // does, but somewhat simpler.
448 calculateSaveRestoreBlocks(MF);
449 SmallVector<int> CalleeSavedFIs;
450 bool HasCSRs = spillCalleeSavedRegs(MF, CalleeSavedFIs);
451
452 MachineFrameInfo &MFI = MF.getFrameInfo();
453 MachineRegisterInfo &MRI = MF.getRegInfo();
454 SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
455
456 if (!MFI.hasStackObjects() && !HasCSRs) {
457 SaveBlocks.clear();
458 RestoreBlocks.clear();
459 return false;
460 }
461
462 bool MadeChange = false;
463 bool SpilledToVirtVGPRLanes = false;
464
465 // TODO: CSR VGPRs will never be spilled to AGPRs. These can probably be
466 // handled as SpilledToReg in regular PrologEpilogInserter.
467 const bool HasSGPRSpillToVGPR = TRI->spillSGPRToVGPR() &&
468 (HasCSRs || FuncInfo->hasSpilledSGPRs());
469 if (HasSGPRSpillToVGPR) {
470 // Process all SGPR spills before frame offsets are finalized. Ideally SGPRs
471 // are spilled to VGPRs, in which case we can eliminate the stack usage.
472 //
473 // This operates under the assumption that only other SGPR spills are users
474 // of the frame index.
475
476 // To track the spill frame indices handled in this pass.
477 BitVector SpillFIs(MFI.getObjectIndexEnd(), false);
478
479 // To track the IMPLICIT_DEF insertion point for the lane vgprs.
480 DenseMap<Register, LaneVGPRInsertPt> LaneVGPRDomInstr;
481
482 for (MachineBasicBlock &MBB : MF) {
483 for (MachineInstr &MI : llvm::make_early_inc_range(MBB)) {
484 if (!TII->isSGPRSpill(MI))
485 continue;
486
487 if (MI.getOperand(0).isUndef()) {
488 if (Indexes)
490 MI.eraseFromParent();
491 continue;
492 }
493
494 int FI = TII->getNamedOperand(MI, AMDGPU::OpName::addr)->getIndex();
496
497 bool IsCalleeSaveSGPRSpill = llvm::is_contained(CalleeSavedFIs, FI);
498 if (IsCalleeSaveSGPRSpill) {
499 // Spill callee-saved SGPRs into physical VGPR lanes.
500
501 // TODO: This is to ensure the CFIs are static for efficient frame
502 // unwinding in the debugger. Spilling them into virtual VGPR lanes
503 // involve regalloc to allocate the physical VGPRs and that might
504 // cause intermediate spill/split of such liveranges for successful
505 // allocation. This would result in broken CFI encoding unless the
506 // regalloc aware CFI generation to insert new CFIs along with the
507 // intermediate spills is implemented. There is no such support
508 // currently exist in the LLVM compiler.
509 if (FuncInfo->allocateSGPRSpillToVGPRLane(
510 MF, FI, /*SpillToPhysVGPRLane=*/true)) {
511 bool Spilled = TRI->eliminateSGPRToVGPRSpillFrameIndex(
512 MI, FI, nullptr, Indexes, LIS, true);
513 if (!Spilled)
515 "failed to spill SGPR to physical VGPR lane when allocated");
516 }
517 } else {
518 MachineInstrSpan MIS(&MI, &MBB);
519 if (FuncInfo->allocateSGPRSpillToVGPRLane(MF, FI)) {
520 bool Spilled = TRI->eliminateSGPRToVGPRSpillFrameIndex(
521 MI, FI, nullptr, Indexes, LIS);
522 if (!Spilled)
524 "failed to spill SGPR to virtual VGPR lane when allocated");
525 SpillFIs.set(FI);
526 updateLaneVGPRDomInstr(FI, &MBB, MIS.begin(), LaneVGPRDomInstr);
527 SpilledToVirtVGPRLanes = true;
528 }
529 }
530 }
531 }
532
533 for (auto Reg : FuncInfo->getSGPRSpillVGPRs()) {
534 LaneVGPRInsertPt IP = LaneVGPRDomInstr[Reg];
535 if (MachineCycle *C = MCI->getTopLevelParentCycle(IP.MBB)) {
536 MachineBasicBlock *AdjMBB = getCycleDomBB(C);
537 IP = insertPt(AdjMBB, AdjMBB->getFirstTerminator());
538 }
539 // Insert the IMPLICIT_DEF at the identified points.
540 MachineBasicBlock &Block = *IP.MBB;
541 DebugLoc DL = Block.findDebugLoc(IP.It);
542 auto MIB = BuildMI(Block, IP.It, DL, TII->get(AMDGPU::IMPLICIT_DEF), Reg);
543
544 // Add WWM flag to the virtual register.
546
547 // Set SGPR_SPILL asm printer flag
548 MIB->setAsmPrinterFlag(AMDGPU::SGPR_SPILL);
549 if (LIS) {
550 LIS->InsertMachineInstrInMaps(*MIB);
552 }
553 }
554
555 // Determine the registers for WWM allocation and also compute the register
556 // mask for non-wwm VGPR allocation.
557 if (FuncInfo->getSGPRSpillVGPRs().size()) {
558 BitVector WwmRegMask(TRI->getNumRegs());
559
560 determineRegsForWWMAllocation(MF, WwmRegMask);
561
562 BitVector NonWwmRegMask(WwmRegMask);
563 NonWwmRegMask.flip().clearBitsNotInMask(TRI->getAllVGPRRegMask());
564
565 // The complement set will be the registers for non-wwm (per-thread) vgpr
566 // allocation.
567 FuncInfo->updateNonWWMRegMask(NonWwmRegMask);
568 }
569
570 for (MachineBasicBlock &MBB : MF)
571 clearDebugInfoForSpillFIs(MFI, MBB, SpillFIs);
572
573 // All those frame indices which are dead by now should be removed from the
574 // function frame. Otherwise, there is a side effect such as re-mapping of
575 // free frame index ids by the later pass(es) like "stack slot coloring"
576 // which in turn could mess-up with the book keeping of "frame index to VGPR
577 // lane".
578 FuncInfo->removeDeadFrameIndices(MFI, /*ResetSGPRSpillStackIDs*/ false);
579
580 MadeChange = true;
581 }
582
583 if (SpilledToVirtVGPRLanes) {
584 const TargetRegisterClass *RC = TRI->getWaveMaskRegClass();
585 // Shift back the reserved SGPR for EXEC copy into the lowest range.
586 // This SGPR is reserved to handle the whole-wave spill/copy operations
587 // that might get inserted during vgpr regalloc.
588 Register UnusedLowSGPR = TRI->findUnusedRegister(MRI, RC, MF);
589 if (UnusedLowSGPR && TRI->getHWRegIndex(UnusedLowSGPR) <
590 TRI->getHWRegIndex(FuncInfo->getSGPRForEXECCopy()))
591 FuncInfo->setSGPRForEXECCopy(UnusedLowSGPR);
592 } else {
593 // No SGPR spills to virtual VGPR lanes and hence there won't be any WWM
594 // spills/copies. Reset the SGPR reserved for EXEC copy.
595 FuncInfo->setSGPRForEXECCopy(AMDGPU::NoRegister);
596 }
597
598 SaveBlocks.clear();
599 RestoreBlocks.clear();
600
601 return MadeChange;
602}
603
604PreservedAnalyses
607 MFPropsModifier _(*this, MF);
608 auto *LIS = MFAM.getCachedResult<LiveIntervalsAnalysis>(MF);
609 auto *Indexes = MFAM.getCachedResult<SlotIndexesAnalysis>(MF);
612 SILowerSGPRSpills(LIS, Indexes, MDT, &MCI).run(MF);
613 return PreservedAnalyses::all();
614}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
Provides AMDGPU specific target descriptions.
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
AMD GCN specific subclass of TargetSubtarget.
#define DEBUG_TYPE
const HexagonInstrInfo * TII
#define _
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
static void insertCSRRestores(MachineBasicBlock &RestoreBlock, std::vector< CalleeSavedInfo > &CSI)
Insert restore code for the callee-saved registers used in the function.
SmallVector< MachineBasicBlock *, 4 > MBBVector
static void insertCSRSaves(MachineBasicBlock &SaveBlock, ArrayRef< CalleeSavedInfo > CSI)
Insert spill code for the callee-saved registers used in the function.
static void updateLiveness(MachineFunction &MF)
Helper function to update the liveness information for the callee-saved registers.
This file declares the machine register scavenger class.
static bool isLiveIntoMBB(MCRegister Reg, MachineBasicBlock &MBB, const TargetRegisterInfo *TRI)
static void insertCSRRestores(MachineBasicBlock &RestoreBlock, MutableArrayRef< CalleeSavedInfo > CSI, SlotIndexes *Indexes, LiveIntervals *LIS)
Insert restore code for the callee-saved registers used in the function.
static void insertCSRSaves(MachineBasicBlock &SaveBlock, ArrayRef< CalleeSavedInfo > CSI, SlotIndexes *Indexes, LiveIntervals *LIS)
Insert spill code for the callee-saved registers used in the function.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
void setPreservesAll()
Set by analyses that do not transform their input at all.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:482
The CalleeSavedInfo class tracks the information need to locate where a callee saved register is in t...
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:178
iterator end()
Definition DenseMap.h:81
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
Find nearest common dominator basic block for basic block A and B.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:358
CycleT * getTopLevelParentCycle(const BlockT *Block) const
const HexagonRegisterInfo & getRegisterInfo() const
LLVM_ABI void emitError(const Instruction *I, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
void removeAllRegUnitsForPhysReg(MCRegister Reg)
Remove associated live ranges for the register units associated with Reg.
SlotIndex InsertMachineInstrInMaps(MachineInstr &MI)
LiveInterval & createAndComputeVirtRegInterval(Register Reg)
MCRegAliasIterator enumerates all registers aliasing Reg.
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
An RAII based helper class to modify MachineFunctionProperties when running pass.
bool isEHFuncletEntry() const
Returns true if this is the entry block of an EH funclet.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
bool isReturnBlock() const
Convenience function that returns true if the block ends in a return instruction.
LLVM_ABI void sortUniqueLiveIns()
Sorts and uniques the LiveIns vector.
LLVM_ABI DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any debug instructions.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineInstrBundleIterator< MachineInstr > iterator
LLVM_ABI Result run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
Legacy analysis pass which computes a MachineCycleInfo.
Analysis pass which computes a MachineDominatorTree.
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
bool dominates(const MachineInstr *A, const MachineInstr *B) const
LLVM_ABI int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
void setCalleeSavedInfoValid(bool v)
int getObjectIndexEnd() const
Return one past the maximum frame object index.
bool hasStackObjects() const
Return true if there are any stack objects in this function.
uint8_t getStackID(int ObjectIdx) const
const SaveRestorePoints & getRestorePoints() const
const SaveRestorePoints & getSavePoints() const
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Properties which a MachineFunction may have at a given point in time.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineBasicBlock & front() const
MachineInstrSpan provides an interface to get an iteration range containing the instruction it was in...
MachineBasicBlock::iterator begin()
Representation of each machine instruction.
LLVM_ABI const MCPhysReg * getCalleeSavedRegs() const
Returns list of callee saved registers.
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
Wrapper class representing virtual and physical registers.
Definition Register.h:20
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
void setFlag(Register Reg, uint8_t Flag)
ArrayRef< SIRegisterInfo::SpilledReg > getSGPRSpillToVirtualVGPRLanes(int FrameIndex) const
bool allocateSGPRSpillToVGPRLane(MachineFunction &MF, int FI, bool SpillToPhysVGPRLane=false, bool IsPrologEpilog=false)
bool removeDeadFrameIndices(MachineFrameInfo &MFI, bool ResetSGPRSpillStackIDs)
If ResetSGPRSpillStackIDs is true, reset the stack ID from sgpr-spill to the default stack.
void updateNonWWMRegMask(BitVector &RegMask)
ArrayRef< Register > getSGPRSpillVGPRs() const
SlotIndexes pass.
SlotIndex insertMachineInstrInMaps(MachineInstr &MI, bool Late=false)
Insert the given machine instruction into the mapping.
LLVM_ABI void removeMachineInstrFromMaps(MachineInstr &MI, bool AllowBundled=false)
Removes machine instruction (bundle) MI from the mapping.
LLVM_ABI void repairIndexesInRange(MachineBasicBlock *MBB, MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End)
Repair indexes after adding and removing instructions.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Information about stack frame layout on the target.
void restoreCalleeSavedRegister(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const CalleeSavedInfo &CS, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const
virtual bool spillCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, ArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const
spillCalleeSavedRegisters - Issues instruction(s) to spill all callee saved registers and returns tru...
virtual bool restoreCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, MutableArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const
restoreCalleeSavedRegisters - Issues instruction(s) to restore all callee saved registers and returns...
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetFrameLowering * getFrameLowering() const
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
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:633
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
void clearDebugInfoForSpillFIs(MachineFrameInfo &MFI, MachineBasicBlock &MBB, const BitVector &SpillFIs)
Replace frame index operands with null registers in debug value instructions for the specified spill ...
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
char & SILowerSGPRSpillsLegacyID
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 is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1946
MachineCycleInfo::CycleT MachineCycle