LLVM 24.0.0git
SIFrameLowering.cpp
Go to the documentation of this file.
1//===----------------------- SIFrameLowering.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#include "SIFrameLowering.h"
10#include "AMDGPU.h"
11#include "AMDGPULaneMaskUtils.h"
12#include "GCNSubtarget.h"
15#include "SISpillUtils.h"
21#include "llvm/Support/LEB128.h"
23
24using namespace llvm;
25
26#define DEBUG_TYPE "frame-info"
27
29 "amdgpu-spill-vgpr-to-agpr",
30 cl::desc("Enable spilling VGPRs to AGPRs"),
32 cl::init(true));
33
34static constexpr unsigned SGPRBitSize = 32;
35static constexpr unsigned SGPRByteSize = SGPRBitSize / 8;
36static constexpr unsigned VGPRLaneBitSize = 32;
37
38// The DWARF register numbers of vcc_lo and vcc_hi (VCC_32_LO and VCC_32_HI) are
39// only defined in wave32. In wave64 both halves are described as part of
40// VCC_64.
41static bool isWave64VCCHalf(const GCNSubtarget &ST, MCRegister Reg) {
42 return ST.isWave64() && (Reg == AMDGPU::VCC_LO || Reg == AMDGPU::VCC_HI);
43}
44
45// Find a register matching \p RC from \p LiveUnits which is unused and
46// available throughout the function. On failure, returns AMDGPU::NoRegister.
47// TODO: Rewrite the loop here to iterate over MCRegUnits instead of
48// MCRegisters. This should reduce the number of iterations and avoid redundant
49// checking.
51 const LiveRegUnits &LiveUnits,
52 const TargetRegisterClass &RC) {
53 for (MCRegister Reg : RC) {
54 if (!MRI.isPhysRegUsed(Reg) && LiveUnits.available(Reg) &&
55 !MRI.isReserved(Reg))
56 return Reg;
57 }
58 return MCRegister();
59}
60
61static void encodeDwarfRegisterLocation(int DwarfReg, raw_ostream &OS) {
62 assert(DwarfReg >= 0);
63 if (DwarfReg < 32) {
64 OS << uint8_t(dwarf::DW_OP_reg0 + DwarfReg);
65 } else {
66 OS << uint8_t(dwarf::DW_OP_regx);
67 encodeULEB128(DwarfReg, OS);
68 }
69}
70
72 int64_t DwarfStackPtrReg) {
73 assert(ST.hasFlatScratchEnabled());
74
75 // When flat scratch is enabled, the stack pointer is an address in the
76 // private_lane DWARF address space (i.e. swizzled), but in order to
77 // accurately and efficiently describe things like masked spills of vector
78 // registers we want to define the CFA to be an address in the private_wave
79 // DWARF address space (i.e. unswizzled). To achieve this we scale the stack
80 // pointer by the wavefront size, implemented as (SP << wave_size_log2).
81 const unsigned WavefrontSizeLog2 = ST.getWavefrontSizeLog2();
82 assert(WavefrontSizeLog2 < 32);
83
86 encodeDwarfRegisterLocation(DwarfStackPtrReg, OSBlock);
87 OSBlock << uint8_t(dwarf::DW_OP_deref_size) << uint8_t(SGPRByteSize)
88 << uint8_t(dwarf::DW_OP_lit0 + WavefrontSizeLog2)
89 << uint8_t(dwarf::DW_OP_shl)
90 << uint8_t(dwarf::DW_OP_lit0 +
91 dwarf::DW_ASPACE_LLVM_AMDGPU_private_wave)
92 << uint8_t(dwarf::DW_OP_LLVM_user)
93 << uint8_t(dwarf::DW_OP_LLVM_form_aspace_address);
94
95 SmallString<20> CFIInst;
96 raw_svector_ostream OSCFIInst(CFIInst);
97 OSCFIInst << uint8_t(dwarf::DW_CFA_def_cfa_expression);
98 encodeULEB128(Block.size(), OSCFIInst);
99 OSCFIInst << Block;
100
101 return MCCFIInstruction::createEscape(nullptr, OSCFIInst.str());
102}
103
104void SIFrameLowering::emitDefCFA(MachineBasicBlock &MBB,
106 DebugLoc const &DL, MCRegister StackPtrReg,
107 bool AspaceAlreadyDefined,
108 MachineInstr::MIFlag Flags) const {
110 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
111 const SIRegisterInfo *TRI = ST.getRegisterInfo();
112
113 int64_t DwarfStackPtrReg = TRI->getDwarfRegNum(StackPtrReg, false);
114 MCCFIInstruction CFIInst =
115 ST.hasFlatScratchEnabled()
116 ? createScaledCFAInPrivateWave(ST, DwarfStackPtrReg)
117 : (AspaceAlreadyDefined
118 ? MCCFIInstruction::createLLVMDefAspaceCfa(
119 nullptr, DwarfStackPtrReg, 0,
120 dwarf::DW_ASPACE_LLVM_AMDGPU_private_wave, SMLoc())
121 : MCCFIInstruction::createDefCfaRegister(nullptr,
122 DwarfStackPtrReg));
123 buildCFI(MBB, MBBI, DL, CFIInst, Flags);
124}
125
126// Find a scratch register that we can use in the prologue. We avoid using
127// callee-save registers since they may appear to be free when this is called
128// from canUseAsPrologue (during shrink wrapping), but then no longer be free
129// when this is called from emitPrologue.
132 const TargetRegisterClass &RC, bool Unused = false) {
133 // Mark callee saved registers as used so we will not choose them.
134 const MCPhysReg *CSRegs = MRI.getCalleeSavedRegs();
135 for (unsigned i = 0; CSRegs[i]; ++i)
136 LiveUnits.addReg(CSRegs[i]);
137
138 // We are looking for a register that can be used throughout the entire
139 // function, so any use is unacceptable.
140 if (Unused)
141 return findUnusedRegister(MRI, LiveUnits, RC);
142
143 for (MCRegister Reg : RC) {
144 if (LiveUnits.available(Reg) && !MRI.isReserved(Reg))
145 return Reg;
146 }
147
148 return MCRegister();
149}
150
151/// Query target location for spilling SGPRs
152/// \p IncludeScratchCopy : Also look for free scratch SGPRs
154 MachineFunction &MF, LiveRegUnits &LiveUnits, Register SGPR,
155 const TargetRegisterClass &RC = AMDGPU::SReg_32_XM0_XEXECRegClass,
156 bool IncludeScratchCopy = true) {
158 MachineFrameInfo &FrameInfo = MF.getFrameInfo();
159
160 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
161 const SIRegisterInfo *TRI = ST.getRegisterInfo();
162 unsigned Size = TRI->getSpillSize(RC);
163 Align Alignment = TRI->getSpillAlign(RC);
164
165 // We need to save and restore the given SGPR.
166
167 Register ScratchSGPR;
168 // 1: Try to save the given register into an unused scratch SGPR. The
169 // LiveUnits should have all the callee saved registers marked as used. For
170 // certain cases we skip copy to scratch SGPR.
171 if (IncludeScratchCopy)
172 ScratchSGPR = findUnusedRegister(MF.getRegInfo(), LiveUnits, RC);
173
174 if (!ScratchSGPR) {
175 int FI = FrameInfo.CreateStackObject(Size, Alignment, true, nullptr,
177
178 if (TRI->spillSGPRToVGPR() &&
179 MFI->allocateSGPRSpillToVGPRLane(MF, FI, /*SpillToPhysVGPRLane=*/true,
180 /*IsPrologEpilog=*/true)) {
181 // 2: There's no free lane to spill, and no free register to save the
182 // SGPR, so we're forced to take another VGPR to use for the spill.
186
187 LLVM_DEBUG(auto Spill = MFI->getSGPRSpillToPhysicalVGPRLanes(FI).front();
188 dbgs() << printReg(SGPR, TRI) << " requires fallback spill to "
189 << printReg(Spill.VGPR, TRI) << ':' << Spill.Lane
190 << '\n';);
191 } else {
192 // Remove dead <FI> index
194 // 3: If all else fails, spill the register to memory.
195 FI = FrameInfo.CreateSpillStackObject(Size, Alignment);
197 SGPR,
199 LLVM_DEBUG(dbgs() << "Reserved FI " << FI << " for spilling "
200 << printReg(SGPR, TRI) << '\n');
201 }
202 } else {
206 LiveUnits.addReg(ScratchSGPR);
207 LLVM_DEBUG(dbgs() << "Saving " << printReg(SGPR, TRI) << " with copy to "
208 << printReg(ScratchSGPR, TRI) << '\n');
209 }
210}
211
212// We need to specially emit stack operations here because a different frame
213// register is used than in the rest of the function, as getFrameRegister would
214// use.
215static void buildPrologSpill(const GCNSubtarget &ST, const SIRegisterInfo &TRI,
216 const SIMachineFunctionInfo &FuncInfo,
217 LiveRegUnits &LiveUnits, MachineFunction &MF,
220 Register SpillReg, int FI, Register FrameReg,
221 int64_t DwordOff = 0) {
222 unsigned Opc = ST.hasFlatScratchEnabled() ? AMDGPU::SCRATCH_STORE_DWORD_SADDR
223 : AMDGPU::BUFFER_STORE_DWORD_OFFSET;
224
225 MachineFrameInfo &FrameInfo = MF.getFrameInfo();
228 PtrInfo, MachineMemOperand::MOStore, FrameInfo.getObjectSize(FI),
229 FrameInfo.getObjectAlign(FI));
230 LiveUnits.addReg(SpillReg);
231 bool IsKill = !MBB.isLiveIn(SpillReg);
232 TRI.buildSpillLoadStore(MBB, I, DL, Opc, FI, SpillReg, IsKill, FrameReg,
233 DwordOff, MMO, nullptr, &LiveUnits);
234 if (IsKill)
235 LiveUnits.removeReg(SpillReg);
236}
237
238static void buildEpilogRestore(const GCNSubtarget &ST,
239 const SIRegisterInfo &TRI,
240 const SIMachineFunctionInfo &FuncInfo,
241 LiveRegUnits &LiveUnits, MachineFunction &MF,
244 const DebugLoc &DL, Register SpillReg, int FI,
245 Register FrameReg, int64_t DwordOff = 0) {
246 unsigned Opc = ST.hasFlatScratchEnabled() ? AMDGPU::SCRATCH_LOAD_DWORD_SADDR
247 : AMDGPU::BUFFER_LOAD_DWORD_OFFSET;
248
249 MachineFrameInfo &FrameInfo = MF.getFrameInfo();
252 PtrInfo, MachineMemOperand::MOLoad, FrameInfo.getObjectSize(FI),
253 FrameInfo.getObjectAlign(FI));
254 TRI.buildSpillLoadStore(MBB, I, DL, Opc, FI, SpillReg, false, FrameReg,
255 DwordOff, MMO, nullptr, &LiveUnits);
256}
257
259 const DebugLoc &DL, const SIInstrInfo *TII,
260 Register TargetReg) {
261 MachineFunction *MF = MBB.getParent();
263 const SIRegisterInfo *TRI = &TII->getRegisterInfo();
264 const MCInstrDesc &SMovB32 = TII->get(AMDGPU::S_MOV_B32);
265 Register TargetLo = TRI->getSubReg(TargetReg, AMDGPU::sub0);
266 Register TargetHi = TRI->getSubReg(TargetReg, AMDGPU::sub1);
267
268 if (MFI->getGITPtrHigh() != 0xffffffff) {
269 BuildMI(MBB, I, DL, SMovB32, TargetHi)
270 .addImm(MFI->getGITPtrHigh())
271 .addReg(TargetReg, RegState::ImplicitDefine);
272 } else {
273 const MCInstrDesc &GetPC64 = TII->get(AMDGPU::S_GETPC_B64_pseudo);
274 BuildMI(MBB, I, DL, GetPC64, TargetReg);
275 }
276 Register GitPtrLo = MFI->getGITPtrLoReg(*MF);
277 MF->getRegInfo().addLiveIn(GitPtrLo);
278 MBB.addLiveIn(GitPtrLo);
279 BuildMI(MBB, I, DL, SMovB32, TargetLo)
280 .addReg(GitPtrLo);
281}
282
283static void initLiveUnits(LiveRegUnits &LiveUnits, const SIRegisterInfo &TRI,
284 const SIMachineFunctionInfo *FuncInfo,
286 MachineBasicBlock::iterator MBBI, bool IsProlog) {
287 if (LiveUnits.empty()) {
288 LiveUnits.init(TRI);
289 if (IsProlog) {
290 LiveUnits.addLiveIns(MBB);
291 } else {
292 // In epilog.
293 LiveUnits.addLiveOuts(MBB);
294 LiveUnits.stepBackward(*MBBI);
295 }
296 }
297}
298
299namespace llvm {
300
301// SpillBuilder to save/restore special SGPR spills like the one needed for FP,
302// BP, etc. These spills are delayed until the current function's frame is
303// finalized. For a given register, the builder uses the
304// PrologEpilogSGPRSaveRestoreInfo to decide the spill method.
308 MachineFunction &MF;
309 const GCNSubtarget &ST;
310 MachineFrameInfo &MFI;
311 SIMachineFunctionInfo *FuncInfo;
312 const SIInstrInfo *TII;
313 const SIRegisterInfo &TRI;
314 const MCRegisterInfo *MCRI;
315 const SIFrameLowering *TFI;
316 Register SuperReg;
318 LiveRegUnits &LiveUnits;
319 const DebugLoc &DL;
320 Register FrameReg;
321 ArrayRef<int16_t> SplitParts;
322 unsigned NumSubRegs;
323 unsigned EltSize = 4;
324 bool IsFramePtrPrologSpill;
325 bool NeedsFrameMoves;
326
327 static bool isExec(Register Reg) {
328 return Reg == AMDGPU::EXEC_LO || Reg == AMDGPU::EXEC;
329 }
330
331 /// If this builder requires SuperReg-based CFI, which is emitted after all
332 /// SubRegs are actually spilled, return the Register which should be used
333 /// as input to getDwarfRegNum. Otherwise, CFI should be generated per-SubReg.
334 ///
335 /// Note: Most spills handled by this builder generate CFI after each
336 /// SubReg spill, as each SubReg maps directly to a CFI register via
337 /// getDwarfRegNum(SubReg, false). All other cases currently currently
338 /// correspond to the SuperReg directly.
339 MCRegister getCFISuperReg() const {
340 if (IsFramePtrPrologSpill)
341 return FuncInfo->getFrameOffsetReg();
342 // FIXME: CFI for EXEC needs a fix by accurately computing the spill
343 // offset for both the low and high components.
344 if (isExec(SuperReg))
345 return AMDGPU::EXEC;
346 return {};
347 }
348
349 void saveToMemory(const int FI) const {
350 MachineRegisterInfo &MRI = MF.getRegInfo();
351 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
352 assert(!MFI.isDeadObjectIndex(FI));
353
354 initLiveUnits(LiveUnits, TRI, FuncInfo, MF, MBB, MI, /*IsProlog*/ true);
355
357 MRI, LiveUnits, AMDGPU::VGPR_32RegClass);
358 if (!TmpVGPR)
359 report_fatal_error("failed to find free scratch register");
360
361 auto BuildCFI = [&](Register Reg) {
362 TFI->buildCFI(MBB, MI, DL,
364 nullptr, MCRI->getDwarfRegNum(Reg, false),
365 MFI.getObjectOffset(FI) * ST.getWavefrontSize()));
366 };
367 MCRegister CFISuperReg = getCFISuperReg();
368 for (unsigned I = 0, DwordOff = 0; I < NumSubRegs; ++I) {
369 Register SubReg = NumSubRegs == 1
370 ? SuperReg
371 : Register(TRI.getSubReg(SuperReg, SplitParts[I]));
372 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_MOV_B32_e32), TmpVGPR)
373 .addReg(SubReg);
374
375 buildPrologSpill(ST, TRI, *FuncInfo, LiveUnits, MF, MBB, MI, DL, TmpVGPR,
376 FI, FrameReg, DwordOff);
377 if (NeedsFrameMoves && !CFISuperReg)
378 BuildCFI(SubReg);
379 DwordOff += 4;
380 }
381 if (NeedsFrameMoves && CFISuperReg)
382 BuildCFI(CFISuperReg);
383 }
384
385 void saveToVGPRLane(const int FI) const {
386 assert(!MFI.isDeadObjectIndex(FI));
387
388 assert(MFI.getStackID(FI) == TargetStackID::SGPRSpill);
390 FuncInfo->getSGPRSpillToPhysicalVGPRLanes(FI);
391 assert(Spill.size() == NumSubRegs);
392
393 MCRegister CFISuperReg = getCFISuperReg();
394 for (unsigned I = 0; I < NumSubRegs; ++I) {
395 Register SubReg = NumSubRegs == 1
396 ? SuperReg
397 : Register(TRI.getSubReg(SuperReg, SplitParts[I]));
398 BuildMI(MBB, MI, DL, TII->get(AMDGPU::SI_SPILL_S32_TO_VGPR),
399 Spill[I].VGPR)
400 .addReg(SubReg)
401 .addImm(Spill[I].Lane)
402 .addReg(Spill[I].VGPR, RegState::Undef);
403 if (NeedsFrameMoves && !CFISuperReg)
404 TFI->buildCFIForSGPRToVGPRSpill(MBB, MI, DL, SubReg, Spill[I].VGPR,
405 Spill[I].Lane);
406 }
407 if (NeedsFrameMoves && CFISuperReg)
408 TFI->buildCFIForSGPRToVGPRSpill(MBB, MI, DL, CFISuperReg, Spill);
409 }
410
411 void copyToScratchSGPR(Register DstReg) const {
412 BuildMI(MBB, MI, DL, TII->get(AMDGPU::COPY), DstReg)
413 .addReg(SuperReg)
415 if (NeedsFrameMoves) {
416 MCRegister CFISuperReg = getCFISuperReg();
417 if (!CFISuperReg)
418 CFISuperReg = SuperReg;
419 if (isWave64VCCHalf(ST, DstReg)) {
420 assert(NumSubRegs == 1 && "Expected a 32-bit SGPR");
421 TFI->buildCFIForSGPRToVCCHalfCopy(MBB, MI, DL, CFISuperReg, DstReg);
422 } else {
423 TFI->buildCFIForSRegToSRegSpill(MBB, MI, DL, CFISuperReg, DstReg);
424 }
425 }
426 }
427
428 void restoreFromMemory(const int FI) {
429 MachineRegisterInfo &MRI = MF.getRegInfo();
430 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
431
432 initLiveUnits(LiveUnits, TRI, FuncInfo, MF, MBB, MI, /*IsProlog*/ false);
434 MRI, LiveUnits, AMDGPU::VGPR_32RegClass);
435 if (!TmpVGPR)
436 report_fatal_error("failed to find free scratch register");
437
438 for (unsigned I = 0, DwordOff = 0; I < NumSubRegs; ++I) {
439 MCRegister SubReg = NumSubRegs == 1
440 ? SuperReg.asMCReg()
441 : TRI.getSubReg(SuperReg, SplitParts[I]);
442
443 buildEpilogRestore(ST, TRI, *FuncInfo, LiveUnits, MF, MBB, MI, DL,
444 TmpVGPR, FI, FrameReg, DwordOff);
445 assert(SubReg.isPhysical());
446
447 BuildMI(MBB, MI, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), SubReg)
448 .addReg(TmpVGPR, RegState::Kill);
449 DwordOff += 4;
450 }
451 }
452
453 void restoreFromVGPRLane(const int FI) {
454 assert(MFI.getStackID(FI) == TargetStackID::SGPRSpill);
456 FuncInfo->getSGPRSpillToPhysicalVGPRLanes(FI);
457 assert(Spill.size() == NumSubRegs);
458
459 for (unsigned I = 0; I < NumSubRegs; ++I) {
460 MCRegister SubReg = NumSubRegs == 1
461 ? SuperReg.asMCReg()
462 : TRI.getSubReg(SuperReg, SplitParts[I]);
463 BuildMI(MBB, MI, DL, TII->get(AMDGPU::SI_RESTORE_S32_FROM_VGPR), SubReg)
464 .addReg(Spill[I].VGPR)
465 .addImm(Spill[I].Lane);
466 }
467 }
468
469 void copyFromScratchSGPR(Register SrcReg) const {
470 BuildMI(MBB, MI, DL, TII->get(AMDGPU::COPY), SuperReg)
471 .addReg(SrcReg)
473 }
474
475public:
480 const DebugLoc &DL, const SIInstrInfo *TII,
481 const SIRegisterInfo &TRI,
482 LiveRegUnits &LiveUnits, Register FrameReg,
483 bool IsFramePtrPrologSpill = false)
484 : MI(MI), MBB(MBB), MF(*MBB.getParent()),
485 ST(MF.getSubtarget<GCNSubtarget>()), MFI(MF.getFrameInfo()),
486 FuncInfo(MF.getInfo<SIMachineFunctionInfo>()), TII(TII), TRI(TRI),
487 MCRI(MF.getContext().getRegisterInfo()), TFI(ST.getFrameLowering()),
488 SuperReg(Reg), SI(SI), LiveUnits(LiveUnits), DL(DL), FrameReg(FrameReg),
489 IsFramePtrPrologSpill(IsFramePtrPrologSpill),
490 NeedsFrameMoves(MF.needsFrameMoves()) {
491 const TargetRegisterClass *RC = TRI.getPhysRegBaseClass(SuperReg);
492 SplitParts = TRI.getRegSplitParts(RC, EltSize);
493 NumSubRegs = SplitParts.empty() ? 1 : SplitParts.size();
494
495 assert(SuperReg != AMDGPU::M0 && "m0 should never spill");
496 }
497
498 void save() {
499 switch (SI.getKind()) {
501 return saveToMemory(SI.getIndex());
503 return saveToVGPRLane(SI.getIndex());
505 return copyToScratchSGPR(SI.getReg());
506 }
507 }
508
509 void restore() {
510 switch (SI.getKind()) {
512 return restoreFromMemory(SI.getIndex());
514 return restoreFromVGPRLane(SI.getIndex());
516 return copyFromScratchSGPR(SI.getReg());
517 }
518 }
519};
520
521} // namespace llvm
522
523// Emit flat scratch setup code, assuming `MFI->hasFlatScratchInit()`
524void SIFrameLowering::emitEntryFunctionFlatScratchInit(
526 const DebugLoc &DL, Register ScratchWaveOffsetReg) const {
527 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
528 const SIInstrInfo *TII = ST.getInstrInfo();
529 const SIRegisterInfo *TRI = &TII->getRegisterInfo();
530 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
531
532 // We don't need this if we only have spills since there is no user facing
533 // scratch.
534
535 // TODO: If we know we don't have flat instructions earlier, we can omit
536 // this from the input registers.
537 //
538 // TODO: We only need to know if we access scratch space through a flat
539 // pointer. Because we only detect if flat instructions are used at all,
540 // this will be used more often than necessary on VI.
541
542 Register FlatScrInitLo;
543 Register FlatScrInitHi;
544
545 if (ST.isAmdPalOS()) {
546 // Extract the scratch offset from the descriptor in the GIT
547 LiveRegUnits LiveUnits;
548 LiveUnits.init(*TRI);
549 LiveUnits.addLiveIns(MBB);
550
551 // Find unused reg to load flat scratch init into
552 MachineRegisterInfo &MRI = MF.getRegInfo();
553 Register FlatScrInit = AMDGPU::NoRegister;
554 ArrayRef<MCPhysReg> AllSGPR64s = TRI->getAllSGPR64(MF);
555 unsigned NumPreloaded = (MFI->getNumPreloadedSGPRs() + 1) / 2;
556 AllSGPR64s = AllSGPR64s.slice(
557 std::min(static_cast<unsigned>(AllSGPR64s.size()), NumPreloaded));
558 Register GITPtrLoReg = MFI->getGITPtrLoReg(MF);
559 for (MCPhysReg Reg : AllSGPR64s) {
560 if (LiveUnits.available(Reg) && !MRI.isReserved(Reg) &&
561 MRI.isAllocatable(Reg) && !TRI->isSubRegisterEq(Reg, GITPtrLoReg)) {
562 FlatScrInit = Reg;
563 break;
564 }
565 }
566 assert(FlatScrInit && "Failed to find free register for scratch init");
567
568 FlatScrInitLo = TRI->getSubReg(FlatScrInit, AMDGPU::sub0);
569 FlatScrInitHi = TRI->getSubReg(FlatScrInit, AMDGPU::sub1);
570
571 buildGitPtr(MBB, I, DL, TII, FlatScrInit);
572
573 // We now have the GIT ptr - now get the scratch descriptor from the entry
574 // at offset 0 (or offset 16 for a compute shader).
575 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
576 const MCInstrDesc &LoadDwordX2 = TII->get(AMDGPU::S_LOAD_DWORDX2_IMM);
577 auto *MMO = MF.getMachineMemOperand(
578 PtrInfo,
581 8, Align(4));
582 unsigned Offset =
584 const GCNSubtarget &Subtarget = MF.getSubtarget<GCNSubtarget>();
585 unsigned EncodedOffset = AMDGPU::convertSMRDOffsetUnits(Subtarget, Offset);
586 BuildMI(MBB, I, DL, LoadDwordX2, FlatScrInit)
587 .addReg(FlatScrInit)
588 .addImm(EncodedOffset) // offset
589 .addImm(0) // cpol
590 .addMemOperand(MMO);
591
592 // Mask the offset in [47:0] of the descriptor
593 const MCInstrDesc &SAndB32 = TII->get(AMDGPU::S_AND_B32);
594 auto And = BuildMI(MBB, I, DL, SAndB32, FlatScrInitHi)
595 .addReg(FlatScrInitHi)
596 .addImm(0xffff);
597 And->getOperand(3).setIsDead(); // Mark SCC as dead.
598 } else {
599 Register FlatScratchInitReg =
601 assert(FlatScratchInitReg);
602
603 MachineRegisterInfo &MRI = MF.getRegInfo();
604 MRI.addLiveIn(FlatScratchInitReg);
605 MBB.addLiveIn(FlatScratchInitReg);
606
607 FlatScrInitLo = TRI->getSubReg(FlatScratchInitReg, AMDGPU::sub0);
608 FlatScrInitHi = TRI->getSubReg(FlatScratchInitReg, AMDGPU::sub1);
609 }
610
611 // Do a 64-bit pointer add.
612 if (ST.flatScratchIsPointer()) {
613 if (ST.getGeneration() >= AMDGPUSubtarget::GFX10) {
614 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_ADD_U32), FlatScrInitLo)
615 .addReg(FlatScrInitLo)
616 .addReg(ScratchWaveOffsetReg);
617 auto Addc = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_ADDC_U32),
618 FlatScrInitHi)
619 .addReg(FlatScrInitHi)
620 .addImm(0);
621 Addc->getOperand(3).setIsDead(); // Mark SCC as dead.
622
623 using namespace AMDGPU::Hwreg;
624 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SETREG_B32))
625 .addReg(FlatScrInitLo)
626 .addImm(int16_t(HwregEncoding::encode(ID_FLAT_SCR_LO, 0, 32)));
627 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SETREG_B32))
628 .addReg(FlatScrInitHi)
629 .addImm(int16_t(HwregEncoding::encode(ID_FLAT_SCR_HI, 0, 32)));
630 return;
631 }
632
633 // For GFX9.
634 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_ADD_U32), AMDGPU::FLAT_SCR_LO)
635 .addReg(FlatScrInitLo)
636 .addReg(ScratchWaveOffsetReg);
637 auto Addc = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_ADDC_U32),
638 AMDGPU::FLAT_SCR_HI)
639 .addReg(FlatScrInitHi)
640 .addImm(0);
641 Addc->getOperand(3).setIsDead(); // Mark SCC as dead.
642
643 return;
644 }
645
646 assert(ST.getGeneration() < AMDGPUSubtarget::GFX9);
647
648 // Copy the size in bytes.
649 BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), AMDGPU::FLAT_SCR_LO)
650 .addReg(FlatScrInitHi, RegState::Kill);
651
652 // Add wave offset in bytes to private base offset.
653 // See comment in AMDKernelCodeT.h for enable_sgpr_flat_scratch_init.
654 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), FlatScrInitLo)
655 .addReg(FlatScrInitLo)
656 .addReg(ScratchWaveOffsetReg);
657
658 // Convert offset to 256-byte units.
659 auto LShr = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_LSHR_B32),
660 AMDGPU::FLAT_SCR_HI)
661 .addReg(FlatScrInitLo, RegState::Kill)
662 .addImm(8);
663 LShr->getOperand(3).setIsDead(); // Mark SCC as dead.
664}
665
666// Note SGPRSpill stack IDs should only be used for SGPR spilling to VGPRs, not
667// memory. They should have been removed by now.
669 for (int I = MFI.getObjectIndexBegin(), E = MFI.getObjectIndexEnd();
670 I != E; ++I) {
671 if (!MFI.isDeadObjectIndex(I))
672 return false;
673 }
674
675 return true;
676}
677
678// Shift down registers reserved for the scratch RSRC.
679Register SIFrameLowering::getEntryFunctionReservedScratchRsrcReg(
680 MachineFunction &MF) const {
681
682 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
683 const SIInstrInfo *TII = ST.getInstrInfo();
684 const SIRegisterInfo *TRI = &TII->getRegisterInfo();
685 MachineRegisterInfo &MRI = MF.getRegInfo();
686 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
687
688 assert(MFI->isEntryFunction());
689
690 Register ScratchRsrcReg = MFI->getScratchRSrcReg();
691
692 if (!ScratchRsrcReg || (!MRI.isPhysRegUsed(ScratchRsrcReg) &&
694 return Register();
695
696 if (ST.hasSGPRInitBug() ||
697 ScratchRsrcReg != TRI->reservedPrivateSegmentBufferReg(MF))
698 return ScratchRsrcReg;
699
700 // We reserved the last registers for this. Shift it down to the end of those
701 // which were actually used.
702 //
703 // FIXME: It might be safer to use a pseudoregister before replacement.
704
705 // FIXME: We should be able to eliminate unused input registers. We only
706 // cannot do this for the resources required for scratch access. For now we
707 // skip over user SGPRs and may leave unused holes.
708
709 unsigned NumPreloaded = (MFI->getNumPreloadedSGPRs() + 3) / 4;
710 ArrayRef<MCPhysReg> AllSGPR128s = TRI->getAllSGPR128(MF);
711 AllSGPR128s = AllSGPR128s.slice(std::min(static_cast<unsigned>(AllSGPR128s.size()), NumPreloaded));
712
713 // Skip the last N reserved elements because they should have already been
714 // reserved for VCC etc.
715 Register GITPtrLoReg = MFI->getGITPtrLoReg(MF);
716 for (MCPhysReg Reg : AllSGPR128s) {
717 // Pick the first unallocated one. Make sure we don't clobber the other
718 // reserved input we needed. Also for PAL, make sure we don't clobber
719 // the GIT pointer passed in SGPR0 or SGPR8.
721 (!GITPtrLoReg || !TRI->isSubRegisterEq(Reg, GITPtrLoReg))) {
722 MRI.replaceRegWith(ScratchRsrcReg, Reg);
725 return Reg;
726 }
727 }
728
729 return ScratchRsrcReg;
730}
731
732static unsigned getScratchScaleFactor(const GCNSubtarget &ST) {
733 return ST.hasFlatScratchEnabled() ? 1 : ST.getWavefrontSize();
734}
735
737 MachineBasicBlock &MBB) const {
738 assert(&MF.front() == &MBB && "Shrink-wrapping not yet supported");
739
740 // FIXME: If we only have SGPR spills, we won't actually be using scratch
741 // memory since these spill to VGPRs. We should be cleaning up these unused
742 // SGPR spill frame indices somewhere.
743
744 // FIXME: We still have implicit uses on SGPR spill instructions in case they
745 // need to spill to vector memory. It's likely that will not happen, but at
746 // this point it appears we need the setup. This part of the prolog should be
747 // emitted after frame indices are eliminated.
748
749 // FIXME: Remove all of the isPhysRegUsed checks
750
752 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
753 const SIInstrInfo *TII = ST.getInstrInfo();
754 const SIRegisterInfo *TRI = &TII->getRegisterInfo();
756 const Function &F = MF.getFunction();
757 MachineFrameInfo &FrameInfo = MF.getFrameInfo();
758
759 assert(MFI->isEntryFunction());
760
761 // Debug location must be unknown since the first debug location is used to
762 // determine the end of the prologue.
763 DebugLoc DL;
765
766 if (MF.needsFrameMoves()) {
767 // On entry the SP/FP are not set up, so we need to define the CFA in terms
768 // of a literal location expression.
769 static const char CFAEncodedInstUserOpsArr[] = {
770 dwarf::DW_CFA_def_cfa_expression,
771 4, // length
772 static_cast<char>(dwarf::DW_OP_lit0),
773 static_cast<char>(dwarf::DW_OP_lit0 +
774 dwarf::DW_ASPACE_LLVM_AMDGPU_private_wave),
775 static_cast<char>(dwarf::DW_OP_LLVM_user),
776 static_cast<char>(dwarf::DW_OP_LLVM_form_aspace_address)};
777 static StringRef CFAEncodedInstUserOps =
778 StringRef(CFAEncodedInstUserOpsArr, sizeof(CFAEncodedInstUserOpsArr));
779 buildCFI(MBB, I, DL,
780 MCCFIInstruction::createEscape(nullptr, CFAEncodedInstUserOps,
781 SMLoc(),
782 "CFA is 0 in private_wave aspace"));
783 // Unwinding halts when the return address (PC) is undefined.
784 buildCFI(MBB, I, DL,
786 nullptr, TRI->getDwarfRegNum(AMDGPU::PC_REG, false)));
787 }
788
789 Register PreloadedScratchWaveOffsetReg = MFI->getPreloadedReg(
791
792 // We need to do the replacement of the private segment buffer register even
793 // if there are no stack objects. There could be stores to undef or a
794 // constant without an associated object.
795 //
796 // This will return `Register()` in cases where there are no actual
797 // uses of the SRSRC.
798 Register ScratchRsrcReg;
799 if (!ST.hasFlatScratchEnabled())
800 ScratchRsrcReg = getEntryFunctionReservedScratchRsrcReg(MF);
801
802 // Make the selected register live throughout the function.
803 if (ScratchRsrcReg) {
804 for (MachineBasicBlock &OtherBB : MF) {
805 if (&OtherBB != &MBB) {
806 OtherBB.addLiveIn(ScratchRsrcReg);
807 }
808 }
809 }
810
811 // Now that we have fixed the reserved SRSRC we need to locate the
812 // (potentially) preloaded SRSRC.
813 Register PreloadedScratchRsrcReg;
814 if (ST.isAmdHsaOrMesa(F)) {
815 PreloadedScratchRsrcReg =
817 if (ScratchRsrcReg && PreloadedScratchRsrcReg) {
818 // We added live-ins during argument lowering, but since they were not
819 // used they were deleted. We're adding the uses now, so add them back.
820 MRI.addLiveIn(PreloadedScratchRsrcReg);
821 MBB.addLiveIn(PreloadedScratchRsrcReg);
822 }
823 }
824
825 // We found the SRSRC first because it needs four registers and has an
826 // alignment requirement. If the SRSRC that we found is clobbering with
827 // the scratch wave offset, which may be in a fixed SGPR or a free SGPR
828 // chosen by SITargetLowering::allocateSystemSGPRs, COPY the scratch
829 // wave offset to a free SGPR.
830 Register ScratchWaveOffsetReg;
831 if (PreloadedScratchWaveOffsetReg &&
832 TRI->isSubRegisterEq(ScratchRsrcReg, PreloadedScratchWaveOffsetReg)) {
833 ArrayRef<MCPhysReg> AllSGPRs = TRI->getAllSGPR32(MF);
834 unsigned NumPreloaded = MFI->getNumPreloadedSGPRs();
835 AllSGPRs = AllSGPRs.slice(
836 std::min(static_cast<unsigned>(AllSGPRs.size()), NumPreloaded));
837 Register GITPtrLoReg = MFI->getGITPtrLoReg(MF);
838 for (MCPhysReg Reg : AllSGPRs) {
839 if (!MRI.isPhysRegUsed(Reg) && MRI.isAllocatable(Reg) &&
840 !TRI->isSubRegisterEq(ScratchRsrcReg, Reg) && GITPtrLoReg != Reg) {
841 ScratchWaveOffsetReg = Reg;
842 BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), ScratchWaveOffsetReg)
843 .addReg(PreloadedScratchWaveOffsetReg, RegState::Kill);
844 break;
845 }
846 }
847
848 // FIXME: We can spill incoming arguments and restore at the end of the
849 // prolog.
850 if (!ScratchWaveOffsetReg)
852 "could not find temporary scratch offset register in prolog");
853 } else {
854 ScratchWaveOffsetReg = PreloadedScratchWaveOffsetReg;
855 }
856 assert(ScratchWaveOffsetReg || !PreloadedScratchWaveOffsetReg);
857
858 unsigned Offset = FrameInfo.getStackSize() * getScratchScaleFactor(ST);
859 if (!mayReserveScratchForCWSR(MF)) {
860 if (hasFP(MF)) {
862 assert(FPReg != AMDGPU::FP_REG);
863 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), FPReg).addImm(0);
864 }
865
868 assert(SPReg != AMDGPU::SP_REG);
869 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), SPReg).addImm(Offset);
870 }
871 } else {
872 // We need to check if we're on a compute queue - if we are, then the CWSR
873 // trap handler may need to store some VGPRs on the stack. The first VGPR
874 // block is saved separately, so we only need to allocate space for any
875 // additional VGPR blocks used. For now, we will make sure there's enough
876 // room for the theoretical maximum number of VGPRs that can be allocated.
877 // FIXME: Figure out if the shader uses fewer VGPRs in practice.
878 assert(hasFP(MF));
880 assert(FPReg != AMDGPU::FP_REG);
881 unsigned VGPRSize = llvm::alignTo(
882 (ST.getAddressableNumVGPRs(MFI->getDynamicVGPRBlockSize()) -
884 MFI->getDynamicVGPRBlockSize())) *
885 4,
886 FrameInfo.getMaxAlign());
888
889 BuildMI(MBB, I, DL, TII->get(AMDGPU::GET_STACK_BASE), FPReg);
892 assert(SPReg != AMDGPU::SP_REG);
893
894 // If at least one of the constants can be inlined, then we can use
895 // s_cselect. Otherwise, use a mov and cmovk.
896 if (AMDGPU::isInlinableLiteral32(Offset, ST.hasInv2PiInlineImm()) ||
898 ST.hasInv2PiInlineImm())) {
899 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_CSELECT_B32), SPReg)
900 .addImm(Offset + VGPRSize)
901 .addImm(Offset);
902 } else {
903 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), SPReg).addImm(Offset);
904 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_CMOVK_I32), SPReg)
905 .addImm(Offset + VGPRSize);
906 }
907 }
908 }
909
910 bool NeedsFlatScratchInit =
912 (MRI.isPhysRegUsed(AMDGPU::FLAT_SCR) || FrameInfo.hasCalls() ||
913 (!allStackObjectsAreDead(FrameInfo) && ST.hasFlatScratchEnabled()));
914
915 if ((NeedsFlatScratchInit || ScratchRsrcReg) &&
916 PreloadedScratchWaveOffsetReg && !ST.hasArchitectedFlatScratch()) {
917 MRI.addLiveIn(PreloadedScratchWaveOffsetReg);
918 MBB.addLiveIn(PreloadedScratchWaveOffsetReg);
919 }
920
921 if (NeedsFlatScratchInit) {
922 emitEntryFunctionFlatScratchInit(MF, MBB, I, DL, ScratchWaveOffsetReg);
923 }
924
925 if (ScratchRsrcReg) {
926 emitEntryFunctionScratchRsrcRegSetup(MF, MBB, I, DL,
927 PreloadedScratchRsrcReg,
928 ScratchRsrcReg, ScratchWaveOffsetReg);
929 }
930}
931
932// Emit scratch RSRC setup code, assuming `ScratchRsrcReg != AMDGPU::NoReg`
933void SIFrameLowering::emitEntryFunctionScratchRsrcRegSetup(
935 const DebugLoc &DL, Register PreloadedScratchRsrcReg,
936 Register ScratchRsrcReg, Register ScratchWaveOffsetReg) const {
937
938 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
939 const SIInstrInfo *TII = ST.getInstrInfo();
940 const SIRegisterInfo *TRI = &TII->getRegisterInfo();
942 const Function &Fn = MF.getFunction();
943
944 if (ST.isAmdPalOS()) {
945 // The pointer to the GIT is formed from the offset passed in and either
946 // the amdgpu-git-ptr-high function attribute or the top part of the PC
947 Register Rsrc01 = TRI->getSubReg(ScratchRsrcReg, AMDGPU::sub0_sub1);
948 Register Rsrc03 = TRI->getSubReg(ScratchRsrcReg, AMDGPU::sub3);
949
950 buildGitPtr(MBB, I, DL, TII, Rsrc01);
951
952 // We now have the GIT ptr - now get the scratch descriptor from the entry
953 // at offset 0 (or offset 16 for a compute shader).
955 const MCInstrDesc &LoadDwordX4 = TII->get(AMDGPU::S_LOAD_DWORDX4_IMM);
956 auto *MMO = MF.getMachineMemOperand(
957 PtrInfo,
960 16, Align(4));
961 unsigned Offset = Fn.getCallingConv() == CallingConv::AMDGPU_CS ? 16 : 0;
962 const GCNSubtarget &Subtarget = MF.getSubtarget<GCNSubtarget>();
963 unsigned EncodedOffset = AMDGPU::convertSMRDOffsetUnits(Subtarget, Offset);
964 BuildMI(MBB, I, DL, LoadDwordX4, ScratchRsrcReg)
965 .addReg(Rsrc01)
966 .addImm(EncodedOffset) // offset
967 .addImm(0) // cpol
968 .addReg(ScratchRsrcReg, RegState::ImplicitDefine)
969 .addMemOperand(MMO);
970
971 // The driver will always set the SRD for wave 64 (bits 118:117 of
972 // descriptor / bits 22:21 of third sub-reg will be 0b11)
973 // If the shader is actually wave32 we have to modify the const_index_stride
974 // field of the descriptor 3rd sub-reg (bits 22:21) to 0b10 (stride=32). The
975 // reason the driver does this is that there can be cases where it presents
976 // 2 shaders with different wave size (e.g. VsFs).
977 // TODO: convert to using SCRATCH instructions or multiple SRD buffers
978 if (ST.isWave32()) {
979 const MCInstrDesc &SBitsetB32 = TII->get(AMDGPU::S_BITSET0_B32);
980 BuildMI(MBB, I, DL, SBitsetB32, Rsrc03)
981 .addImm(21)
982 .addReg(Rsrc03);
983 }
984 } else if (ST.isMesaGfxShader(Fn) || !PreloadedScratchRsrcReg) {
985 assert(!ST.isAmdHsaOrMesa(Fn));
986 const MCInstrDesc &SMovB32 = TII->get(AMDGPU::S_MOV_B32);
987
988 Register Rsrc2 = TRI->getSubReg(ScratchRsrcReg, AMDGPU::sub2);
989 Register Rsrc3 = TRI->getSubReg(ScratchRsrcReg, AMDGPU::sub3);
990
991 // Use relocations to get the pointer, and setup the other bits manually.
992 uint64_t Rsrc23 = TII->getScratchRsrcWords23();
993
995 Register Rsrc01 = TRI->getSubReg(ScratchRsrcReg, AMDGPU::sub0_sub1);
996
998 const MCInstrDesc &Mov64 = TII->get(AMDGPU::S_MOV_B64);
999
1000 BuildMI(MBB, I, DL, Mov64, Rsrc01)
1002 .addReg(ScratchRsrcReg, RegState::ImplicitDefine);
1003 } else {
1004 const MCInstrDesc &LoadDwordX2 = TII->get(AMDGPU::S_LOAD_DWORDX2_IMM);
1005
1006 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1007 auto *MMO = MF.getMachineMemOperand(
1008 PtrInfo,
1011 8, Align(4));
1012 BuildMI(MBB, I, DL, LoadDwordX2, Rsrc01)
1014 .addImm(0) // offset
1015 .addImm(0) // cpol
1016 .addMemOperand(MMO)
1017 .addReg(ScratchRsrcReg, RegState::ImplicitDefine);
1018 }
1019
1022 } else {
1023 Register Rsrc0 = TRI->getSubReg(ScratchRsrcReg, AMDGPU::sub0);
1024 Register Rsrc1 = TRI->getSubReg(ScratchRsrcReg, AMDGPU::sub1);
1025
1026 BuildMI(MBB, I, DL, SMovB32, Rsrc0)
1027 .addExternalSymbol("SCRATCH_RSRC_DWORD0")
1028 .addReg(ScratchRsrcReg, RegState::ImplicitDefine);
1029
1030 BuildMI(MBB, I, DL, SMovB32, Rsrc1)
1031 .addExternalSymbol("SCRATCH_RSRC_DWORD1")
1032 .addReg(ScratchRsrcReg, RegState::ImplicitDefine);
1033 }
1034
1035 BuildMI(MBB, I, DL, SMovB32, Rsrc2)
1036 .addImm(Lo_32(Rsrc23))
1037 .addReg(ScratchRsrcReg, RegState::ImplicitDefine);
1038
1039 BuildMI(MBB, I, DL, SMovB32, Rsrc3)
1040 .addImm(Hi_32(Rsrc23))
1041 .addReg(ScratchRsrcReg, RegState::ImplicitDefine);
1042 } else if (ST.isAmdHsaOrMesa(Fn)) {
1043 assert(PreloadedScratchRsrcReg);
1044
1045 if (ScratchRsrcReg != PreloadedScratchRsrcReg) {
1046 BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), ScratchRsrcReg)
1047 .addReg(PreloadedScratchRsrcReg, RegState::Kill);
1048 }
1049 }
1050
1051 // Add the scratch wave offset into the scratch RSRC.
1052 //
1053 // We only want to update the first 48 bits, which is the base address
1054 // pointer, without touching the adjacent 16 bits of flags. We know this add
1055 // cannot carry-out from bit 47, otherwise the scratch allocation would be
1056 // impossible to fit in the 48-bit global address space.
1057 //
1058 // TODO: Evaluate if it is better to just construct an SRD using the flat
1059 // scratch init and some constants rather than update the one we are passed.
1060 Register ScratchRsrcSub0 = TRI->getSubReg(ScratchRsrcReg, AMDGPU::sub0);
1061 Register ScratchRsrcSub1 = TRI->getSubReg(ScratchRsrcReg, AMDGPU::sub1);
1062
1063 // We cannot Kill ScratchWaveOffsetReg here because we allow it to be used in
1064 // the kernel body via inreg arguments.
1065 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_ADD_U32), ScratchRsrcSub0)
1066 .addReg(ScratchRsrcSub0)
1067 .addReg(ScratchWaveOffsetReg)
1068 .addReg(ScratchRsrcReg, RegState::ImplicitDefine);
1069 auto Addc = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_ADDC_U32), ScratchRsrcSub1)
1070 .addReg(ScratchRsrcSub1)
1071 .addImm(0)
1072 .addReg(ScratchRsrcReg, RegState::ImplicitDefine);
1073 Addc->getOperand(3).setIsDead(); // Mark SCC as dead.
1074}
1075
1077 switch (ID) {
1081 return true;
1086 return false;
1087 }
1088 llvm_unreachable("Invalid TargetStackID::Value");
1089}
1090
1091void SIFrameLowering::emitPrologueEntryCFI(MachineBasicBlock &MBB,
1093 const DebugLoc &DL) const {
1094 const MachineFunction &MF = *MBB.getParent();
1095 const MachineRegisterInfo &MRI = MF.getRegInfo();
1096 const MCRegisterInfo *MCRI = MF.getContext().getRegisterInfo();
1097 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1098 const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo();
1099 MCRegister StackPtrReg =
1100 MF.getInfo<SIMachineFunctionInfo>()->getStackPtrOffsetReg();
1101
1102 emitDefCFA(MBB, MBBI, DL, StackPtrReg, /*AspaceAlreadyDefined=*/true,
1104
1105 buildCFIForSRegToSRegSpill(MBB, MBBI, DL, AMDGPU::PC_REG,
1106 TRI.getReturnAddressReg(MF));
1107
1108 BitVector IsCalleeSaved(TRI.getNumRegs());
1109 const MCPhysReg *CSRegs = MRI.getCalleeSavedRegs();
1110 for (unsigned I = 0; CSRegs[I]; ++I) {
1111 IsCalleeSaved.set(CSRegs[I]);
1112 }
1113 auto ProcessReg = [&](MCPhysReg Reg) {
1114 // VCC is not preserved across calls.
1115 if (Reg == AMDGPU::VCC || Reg == AMDGPU::VCC_LO || Reg == AMDGPU::VCC_HI)
1116 return;
1117 if (IsCalleeSaved.test(Reg) || !MRI.isPhysRegModified(Reg))
1118 return;
1119 unsigned DwarfReg = MCRI->getDwarfRegNum(Reg, false);
1120 buildCFI(MBB, MBBI, DL,
1121 MCCFIInstruction::createUndefined(nullptr, DwarfReg));
1122 };
1123
1124 // Emit CFI rules for caller saved Arch VGPRs which are clobbered
1125 unsigned NumArchVGPRs = ST.hasVGPRMSBs() ? 1024 : 256;
1126 for_each(AMDGPU::VGPR_32RegClass.getRegisters().take_front(NumArchVGPRs),
1127 ProcessReg);
1128
1129 // Emit CFI rules for caller saved Accum VGPRs which are clobbered
1130 if (ST.hasMAIInsts()) {
1131 for_each(AMDGPU::AGPR_32RegClass.getRegisters(), ProcessReg);
1132 }
1133
1134 // Emit CFI rules for caller saved SGPRs which are clobbered
1135 for_each(AMDGPU::SGPR_32RegClass.getRegisters(), ProcessReg);
1136}
1137
1138// Activate only the inactive lanes when \p EnableInactiveLanes is true.
1139// Otherwise, activate all lanes. It returns the saved exec.
1141 MachineFunction &MF,
1144 const DebugLoc &DL, bool IsProlog,
1145 bool EnableInactiveLanes) {
1146 Register ScratchExecCopy;
1148 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1149 const SIInstrInfo *TII = ST.getInstrInfo();
1150 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1152
1153 initLiveUnits(LiveUnits, TRI, FuncInfo, MF, MBB, MBBI, IsProlog);
1154
1155 if (FuncInfo->isWholeWaveFunction()) {
1156 // Whole wave functions already have a copy of the original EXEC mask that
1157 // we can use.
1158 assert(IsProlog && "Epilog should look at return, not setup");
1159 ScratchExecCopy =
1160 TII->getWholeWaveFunctionSetup(MF)->getOperand(0).getReg();
1161 assert(ScratchExecCopy && "Couldn't find copy of EXEC");
1162 } else {
1163 ScratchExecCopy = findScratchNonCalleeSaveRegister(
1164 MRI, LiveUnits, *TRI.getWaveMaskRegClass());
1165 }
1166
1167 if (!ScratchExecCopy)
1168 report_fatal_error("failed to find free scratch register");
1169
1170 LiveUnits.addReg(ScratchExecCopy);
1171
1172 const unsigned SaveExecOpc =
1173 ST.isWave32() ? (EnableInactiveLanes ? AMDGPU::S_XOR_SAVEEXEC_B32
1174 : AMDGPU::S_OR_SAVEEXEC_B32)
1175 : (EnableInactiveLanes ? AMDGPU::S_XOR_SAVEEXEC_B64
1176 : AMDGPU::S_OR_SAVEEXEC_B64);
1177 auto SaveExec =
1178 BuildMI(MBB, MBBI, DL, TII->get(SaveExecOpc), ScratchExecCopy).addImm(-1);
1179 SaveExec->getOperand(3).setIsDead(); // Mark SCC as dead.
1180
1181 return ScratchExecCopy;
1182}
1183
1187 LiveRegUnits &LiveUnits, Register FrameReg, Register FramePtrRegScratchCopy,
1188 const bool NeedsFrameMoves) const {
1190 MachineFrameInfo &MFI = MF.getFrameInfo();
1191 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1192 const SIInstrInfo *TII = ST.getInstrInfo();
1193 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1194 const MCRegisterInfo *MCRI = MF.getContext().getRegisterInfo();
1197
1198 // Spill Whole-Wave Mode VGPRs. Save only the inactive lanes of the scratch
1199 // registers. However, save all lanes of callee-saved VGPRs. Due to this, we
1200 // might end up flipping the EXEC bits twice.
1201 Register ScratchExecCopy;
1202 SmallVector<std::pair<Register, int>, 2> WWMCalleeSavedRegs, WWMScratchRegs;
1203 FuncInfo->splitWWMSpillRegisters(MF, WWMCalleeSavedRegs, WWMScratchRegs);
1204 if (!WWMScratchRegs.empty())
1205 ScratchExecCopy =
1206 buildScratchExecCopy(LiveUnits, MF, MBB, MBBI, DL,
1207 /*IsProlog*/ true, /*EnableInactiveLanes*/ true);
1208
1209 auto StoreWWMRegisters =
1211 for (const auto &Reg : WWMRegs) {
1212 Register VGPR = Reg.first;
1213 int FI = Reg.second;
1214 buildPrologSpill(ST, TRI, *FuncInfo, LiveUnits, MF, MBB, MBBI, DL,
1215 VGPR, FI, FrameReg);
1216 if (NeedsFrameMoves) {
1217 // We spill the entire VGPR, so we can get away with just cfi_offset
1218 buildCFI(MBB, MBBI, DL,
1220 nullptr, MCRI->getDwarfRegNum(VGPR, false),
1221 MFI.getObjectOffset(FI) * ST.getWavefrontSize()));
1222 }
1223 }
1224 };
1225
1226 for (const Register Reg : make_first_range(WWMScratchRegs)) {
1227 if (!MRI.isReserved(Reg)) {
1228 MRI.addLiveIn(Reg);
1229 MBB.addLiveIn(Reg);
1230 }
1231 }
1232 StoreWWMRegisters(WWMScratchRegs);
1233
1234 auto EnableAllLanes = [&]() {
1235 BuildMI(MBB, MBBI, DL, TII->get(LMC.MovOpc), LMC.ExecReg).addImm(-1);
1236 };
1237
1238 if (!WWMCalleeSavedRegs.empty()) {
1239 if (ScratchExecCopy) {
1240 EnableAllLanes();
1241 } else {
1242 ScratchExecCopy = buildScratchExecCopy(LiveUnits, MF, MBB, MBBI, DL,
1243 /*IsProlog*/ true,
1244 /*EnableInactiveLanes*/ false);
1245 }
1246 }
1247
1248 StoreWWMRegisters(WWMCalleeSavedRegs);
1249 if (FuncInfo->isWholeWaveFunction()) {
1250 // If we have already saved some WWM CSR registers, then the EXEC is already
1251 // -1 and we don't need to do anything else. Otherwise, save the original
1252 // EXEC into the setup register and set EXEC to -1 here.
1253 if (!ScratchExecCopy)
1254 buildScratchExecCopy(LiveUnits, MF, MBB, MBBI, DL, /*IsProlog*/ true,
1255 /*EnableInactiveLanes*/ false);
1256 else if (WWMCalleeSavedRegs.empty())
1257 EnableAllLanes();
1258 } else if (ScratchExecCopy) {
1259 // FIXME: Split block and make terminator.
1260 BuildMI(MBB, MBBI, DL, TII->get(LMC.MovOpc), LMC.ExecReg)
1261 .addReg(ScratchExecCopy, RegState::Kill);
1262 LiveUnits.addReg(ScratchExecCopy);
1263 }
1264
1265 Register FramePtrReg = FuncInfo->getFrameOffsetReg();
1266
1267 for (const auto &Spill : FuncInfo->getPrologEpilogSGPRSpills()) {
1268 // Special handle FP spill:
1269 // Skip if FP is saved to a scratch SGPR, the save has already been emitted.
1270 // Otherwise, FP has been moved to a temporary register and spill it
1271 // instead.
1272 bool IsFramePtrPrologSpill = Spill.first == FramePtrReg;
1273 Register Reg = IsFramePtrPrologSpill ? FramePtrRegScratchCopy : Spill.first;
1274 if (!Reg)
1275 continue;
1276
1277 PrologEpilogSGPRSpillBuilder SB(Reg, Spill.second, MBB, MBBI, DL, TII, TRI,
1278 LiveUnits, FrameReg, IsFramePtrPrologSpill);
1279 SB.save();
1280 }
1281
1282 // If a copy to scratch SGPR has been chosen for any of the SGPR spills, make
1283 // such scratch registers live throughout the function.
1284 SmallVector<Register, 1> ScratchSGPRs;
1285 FuncInfo->getAllScratchSGPRCopyDstRegs(ScratchSGPRs);
1286 if (!ScratchSGPRs.empty()) {
1287 for (MachineBasicBlock &MBB : MF) {
1288 for (MCPhysReg Reg : ScratchSGPRs)
1289 MBB.addLiveIn(Reg);
1290
1291 MBB.sortUniqueLiveIns();
1292 }
1293 if (!LiveUnits.empty()) {
1294 for (MCPhysReg Reg : ScratchSGPRs)
1295 LiveUnits.addReg(Reg);
1296 }
1297 }
1298
1299 // Remove the spill entry created for EXEC. It is needed only for CFISaves in
1300 // the prologue.
1301 if (TRI.isCFISavedRegsSpillEnabled())
1302 FuncInfo->removePrologEpilogSGPRSpillEntry(TRI.getExec());
1303}
1304
1308 LiveRegUnits &LiveUnits, Register FrameReg,
1309 Register FramePtrRegScratchCopy) const {
1310 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
1311 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1312 const SIInstrInfo *TII = ST.getInstrInfo();
1313 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1315 Register FramePtrReg = FuncInfo->getFrameOffsetReg();
1316
1317 for (const auto &Spill : FuncInfo->getPrologEpilogSGPRSpills()) {
1318 // Special handle FP restore:
1319 // Skip if FP needs to be restored from the scratch SGPR. Otherwise, restore
1320 // the FP value to a temporary register. The frame pointer should be
1321 // overwritten only at the end when all other spills are restored from
1322 // current frame.
1323 Register Reg =
1324 Spill.first == FramePtrReg ? FramePtrRegScratchCopy : Spill.first;
1325 if (!Reg)
1326 continue;
1327
1328 PrologEpilogSGPRSpillBuilder SB(Reg, Spill.second, MBB, MBBI, DL, TII, TRI,
1329 LiveUnits, FrameReg);
1330 SB.restore();
1331 }
1332
1333 // Restore Whole-Wave Mode VGPRs. Restore only the inactive lanes of the
1334 // scratch registers. However, restore all lanes of callee-saved VGPRs. Due to
1335 // this, we might end up flipping the EXEC bits twice.
1336 Register ScratchExecCopy;
1337 SmallVector<std::pair<Register, int>, 2> WWMCalleeSavedRegs, WWMScratchRegs;
1338 FuncInfo->splitWWMSpillRegisters(MF, WWMCalleeSavedRegs, WWMScratchRegs);
1339 auto RestoreWWMRegisters =
1341 for (const auto &Reg : WWMRegs) {
1342 Register VGPR = Reg.first;
1343 int FI = Reg.second;
1344 buildEpilogRestore(ST, TRI, *FuncInfo, LiveUnits, MF, MBB, MBBI, DL,
1345 VGPR, FI, FrameReg);
1346 }
1347 };
1348
1349 if (FuncInfo->isWholeWaveFunction()) {
1350 // For whole wave functions, the EXEC is already -1 at this point.
1351 // Therefore, we can restore the CSR WWM registers right away.
1352 RestoreWWMRegisters(WWMCalleeSavedRegs);
1353
1354 // The original EXEC is the first operand of the return instruction.
1355 MachineInstr &Return = MBB.instr_back();
1356 unsigned Opcode = Return.getOpcode();
1357 switch (Opcode) {
1358 case AMDGPU::SI_WHOLE_WAVE_FUNC_RETURN:
1359 Opcode = AMDGPU::SI_RETURN;
1360 break;
1361 case AMDGPU::SI_TCRETURN_GFX_WholeWave:
1362 Opcode = AMDGPU::SI_TCRETURN_GFX;
1363 break;
1364 default:
1365 llvm_unreachable("Unexpected return inst");
1366 }
1367 Register OrigExec = Return.getOperand(0).getReg();
1368
1369 if (!WWMScratchRegs.empty()) {
1370 BuildMI(MBB, MBBI, DL, TII->get(LMC.XorOpc), LMC.ExecReg)
1371 .addReg(OrigExec)
1372 .addImm(-1);
1373 RestoreWWMRegisters(WWMScratchRegs);
1374 }
1375
1376 // Restore original EXEC.
1377 BuildMI(MBB, MBBI, DL, TII->get(LMC.MovOpc), LMC.ExecReg).addReg(OrigExec);
1378
1379 // Drop the first operand and update the opcode.
1380 Return.removeOperand(0);
1381 Return.setDesc(TII->get(Opcode));
1382
1383 return;
1384 }
1385
1386 if (!WWMScratchRegs.empty()) {
1387 ScratchExecCopy =
1388 buildScratchExecCopy(LiveUnits, MF, MBB, MBBI, DL,
1389 /*IsProlog=*/false, /*EnableInactiveLanes=*/true);
1390 }
1391 RestoreWWMRegisters(WWMScratchRegs);
1392 if (!WWMCalleeSavedRegs.empty()) {
1393 if (ScratchExecCopy) {
1394 BuildMI(MBB, MBBI, DL, TII->get(LMC.MovOpc), LMC.ExecReg).addImm(-1);
1395 } else {
1396 ScratchExecCopy = buildScratchExecCopy(LiveUnits, MF, MBB, MBBI, DL,
1397 /*IsProlog*/ false,
1398 /*EnableInactiveLanes*/ false);
1399 }
1400 }
1401
1402 RestoreWWMRegisters(WWMCalleeSavedRegs);
1403 if (ScratchExecCopy) {
1404 // FIXME: Split block and make terminator.
1405 BuildMI(MBB, MBBI, DL, TII->get(LMC.MovOpc), LMC.ExecReg)
1406 .addReg(ScratchExecCopy, RegState::Kill);
1407 }
1408}
1409
1411 MachineBasicBlock &MBB) const {
1413 if (FuncInfo->isEntryFunction()) {
1415 return;
1416 }
1417
1418 MachineFrameInfo &MFI = MF.getFrameInfo();
1419 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1420 const SIInstrInfo *TII = ST.getInstrInfo();
1421 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1423
1424 Register StackPtrReg = FuncInfo->getStackPtrOffsetReg();
1425 Register FramePtrReg = FuncInfo->getFrameOffsetReg();
1426 Register BasePtrReg =
1427 TRI.hasBasePointer(MF) ? TRI.getBaseRegister() : Register();
1428 LiveRegUnits LiveUnits;
1429
1431 // DebugLoc must be unknown since the first instruction with DebugLoc is used
1432 // to determine the end of the prologue.
1433 DebugLoc DL;
1434
1435 bool HasFP = false;
1436 bool HasBP = false;
1437 int64_t NumBytes = MFI.getStackSize();
1438 int64_t RoundedSize = NumBytes;
1439
1440 // Functions that never return don't need to save and restore the FP or BP.
1441 const Function &F = MF.getFunction();
1442 bool SavesStackRegs =
1443 !F.hasFnAttribute(Attribute::NoReturn) && !FuncInfo->isChainFunction();
1444
1445 const bool NeedsFrameMoves = MF.needsFrameMoves();
1446
1447 if (NeedsFrameMoves)
1448 emitPrologueEntryCFI(MBB, MBBI, DL);
1449
1450 if (TRI.hasStackRealignment(MF))
1451 HasFP = true;
1452
1453 Register FramePtrRegScratchCopy;
1454 if (!HasFP && !hasFP(MF)) {
1455 // Emit the CSR spill stores with SP base register.
1456 emitCSRSpillStores(MF, MBB, MBBI, DL, LiveUnits, StackPtrReg,
1457 FramePtrRegScratchCopy, NeedsFrameMoves);
1458 } else if (SavesStackRegs) {
1459 // CSR spill stores will use FP as base register.
1460 Register SGPRForFPSaveRestoreCopy =
1461 FuncInfo->getScratchSGPRCopyDstReg(FramePtrReg);
1462
1463 initLiveUnits(LiveUnits, TRI, FuncInfo, MF, MBB, MBBI, /*IsProlog*/ true);
1464 if (SGPRForFPSaveRestoreCopy) {
1465 // Copy FP to the scratch register now and emit the CFI entry. It avoids
1466 // the extra FP copy needed in the other two cases when FP is spilled to
1467 // memory or to a VGPR lane.
1469 FramePtrReg,
1470 FuncInfo->getPrologEpilogSGPRSaveRestoreInfo(FramePtrReg), MBB, MBBI,
1471 DL, TII, TRI, LiveUnits, FramePtrReg,
1472 /*IsFramePtrPrologSpill*/ true);
1473 SB.save();
1474 LiveUnits.addReg(SGPRForFPSaveRestoreCopy);
1475 } else {
1476 // Copy FP into a new scratch register so that its previous value can be
1477 // spilled after setting up the new frame.
1478 FramePtrRegScratchCopy = findScratchNonCalleeSaveRegister(
1479 MRI, LiveUnits, AMDGPU::SReg_32_XM0_XEXECRegClass);
1480 if (!FramePtrRegScratchCopy)
1481 report_fatal_error("failed to find free scratch register");
1482
1483 LiveUnits.addReg(FramePtrRegScratchCopy);
1484 BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::COPY), FramePtrRegScratchCopy)
1485 .addReg(FramePtrReg);
1486 }
1487 }
1488
1489 if (HasFP) {
1490 const unsigned Alignment = MFI.getMaxAlign().value();
1491
1492 RoundedSize += Alignment;
1493 if (LiveUnits.empty()) {
1494 LiveUnits.init(TRI);
1495 LiveUnits.addLiveIns(MBB);
1496 }
1497
1498 // s_add_i32 s33, s32, NumBytes
1499 // s_and_b32 s33, s33, 0b111...0000
1500 BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::S_ADD_I32), FramePtrReg)
1501 .addReg(StackPtrReg)
1502 .addImm((Alignment - 1) * getScratchScaleFactor(ST))
1504 auto And = BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::S_AND_B32), FramePtrReg)
1505 .addReg(FramePtrReg, RegState::Kill)
1506 .addImm(-Alignment * getScratchScaleFactor(ST))
1508 And->getOperand(3).setIsDead(); // Mark SCC as dead.
1509 FuncInfo->setIsStackRealigned(true);
1510 } else if ((HasFP = hasFP(MF))) {
1511 BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::COPY), FramePtrReg)
1512 .addReg(StackPtrReg)
1514 }
1515
1516 // If FP is used, emit the CSR spills with FP base register.
1517 if (HasFP) {
1518 emitCSRSpillStores(MF, MBB, MBBI, DL, LiveUnits, FramePtrReg,
1519 FramePtrRegScratchCopy, NeedsFrameMoves);
1520 if (FramePtrRegScratchCopy)
1521 LiveUnits.removeReg(FramePtrRegScratchCopy);
1522 }
1523
1524 // If we need a base pointer, set it up here. It's whatever the value of
1525 // the stack pointer is at this point. Any variable size objects will be
1526 // allocated after this, so we can still use the base pointer to reference
1527 // the incoming arguments.
1528 if ((HasBP = TRI.hasBasePointer(MF))) {
1529 BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::COPY), BasePtrReg)
1530 .addReg(StackPtrReg)
1532 }
1533
1534 if (HasFP) {
1535 if (NeedsFrameMoves)
1536 emitDefCFA(MBB, MBBI, DL, FramePtrReg, /*AspaceAlreadyDefined=*/false,
1538 }
1539
1540 if (HasFP && RoundedSize != 0) {
1541 auto Add = BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::S_ADD_I32), StackPtrReg)
1542 .addReg(StackPtrReg)
1543 .addImm(RoundedSize * getScratchScaleFactor(ST))
1545 Add->getOperand(3).setIsDead(); // Mark SCC as dead.
1546 }
1547
1548 bool FPSaved = FuncInfo->hasPrologEpilogSGPRSpillEntry(FramePtrReg);
1549 (void)FPSaved;
1550 assert((!HasFP || FPSaved || !SavesStackRegs) &&
1551 "Needed to save FP but didn't save it anywhere");
1552
1553 // If we allow spilling to AGPRs we may have saved FP but then spill
1554 // everything into AGPRs instead of the stack.
1555 assert((HasFP || !FPSaved || !SavesStackRegs || EnableSpillVGPRToAGPR) &&
1556 "Saved FP but didn't need it");
1557
1558 bool BPSaved = FuncInfo->hasPrologEpilogSGPRSpillEntry(BasePtrReg);
1559 (void)BPSaved;
1560 assert((!HasBP || BPSaved || !SavesStackRegs) &&
1561 "Needed to save BP but didn't save it anywhere");
1562
1563 assert((HasBP || !BPSaved) && "Saved BP but didn't need it");
1564
1565 if (FuncInfo->isWholeWaveFunction()) {
1566 // SI_WHOLE_WAVE_FUNC_SETUP has outlived its purpose.
1567 TII->getWholeWaveFunctionSetup(MF)->eraseFromParent();
1568 }
1569}
1570
1572 MachineBasicBlock &MBB) const {
1573 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
1574 if (FuncInfo->isEntryFunction())
1575 return;
1576
1577 const MachineFrameInfo &MFI = MF.getFrameInfo();
1578 if (FuncInfo->isChainFunction() && !MFI.hasTailCall())
1579 return;
1580
1581 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1582 const SIInstrInfo *TII = ST.getInstrInfo();
1583 const SIRegisterInfo &TRI = TII->getRegisterInfo();
1585 LiveRegUnits LiveUnits;
1586 // Get the insert location for the epilogue. If there were no terminators in
1587 // the block, get the last instruction.
1589 DebugLoc DL;
1590 if (!MBB.empty()) {
1591 MBBI = MBB.getLastNonDebugInstr();
1592 if (MBBI != MBB.end())
1593 DL = MBBI->getDebugLoc();
1594
1595 MBBI = MBB.getFirstTerminator();
1596 }
1597
1598 uint32_t NumBytes = MFI.getStackSize();
1599 uint32_t RoundedSize = FuncInfo->isStackRealigned()
1600 ? NumBytes + MFI.getMaxAlign().value()
1601 : NumBytes;
1602 const Register StackPtrReg = FuncInfo->getStackPtrOffsetReg();
1603 Register FramePtrReg = FuncInfo->getFrameOffsetReg();
1604 bool FPSaved = FuncInfo->hasPrologEpilogSGPRSpillEntry(FramePtrReg);
1605
1606 if (RoundedSize != 0) {
1607 if (TRI.hasBasePointer(MF)) {
1608 BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::COPY), StackPtrReg)
1609 .addReg(TRI.getBaseRegister())
1611 } else if (hasFP(MF)) {
1612 BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::COPY), StackPtrReg)
1613 .addReg(FramePtrReg)
1615 }
1616 }
1617
1618 Register FramePtrRegScratchCopy;
1619 Register SGPRForFPSaveRestoreCopy =
1620 FuncInfo->getScratchSGPRCopyDstReg(FramePtrReg);
1621 if (FPSaved) {
1622 // CSR spill restores should use FP as base register. If
1623 // SGPRForFPSaveRestoreCopy is not true, restore the previous value of FP
1624 // into a new scratch register and copy to FP later when other registers are
1625 // restored from the current stack frame.
1626 initLiveUnits(LiveUnits, TRI, FuncInfo, MF, MBB, MBBI, /*IsProlog*/ false);
1627 if (SGPRForFPSaveRestoreCopy) {
1628 LiveUnits.addReg(SGPRForFPSaveRestoreCopy);
1629 } else {
1630 FramePtrRegScratchCopy = findScratchNonCalleeSaveRegister(
1631 MRI, LiveUnits, AMDGPU::SReg_32_XM0_XEXECRegClass);
1632 if (!FramePtrRegScratchCopy)
1633 report_fatal_error("failed to find free scratch register");
1634
1635 LiveUnits.addReg(FramePtrRegScratchCopy);
1636 }
1637
1638 emitCSRSpillRestores(MF, MBB, MBBI, DL, LiveUnits, FramePtrReg,
1639 FramePtrRegScratchCopy);
1640 }
1641
1642 if (hasFP(MF) && MF.needsFrameMoves()) {
1643 emitDefCFA(MBB, MBBI, DL, StackPtrReg, /*AspaceAlreadyDefined=*/false,
1645 }
1646
1647 if (FPSaved) {
1648 // Insert the copy to restore FP.
1649 Register SrcReg = SGPRForFPSaveRestoreCopy ? SGPRForFPSaveRestoreCopy
1650 : FramePtrRegScratchCopy;
1652 BuildMI(MBB, MBBI, DL, TII->get(AMDGPU::COPY), FramePtrReg)
1653 .addReg(SrcReg);
1654 if (SGPRForFPSaveRestoreCopy)
1656 } else {
1657 // Insert the CSR spill restores with SP as the base register.
1658 emitCSRSpillRestores(MF, MBB, MBBI, DL, LiveUnits, StackPtrReg,
1659 FramePtrRegScratchCopy);
1660 }
1661}
1662
1663#ifndef NDEBUG
1665 const MachineFrameInfo &MFI = MF.getFrameInfo();
1666 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
1667 for (int I = MFI.getObjectIndexBegin(), E = MFI.getObjectIndexEnd();
1668 I != E; ++I) {
1669 if (!MFI.isDeadObjectIndex(I) &&
1672 return false;
1673 }
1674 }
1675
1676 return true;
1677}
1678#endif
1679
1681 int FI,
1682 Register &FrameReg) const {
1683 const SIRegisterInfo *RI = MF.getSubtarget<GCNSubtarget>().getRegisterInfo();
1684
1685 FrameReg = RI->getFrameRegister(MF);
1687}
1688
1690 MachineFunction &MF,
1691 RegScavenger *RS) const {
1692 MachineFrameInfo &MFI = MF.getFrameInfo();
1693
1694 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1695 const SIInstrInfo *TII = ST.getInstrInfo();
1696 const SIRegisterInfo *TRI = ST.getRegisterInfo();
1699
1700 const bool SpillVGPRToAGPR = ST.hasMAIInsts() && FuncInfo->hasSpilledVGPRs()
1702
1703 if (SpillVGPRToAGPR) {
1704 // To track the spill frame indices handled in this pass.
1705 BitVector SpillFIs(MFI.getObjectIndexEnd(), false);
1706 BitVector NonVGPRSpillFIs(MFI.getObjectIndexEnd(), false);
1707
1708 bool SeenDbgInstr = false;
1709
1710 for (MachineBasicBlock &MBB : MF) {
1712 int FrameIndex;
1713 if (MI.isDebugInstr())
1714 SeenDbgInstr = true;
1715
1716 if (TII->isVGPRSpill(MI)) {
1717 // Try to eliminate stack used by VGPR spills before frame
1718 // finalization.
1719 unsigned FIOp = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
1720 AMDGPU::OpName::vaddr);
1721 int FI = MI.getOperand(FIOp).getIndex();
1722 Register VReg =
1723 TII->getNamedOperand(MI, AMDGPU::OpName::vdata)->getReg();
1724 if (FuncInfo->allocateVGPRSpillToAGPR(MF, FI,
1725 TRI->isAGPR(MRI, VReg))) {
1726 assert(RS != nullptr);
1727 RS->enterBasicBlockEnd(MBB);
1728 RS->backward(std::next(MI.getIterator()));
1729 TRI->eliminateFrameIndex(MI, 0, FIOp, RS);
1730 SpillFIs.set(FI);
1731 continue;
1732 }
1733 } else if (TII->isStoreToStackSlot(MI, FrameIndex) ||
1734 TII->isLoadFromStackSlot(MI, FrameIndex))
1735 if (!MFI.isFixedObjectIndex(FrameIndex))
1736 NonVGPRSpillFIs.set(FrameIndex);
1737 }
1738 }
1739
1740 // Stack slot coloring may assign different objects to the same stack slot.
1741 // If not, then the VGPR to AGPR spill slot is dead.
1742 for (unsigned FI : SpillFIs.set_bits())
1743 if (!NonVGPRSpillFIs.test(FI))
1744 FuncInfo->setVGPRToAGPRSpillDead(FI);
1745
1746 for (MachineBasicBlock &MBB : MF) {
1747 for (MCPhysReg Reg : FuncInfo->getVGPRSpillAGPRs())
1748 MBB.addLiveIn(Reg);
1749
1750 for (MCPhysReg Reg : FuncInfo->getAGPRSpillVGPRs())
1751 MBB.addLiveIn(Reg);
1752
1753 MBB.sortUniqueLiveIns();
1754
1755 if (!SpillFIs.empty() && SeenDbgInstr)
1756 clearDebugInfoForSpillFIs(MFI, MBB, SpillFIs);
1757 }
1758 }
1759
1760 // At this point we've already allocated all spilled SGPRs to VGPRs if we
1761 // can. Any remaining SGPR spills will go to memory, so move them back to the
1762 // default stack.
1763 bool HaveSGPRToVMemSpill =
1764 FuncInfo->removeDeadFrameIndices(MFI, /*ResetSGPRSpillStackIDs*/ true);
1766 "SGPR spill should have been removed in SILowerSGPRSpills");
1767
1768 // FIXME: The other checks should be redundant with allStackObjectsAreDead,
1769 // but currently hasNonSpillStackObjects is set only from source
1770 // allocas. Stack temps produced from legalization are not counted currently.
1771 if (!allStackObjectsAreDead(MFI)) {
1772 assert(RS && "RegScavenger required if spilling");
1773
1774 // Add an emergency spill slot
1775 RS->addScavengingFrameIndex(FuncInfo->getScavengeFI(MFI, *TRI));
1776
1777 if (HaveSGPRToVMemSpill && FuncInfo->hasNoWWMPoolSGPRSpillFallback()) {
1778 // The no-WWM-pool fallback can reach SGPR-to-memory lowering while an
1779 // ordinary frame-index scavenge is live. It may then need one slot for
1780 // its temporary VGPR and another for recursive address materialization.
1781 RS->addScavengingFrameIndex(MFI.CreateSpillStackObject(4, Align(4)));
1782 RS->addScavengingFrameIndex(MFI.CreateSpillStackObject(4, Align(4)));
1783 } else if (HaveSGPRToVMemSpill &&
1785 // Existing large-frame SGPR-to-memory spills need one additional VGPR
1786 // emergency frame index.
1787 RS->addScavengingFrameIndex(MFI.CreateSpillStackObject(4, Align(4)));
1788 }
1789 }
1790}
1791
1793 MachineFunction &MF, RegScavenger *RS) const {
1794 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1795 const SIRegisterInfo *TRI = ST.getRegisterInfo();
1798
1799 if (ST.hasMAIInsts() && !ST.hasGFX90AInsts()) {
1800 // On gfx908, we had initially reserved highest available VGPR for AGPR
1801 // copy. Now since we are done with RA, check if there exist an unused VGPR
1802 // which is lower than the eariler reserved VGPR before RA. If one exist,
1803 // use it for AGPR copy instead of one reserved before RA.
1804 Register VGPRForAGPRCopy = FuncInfo->getVGPRForAGPRCopy();
1805 Register UnusedLowVGPR =
1806 TRI->findUnusedRegister(MRI, &AMDGPU::VGPR_32RegClass, MF);
1807 if (UnusedLowVGPR && (TRI->getHWRegIndex(UnusedLowVGPR) <
1808 TRI->getHWRegIndex(VGPRForAGPRCopy))) {
1809 // Reserve this newly identified VGPR (for AGPR copy)
1810 // reserved registers should already be frozen at this point
1811 // so we can avoid calling MRI.freezeReservedRegs and just use
1812 // MRI.reserveReg
1813 FuncInfo->setVGPRForAGPRCopy(UnusedLowVGPR);
1814 MRI.reserveReg(UnusedLowVGPR, TRI);
1815 }
1816 }
1817 // We initally reserved the highest available SGPR pair for long branches
1818 // now, after RA, we shift down to a lower unused one if one exists
1819 Register LongBranchReservedReg = FuncInfo->getLongBranchReservedReg();
1820 Register UnusedLowSGPR =
1821 TRI->findUnusedRegister(MRI, &AMDGPU::SGPR_64RegClass, MF);
1822 // If LongBranchReservedReg is null then we didn't find a long branch
1823 // and never reserved a register to begin with so there is nothing to
1824 // shift down. Then if UnusedLowSGPR is null, there isn't available lower
1825 // register to use so just keep the original one we set.
1826 if (LongBranchReservedReg && UnusedLowSGPR) {
1827 FuncInfo->setLongBranchReservedReg(UnusedLowSGPR);
1828 MRI.reserveReg(UnusedLowSGPR, TRI);
1829 }
1830}
1831
1832// The special SGPR spills like the one needed for FP, BP or any reserved
1833// registers delayed until frame lowering.
1835 MachineFunction &MF, BitVector &SavedVGPRs,
1836 bool NeedExecCopyReservedReg) const {
1837 MachineFrameInfo &FrameInfo = MF.getFrameInfo();
1840 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1841 const SIRegisterInfo *TRI = ST.getRegisterInfo();
1842 LiveRegUnits LiveUnits;
1843 LiveUnits.init(*TRI);
1844 // Initially mark callee saved registers as used so we will not choose them
1845 // while looking for scratch SGPRs.
1846 const MCPhysReg *CSRegs = MF.getRegInfo().getCalleeSavedRegs();
1847 for (unsigned I = 0; CSRegs[I]; ++I)
1848 LiveUnits.addReg(CSRegs[I]);
1849
1850 const TargetRegisterClass &RC = *TRI->getWaveMaskRegClass();
1851
1852 Register ReservedRegForExecCopy = MFI->getSGPRForEXECCopy();
1853 if (NeedExecCopyReservedReg ||
1854 (ReservedRegForExecCopy &&
1855 MRI.isPhysRegUsed(ReservedRegForExecCopy, /*SkipRegMaskTest=*/true))) {
1856 MRI.reserveReg(ReservedRegForExecCopy, TRI);
1857 Register UnusedScratchReg = findUnusedRegister(MRI, LiveUnits, RC);
1858 if (UnusedScratchReg) {
1859 // If found any unused scratch SGPR, reserve the register itself for Exec
1860 // copy and there is no need for any spills in that case.
1861 MFI->setSGPRForEXECCopy(UnusedScratchReg);
1862 MRI.replaceRegWith(ReservedRegForExecCopy, UnusedScratchReg);
1863 LiveUnits.addReg(UnusedScratchReg);
1864 } else {
1865 // Needs spill.
1866 assert(!MFI->hasPrologEpilogSGPRSpillEntry(ReservedRegForExecCopy) &&
1867 "Re-reserving spill slot for EXEC copy register");
1868 getVGPRSpillLaneOrTempRegister(MF, LiveUnits, ReservedRegForExecCopy, RC,
1869 /*IncludeScratchCopy=*/false);
1870 }
1871 } else if (ReservedRegForExecCopy) {
1872 // Reset it at this point. There are no whole-wave copies and spills
1873 // encountered.
1874 MFI->setSGPRForEXECCopy(AMDGPU::NoRegister);
1875 }
1876
1877 if (TRI->isCFISavedRegsSpillEnabled()) {
1878 Register Exec = TRI->getExec();
1880 "Re-reserving spill slot for EXEC");
1881 getVGPRSpillLaneOrTempRegister(MF, LiveUnits, Exec, RC);
1882 }
1883
1884 // Functions that don't return to the caller don't need to preserve
1885 // the FP and BP.
1886 const Function &F = MF.getFunction();
1887 if (F.hasFnAttribute(Attribute::NoReturn) ||
1888 AMDGPU::isChainCC(F.getCallingConv()))
1889 return;
1890
1891 // hasFP only knows about stack objects that already exist. We're now
1892 // determining the stack slots that will be created, so we have to predict
1893 // them. Stack objects force FP usage with calls.
1894 //
1895 // Note a new VGPR CSR may be introduced if one is used for the spill, but we
1896 // don't want to report it here.
1897 //
1898 // FIXME: Is this really hasReservedCallFrame?
1899 const bool WillHaveFP =
1900 FrameInfo.hasCalls() &&
1901 (SavedVGPRs.any() || !allStackObjectsAreDead(FrameInfo));
1902
1903 if (WillHaveFP || hasFP(MF)) {
1904 Register FramePtrReg = MFI->getFrameOffsetReg();
1905 assert(!MFI->hasPrologEpilogSGPRSpillEntry(FramePtrReg) &&
1906 "Re-reserving spill slot for FP");
1907 getVGPRSpillLaneOrTempRegister(MF, LiveUnits, FramePtrReg);
1908 }
1909
1910 if (TRI->hasBasePointer(MF)) {
1911 Register BasePtrReg = TRI->getBaseRegister();
1912 assert(!MFI->hasPrologEpilogSGPRSpillEntry(BasePtrReg) &&
1913 "Re-reserving spill slot for BP");
1914 getVGPRSpillLaneOrTempRegister(MF, LiveUnits, BasePtrReg);
1915 }
1916}
1917
1918// Only report VGPRs to generic code.
1920 BitVector &SavedVGPRs,
1921 RegScavenger *RS) const {
1923
1924 // If this is a function with the amdgpu_cs_chain[_preserve] calling
1925 // convention and it doesn't contain any calls to llvm.amdgcn.cs.chain, then
1926 // we don't need to save and restore anything.
1927 if (MFI->isChainFunction() && !MF.getFrameInfo().hasTailCall())
1928 return;
1929
1931
1932 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1933 const SIRegisterInfo *TRI = ST.getRegisterInfo();
1934 const SIInstrInfo *TII = ST.getInstrInfo();
1935 bool NeedExecCopyReservedReg = false;
1936
1937 MachineInstr *ReturnMI = nullptr;
1938 for (MachineBasicBlock &MBB : MF) {
1939 for (MachineInstr &MI : MBB) {
1940 // TODO: Walking through all MBBs here would be a bad heuristic. Better
1941 // handle them elsewhere.
1942 if (TII->isWWMRegSpillOpcode(MI.getOpcode()))
1943 NeedExecCopyReservedReg = true;
1944 else if (MI.getOpcode() == AMDGPU::SI_RETURN ||
1945 MI.getOpcode() == AMDGPU::SI_RETURN_TO_EPILOG ||
1946 MI.getOpcode() == AMDGPU::SI_WHOLE_WAVE_FUNC_RETURN ||
1947 (MFI->isChainFunction() &&
1948 TII->isChainCallOpcode(MI.getOpcode()))) {
1949 // We expect all return to be the same size.
1950 assert(!ReturnMI ||
1951 (count_if(MI.operands(), [](auto Op) { return Op.isReg(); }) ==
1952 count_if(ReturnMI->operands(), [](auto Op) { return Op.isReg(); })));
1953 ReturnMI = &MI;
1954 }
1955 }
1956 }
1957
1958 SmallVector<Register> SortedWWMVGPRs;
1959 for (Register Reg : MFI->getWWMReservedRegs()) {
1960 // The shift-back is needed only for the VGPRs used for SGPR spills and they
1961 // are of 32-bit size. SIPreAllocateWWMRegs pass can add tuples into WWM
1962 // reserved registers.
1963 const TargetRegisterClass *RC = TRI->getPhysRegBaseClass(Reg);
1964 if (TRI->getRegSizeInBits(*RC) != 32)
1965 continue;
1966 SortedWWMVGPRs.push_back(Reg);
1967 }
1968
1969 sort(SortedWWMVGPRs, std::greater<Register>());
1970 MFI->shiftWwmVGPRsToLowestRange(MF, SortedWWMVGPRs, SavedVGPRs);
1971
1972 if (MFI->isEntryFunction())
1973 return;
1974
1975 if (MFI->isWholeWaveFunction()) {
1976 // In practice, all the VGPRs are WWM registers, and we will need to save at
1977 // least their inactive lanes. Add them to WWMReservedRegs.
1978 assert(!NeedExecCopyReservedReg &&
1979 "Whole wave functions can use the reg mapped for their i1 argument");
1980
1981 unsigned NumArchVGPRs = ST.getAddressableNumArchVGPRs();
1982 for (MCRegister Reg :
1983 AMDGPU::VGPR_32RegClass.getRegisters().take_front(NumArchVGPRs))
1984 if (MF.getRegInfo().isPhysRegModified(Reg)) {
1985 MFI->reserveWWMRegister(Reg);
1986 MF.begin()->addLiveIn(Reg);
1987 }
1988 MF.begin()->sortUniqueLiveIns();
1989 }
1990
1991 // Remove any VGPRs used in the return value because these do not need to be saved.
1992 // This prevents CSR restore from clobbering return VGPRs.
1993 if (ReturnMI) {
1994 for (auto &Op : ReturnMI->operands()) {
1995 if (Op.isReg())
1996 SavedVGPRs.reset(Op.getReg());
1997 }
1998 }
1999
2000 // Create the stack objects for WWM registers now.
2001 for (Register Reg : MFI->getWWMReservedRegs()) {
2002 const TargetRegisterClass *RC = TRI->getPhysRegBaseClass(Reg);
2003 MFI->allocateWWMSpill(MF, Reg, TRI->getSpillSize(*RC),
2004 TRI->getSpillAlign(*RC));
2005 }
2006
2007 // Ignore the SGPRs the default implementation found.
2008 SavedVGPRs.clearBitsNotInMask(TRI->getAllVectorRegMask());
2009
2010 // Do not save AGPRs prior to GFX90A because there was no easy way to do so.
2011 // In gfx908 there was do AGPR loads and stores and thus spilling also
2012 // require a temporary VGPR.
2013 if (!ST.hasGFX90AInsts())
2014 SavedVGPRs.clearBitsInMask(TRI->getAllAGPRRegMask());
2015
2016 determinePrologEpilogSGPRSaves(MF, SavedVGPRs, NeedExecCopyReservedReg);
2017
2018 // The Whole-Wave VGPRs need to be specially inserted in the prolog, so don't
2019 // allow the default insertion to handle them.
2020 for (auto &Reg : MFI->getWWMSpills())
2021 SavedVGPRs.reset(Reg.first);
2022}
2023
2025 BitVector &SavedRegs,
2026 RegScavenger *RS) const {
2029 if (MFI->isEntryFunction())
2030 return;
2031
2032 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2033 const SIRegisterInfo *TRI = ST.getRegisterInfo();
2034
2035 // The SP is specifically managed and we don't want extra spills of it.
2036 SavedRegs.reset(MFI->getStackPtrOffsetReg());
2037
2038 const BitVector AllSavedRegs = SavedRegs;
2039 SavedRegs.clearBitsInMask(TRI->getAllVectorRegMask());
2040
2041 // We have to anticipate introducing CSR VGPR spills or spill of caller
2042 // save VGPR reserved for SGPR spills as we now always create stack entry
2043 // for it, if we don't have any stack objects already, since we require a FP
2044 // if there is a call and stack. We will allocate a VGPR for SGPR spills if
2045 // there are any SGPR spills. Whether they are CSR spills or otherwise.
2046 MachineFrameInfo &FrameInfo = MF.getFrameInfo();
2047 const bool WillHaveFP =
2048 FrameInfo.hasCalls() && (AllSavedRegs.any() || MFI->hasSpilledSGPRs());
2049
2050 // FP will be specially managed like SP.
2051 if (WillHaveFP || hasFP(MF))
2052 SavedRegs.reset(MFI->getFrameOffsetReg());
2053
2054 // Return address use with return instruction is hidden through the SI_RETURN
2055 // pseudo. Given that and since the IPRA computes actual register usage and
2056 // does not use CSR list, the clobbering of return address by function calls
2057 // (D117243) or otherwise (D120922) is ignored/not seen by the IPRA's register
2058 // usage collection. This will ensure save/restore of return address happens
2059 // in those scenarios.
2060 const MachineRegisterInfo &MRI = MF.getRegInfo();
2061 Register RetAddrReg = TRI->getReturnAddressReg(MF);
2062 if (!MFI->isEntryFunction() &&
2063 (FrameInfo.hasCalls() || MRI.isPhysRegModified(RetAddrReg))) {
2064 SavedRegs.set(TRI->getSubReg(RetAddrReg, AMDGPU::sub0));
2065 SavedRegs.set(TRI->getSubReg(RetAddrReg, AMDGPU::sub1));
2066 }
2067}
2068
2070 const GCNSubtarget &ST,
2071 std::vector<CalleeSavedInfo> &CSI) {
2073 MachineFrameInfo &MFI = MF.getFrameInfo();
2074 const SIRegisterInfo *TRI = ST.getRegisterInfo();
2075
2076 assert(
2077 llvm::is_sorted(CSI,
2078 [](const CalleeSavedInfo &A, const CalleeSavedInfo &B) {
2079 return A.getReg() < B.getReg();
2080 }) &&
2081 "Callee saved registers not sorted");
2082
2083 auto CanUseBlockOps = [&](const CalleeSavedInfo &CSI) {
2084 return !CSI.isSpilledToReg() &&
2085 TRI->getPhysRegBaseClass(CSI.getReg()) == &AMDGPU::VGPR_32RegClass &&
2086 !FuncInfo->isWWMReservedRegister(CSI.getReg());
2087 };
2088
2089 auto CSEnd = CSI.end();
2090 for (auto CSIt = CSI.begin(); CSIt != CSEnd; ++CSIt) {
2091 Register Reg = CSIt->getReg();
2092 if (!CanUseBlockOps(*CSIt))
2093 continue;
2094
2095 // Find all the regs that will fit in a 32-bit mask starting at the current
2096 // reg and build said mask. It should have 1 for every register that's
2097 // included, with the current register as the least significant bit.
2098 uint32_t Mask = 1;
2099 CSEnd = std::remove_if(
2100 CSIt + 1, CSEnd, [&](const CalleeSavedInfo &CSI) -> bool {
2101 if (CanUseBlockOps(CSI) && CSI.getReg() < Reg + 32) {
2102 Mask |= 1 << (CSI.getReg() - Reg);
2103 return true;
2104 } else {
2105 return false;
2106 }
2107 });
2108
2109 const TargetRegisterClass *BlockRegClass = TRI->getRegClassForBlockOp(MF);
2110 Register RegBlock =
2111 TRI->getMatchingSuperReg(Reg, AMDGPU::sub0, BlockRegClass);
2112 if (!RegBlock) {
2113 // We couldn't find a super register for the block. This can happen if
2114 // the register we started with is too high (e.g. v232 if the maximum is
2115 // v255). We therefore try to get the last register block and figure out
2116 // the mask from there.
2117 Register LastBlockStart =
2118 AMDGPU::VGPR0 + alignDown(Reg - AMDGPU::VGPR0, 32);
2119 RegBlock =
2120 TRI->getMatchingSuperReg(LastBlockStart, AMDGPU::sub0, BlockRegClass);
2121 assert(RegBlock && TRI->isSubRegister(RegBlock, Reg) &&
2122 "Couldn't find super register");
2123 int RegDelta = Reg - LastBlockStart;
2124 assert(RegDelta > 0 && llvm::countl_zero(Mask) >= RegDelta &&
2125 "Bad shift amount");
2126 Mask <<= RegDelta;
2127 }
2128
2129 FuncInfo->setMaskForVGPRBlockOps(RegBlock, Mask);
2130
2131 // The stack objects can be a bit smaller than the register block if we know
2132 // some of the high bits of Mask are 0. This may happen often with calling
2133 // conventions where the caller and callee-saved VGPRs are interleaved at
2134 // a small boundary (e.g. 8 or 16).
2135 int UnusedBits = llvm::countl_zero(Mask);
2136 unsigned BlockSize = TRI->getSpillSize(*BlockRegClass) - UnusedBits * 4;
2137 int FrameIdx =
2138 MFI.CreateStackObject(BlockSize, TRI->getSpillAlign(*BlockRegClass),
2139 /*isSpillSlot=*/true);
2140 MFI.setIsCalleeSavedObjectIndex(FrameIdx, true);
2141
2142 CSIt->setFrameIdx(FrameIdx);
2143 CSIt->setReg(RegBlock);
2144 }
2145 CSI.erase(CSEnd, CSI.end());
2146}
2147
2150 std::vector<CalleeSavedInfo> &CSI) const {
2151 if (CSI.empty())
2152 return true; // Early exit if no callee saved registers are modified!
2153
2154 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2155 bool UseVGPRBlocks = ST.useVGPRBlockOpsForCSR();
2156
2157 if (UseVGPRBlocks)
2158 assignSlotsUsingVGPRBlocks(MF, ST, CSI);
2159
2160 return assignCalleeSavedSpillSlotsImpl(MF, TRI, CSI) || UseVGPRBlocks;
2161}
2162
2165 std::vector<CalleeSavedInfo> &CSI) const {
2166 if (CSI.empty())
2167 return true; // Early exit if no callee saved registers are modified!
2168
2169 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2170 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2171 const SIRegisterInfo *RI = ST.getRegisterInfo();
2172 Register FramePtrReg = FuncInfo->getFrameOffsetReg();
2173 Register BasePtrReg = RI->getBaseRegister();
2174 Register SGPRForFPSaveRestoreCopy =
2175 FuncInfo->getScratchSGPRCopyDstReg(FramePtrReg);
2176 Register SGPRForBPSaveRestoreCopy =
2177 FuncInfo->getScratchSGPRCopyDstReg(BasePtrReg);
2178 if (!SGPRForFPSaveRestoreCopy && !SGPRForBPSaveRestoreCopy)
2179 return false;
2180
2181 unsigned NumModifiedRegs = 0;
2182
2183 if (SGPRForFPSaveRestoreCopy)
2184 NumModifiedRegs++;
2185 if (SGPRForBPSaveRestoreCopy)
2186 NumModifiedRegs++;
2187
2188 for (auto &CS : CSI) {
2189 if (CS.getReg() == FramePtrReg.asMCReg() && SGPRForFPSaveRestoreCopy) {
2190 CS.setDstReg(SGPRForFPSaveRestoreCopy);
2191 if (--NumModifiedRegs)
2192 break;
2193 } else if (CS.getReg() == BasePtrReg.asMCReg() &&
2194 SGPRForBPSaveRestoreCopy) {
2195 CS.setDstReg(SGPRForBPSaveRestoreCopy);
2196 if (--NumModifiedRegs)
2197 break;
2198 }
2199 }
2200
2201 return false;
2202}
2203
2205 const MachineFunction &MF) const {
2206
2207 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2208 const MachineFrameInfo &MFI = MF.getFrameInfo();
2209 const SIInstrInfo *TII = ST.getInstrInfo();
2210 uint64_t EstStackSize = MFI.estimateStackSize(MF);
2211 uint64_t MaxOffset = EstStackSize - 1;
2212
2213 // We need the emergency stack slots to be allocated in range of the
2214 // MUBUF/flat scratch immediate offset from the base register, so assign these
2215 // first at the incoming SP position.
2216 //
2217 // TODO: We could try sorting the objects to find a hole in the first bytes
2218 // rather than allocating as close to possible. This could save a lot of space
2219 // on frames with alignment requirements.
2220 if (ST.hasFlatScratchEnabled()) {
2221 if (TII->isLegalFLATOffset(MaxOffset, AMDGPUAS::PRIVATE_ADDRESS,
2223 return false;
2224 } else {
2225 if (TII->isLegalMUBUFImmOffset(MaxOffset))
2226 return false;
2227 }
2228
2229 return true;
2230}
2231
2232/// Return the set of all root registers of regunits live-in to @p MBB.
2233///
2234/// Intended to avoid using the expensive @c MCRegAliasIterator when deciding
2235/// if a register to be spilled is already live-in (see @c isAnyRootLiveIn).
2237 const SIRegisterInfo &TRI) {
2238 SparseBitVector<> LiveInRoots;
2239 for (const auto &LI : MBB.liveins()) {
2240 for (MCRegUnitMaskIterator MI(LI.PhysReg, &TRI); MI.isValid(); ++MI) {
2241 auto [Unit, UnitLaneMask] = *MI;
2242 if ((LI.LaneMask & UnitLaneMask).none())
2243 continue;
2244 for (MCRegUnitRootIterator RI(Unit, &TRI); RI.isValid(); ++RI)
2245 LiveInRoots.set(*RI);
2246 }
2247 }
2248 return LiveInRoots;
2249}
2250
2251/// Returns true iff any root of @p Reg is in @p LiveInRoots
2252/// (see @c buildLiveInRoots).
2253static bool isAnyRootLiveIn(const SparseBitVector<> &LiveInRoots,
2254 const SIRegisterInfo &TRI, MCRegister Reg) {
2255 for (MCRegUnitIterator UI(Reg, &TRI); UI.isValid(); ++UI) {
2256 for (MCRegUnitRootIterator RI(*UI, &TRI); RI.isValid(); ++RI) {
2257 if (LiveInRoots.test(*RI))
2258 return true;
2259 }
2260 }
2261 return false;
2262}
2263
2264void SIFrameLowering::spillCalleeSavedRegisterWithoutBlockOps(
2266 const CalleeSavedInfo &CS, const SIInstrInfo *TII,
2267 const SIRegisterInfo &TRI,
2268 const std::optional<SparseBitVector<>> &LiveInRoots) const {
2269 MCRegister Reg = CS.getReg();
2270
2271 // We assume a sortUniqueLiveIns later
2272 MBB.addLiveIn(Reg);
2273
2274 if (CS.isSpilledToReg()) {
2275 BuildMI(MBB, MI, DebugLoc(), TII->get(TargetOpcode::COPY), CS.getDstReg())
2276 .addReg(Reg, getKillRegState(true));
2277 } else {
2278 const TargetRegisterClass *RC = TRI.getMinimalPhysRegClass(Reg);
2279 bool IsKill = true;
2280 // If this value was already livein, we probably have a direct use of
2281 // the incoming register value, so don't kill at the spill point. This
2282 // happens since we pass some special inputs (workgroup IDs) in the
2283 // callee saved range.
2284 if (LiveInRoots)
2285 IsKill = !isAnyRootLiveIn(*LiveInRoots, TRI, Reg);
2286 TII->storeRegToStackSlotCFI(MBB, MI, Reg, IsKill, CS.getFrameIdx(), RC);
2287 }
2288}
2289
2292 ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *OrigTRI) const {
2293 auto &TRI = *static_cast<const SIRegisterInfo *>(OrigTRI);
2294 MachineFunction *MF = MBB.getParent();
2295 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
2296 const SIInstrInfo *TII = ST.getInstrInfo();
2297
2298 std::optional<SparseBitVector<>> LiveInRoots;
2299 if (MBB.getParent()->getRegInfo().tracksLiveness())
2300 LiveInRoots = buildLiveInRoots(MBB, TRI);
2301
2302 if (!ST.useVGPRBlockOpsForCSR()) {
2303 for (const CalleeSavedInfo &CS : CSI)
2304 spillCalleeSavedRegisterWithoutBlockOps(MBB, MI, CS, TII, TRI,
2305 LiveInRoots);
2306 if (LiveInRoots)
2307 MBB.sortUniqueLiveIns();
2308 return true;
2309 }
2310
2311 MachineFrameInfo &FrameInfo = MF->getFrameInfo();
2313
2314 const TargetRegisterClass *BlockRegClass = TRI.getRegClassForBlockOp(*MF);
2315 for (const CalleeSavedInfo &CS : CSI) {
2316 Register Reg = CS.getReg();
2317 if (!BlockRegClass->contains(Reg) ||
2318 !FuncInfo->hasMaskForVGPRBlockOps(Reg)) {
2319 spillCalleeSavedRegisterWithoutBlockOps(MBB, MI, CS, TII, TRI,
2320 LiveInRoots);
2321 continue;
2322 }
2323
2324 // Build a scratch block store.
2325 uint32_t Mask = FuncInfo->getMaskForVGPRBlockOps(Reg);
2326 int FrameIndex = CS.getFrameIdx();
2327 MachinePointerInfo PtrInfo =
2328 MachinePointerInfo::getFixedStack(*MF, FrameIndex);
2329 MachineMemOperand *MMO =
2331 FrameInfo.getObjectSize(FrameIndex),
2332 FrameInfo.getObjectAlign(FrameIndex));
2333
2334 BuildMI(MBB, MI, MI->getDebugLoc(),
2335 TII->get(AMDGPU::SI_BLOCK_SPILL_V1024_CFI_SAVE))
2336 .addReg(Reg, getKillRegState(false))
2337 .addFrameIndex(FrameIndex)
2338 .addReg(FuncInfo->getStackPtrOffsetReg())
2339 .addImm(0)
2340 .addImm(Mask)
2341 .addMemOperand(MMO);
2342
2343 FuncInfo->setHasSpilledVGPRs();
2344
2345 // Add the register to the liveins. This is necessary because if any of the
2346 // VGPRs in the register block is reserved (e.g. if it's a WWM register),
2347 // then the whole block will be marked as reserved and `updateLiveness` will
2348 // skip it.
2349 if (LiveInRoots)
2350 MBB.addLiveIn(Reg);
2351 }
2352 if (LiveInRoots)
2353 MBB.sortUniqueLiveIns();
2354
2355 return true;
2356}
2357
2361 const TargetRegisterInfo *OrigTRI) const {
2362 auto &TRI = *static_cast<const SIRegisterInfo *>(OrigTRI);
2363 MachineFunction *MF = MBB.getParent();
2364 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
2365 if (!ST.useVGPRBlockOpsForCSR())
2366 return false;
2367
2369 MachineFrameInfo &MFI = MF->getFrameInfo();
2370 const SIInstrInfo *TII = ST.getInstrInfo();
2371 const TargetRegisterClass *BlockRegClass = TRI.getRegClassForBlockOp(*MF);
2372 for (const CalleeSavedInfo &CS : reverse(CSI)) {
2373 Register Reg = CS.getReg();
2374 if (!BlockRegClass->contains(Reg) ||
2375 !FuncInfo->hasMaskForVGPRBlockOps(Reg)) {
2377 continue;
2378 }
2379
2380 // Build a scratch block load.
2381 uint32_t Mask = FuncInfo->getMaskForVGPRBlockOps(Reg);
2382 int FrameIndex = CS.getFrameIdx();
2383 MachinePointerInfo PtrInfo =
2384 MachinePointerInfo::getFixedStack(*MF, FrameIndex);
2386 PtrInfo, MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIndex),
2387 MFI.getObjectAlign(FrameIndex));
2388
2389 auto MIB = BuildMI(MBB, MI, MI->getDebugLoc(),
2390 TII->get(AMDGPU::SI_BLOCK_SPILL_V1024_RESTORE), Reg)
2391 .addFrameIndex(FrameIndex)
2392 .addReg(FuncInfo->getStackPtrOffsetReg())
2393 .addImm(0)
2394 .addImm(Mask)
2395 .addMemOperand(MMO);
2396 TRI.addImplicitUsesForBlockCSRLoad(MIB, Reg);
2397
2398 // Add the register to the liveins. This is necessary because if any of the
2399 // VGPRs in the register block is reserved (e.g. if it's a WWM register),
2400 // then the whole block will be marked as reserved and `updateLiveness` will
2401 // skip it.
2402 MBB.addLiveIn(Reg);
2403 }
2404
2405 MBB.sortUniqueLiveIns();
2406 return true;
2407}
2408
2410 MachineFunction &MF,
2413 int64_t Amount = I->getOperand(0).getImm();
2414 if (Amount == 0)
2415 return MBB.erase(I);
2416
2417 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2418 const SIInstrInfo *TII = ST.getInstrInfo();
2419 const DebugLoc &DL = I->getDebugLoc();
2420 unsigned Opc = I->getOpcode();
2421 bool IsDestroy = Opc == TII->getCallFrameDestroyOpcode();
2422 uint64_t CalleePopAmount = IsDestroy ? I->getOperand(1).getImm() : 0;
2423
2424 if (!hasReservedCallFrame(MF)) {
2425 Amount = alignTo(Amount, getStackAlign());
2426 assert(isUInt<32>(Amount) && "exceeded stack address space size");
2429
2430 Amount *= getScratchScaleFactor(ST);
2431 if (IsDestroy)
2432 Amount = -Amount;
2433 auto Add = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SPReg)
2434 .addReg(SPReg)
2435 .addImm(Amount);
2436 Add->getOperand(3).setIsDead(); // Mark SCC as dead.
2437 } else if (CalleePopAmount != 0) {
2438 llvm_unreachable("is this used?");
2439 }
2440
2441 return MBB.erase(I);
2442}
2443
2444/// Returns true if the frame will require a reference to the stack pointer.
2445///
2446/// This is the set of conditions common to setting up the stack pointer in a
2447/// kernel, and for using a frame pointer in a callable function.
2448///
2449/// FIXME: Should also check hasOpaqueSPAdjustment and if any inline asm
2450/// references SP.
2452 return MFI.hasVarSizedObjects() || MFI.hasStackMap() || MFI.hasPatchPoint();
2453}
2454
2455// The FP for kernels is always known 0, so we never really need to setup an
2456// explicit register for it. However, DisableFramePointerElim will force us to
2457// use a register for it.
2459 const MachineFrameInfo &MFI = MF.getFrameInfo();
2460
2461 // For entry functions we can use an immediate offset in most cases,
2462 // so the presence of calls doesn't imply we need a distinct frame pointer.
2463 if (MFI.hasCalls() &&
2465 // All offsets are unsigned, so need to be addressed in the same direction
2466 // as stack growth.
2467
2468 // FIXME: This function is pretty broken, since it can be called before the
2469 // frame layout is determined or CSR spills are inserted.
2470 return MFI.getStackSize() != 0;
2471 }
2472
2473 return frameTriviallyRequiresSP(MFI) || MFI.isFrameAddressTaken() ||
2474 MF.getSubtarget<GCNSubtarget>().getRegisterInfo()->hasStackRealignment(
2475 MF) ||
2477}
2478
2480 const MachineFunction &MF) const {
2481 return MF.getInfo<SIMachineFunctionInfo>()->isDynamicVGPREnabled() &&
2484}
2485
2486// This is essentially a reduced version of hasFP for entry functions. Since the
2487// stack pointer is known 0 on entry to kernels, we never really need an FP
2488// register. We may need to initialize the stack pointer depending on the frame
2489// properties, which logically overlaps many of the cases where an ordinary
2490// function would require an FP.
2492 const MachineFunction &MF) const {
2493 // Callable functions always require a stack pointer reference.
2495 "only expected to call this for entry points functions");
2496
2497 const MachineFrameInfo &MFI = MF.getFrameInfo();
2498
2499 // Entry points ordinarily don't need to initialize SP. We have to set it up
2500 // for callees if there are any. Also note tail calls are only possible via
2501 // the `llvm.amdgcn.cs.chain` intrinsic.
2502 if (MFI.hasCalls() || MFI.hasTailCall())
2503 return true;
2504
2505 // We still need to initialize the SP if we're doing anything weird that
2506 // references the SP, like variable sized stack objects.
2507 return frameTriviallyRequiresSP(MFI);
2508}
2509
2512 const DebugLoc &DL,
2513 const MCCFIInstruction &CFIInst,
2514 MachineInstr::MIFlag Flag) const {
2515 MachineFunction &MF = *MBB.getParent();
2516 const SIInstrInfo *TII = MF.getSubtarget<GCNSubtarget>().getInstrInfo();
2517 return BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
2518 .addCFIIndex(MF.addFrameInst(CFIInst))
2519 .setMIFlag(Flag);
2520}
2521
2524 const DebugLoc &DL, const MCRegister Reg, const MCRegister RegCopy) const {
2525 MachineFunction &MF = *MBB.getParent();
2526 const MCRegisterInfo &MCRI = *MF.getContext().getRegisterInfo();
2527 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2528
2529 unsigned MaskReg = MCRI.getDwarfRegNum(
2530 ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC, false);
2532 nullptr, MCRI.getDwarfRegNum(Reg, false),
2533 MCRI.getDwarfRegNum(RegCopy, false), VGPRLaneBitSize, MaskReg,
2534 ST.getWavefrontSize());
2535 return buildCFI(MBB, MBBI, DL, std::move(CFIInst));
2536}
2537
2540 const DebugLoc &DL, const MCRegister SGPR, const MCRegister VGPR,
2541 const int Lane) const {
2542 const MachineFunction &MF = *MBB.getParent();
2543 const MCRegisterInfo &MCRI = *MF.getContext().getRegisterInfo();
2544
2545 int DwarfSGPR = MCRI.getDwarfRegNum(SGPR, false);
2546 int DwarfVGPR = MCRI.getDwarfRegNum(VGPR, false);
2547 assert(DwarfSGPR != -1 && DwarfVGPR != -1);
2548 assert(Lane != -1 && "Expected a lane to be present");
2549
2550 // Build a CFI instruction that represents a SGPR spilled to a single lane of
2551 // a VGPR.
2553 unsigned(Lane), VGPRLaneBitSize};
2554 auto CFIInst =
2555 MCCFIInstruction::createLLVMVectorRegisters(nullptr, DwarfSGPR, {VR});
2556 return buildCFI(MBB, MBBI, DL, std::move(CFIInst));
2557}
2558
2561 const DebugLoc &DL, MCRegister SGPR,
2562 ArrayRef<SIRegisterInfo::SpilledReg> VGPRSpills) const {
2563 if (VGPRSpills.size() == 1u)
2564 return buildCFIForSGPRToVGPRSpill(MBB, MBBI, DL, SGPR, VGPRSpills[0].VGPR,
2565 VGPRSpills[0].Lane);
2566 const MachineFunction &MF = *MBB.getParent();
2567 const MCRegisterInfo &MCRI = *MF.getContext().getRegisterInfo();
2568
2569 int DwarfSGPR = MCRI.getDwarfRegNum(SGPR, false);
2570 assert(DwarfSGPR != -1);
2571
2572 // Build a CFI instruction that represents a SGPR spilled to multiple lanes of
2573 // multiple VGPRs.
2574
2576 for (SIRegisterInfo::SpilledReg Spill : VGPRSpills) {
2577 int DwarfVGPR = MCRI.getDwarfRegNum(Spill.VGPR, false);
2578 assert(DwarfVGPR != -1);
2579 assert(Spill.hasLane() && "Expected a lane to be present");
2580 VGPRs.push_back(
2581 {unsigned(DwarfVGPR), unsigned(Spill.Lane), VGPRLaneBitSize});
2582 }
2583
2584 auto CFIInst = MCCFIInstruction::createLLVMVectorRegisters(nullptr, DwarfSGPR,
2585 std::move(VGPRs));
2586 return buildCFI(MBB, MBBI, DL, std::move(CFIInst));
2587}
2588
2591 const DebugLoc &DL, MCRegister SGPR, int64_t Offset) const {
2592 MachineFunction &MF = *MBB.getParent();
2593 const MCRegisterInfo &MCRI = *MF.getContext().getRegisterInfo();
2594 return buildCFI(MBB, MBBI, DL,
2596 nullptr, MCRI.getDwarfRegNum(SGPR, false), Offset));
2597}
2598
2601 const DebugLoc &DL, MCRegister VGPR, int64_t Offset) const {
2602 const MachineFunction &MF = *MBB.getParent();
2603 const MCRegisterInfo &MCRI = *MF.getContext().getRegisterInfo();
2604 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2605
2606 int DwarfVGPR = MCRI.getDwarfRegNum(VGPR, false);
2607 assert(DwarfVGPR != -1);
2608
2609 unsigned MaskReg = MCRI.getDwarfRegNum(
2610 ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC, false);
2612 nullptr, DwarfVGPR, VGPRLaneBitSize, MaskReg, ST.getWavefrontSize(),
2613 Offset);
2614 return buildCFI(MBB, MBBI, DL, std::move(CFIInst));
2615}
2616
2618 SmallVectorImpl<unsigned> &DwarfRegs) {
2619 int64_t DwarfReg = TRI.getDwarfRegNum(Reg, /*IsEH=*/false);
2620 if (DwarfReg >= 0) {
2621 DwarfRegs.push_back(unsigned(DwarfReg));
2622 return;
2623 }
2624
2625 const TargetRegisterClass *RC = TRI.getPhysRegBaseClass(Reg);
2626 ArrayRef<int16_t> SplitParts = TRI.getRegSplitParts(RC, SGPRByteSize);
2627 for (unsigned I = 0; I < SplitParts.size(); ++I) {
2628 MCRegister SubReg = TRI.getSubReg(Reg, SplitParts[I]);
2629 DwarfReg = TRI.getDwarfRegNum(SubReg, /*IsEH=*/false);
2630 if (DwarfReg < 0) {
2631 DwarfRegs.clear();
2632 return;
2633 }
2634 DwarfRegs.push_back(unsigned(DwarfReg));
2635 }
2636}
2637
2640 const DebugLoc &DL, MCRegister Reg, MCRegister CopyReg) const {
2641 const MachineFunction &MF = *MBB.getParent();
2642 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2643 const SIRegisterInfo &TRI = *ST.getRegisterInfo();
2644
2645 SmallVector<unsigned> DwarfRegs, DwarfCopyRegs;
2646 decomposeDwarfRegs(TRI, Reg, DwarfRegs);
2647 decomposeDwarfRegs(TRI, CopyReg, DwarfCopyRegs);
2648
2649 if (DwarfRegs.size() == DwarfCopyRegs.size()) {
2650 for (unsigned I = 0, E = DwarfRegs.size(); I < E; ++I) {
2651 auto CFI = MCCFIInstruction::createRegister(nullptr, DwarfRegs[I],
2652 DwarfCopyRegs[I]);
2653 buildCFI(MBB, MBBI, DL, CFI);
2654 }
2655 return;
2656 }
2657
2658 if (DwarfRegs.size() == 1 && DwarfCopyRegs.size() == 2) {
2660 nullptr, DwarfRegs[0], DwarfCopyRegs[0], SGPRBitSize, DwarfCopyRegs[1],
2661 SGPRBitSize);
2662 buildCFI(MBB, MBBI, DL, CFI);
2663 return;
2664 }
2665
2666 for (unsigned I = 0, E = DwarfRegs.size(); I < E; ++I) {
2667 auto CFI = MCCFIInstruction::createUndefined(nullptr, DwarfRegs[I]);
2668 buildCFI(MBB, MBBI, DL, CFI);
2669 }
2670}
2671
2674 const DebugLoc &DL, MCRegister SGPR, MCRegister VCCHalf) const {
2675 const MachineFunction &MF = *MBB.getParent();
2676 const MCRegisterInfo &MCRI = *MF.getContext().getRegisterInfo();
2678
2679 int DwarfSGPR = MCRI.getDwarfRegNum(SGPR, false);
2680 int DwarfVCC = MCRI.getDwarfRegNum(AMDGPU::VCC, false);
2681 assert(DwarfSGPR != -1 && DwarfVCC != -1);
2682
2683 // Describe the copy as one 32-bit lane of VCC_64: lane 0 is vcc_lo and lane 1
2684 // is vcc_hi.
2686 unsigned(DwarfVCC), VCCHalf == AMDGPU::VCC_HI ? 1u : 0u, SGPRBitSize};
2687 auto CFIInst =
2688 MCCFIInstruction::createLLVMVectorRegisters(nullptr, DwarfSGPR, {Half});
2689 return buildCFI(MBB, MBBI, DL, std::move(CFIInst));
2690}
2691
2694 const DebugLoc &DL, MCRegister Reg) const {
2695 const MachineFunction &MF = *MBB.getParent();
2696 const MCRegisterInfo &MCRI = *MF.getContext().getRegisterInfo();
2697 int DwarfReg = MCRI.getDwarfRegNum(Reg, /*isEH=*/false);
2698 auto CFIInst = MCCFIInstruction::createSameValue(nullptr, DwarfReg);
2699 return buildCFI(MBB, MBBI, DL, std::move(CFIInst));
2700}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
Provides AMDGPU specific target descriptions.
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
MachineBasicBlock MachineBasicBlock::iterator MBBI
static const Function * getParent(const Value *V)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains constants used for implementing Dwarf debug support.
AMD GCN specific subclass of TargetSubtarget.
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
A set of register units.
#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
static constexpr MCPhysReg FPReg
static constexpr MCPhysReg SPReg
MachineRegisterInfo & MRI
This file declares the machine register scavenger class.
static void buildEpilogRestore(const GCNSubtarget &ST, const SIRegisterInfo &TRI, const SIMachineFunctionInfo &FuncInfo, LiveRegUnits &LiveUnits, MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, Register SpillReg, int FI, Register FrameReg, int64_t DwordOff=0)
static cl::opt< bool > EnableSpillVGPRToAGPR("amdgpu-spill-vgpr-to-agpr", cl::desc("Enable spilling VGPRs to AGPRs"), cl::ReallyHidden, cl::init(true))
static void getVGPRSpillLaneOrTempRegister(MachineFunction &MF, LiveRegUnits &LiveUnits, Register SGPR, const TargetRegisterClass &RC=AMDGPU::SReg_32_XM0_XEXECRegClass, bool IncludeScratchCopy=true)
Query target location for spilling SGPRs IncludeScratchCopy : Also look for free scratch SGPRs.
static void buildGitPtr(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, const SIInstrInfo *TII, Register TargetReg)
static bool allStackObjectsAreDead(const MachineFrameInfo &MFI)
static MCCFIInstruction createScaledCFAInPrivateWave(const GCNSubtarget &ST, int64_t DwarfStackPtrReg)
static void buildPrologSpill(const GCNSubtarget &ST, const SIRegisterInfo &TRI, const SIMachineFunctionInfo &FuncInfo, LiveRegUnits &LiveUnits, MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, Register SpillReg, int FI, Register FrameReg, int64_t DwordOff=0)
static Register buildScratchExecCopy(LiveRegUnits &LiveUnits, MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool IsProlog, bool EnableInactiveLanes)
static void encodeDwarfRegisterLocation(int DwarfReg, raw_ostream &OS)
static constexpr unsigned SGPRBitSize
static bool frameTriviallyRequiresSP(const MachineFrameInfo &MFI)
Returns true if the frame will require a reference to the stack pointer.
static void decomposeDwarfRegs(const SIRegisterInfo &TRI, MCRegister Reg, SmallVectorImpl< unsigned > &DwarfRegs)
static SparseBitVector buildLiveInRoots(const MachineBasicBlock &MBB, const SIRegisterInfo &TRI)
Return the set of all root registers of regunits live-in to MBB.
static void initLiveUnits(LiveRegUnits &LiveUnits, const SIRegisterInfo &TRI, const SIMachineFunctionInfo *FuncInfo, MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, bool IsProlog)
static constexpr unsigned VGPRLaneBitSize
static bool allSGPRSpillsAreDead(const MachineFunction &MF)
static bool isWave64VCCHalf(const GCNSubtarget &ST, MCRegister Reg)
static MCRegister findScratchNonCalleeSaveRegister(MachineRegisterInfo &MRI, LiveRegUnits &LiveUnits, const TargetRegisterClass &RC, bool Unused=false)
static MCRegister findUnusedRegister(MachineRegisterInfo &MRI, const LiveRegUnits &LiveUnits, const TargetRegisterClass &RC)
static constexpr unsigned SGPRByteSize
static void assignSlotsUsingVGPRBlocks(MachineFunction &MF, const GCNSubtarget &ST, std::vector< CalleeSavedInfo > &CSI)
static bool isAnyRootLiveIn(const SparseBitVector<> &LiveInRoots, const SIRegisterInfo &TRI, MCRegister Reg)
Returns true iff any root of Reg is in LiveInRoots (see buildLiveInRoots).
static unsigned getScratchScaleFactor(const GCNSubtarget &ST)
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
#define LLVM_DEBUG(...)
Definition Debug.h:119
static const int BlockSize
Definition TarWriter.cpp:33
static const LaneMaskConstants & get(const GCNSubtarget &ST)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:185
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:482
BitVector & reset()
Reset all bits in the bitvector.
Definition BitVector.h:409
void clearBitsNotInMask(const uint32_t *Mask, unsigned MaskWords=~0u)
Clear a bit in this vector for every '0' bit in Mask.
Definition BitVector.h:760
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:366
bool any() const
Returns true if any bit is set.
Definition BitVector.h:189
void clearBitsInMask(const uint32_t *Mask, unsigned MaskWords=~0u)
Clear any bits in this vector that are set in Mask.
Definition BitVector.h:748
iterator_range< const_set_bits_iterator > set_bits() const
Definition BitVector.h:159
bool empty() const
Returns whether there are no bits in this bitvector.
Definition BitVector.h:175
The CalleeSavedInfo class tracks the information need to locate where a callee saved register is in t...
MCRegister getReg() const
MCRegister getDstReg() const
A debug info location.
Definition DebugLoc.h:126
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
const HexagonRegisterInfo & getRegisterInfo() const
A set of register units used to track register liveness.
bool available(MCRegister Reg) const
Returns true if no part of physical register Reg is live.
void init(const TargetRegisterInfo &TRI)
Initialize and clear the set.
void addReg(MCRegister Reg)
Adds register units covered by physical register Reg.
LLVM_ABI void stepBackward(const MachineInstr &MI)
Updates liveness when stepping backwards over the instruction MI.
LLVM_ABI void addLiveOuts(const MachineBasicBlock &MBB)
Adds registers living out of block MBB.
void removeReg(MCRegister Reg)
Removes all register units covered by physical register Reg.
bool empty() const
Returns true if the set is empty.
LLVM_ABI void addLiveIns(const MachineBasicBlock &MBB)
Adds registers living into block MBB.
static MCCFIInstruction createLLVMVectorOffset(MCSymbol *L, unsigned Register, unsigned RegisterSizeInBits, unsigned MaskRegister, unsigned MaskRegisterSizeInBits, int64_t Offset, SMLoc Loc={})
.cfi_llvm_vector_offset Previous value of Register is saved at Offset from CFA.
Definition MCDwarf.h:797
static MCCFIInstruction createUndefined(MCSymbol *L, unsigned Register, SMLoc Loc={})
.cfi_undefined From now on the previous value of Register can't be restored anymore.
Definition MCDwarf.h:732
static MCCFIInstruction createLLVMVectorRegisters(MCSymbol *L, unsigned Register, ArrayRef< VectorRegisterWithLane > VectorRegisters, SMLoc Loc={})
.cfi_llvm_vector_registers Previous value of Register is saved in lanes of vector registers.
Definition MCDwarf.h:787
static MCCFIInstruction createLLVMVectorRegisterMask(MCSymbol *L, unsigned Register, unsigned SpillRegister, unsigned SpillRegisterLaneSizeInBits, unsigned MaskRegister, unsigned MaskRegisterSizeInBits, SMLoc Loc={})
.cfi_llvm_vector_register_mask Previous value of Register is saved in SpillRegister,...
Definition MCDwarf.h:808
static MCCFIInstruction createRegister(MCSymbol *L, unsigned Register1, unsigned Register2, SMLoc Loc={})
.cfi_register Previous value of Register1 is saved in register Register2.
Definition MCDwarf.h:685
static MCCFIInstruction createOffset(MCSymbol *L, unsigned Register, int64_t Offset, SMLoc Loc={})
.cfi_offset Previous value of Register is saved at offset Offset from CFA.
Definition MCDwarf.h:670
static MCCFIInstruction createLLVMRegisterPair(MCSymbol *L, unsigned Register, unsigned R1, unsigned R1SizeInBits, unsigned R2, unsigned R2SizeInBits, SMLoc Loc={})
.cfi_llvm_register_pair Previous value of Register is saved in R1:R2.
Definition MCDwarf.h:777
static MCCFIInstruction createEscape(MCSymbol *L, StringRef Vals, SMLoc Loc={}, StringRef Comment="")
.cfi_escape Allows the user to add arbitrary bytes to the unwind info.
Definition MCDwarf.h:756
static MCCFIInstruction createSameValue(MCSymbol *L, unsigned Register, SMLoc Loc={})
.cfi_same_value Current value of Register is the same as in the previous frame.
Definition MCDwarf.h:739
const MCRegisterInfo * getRegisterInfo() const
Definition MCContext.h:413
Describe properties that are true of each instruction in the target description file.
bool isValid() const
Returns true if this iterator is not yet at the end.
MCRegUnitMaskIterator enumerates a list of register units and their associated lane masks for Reg.
MCRegUnitRootIterator enumerates the root registers of a register unit.
bool isValid() const
Check if the iterator is at the end of the list.
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
virtual int64_t getDwarfRegNum(MCRegister Reg, bool isEH) const
Map a target register to an equivalent dwarf register number.
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition MCRegister.h:72
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
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
bool hasCalls() const
Return true if the current function has any function calls.
bool isFrameAddressTaken() const
This method may be called any time after instruction selection is complete to determine if there is a...
Align getMaxAlign() const
Return alignment of this function's frame.
bool hasPatchPoint() const
This method may be called any time after instruction selection is complete to determine if there is a...
bool hasTailCall() const
Returns true if the function contains a tail call.
bool hasStackMap() const
This method may be called any time after instruction selection is complete to determine if there is a...
LLVM_ABI int CreateSpillStackObject(uint64_t Size, Align Alignment, TargetStackID::Value StackID=TargetStackID::Default)
Create a new statically sized stack object that represents a spill slot, returning a nonnegative iden...
void RemoveStackObject(int ObjectIdx)
Remove or mark dead a statically sized stack object.
int getObjectIndexEnd() const
Return one past the maximum frame object index.
uint8_t getStackID(int ObjectIdx) const
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
int getObjectIndexBegin() const
Return the minimum frame object index.
bool isDeadObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a dead object.
unsigned addFrameInst(const MCCFIInstruction &Inst)
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
bool needsFrameMoves() const
True if this function needs frame moves for debug or exceptions.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MCContext & getContext() const
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
bool disableFramePointerElim() const
Returns true if frame pointer elimination should be disabled for this function.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineBasicBlock & front() const
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy, Align BaseAlignment, const MMOMetadata &Metadata=MMOMetadata(), SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
const MachineInstrBuilder & addExternalSymbol(const char *FnName, unsigned TargetFlags=0) const
const MachineInstrBuilder & addCFIIndex(unsigned CFIIndex) const
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & setMIFlag(MachineInstr::MIFlag Flag) const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addFrameIndex(int Idx) const
const MachineInstrBuilder & addMemOperand(MachineMemOperand *MMO) const
Representation of each machine instruction.
mop_range operands()
const MachineOperand & getOperand(unsigned i) const
A description of a memory reference used in the backend.
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ MOLoad
The memory access reads data.
@ MOInvariant
The memory access always returns the same value (or traps).
@ MOStore
The memory access writes data.
void setIsDead(bool Val=true)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
bool isAllocatable(MCRegister PhysReg) const
isAllocatable - Returns true when PhysReg belongs to an allocatable register class and it hasn't been...
LLVM_ABI const MCPhysReg * getCalleeSavedRegs() const
Returns list of callee saved registers.
void reserveReg(MCRegister PhysReg, const TargetRegisterInfo *TRI)
reserveReg – Mark a register as reserved so checks like isAllocatable will not suggest using it.
void addLiveIn(MCRegister Reg, Register vreg=Register())
addLiveIn - Add the specified register as a live-in.
LLVM_ABI void replaceRegWith(Register FromReg, Register ToReg)
replaceRegWith - Replace all instances of FromReg with ToReg in the machine function.
LLVM_ABI bool isPhysRegModified(MCRegister PhysReg, bool SkipNoReturnDef=false) const
Return true if the specified register is modified in this function.
LLVM_ABI bool isPhysRegUsed(MCRegister PhysReg, bool SkipRegMaskTest=false) const
Return true if the specified register is modified or read in this function.
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
PrologEpilogSGPRSpillBuilder(Register Reg, const PrologEpilogSGPRSaveRestoreInfo SI, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const DebugLoc &DL, const SIInstrInfo *TII, const SIRegisterInfo &TRI, LiveRegUnits &LiveUnits, Register FrameReg, bool IsFramePtrPrologSpill=false)
Wrapper class representing virtual and physical registers.
Definition Register.h:20
MCRegister asMCReg() const
Utility to check-convert this value to a MCRegister.
Definition Register.h:107
void determinePrologEpilogSGPRSaves(MachineFunction &MF, BitVector &SavedRegs, bool NeedExecCopyReservedReg) const
MachineInstr * buildCFIForSGPRToVMEMSpill(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, MCRegister SGPR, int64_t Offset) const
Create a CFI index describing a spill of a SGPR to VMEM and build a MachineInstr around it.
void buildCFIForSRegToSRegSpill(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, MCRegister Reg, MCRegister CopyReg) const
void emitCSRSpillRestores(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, LiveRegUnits &LiveUnits, Register FrameReg, Register FramePtrRegScratchCopy) const
StackOffset getFrameIndexReference(const MachineFunction &MF, int FI, Register &FrameReg) const override
getFrameIndexReference - This method should return the base register and offset used to reference a f...
void processFunctionBeforeFrameFinalized(MachineFunction &MF, RegScavenger *RS=nullptr) const override
processFunctionBeforeFrameFinalized - This method is called immediately before the specified function...
bool mayReserveScratchForCWSR(const MachineFunction &MF) const
bool allocateScavengingFrameIndexesNearIncomingSP(const MachineFunction &MF) const override
Control the placement of special register scavenging spill slots when allocating a stack frame.
bool requiresStackPointerReference(const MachineFunction &MF) const
void emitEntryFunctionPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const
MachineInstr * buildCFIForSGPRToVCCHalfCopy(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, MCRegister SGPR, MCRegister VCCHalf) const
Create a CFI index describing a copy of the 32-bit SGPR to VCCHalf (vcc_lo or vcc_hi) in wave64 and b...
void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const override
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
bool hasFPImpl(const MachineFunction &MF) const override
bool assignCalleeSavedSpillSlotsImpl(MachineFunction &MF, const TargetRegisterInfo *TRI, std::vector< CalleeSavedInfo > &CSI) const
MachineInstr * buildCFIForVRegToVRegSpill(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, const MCRegister Reg, const MCRegister RegCopy) const
Create a CFI index describing a spill of the VGPR/AGPR Reg to another VGPR/AGPR RegCopy and build a M...
bool spillCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, ArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const override
spillCalleeSavedRegisters - Issues instruction(s) to spill all callee saved registers and returns tru...
MachineInstr * buildCFIForVGPRToVMEMSpill(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, MCRegister VGPR, int64_t Offset) const
Create a CFI index describing a spill of a VGPR to VMEM and build a MachineInstr around it.
MachineInstr * buildCFIForSGPRToVGPRSpill(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, const MCRegister SGPR, const MCRegister VGPR, const int Lane) const
Create a CFI index describing a spill of an SGPR to a single lane of a VGPR and build a MachineInstr ...
bool assignCalleeSavedSpillSlots(MachineFunction &MF, const TargetRegisterInfo *TRI, std::vector< CalleeSavedInfo > &CSI) const override
assignCalleeSavedSpillSlots - Allows target to override spill slot assignment logic.
void determineCalleeSavesSGPR(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const
void emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const override
MachineInstr * buildCFIForSameValue(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, MCRegister Reg) const
MachineInstr * buildCFI(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, const MCCFIInstruction &CFIInst, MachineInstr::MIFlag flag=MachineInstr::FrameSetup) const
Create a CFI index for CFIInst and build a MachineInstr around it.
void emitCSRSpillStores(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, const DebugLoc &DL, LiveRegUnits &LiveUnits, Register FrameReg, Register FramePtrRegScratchCopy, const bool NeedsFrameMoves) const
void processFunctionBeforeFrameIndicesReplaced(MachineFunction &MF, RegScavenger *RS=nullptr) const override
processFunctionBeforeFrameIndicesReplaced - This method is called immediately before MO_FrameIndex op...
bool isSupportedStackID(TargetStackID::Value ID) const override
void emitPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const override
emitProlog/emitEpilog - These methods insert prolog and epilog code into the function.
MachineBasicBlock::iterator eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const override
This method is called during prolog/epilog code insertion to eliminate call frame setup and destroy p...
bool restoreCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, MutableArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const override
restoreCalleeSavedRegisters - Issues instruction(s) to restore all callee saved registers and returns...
This class keeps track of the SPI_SP_INPUT_ADDR config register, which tells the hardware which inter...
ArrayRef< PrologEpilogSGPRSpill > getPrologEpilogSGPRSpills() const
const WWMSpillsMap & getWWMSpills() const
void getAllScratchSGPRCopyDstRegs(SmallVectorImpl< Register > &Regs) const
ArrayRef< MCPhysReg > getAGPRSpillVGPRs() const
void removePrologEpilogSGPRSpillEntry(Register Reg)
void shiftWwmVGPRsToLowestRange(MachineFunction &MF, SmallVectorImpl< Register > &WWMVGPRs, BitVector &SavedVGPRs)
void setMaskForVGPRBlockOps(Register RegisterBlock, uint32_t Mask)
GCNUserSGPRUsageInfo & getUserSGPRInfo()
void allocateWWMSpill(MachineFunction &MF, Register VGPR, uint64_t Size=4, Align Alignment=Align(4))
void setVGPRToAGPRSpillDead(int FrameIndex)
Register getScratchRSrcReg() const
Returns the physical register reserved for use as the resource descriptor for scratch accesses.
ArrayRef< MCPhysReg > getVGPRSpillAGPRs() const
int getScavengeFI(MachineFrameInfo &MFI, const SIRegisterInfo &TRI)
uint32_t getMaskForVGPRBlockOps(Register RegisterBlock) const
bool hasMaskForVGPRBlockOps(Register RegisterBlock) const
bool hasPrologEpilogSGPRSpillEntry(Register Reg) const
Register getGITPtrLoReg(const MachineFunction &MF) const
void setVGPRForAGPRCopy(Register NewVGPRForAGPRCopy)
bool allocateVGPRSpillToAGPR(MachineFunction &MF, int FI, bool isAGPRtoVGPR)
Reserve AGPRs or VGPRs to support spilling for FrameIndex FI.
void splitWWMSpillRegisters(MachineFunction &MF, SmallVectorImpl< std::pair< Register, int > > &CalleeSavedRegs, SmallVectorImpl< std::pair< Register, int > > &ScratchRegs) const
bool isWWMReservedRegister(Register Reg) const
ArrayRef< SIRegisterInfo::SpilledReg > getSGPRSpillToPhysicalVGPRLanes(int FrameIndex) const
bool allocateSGPRSpillToVGPRLane(MachineFunction &MF, int FI, bool SpillToPhysVGPRLane=false, bool IsPrologEpilog=false)
void setLongBranchReservedReg(Register Reg)
void setHasSpilledVGPRs(bool Spill=true)
bool removeDeadFrameIndices(MachineFrameInfo &MFI, bool ResetSGPRSpillStackIDs)
If ResetSGPRSpillStackIDs is true, reset the stack ID from sgpr-spill to the default stack.
void setScratchReservedForDynamicVGPRs(unsigned SizeInBytes)
MCRegister getPreloadedReg(AMDGPUFunctionArgInfo::PreloadedValue Value) const
bool checkIndexInPrologEpilogSGPRSpills(int FI) const
const ReservedRegSet & getWWMReservedRegs() const
const PrologEpilogSGPRSaveRestoreInfo & getPrologEpilogSGPRSaveRestoreInfo(Register Reg) const
void setIsStackRealigned(bool Realigned=true)
void addToPrologEpilogSGPRSpills(Register Reg, PrologEpilogSGPRSaveRestoreInfo SI)
Register getScratchSGPRCopyDstReg(Register Reg) const
Register getFrameRegister(const MachineFunction &MF) const override
Represents a location in source code.
Definition SMLoc.h:22
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
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.
void set(unsigned Idx)
bool test(unsigned Idx) const
StackOffset holds a fixed and a scalable offset in bytes.
Definition TypeSize.h:31
int64_t getFixed() const
Returns the fixed component of the stack.
Definition TypeSize.h:47
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool hasFP(const MachineFunction &MF) const
hasFP - Return true if the specified function should have a dedicated frame pointer register.
virtual bool hasReservedCallFrame(const MachineFunction &MF) const
hasReservedCallFrame - Under normal circumstances, when a frame pointer is not required,...
virtual void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
void restoreCalleeSavedRegister(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const CalleeSavedInfo &CS, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an SmallVector or SmallString.
StringRef str() const
Return a StringRef for the vector contents.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ CONSTANT_ADDRESS
Address space for constant memory (VTX2).
@ PRIVATE_ADDRESS
Address space for private memory.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
unsigned getVGPRAllocGranule(const MCSubtargetInfo &STI, unsigned DynamicVGPRBlockSize, std::optional< bool > EnableWavefrontSize32)
uint64_t convertSMRDOffsetUnits(const MCSubtargetInfo &ST, uint64_t ByteOffset)
Convert ByteOffset to dwords if the subtarget uses dword SMRD immediate offsets.
LLVM_READNONE constexpr bool isEntryFunctionCC(CallingConv::ID CC)
bool isInlinableLiteral32(int32_t Literal, bool HasInv2Pi)
LLVM_READNONE constexpr bool isCompute(CallingConv::ID CC)
LLVM_READNONE constexpr bool isChainCC(CallingConv::ID CC)
@ AMDGPU_CS
Used for Mesa/AMDPAL compute shaders.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
UnaryFunction for_each(R &&Range, UnaryFunction F)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1748
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
@ Kill
The last use of a register.
@ Undef
Value of the register doesn't matter.
constexpr RegState getKillRegState(bool B)
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
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition MathExtras.h:546
void clearDebugInfoForSpillFIs(MachineFrameInfo &MFI, MachineBasicBlock &MBB, const BitVector &SpillFIs)
Replace frame index operands with null registers in debug value instructions for the specified spill ...
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:263
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
constexpr uint32_t Hi_32(uint64_t Value)
Return the high 32 bits of a 64 bit value.
Definition MathExtras.h:151
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
Definition STLExtras.h:1415
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
bool is_sorted(R &&Range, Compare C)
Wrapper function around std::is_sorted to check if elements in a range R are sorted with respect to a...
Definition STLExtras.h:1986
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
constexpr uint32_t Lo_32(uint64_t Value)
Return the low 32 bits of a 64 bit value.
Definition MathExtras.h:156
@ And
Bitwise or logical AND of integers.
@ Add
Sum of integers.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2035
unsigned encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a ULEB128 value to an output stream.
Definition LEB128.h:79
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.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
Matching combinators.
This class contains a discriminated union of information about pointers in memory operands,...
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.