Skip to content

Commit 2e5c298

Browse files
authored
[AMDGPU] Add backward compatibility layer for kernarg preloading (#119167)
Add a prologue to the kernel entry to handle cases where code designed for kernarg preloading is executed on hardware equipped with incompatible firmware. If hardware has compatible firmware the 256 bytes at the start of the kernel entry will be skipped. This skipping is done automatically by hardware that supports the feature. A pass is added which is intended to be run at the very end of the pipeline to avoid any optimizations that would assume the prologue is a real predecessor block to the actual code start. In reality we have two possible entry points for the function. 1. The optimized path that supports kernarg preloading which begins at an offset of 256 bytes. 2. The backwards compatible entry point which starts at offset 0.
1 parent b900379 commit 2e5c298

15 files changed

+1203
-402
lines changed

llvm/docs/AMDGPUUsage.rst

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5914,10 +5914,7 @@ additional 256 bytes to the kernel_code_entry_byte_offset. This addition
59145914
facilitates the incorporation of a prologue to the kernel entry to handle cases
59155915
where code designed for kernarg preloading is executed on hardware equipped with
59165916
incompatible firmware. If hardware has compatible firmware the 256 bytes at the
5917-
start of the kernel entry will be skipped. Additionally, the compiler backend
5918-
may insert a trap instruction at the start of the kernel prologue to manage
5919-
situations where kernarg preloading is attempted on hardware with incompatible
5920-
firmware.
5917+
start of the kernel entry will be skipped.
59215918

59225919
With code object V5 and later, hidden kernel arguments that are normally
59235920
accessed through the Implicit Argument Ptr, may be preloaded into User SGPRs.

llvm/lib/Target/AMDGPU/AMDGPU.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ createAMDGPULowerModuleLDSLegacyPass(const AMDGPUTargetMachine *TM = nullptr);
6464
ModulePass *createAMDGPULowerBufferFatPointersPass();
6565
FunctionPass *createSIModeRegisterPass();
6666
FunctionPass *createGCNPreRAOptimizationsPass();
67+
FunctionPass *createAMDGPUPreloadKernArgPrologLegacyPass();
6768

6869
struct AMDGPUSimplifyLibCallsPass : PassInfoMixin<AMDGPUSimplifyLibCallsPass> {
6970
AMDGPUSimplifyLibCallsPass() {}
@@ -230,6 +231,9 @@ extern char &AMDGPUPerfHintAnalysisLegacyID;
230231
void initializeGCNRegPressurePrinterPass(PassRegistry &);
231232
extern char &GCNRegPressurePrinterID;
232233

234+
void initializeAMDGPUPreloadKernArgPrologLegacyPass(PassRegistry &);
235+
extern char &AMDGPUPreloadKernArgPrologLegacyID;
236+
233237
// Passes common to R600 and SI
234238
FunctionPass *createAMDGPUPromoteAlloca();
235239
void initializeAMDGPUPromoteAllocaPass(PassRegistry&);

llvm/lib/Target/AMDGPU/AMDGPUArgumentUsageInfo.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
#ifndef LLVM_LIB_TARGET_AMDGPU_AMDGPUARGUMENTUSAGEINFO_H
1010
#define LLVM_LIB_TARGET_AMDGPU_AMDGPUARGUMENTUSAGEINFO_H
1111

12+
#include "MCTargetDesc/AMDGPUMCTargetDesc.h"
1213
#include "llvm/ADT/DenseMap.h"
1314
#include "llvm/CodeGen/Register.h"
1415
#include "llvm/Pass.h"
@@ -161,6 +162,8 @@ struct AMDGPUFunctionArgInfo {
161162

162163
// Map the index of preloaded kernel arguments to its descriptor.
163164
SmallDenseMap<int, KernArgPreloadDescriptor> PreloadKernArgs{};
165+
// The first user SGPR allocated for kernarg preloading.
166+
Register FirstKernArgPreloadReg;
164167

165168
std::tuple<const ArgDescriptor *, const TargetRegisterClass *, LLT>
166169
getPreloadedValue(PreloadedValue Value) const;

llvm/lib/Target/AMDGPU/AMDGPUAsmPrinter.cpp

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -207,12 +207,6 @@ void AMDGPUAsmPrinter::emitFunctionBodyStart() {
207207

208208
if (STM.isAmdHsaOS())
209209
HSAMetadataStream->emitKernel(*MF, CurrentProgramInfo);
210-
211-
if (MFI.getNumKernargPreloadedSGPRs() > 0) {
212-
assert(AMDGPU::hasKernargPreload(STM));
213-
getTargetStreamer()->EmitKernargPreloadHeader(*getGlobalSTI(),
214-
STM.isAmdHsaOS());
215-
}
216210
}
217211

218212
void AMDGPUAsmPrinter::emitFunctionBodyEnd() {
Lines changed: 211 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,211 @@
1+
//===- AMDGPUPreloadKernArgProlog.cpp - Preload KernArg Prolog ------------===//
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+
/// \file This pass creates a backward compatibility layer for kernel argument
10+
/// preloading in situations where code is compiled with kernel argument
11+
/// preloading enabled but executed on hardware without firmware support for it.
12+
///
13+
/// To avoid recompilation, the pass inserts a block at the beginning of the
14+
/// program that loads the kernel arguments into SGPRs using s_load
15+
/// instructions. This sets up the registers exactly as they would be on systems
16+
/// with compatible firmware.
17+
///
18+
/// This effectively creates two entry points for the kernel. Firmware that
19+
/// supports the feature will automatically jump past the first 256 bytes of the
20+
/// program, skipping the compatibility layer and directly starting execution on
21+
/// the optimized code path.
22+
///
23+
/// This pass should be run as late as possible to prevent any optimizations
24+
/// that might assume the padding is dead code or that the added prologue is a
25+
/// true predecessor of the kernel entry block.
26+
//
27+
//===----------------------------------------------------------------------===//
28+
29+
#include "AMDGPUPreloadKernArgProlog.h"
30+
#include "AMDGPU.h"
31+
#include "GCNSubtarget.h"
32+
#include "SIMachineFunctionInfo.h"
33+
#include "llvm/CodeGen/MachineFunctionPass.h"
34+
#include "llvm/TargetParser/TargetParser.h"
35+
36+
using namespace llvm;
37+
38+
#define DEBUG_TYPE "amdgpu-preload-kern-arg-prolog"
39+
40+
namespace {
41+
42+
// Used to build s_loads maping user SGPRs to kernel arguments
43+
struct LoadConfig {
44+
unsigned Size;
45+
const TargetRegisterClass *RegClass;
46+
unsigned Opcode;
47+
Register LoadReg = Register();
48+
};
49+
50+
class AMDGPUPreloadKernArgProlog {
51+
public:
52+
AMDGPUPreloadKernArgProlog(MachineFunction &MF);
53+
54+
bool run();
55+
56+
private:
57+
MachineFunction &MF;
58+
const GCNSubtarget &ST;
59+
const SIMachineFunctionInfo &MFI;
60+
const SIInstrInfo &TII;
61+
const TargetRegisterInfo &TRI;
62+
63+
// Create a new block before the entry point to the kernel. Firmware that
64+
// supports preloading kernel arguments will automatically jump past this
65+
// block to the alternative kernel entry point.
66+
void createBackCompatBlock(unsigned NumKernArgPreloadSGPRs);
67+
68+
// Add instructions to load kernel arguments into SGPRs.
69+
void addBackCompatLoads(MachineBasicBlock *BackCompatMBB,
70+
Register KernArgSegmentPtr,
71+
unsigned NumKernArgPreloadSGPRs);
72+
};
73+
74+
class AMDGPUPreloadKernArgPrologLegacy : public MachineFunctionPass {
75+
public:
76+
static char ID;
77+
78+
AMDGPUPreloadKernArgPrologLegacy() : MachineFunctionPass(ID) {}
79+
80+
StringRef getPassName() const override {
81+
return "AMDGPU Preload Kernel Arguments Prolog";
82+
}
83+
84+
bool runOnMachineFunction(MachineFunction &MF) override;
85+
};
86+
87+
} // end anonymous namespace
88+
89+
char AMDGPUPreloadKernArgPrologLegacy::ID = 0;
90+
91+
INITIALIZE_PASS(AMDGPUPreloadKernArgPrologLegacy, DEBUG_TYPE,
92+
"AMDGPU Preload Kernel Arguments Prolog", false, false)
93+
94+
char &llvm::AMDGPUPreloadKernArgPrologLegacyID =
95+
AMDGPUPreloadKernArgPrologLegacy::ID;
96+
97+
FunctionPass *llvm::createAMDGPUPreloadKernArgPrologLegacyPass() {
98+
return new AMDGPUPreloadKernArgPrologLegacy();
99+
}
100+
101+
bool AMDGPUPreloadKernArgPrologLegacy::runOnMachineFunction(
102+
MachineFunction &MF) {
103+
return AMDGPUPreloadKernArgProlog(MF).run();
104+
}
105+
106+
AMDGPUPreloadKernArgProlog::AMDGPUPreloadKernArgProlog(MachineFunction &MF)
107+
: MF(MF), ST(MF.getSubtarget<GCNSubtarget>()),
108+
MFI(*MF.getInfo<SIMachineFunctionInfo>()), TII(*ST.getInstrInfo()),
109+
TRI(*ST.getRegisterInfo()) {}
110+
111+
bool AMDGPUPreloadKernArgProlog::run() {
112+
if (!ST.hasKernargPreload())
113+
return false;
114+
115+
unsigned NumKernArgPreloadSGPRs = MFI.getNumKernargPreloadedSGPRs();
116+
if (!NumKernArgPreloadSGPRs)
117+
return false;
118+
119+
createBackCompatBlock(NumKernArgPreloadSGPRs);
120+
return true;
121+
}
122+
123+
void AMDGPUPreloadKernArgProlog::createBackCompatBlock(
124+
unsigned NumKernArgPreloadSGPRs) {
125+
auto KernelEntryMBB = MF.begin();
126+
MachineBasicBlock *BackCompatMBB = MF.CreateMachineBasicBlock();
127+
MF.insert(KernelEntryMBB, BackCompatMBB);
128+
129+
assert(MFI.getUserSGPRInfo().hasKernargSegmentPtr() &&
130+
"Kernel argument segment pointer register not set.");
131+
Register KernArgSegmentPtr = MFI.getArgInfo().KernargSegmentPtr.getRegister();
132+
BackCompatMBB->addLiveIn(KernArgSegmentPtr);
133+
134+
// Load kernel arguments to SGPRs
135+
addBackCompatLoads(BackCompatMBB, KernArgSegmentPtr, NumKernArgPreloadSGPRs);
136+
137+
// Wait for loads to complete
138+
AMDGPU::IsaVersion IV = AMDGPU::getIsaVersion(ST.getCPU());
139+
unsigned Waitcnt =
140+
AMDGPU::encodeWaitcnt(IV, getVmcntBitMask(IV), getExpcntBitMask(IV), 0);
141+
BuildMI(BackCompatMBB, DebugLoc(), TII.get(AMDGPU::S_WAITCNT))
142+
.addImm(Waitcnt);
143+
144+
// Branch to kernel start
145+
BuildMI(BackCompatMBB, DebugLoc(), TII.get(AMDGPU::S_BRANCH))
146+
.addMBB(&*KernelEntryMBB);
147+
BackCompatMBB->addSuccessor(&*KernelEntryMBB);
148+
149+
// Create a new basic block for padding to 256 bytes
150+
MachineBasicBlock *PadMBB = MF.CreateMachineBasicBlock();
151+
MF.insert(++BackCompatMBB->getIterator(), PadMBB);
152+
PadMBB->setAlignment(Align(256));
153+
PadMBB->addSuccessor(&*KernelEntryMBB);
154+
}
155+
156+
/// Find the largest possible load size that fits with SGPR alignment
157+
static LoadConfig getLoadParameters(const TargetRegisterInfo &TRI,
158+
Register KernArgPreloadSGPR,
159+
unsigned NumKernArgPreloadSGPRs) {
160+
static constexpr LoadConfig Configs[] = {
161+
{8, &AMDGPU::SReg_256RegClass, AMDGPU::S_LOAD_DWORDX8_IMM},
162+
{4, &AMDGPU::SReg_128RegClass, AMDGPU::S_LOAD_DWORDX4_IMM},
163+
{2, &AMDGPU::SReg_64RegClass, AMDGPU::S_LOAD_DWORDX2_IMM}};
164+
165+
for (const auto &Config : Configs) {
166+
if (NumKernArgPreloadSGPRs >= Config.Size) {
167+
Register LoadReg = TRI.getMatchingSuperReg(KernArgPreloadSGPR,
168+
AMDGPU::sub0, Config.RegClass);
169+
if (LoadReg) {
170+
LoadConfig C(Config);
171+
C.LoadReg = LoadReg;
172+
return C;
173+
}
174+
}
175+
}
176+
177+
// Fallback to a single register
178+
return LoadConfig{1, &AMDGPU::SReg_32RegClass, AMDGPU::S_LOAD_DWORD_IMM,
179+
KernArgPreloadSGPR};
180+
}
181+
182+
void AMDGPUPreloadKernArgProlog::addBackCompatLoads(
183+
MachineBasicBlock *BackCompatMBB, Register KernArgSegmentPtr,
184+
unsigned NumKernArgPreloadSGPRs) {
185+
Register KernArgPreloadSGPR = MFI.getArgInfo().FirstKernArgPreloadReg;
186+
unsigned Offset = 0;
187+
// Fill all user SGPRs used for kernarg preloading with sequential data from
188+
// the kernarg segment
189+
while (NumKernArgPreloadSGPRs > 0) {
190+
LoadConfig Config =
191+
getLoadParameters(TRI, KernArgPreloadSGPR, NumKernArgPreloadSGPRs);
192+
193+
BuildMI(BackCompatMBB, DebugLoc(), TII.get(Config.Opcode), Config.LoadReg)
194+
.addReg(KernArgSegmentPtr)
195+
.addImm(Offset)
196+
.addImm(0);
197+
198+
Offset += 4 * Config.Size;
199+
KernArgPreloadSGPR = KernArgPreloadSGPR.asMCReg() + Config.Size;
200+
NumKernArgPreloadSGPRs -= Config.Size;
201+
}
202+
}
203+
204+
PreservedAnalyses
205+
AMDGPUPreloadKernArgPrologPass::run(MachineFunction &MF,
206+
MachineFunctionAnalysisManager &) {
207+
if (!AMDGPUPreloadKernArgProlog(MF).run())
208+
return PreservedAnalyses::all();
209+
210+
return PreservedAnalyses::none();
211+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
//===- AMDGPUPreloadKernargProlog.h ----------------------------*- C++ -*-===//
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+
#ifndef LLVM_LIB_TARGET_AMDGPU_PRELOAD_KERNARG_PROLOG_H
10+
#define LLVM_LIB_TARGET_AMDGPU_PRELOAD_KERNARG_PROLOG_H
11+
12+
#include "llvm/CodeGen/MachinePassManager.h"
13+
14+
namespace llvm {
15+
16+
class AMDGPUPreloadKernArgPrologPass
17+
: public PassInfoMixin<AMDGPUPreloadKernArgPrologPass> {
18+
public:
19+
PreservedAnalyses run(MachineFunction &MF,
20+
MachineFunctionAnalysisManager &AM);
21+
};
22+
23+
} // end namespace llvm
24+
25+
#endif // LLVM_LIB_TARGET_AMDGPU_PRELOAD_KERNARG_PROLOG_H

llvm/lib/Target/AMDGPU/AMDGPUTargetMachine.cpp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -540,6 +540,7 @@ extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeAMDGPUTarget() {
540540
initializeGCNPreRALongBranchRegPass(*PR);
541541
initializeGCNRewritePartialRegUsesPass(*PR);
542542
initializeGCNRegPressurePrinterPass(*PR);
543+
initializeAMDGPUPreloadKernArgPrologLegacyPass(*PR);
543544
}
544545

545546
static std::unique_ptr<TargetLoweringObjectFile> createTLOF(const Triple &TT) {
@@ -1669,6 +1670,7 @@ void GCNPassConfig::addPreEmitPass() {
16691670
addPass(&AMDGPUInsertDelayAluID);
16701671

16711672
addPass(&BranchRelaxationPassID);
1673+
addPass(createAMDGPUPreloadKernArgPrologLegacyPass());
16721674
}
16731675

16741676
TargetPassConfig *GCNTargetMachine::createPassConfig(PassManagerBase &PM) {

llvm/lib/Target/AMDGPU/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ add_llvm_target(AMDGPUCodeGen
8888
AMDGPUPerfHintAnalysis.cpp
8989
AMDGPUPostLegalizerCombiner.cpp
9090
AMDGPUPreLegalizerCombiner.cpp
91+
AMDGPUPreloadKernArgProlog.cpp
9192
AMDGPUPrintfRuntimeBinding.cpp
9293
AMDGPUPromoteAlloca.cpp
9394
AMDGPUPromoteKernelArguments.cpp

llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUTargetStreamer.cpp

Lines changed: 0 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -338,15 +338,6 @@ bool AMDGPUTargetAsmStreamer::EmitHSAMetadata(
338338
return true;
339339
}
340340

341-
bool AMDGPUTargetAsmStreamer::EmitKernargPreloadHeader(
342-
const MCSubtargetInfo &STI, bool TrapEnabled) {
343-
OS << (TrapEnabled ? "\ts_trap 2" : "\ts_endpgm")
344-
<< " ; Kernarg preload header. Trap with incompatible firmware that "
345-
"doesn't support preloading kernel arguments.\n";
346-
OS << "\t.fill 63, 4, 0xbf800000 ; s_nop 0\n";
347-
return true;
348-
}
349-
350341
bool AMDGPUTargetAsmStreamer::EmitCodeEnd(const MCSubtargetInfo &STI) {
351342
const uint32_t Encoded_s_code_end = 0xbf9f0000;
352343
const uint32_t Encoded_s_nop = 0xbf800000;
@@ -935,20 +926,6 @@ bool AMDGPUTargetELFStreamer::EmitHSAMetadata(msgpack::Document &HSAMetadataDoc,
935926
return true;
936927
}
937928

938-
bool AMDGPUTargetELFStreamer::EmitKernargPreloadHeader(
939-
const MCSubtargetInfo &STI, bool TrapEnabled) {
940-
const uint32_t Encoded_s_nop = 0xbf800000;
941-
const uint32_t Encoded_s_trap = 0xbf920002;
942-
const uint32_t Encoded_s_endpgm = 0xbf810000;
943-
const uint32_t TrapInstr = TrapEnabled ? Encoded_s_trap : Encoded_s_endpgm;
944-
MCStreamer &OS = getStreamer();
945-
OS.emitInt32(TrapInstr);
946-
for (int i = 0; i < 63; ++i) {
947-
OS.emitInt32(Encoded_s_nop);
948-
}
949-
return true;
950-
}
951-
952929
bool AMDGPUTargetELFStreamer::EmitCodeEnd(const MCSubtargetInfo &STI) {
953930
const uint32_t Encoded_s_code_end = 0xbf9f0000;
954931
const uint32_t Encoded_s_nop = 0xbf800000;

llvm/lib/Target/AMDGPU/MCTargetDesc/AMDGPUTargetStreamer.h

Lines changed: 0 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -96,12 +96,6 @@ class AMDGPUTargetStreamer : public MCTargetStreamer {
9696
/// \returns True on success, false on failure.
9797
virtual bool EmitCodeEnd(const MCSubtargetInfo &STI) { return true; }
9898

99-
/// \returns True on success, false on failure.
100-
virtual bool EmitKernargPreloadHeader(const MCSubtargetInfo &STI,
101-
bool TrapEnabled) {
102-
return true;
103-
}
104-
10599
virtual void
106100
EmitAmdhsaKernelDescriptor(const MCSubtargetInfo &STI, StringRef KernelName,
107101
const AMDGPU::MCKernelDescriptor &KernelDescriptor,
@@ -168,10 +162,6 @@ class AMDGPUTargetAsmStreamer final : public AMDGPUTargetStreamer {
168162
/// \returns True on success, false on failure.
169163
bool EmitCodeEnd(const MCSubtargetInfo &STI) override;
170164

171-
/// \returns True on success, false on failure.
172-
bool EmitKernargPreloadHeader(const MCSubtargetInfo &STI,
173-
bool TrapEnabled) override;
174-
175165
void
176166
EmitAmdhsaKernelDescriptor(const MCSubtargetInfo &STI, StringRef KernelName,
177167
const AMDGPU::MCKernelDescriptor &KernelDescriptor,
@@ -225,10 +215,6 @@ class AMDGPUTargetELFStreamer final : public AMDGPUTargetStreamer {
225215
/// \returns True on success, false on failure.
226216
bool EmitCodeEnd(const MCSubtargetInfo &STI) override;
227217

228-
/// \returns True on success, false on failure.
229-
bool EmitKernargPreloadHeader(const MCSubtargetInfo &STI,
230-
bool TrapEnabled) override;
231-
232218
void
233219
EmitAmdhsaKernelDescriptor(const MCSubtargetInfo &STI, StringRef KernelName,
234220
const AMDGPU::MCKernelDescriptor &KernelDescriptor,

0 commit comments

Comments
 (0)