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