Proteus
Programmable JIT compilation and optimization for C/C++ using LLVM
Loading...
Searching...
No Matches
CoreLLVMCUDA.h
Go to the documentation of this file.
1#ifndef PROTEUS_CORE_LLVM_CUDA_H
2#define PROTEUS_CORE_LLVM_CUDA_H
3
9
10#include <llvm/ADT/SmallVector.h>
11#include <llvm/ADT/StringRef.h>
12#include <llvm/CodeGen/MachineModuleInfo.h>
13#include <llvm/IR/LegacyPassManager.h>
14#include <llvm/IR/Module.h>
15#include <llvm/Support/MemoryBufferRef.h>
16#include <llvm/Support/TargetSelect.h>
17#include <llvm/Target/TargetMachine.h>
18
19namespace proteus {
20
21using namespace llvm;
22
23namespace detail {
24
25inline const SmallVector<StringRef> &gridDimXFnName() {
26 static SmallVector<StringRef> Names = {"llvm.nvvm.read.ptx.sreg.nctaid.x"};
27 return Names;
28}
29
30inline const SmallVector<StringRef> &gridDimYFnName() {
31 static SmallVector<StringRef> Names = {"llvm.nvvm.read.ptx.sreg.nctaid.y"};
32 return Names;
33}
34
35inline const SmallVector<StringRef> &gridDimZFnName() {
36 static SmallVector<StringRef> Names = {"llvm.nvvm.read.ptx.sreg.nctaid.z"};
37 return Names;
38}
39
40inline const SmallVector<StringRef> &blockDimXFnName() {
41 static SmallVector<StringRef> Names = {"llvm.nvvm.read.ptx.sreg.ntid.x"};
42 return Names;
43}
44
45inline const SmallVector<StringRef> &blockDimYFnName() {
46 static SmallVector<StringRef> Names = {"llvm.nvvm.read.ptx.sreg.ntid.y"};
47 return Names;
48}
49
50inline const SmallVector<StringRef> &blockDimZFnName() {
51 static SmallVector<StringRef> Names = {"llvm.nvvm.read.ptx.sreg.ntid.z"};
52 return Names;
53}
54
55inline const SmallVector<StringRef> &blockIdxXFnName() {
56 static SmallVector<StringRef> Names = {"llvm.nvvm.read.ptx.sreg.ctaid.x"};
57 return Names;
58}
59
60inline const SmallVector<StringRef> &blockIdxYFnName() {
61 static SmallVector<StringRef> Names = {"llvm.nvvm.read.ptx.sreg.ctaid.y"};
62 return Names;
63}
64
65inline const SmallVector<StringRef> &blockIdxZFnName() {
66 static SmallVector<StringRef> Names = {"llvm.nvvm.read.ptx.sreg.ctaid.z"};
67 return Names;
68}
69
70inline const SmallVector<StringRef> &threadIdxXFnName() {
71 static SmallVector<StringRef> Names = {"llvm.nvvm.read.ptx.sreg.tid.x"};
72 return Names;
73}
74
75inline const SmallVector<StringRef> &threadIdxYFnName() {
76 static SmallVector<StringRef> Names = {"llvm.nvvm.read.ptx.sreg.tid.y"};
77 return Names;
78}
79
80inline const SmallVector<StringRef> &threadIdxZFnName() {
81 static SmallVector<StringRef> Names = {"llvm.nvvm.read.ptx.sreg.tid.z"};
82 return Names;
83}
84
85} // namespace detail
86
87inline void setLaunchBoundsForKernel(Function &F, int MaxThreadsPerSM,
88 int MinBlocksPerSM = 0) {
89 auto *M = F.getParent();
90 NamedMDNode *NvvmAnnotations = M->getNamedMetadata("nvvm.annotations");
91 assert(NvvmAnnotations && "Expected non-null nvvm.annotations metadata");
92 auto *FuncMetadata = ConstantAsMetadata::get(&F);
93
94 auto SetMDNode = [&](const char *MDName, int MDValue) {
95 auto *MDNodeName = MDString::get(M->getContext(), MDName);
96 auto *MDNodeValue = ConstantAsMetadata::get(
97 ConstantInt::get(Type::getInt32Ty(M->getContext()), MDValue));
98
99 for (auto *MetadataNode : NvvmAnnotations->operands()) {
100 if (MetadataNode->getNumOperands() != 3)
101 continue;
102
103 auto *PtrMetadata = MetadataNode->getOperand(0).get();
104 auto *DescMetadata = MetadataNode->getOperand(1).get();
105 if (PtrMetadata == FuncMetadata && MDNodeName == DescMetadata) {
106 MetadataNode->replaceOperandWith(2, MDNodeValue);
107 return;
108 }
109 }
110 Metadata *MDVals[] = {FuncMetadata, MDNodeName, MDNodeValue};
111 NvvmAnnotations->addOperand(MDNode::get(M->getContext(), MDVals));
112 };
113
114 // TODO: fix hardcoded 1024 as the maximum, by reading device
115 // properties.
116 SetMDNode("maxntid", std::min(1024, MaxThreadsPerSM));
117 if (MinBlocksPerSM != 0)
118 SetMDNode("minctasm", MinBlocksPerSM);
119}
120
121inline void codegenPTX(Module &M, StringRef DeviceArch,
122 SmallVectorImpl<char> &PTXStr) {
123 // TODO: It is possbile to use PTX directly through the CUDA PTX JIT
124 // interface. Maybe useful if we can re-link globals using the CUDA API.
125 // Check this reference for PTX JIT caching:
126 // https://developer.nvidia.com/blog/cuda-pro-tip-understand-fat-binaries-jit-caching/
127 // Interesting env vars: CUDA_CACHE_DISABLE, CUDA_CACHE_MAXSIZE,
128 // CUDA_CACHE_PATH, CUDA_FORCE_PTX_JIT.
129
130 Timer T;
131 auto TMExpected = proteus::detail::createTargetMachine(M, DeviceArch);
132 if (!TMExpected)
133 reportFatalError(toString(TMExpected.takeError()));
134
135 std::unique_ptr<TargetMachine> TM = std::move(*TMExpected);
136 TargetLibraryInfoImpl TLII(Triple(M.getTargetTriple()));
137 M.setDataLayout(TM->createDataLayout());
138
139 legacy::PassManager PM;
140 PM.add(new TargetLibraryInfoWrapperPass(TLII));
141 MachineModuleInfoWrapperPass *MMIWP =
142#if LLVM_VERSION_MAJOR >= 20
143 new MachineModuleInfoWrapperPass(TM.get());
144#else
145 new MachineModuleInfoWrapperPass(
146 reinterpret_cast<LLVMTargetMachine *>(TM.get()));
147#endif
148
149 raw_svector_ostream PTXOS(PTXStr);
150#if LLVM_VERSION_MAJOR >= 18
151 TM->addPassesToEmitFile(PM, PTXOS, nullptr, CodeGenFileType::AssemblyFile,
152 /* DisableVerify */ false, MMIWP);
153#else
154 TM->addPassesToEmitFile(PM, PTXOS, nullptr, CGFT_AssemblyFile,
155 /* DisableVerify */ false, MMIWP);
156#endif
157
158 PM.run(M);
159
161 << "Codegen ptx " << T.elapsed() << " ms\n");
162}
163
164inline std::unique_ptr<MemoryBuffer>
165codegenObject(Module &M, StringRef DeviceArch,
166 SmallPtrSetImpl<void *> &GlobalLinkedBinaries,
168 if (CGOption != CodegenOption::RTC)
169 reportFatalError("Only RTC compilation is supported for CUDA");
170 SmallVector<char, 4096> PTXStr;
171 size_t BinSize;
172
173 codegenPTX(M, DeviceArch, PTXStr);
174 PTXStr.push_back('\0');
175
176 Timer T;
177 nvPTXCompilerHandle PTXCompiler;
179 nvPTXCompilerCreate(&PTXCompiler, PTXStr.size(), PTXStr.data()));
180 std::string ArchOpt = ("--gpu-name=" + DeviceArch).str();
181 std::string RDCOption = "";
182 if (!GlobalLinkedBinaries.empty())
183 RDCOption = "-c";
184
186 const char *CompileOptions[] = {ArchOpt.c_str(), "--verbose",
187 RDCOption.c_str()};
188 size_t NumCompileOptions = 2 + (RDCOption.empty() ? 0 : 1);
190 nvPTXCompilerCompile(PTXCompiler, NumCompileOptions, CompileOptions));
191 } else {
192 const char *CompileOptions[] = {ArchOpt.c_str(), RDCOption.c_str()};
193 size_t NumCompileOptions = 1 + (RDCOption.empty() ? 0 : 1);
195 nvPTXCompilerCompile(PTXCompiler, NumCompileOptions, CompileOptions));
196 }
197
199 nvPTXCompilerGetCompiledProgramSize(PTXCompiler, &BinSize));
200 auto ObjBuf = WritableMemoryBuffer::getNewUninitMemBuffer(BinSize);
202 nvPTXCompilerGetCompiledProgram(PTXCompiler, ObjBuf->getBufferStart()));
203
204 if (Config::get().ProteusDebugOutput) {
205 size_t LogSize;
207 nvPTXCompilerGetInfoLogSize(PTXCompiler, &LogSize));
208 auto Log = std::make_unique<char[]>(LogSize);
210 nvPTXCompilerGetInfoLog(PTXCompiler, Log.get()));
211 Logger::logs("proteus") << "=== nvPTXCompiler Log\n" << Log.get() << "\n";
212 }
213
214 proteusNvPTXCompilerErrCheck(nvPTXCompilerDestroy(&PTXCompiler));
215
216 std::unique_ptr<MemoryBuffer> FinalObjBuf;
217 if (!GlobalLinkedBinaries.empty()) {
218 // Retain the primary CUDA context if needed. This is required by threaded
219 // async compilation for ensuring a valid CUDA context is set when linking
220 // with the CUDA API.
221 CUcontext CUCtx;
222 proteusCuErrCheck(cuCtxGetCurrent(&CUCtx));
223 if (!CUCtx) {
224 CUdevice CUDev;
225 proteusCuErrCheck(cuDeviceGet(&CUDev, 0));
226 proteusCuErrCheck(cuDevicePrimaryCtxRetain(&CUCtx, CUDev));
227 proteusCuErrCheck(cuCtxSetCurrent(CUCtx));
228 }
229
230 // TODO: re-implement using the more recent nvJitLink interface.
231 CUlinkState CULinkState;
232 proteusCuErrCheck(cuLinkCreate(0, nullptr, nullptr, &CULinkState));
233 for (auto *Ptr : GlobalLinkedBinaries) {
234 // We do not know the size of the binary but the CUDA API just needs a
235 // non-zero argument.
236 proteusCuErrCheck(cuLinkAddData(CULinkState, CU_JIT_INPUT_FATBINARY, Ptr,
237 1, "", 0, 0, 0));
238 }
239
240 // Again using a non-zero argument, though we can get the size from the ptx
241 // compiler.
242 proteusCuErrCheck(cuLinkAddData(
243 CULinkState, CU_JIT_INPUT_FATBINARY,
244 static_cast<void *>(ObjBuf->getBufferStart()), 1, "", 0, 0, 0));
245
246 void *BinOut;
247 size_t BinSize;
248 proteusCuErrCheck(cuLinkComplete(CULinkState, &BinOut, &BinSize));
249 FinalObjBuf = MemoryBuffer::getMemBufferCopy(
250 StringRef{static_cast<char *>(BinOut), BinSize});
251 } else {
252 FinalObjBuf = std::move(ObjBuf);
253 }
254
256 << "Codegen CUDA RTC " << T.elapsed() << " ms\n");
257 return FinalObjBuf;
258}
259
260} // namespace proteus
261
262#endif
#define PROTEUS_TIMER_OUTPUT(x)
Definition TimeTracing.h:54
#define proteusNvPTXCompilerErrCheck(CALL)
Definition UtilsCUDA.h:39
#define proteusCuErrCheck(CALL)
Definition UtilsCUDA.h:28
static Config & get()
Definition Config.h:334
bool ProteusDebugOutput
Definition Config.h:350
static llvm::raw_ostream & outs(const std::string &Name)
Definition Logger.h:25
static llvm::raw_ostream & logs(const std::string &Name)
Definition Logger.h:19
Definition TimeTracing.h:40
uint64_t elapsed()
Definition TimeTracing.cpp:51
Definition CompiledLibrary.h:7
const SmallVector< StringRef > & threadIdxXFnName()
Definition CoreLLVMCUDA.h:70
const SmallVector< StringRef > & gridDimYFnName()
Definition CoreLLVMCUDA.h:30
const SmallVector< StringRef > & threadIdxZFnName()
Definition CoreLLVMCUDA.h:80
const SmallVector< StringRef > & blockIdxZFnName()
Definition CoreLLVMCUDA.h:65
const SmallVector< StringRef > & gridDimZFnName()
Definition CoreLLVMCUDA.h:35
const SmallVector< StringRef > & gridDimXFnName()
Definition CoreLLVMCUDA.h:25
const SmallVector< StringRef > & blockIdxXFnName()
Definition CoreLLVMCUDA.h:55
Expected< std::unique_ptr< TargetMachine > > createTargetMachine(Module &M, StringRef Arch, unsigned OptLevel=3)
Definition CoreLLVM.h:52
const SmallVector< StringRef > & threadIdxYFnName()
Definition CoreLLVMCUDA.h:75
const SmallVector< StringRef > & blockIdxYFnName()
Definition CoreLLVMCUDA.h:60
const SmallVector< StringRef > & blockDimYFnName()
Definition CoreLLVMCUDA.h:45
const SmallVector< StringRef > & blockDimZFnName()
Definition CoreLLVMCUDA.h:50
const SmallVector< StringRef > & blockDimXFnName()
Definition CoreLLVMCUDA.h:40
Definition MemoryCache.h:26
void codegenPTX(Module &M, StringRef DeviceArch, SmallVectorImpl< char > &PTXStr)
Definition CoreLLVMCUDA.h:121
void setLaunchBoundsForKernel(Function &F, int MaxThreadsPerSM, int MinBlocksPerSM=0)
Definition CoreLLVMCUDA.h:87
void reportFatalError(const llvm::Twine &Reason, const char *FILE, unsigned Line)
Definition Error.cpp:14
CodegenOption
Definition Config.h:16
std::unique_ptr< MemoryBuffer > codegenObject(Module &M, StringRef DeviceArch, SmallPtrSetImpl< void * > &GlobalLinkedBinaries, CodegenOption CGOption=CodegenOption::RTC)
Definition CoreLLVMCUDA.h:165
std::string toString(CodegenOption Option)
Definition Config.h:28