MLIR 24.0.0git
Target.cpp
Go to the documentation of this file.
1//===- Target.cpp - MLIR LLVM NVVM target compilation -----------*- 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// This files defines NVVM target related functions including registration
10// calls for the `#nvvm.target` compilation attribute.
11//
12//===----------------------------------------------------------------------===//
13
15
28#include "llvm/Support/InterleavedRange.h"
29
30#include "llvm/ADT/ScopeExit.h"
31#include "llvm/Config/Targets.h"
32#include "llvm/Support/DebugLog.h"
33#include "llvm/Support/FileSystem.h"
34#include "llvm/Support/FileUtilities.h"
35#include "llvm/Support/FormatVariadic.h"
36#include "llvm/Support/MemoryBuffer.h"
37#include "llvm/Support/Path.h"
38#include "llvm/Support/Process.h"
39#include "llvm/Support/Program.h"
40#include "llvm/Support/TargetSelect.h"
41#include "llvm/Support/Timer.h"
42#include "llvm/Support/raw_ostream.h"
43
44#include <cstdint>
45#include <cstdlib>
46#include <optional>
47
48using namespace mlir;
49using namespace mlir::NVVM;
50
51#ifndef __DEFAULT_CUDATOOLKIT_PATH__
52#define __DEFAULT_CUDATOOLKIT_PATH__ ""
53#endif
54
55extern "C" const unsigned char _mlir_embedded_libdevice[];
56extern "C" const unsigned _mlir_embedded_libdevice_size;
57
58namespace {
59// Implementation of the `TargetAttrInterface` model.
60class NVVMTargetAttrImpl
61 : public gpu::TargetAttrInterface::FallbackModel<NVVMTargetAttrImpl> {
62public:
63 std::optional<mlir::gpu::SerializedObject>
64 serializeToObject(Attribute attribute, Operation *module,
65 const gpu::TargetOptions &options) const;
66
67 Attribute createObject(Attribute attribute, Operation *module,
68 const mlir::gpu::SerializedObject &object,
69 const gpu::TargetOptions &options) const;
70};
71} // namespace
72
73// Register the NVVM dialect, the NVVM translation & the target interface.
75 DialectRegistry &registry) {
76 registry.addExtension(+[](MLIRContext *ctx, NVVM::NVVMDialect *dialect) {
77 NVVMTargetAttr::attachInterface<NVVMTargetAttrImpl>(*ctx);
78 });
79}
80
87
88// Search for the CUDA toolkit path.
90 if (const char *var = std::getenv("CUDA_ROOT"))
91 return var;
92 if (const char *var = std::getenv("CUDA_HOME"))
93 return var;
94 if (const char *var = std::getenv("CUDA_PATH"))
95 return var;
97}
98
100 Operation &module, NVVMTargetAttr target,
101 const gpu::TargetOptions &targetOptions)
103 module, target.getTriple(), target.getChip(), target.getFeatures(),
104 target.getO(), targetOptions.getInitialLlvmIRCallback(),
105 targetOptions.getLinkedLlvmIRCallback(),
106 targetOptions.getOptimizedLlvmIRCallback(),
107 targetOptions.getISACallback(), targetOptions.getLibraryOptions()),
108 target(target), toolkitPath(targetOptions.getToolkitPath()),
109 librariesToLink(targetOptions.getLibrariesToLink()) {
110
111 // If `targetOptions` have an empty toolkitPath use `getCUDAToolkitPath`
112 if (toolkitPath.empty())
114
115 // Append the files in the target attribute.
116 if (target.getLink())
117 librariesToLink.append(target.getLink().begin(), target.getLink().end());
118
119 // Append libdevice to the files to be loaded.
120 (void)appendStandardLibs();
121}
122
124 static llvm::once_flag initializeBackendOnce;
125 llvm::call_once(initializeBackendOnce, []() {
126 // If the `NVPTX` LLVM target was built, initialize it.
127#if LLVM_HAS_NVPTX_TARGET
128 LLVMInitializeNVPTXTarget();
129 LLVMInitializeNVPTXTargetInfo();
130 LLVMInitializeNVPTXTargetMC();
131 LLVMInitializeNVPTXAsmPrinter();
132#endif
133 });
134}
135
136NVVMTargetAttr SerializeGPUModuleBase::getTarget() const { return target; }
137
139
143
144// Try to append `libdevice` from a CUDA toolkit installation.
146#if MLIR_NVVM_EMBED_LIBDEVICE
147 // If libdevice is embedded in the binary, we don't look it up on the
148 // filesystem.
149 MLIRContext *ctx = target.getContext();
150 auto type =
152 IntegerType::get(ctx, 8));
153 auto resourceManager = DenseResourceElementsHandle::getManagerInterface(ctx);
154
155 // Lookup if we already loaded the resource, otherwise create it.
157 resourceManager.getBlobManager().lookup("_mlir_embedded_libdevice");
158 if (blob) {
159 librariesToLink.push_back(DenseResourceElementsAttr::get(
161 blob, ctx->getLoadedDialect<BuiltinDialect>())));
162 return success();
163 }
164
165 // Allocate a resource using one of the UnManagedResourceBlob method to wrap
166 // the embedded data.
170 librariesToLink.push_back(DenseResourceElementsAttr::get(
171 type, resourceManager.insert("_mlir_embedded_libdevice",
172 std::move(unmanagedBlob))));
173#else
174 StringRef pathRef = getToolkitPath();
175 if (!pathRef.empty()) {
177 path.insert(path.begin(), pathRef.begin(), pathRef.end());
178 pathRef = StringRef(path.data(), path.size());
179 if (!llvm::sys::fs::is_directory(pathRef)) {
180 getOperation().emitError() << "CUDA path: " << pathRef
181 << " does not exist or is not a directory.\n";
182 return failure();
183 }
184 llvm::sys::path::append(path, "nvvm", "libdevice", "libdevice.10.bc");
185 pathRef = StringRef(path.data(), path.size());
186 if (!llvm::sys::fs::is_regular_file(pathRef)) {
187 getOperation().emitError() << "LibDevice path: " << pathRef
188 << " does not exist or is not a file.\n";
189 return failure();
190 }
191 librariesToLink.push_back(StringAttr::get(target.getContext(), pathRef));
192 }
193#endif
194 return success();
195}
196
197std::optional<SmallVector<std::unique_ptr<llvm::Module>>>
200 if (failed(loadBitcodeFilesFromList(module.getContext(), librariesToLink,
201 bcFiles, true)))
202 return std::nullopt;
203 return std::move(bcFiles);
204}
205
206namespace {
207class NVPTXSerializer : public SerializeGPUModuleBase {
208public:
209 NVPTXSerializer(Operation &module, NVVMTargetAttr target,
210 const gpu::TargetOptions &targetOptions);
211
212 /// Returns the GPU module op being serialized.
213 gpu::GPUModuleOp getOperation();
214
215 /// Compiles PTX to cubin using `ptxas`.
216 FailureOr<SmallVector<char, 0>> compileToBinary(StringRef ptxCode);
217
218 /// Compiles PTX to cubin using the `nvptxcompiler` library.
219 FailureOr<SmallVector<char, 0>> compileToBinaryNVPTX(StringRef ptxCode);
220
221 /// Serializes the LLVM module to an object format, depending on the
222 /// compilation target selected in target options.
223 FailureOr<SmallVector<char, 0>>
224 moduleToObject(llvm::Module &llvmModule) override;
225
226 /// Get LLVMIR->ISA performance result.
227 /// Return nullopt if moduleToObject has not been called or the target format
228 /// is LLVMIR.
229 std::optional<int64_t> getLLVMIRToISATimeInMs();
230
231 /// Get ISA->Binary performance result.
232 /// Return nullopt if moduleToObject has not been called or the target format
233 /// is LLVMIR or ISA.
234 std::optional<int64_t> getISAToBinaryTimeInMs();
235
236 /// Get the compiler log from ISA compiler.
237 StringRef getISACompilerLog() const;
238
239private:
240 using TmpFile = std::pair<llvm::SmallString<128>, llvm::FileRemover>;
241
242 /// Creates a temp file.
243 std::optional<TmpFile> createTemp(StringRef name, StringRef suffix);
244
245 /// Finds the `tool` path, where `tool` is the name of the binary to search,
246 /// i.e. `ptxas` or `fatbinary`. The search order is:
247 /// 1. The toolkit path in `targetOptions`.
248 /// 2. In the system PATH.
249 /// 3. The path from `getCUDAToolkitPath()`.
250 std::optional<std::string> findTool(StringRef tool);
251
252 /// Target options.
253 gpu::TargetOptions targetOptions;
254
255 /// LLVMIR->ISA perf result.
256 std::optional<int64_t> llvmToISATimeInMs;
257
258 /// ISA->Binary perf result.
259 std::optional<int64_t> isaToBinaryTimeInMs;
260
261 /// Compiler log from ptxas or libnvptxcompiler.
262 std::string isaCompilerLog;
263};
264} // namespace
265
266NVPTXSerializer::NVPTXSerializer(Operation &module, NVVMTargetAttr target,
267 const gpu::TargetOptions &targetOptions)
268 : SerializeGPUModuleBase(module, target, targetOptions),
269 targetOptions(targetOptions), llvmToISATimeInMs(std::nullopt),
270 isaToBinaryTimeInMs(std::nullopt) {}
271
272std::optional<NVPTXSerializer::TmpFile>
273NVPTXSerializer::createTemp(StringRef name, StringRef suffix) {
274 llvm::SmallString<128> filename;
275 if (name.size() > 80)
276 name = name.substr(0, 80);
277 std::error_code ec =
278 llvm::sys::fs::createTemporaryFile(name, suffix, filename);
279 if (ec) {
280 getOperation().emitError() << "Couldn't create the temp file: `" << filename
281 << "`, error message: " << ec.message();
282 return std::nullopt;
283 }
284 return TmpFile(filename, llvm::FileRemover(filename.c_str()));
285}
286
287std::optional<int64_t> NVPTXSerializer::getLLVMIRToISATimeInMs() {
288 return llvmToISATimeInMs;
289}
290
291std::optional<int64_t> NVPTXSerializer::getISAToBinaryTimeInMs() {
292 return isaToBinaryTimeInMs;
293}
294
295StringRef NVPTXSerializer::getISACompilerLog() const { return isaCompilerLog; }
296
297gpu::GPUModuleOp NVPTXSerializer::getOperation() {
298 return dyn_cast<gpu::GPUModuleOp>(&SerializeGPUModuleBase::getOperation());
299}
300
301std::optional<std::string> NVPTXSerializer::findTool(StringRef tool) {
302 // Find the `tool` path.
303 // 1. Check the toolkit path given in the command line.
304 StringRef pathRef = targetOptions.getToolkitPath();
305 SmallVector<char, 256> path;
306 if (!pathRef.empty()) {
307 path.insert(path.begin(), pathRef.begin(), pathRef.end());
308 llvm::sys::path::append(path, "bin", tool);
309 if (llvm::sys::fs::can_execute(path))
310 return StringRef(path.data(), path.size()).str();
311 }
312
313 // 2. Check PATH.
314 if (std::optional<std::string> toolPath =
315 llvm::sys::Process::FindInEnvPath("PATH", tool))
316 return *toolPath;
317
318 // 3. Check `getCUDAToolkitPath()`.
319 pathRef = getCUDAToolkitPath();
320 path.clear();
321 if (!pathRef.empty()) {
322 path.insert(path.begin(), pathRef.begin(), pathRef.end());
323 llvm::sys::path::append(path, "bin", tool);
324 if (llvm::sys::fs::can_execute(path))
325 return StringRef(path.data(), path.size()).str();
326 }
327 getOperation().emitError()
328 << "Couldn't find the `" << tool
329 << "` binary. Please specify the toolkit "
330 "path, add the compiler to $PATH, or set one of the environment "
331 "variables in `NVVM::getCUDAToolkitPath()`.";
332 return std::nullopt;
333}
334
335/// Adds optional command-line arguments to existing arguments.
336template <typename T>
337static void setOptionalCommandlineArguments(NVVMTargetAttr target,
338 SmallVectorImpl<T> &ptxasArgs) {
339 if (!target.hasCmdOptions())
340 return;
341
342 std::optional<mlir::NamedAttribute> cmdOptions = target.getCmdOptions();
343 for (Attribute attr : cast<ArrayAttr>(cmdOptions->getValue())) {
344 if (auto strAttr = dyn_cast<StringAttr>(attr)) {
345 if constexpr (std::is_same_v<T, StringRef>) {
346 ptxasArgs.push_back(strAttr.getValue());
347 } else if constexpr (std::is_same_v<T, const char *>) {
348 ptxasArgs.push_back(strAttr.getValue().data());
349 }
350 }
351 }
352}
353
354// TODO: clean this method & have a generic tool driver or never emit binaries
355// with this mechanism and let another stage take care of it.
356FailureOr<SmallVector<char, 0>>
357NVPTXSerializer::compileToBinary(StringRef ptxCode) {
358 // Determine if the serializer should create a fatbinary with the PTX embeded
359 // or a simple CUBIN binary.
360 const bool createFatbin =
361 targetOptions.getCompilationTarget() == gpu::CompilationTarget::Fatbin;
362
363 // Find the `ptxas` & `fatbinary` tools.
364 std::optional<std::string> ptxasCompiler = findTool("ptxas");
365 if (!ptxasCompiler)
366 return failure();
367 std::optional<std::string> fatbinaryTool;
368 if (createFatbin) {
369 fatbinaryTool = findTool("fatbinary");
370 if (!fatbinaryTool)
371 return failure();
372 }
373 Location loc = getOperation().getLoc();
374
375 // Base name for all temp files: mlir-<module name>-<target triple>-<chip>.
376 std::string basename =
377 llvm::formatv("mlir-{0}-{1}-{2}", getOperation().getNameAttr().getValue(),
378 getTarget().getTriple(), getTarget().getChip());
379
380 // Create temp files:
381 std::optional<TmpFile> ptxFile = createTemp(basename, "ptx");
382 if (!ptxFile)
383 return failure();
384 std::optional<TmpFile> logFile = createTemp(basename, "log");
385 if (!logFile)
386 return failure();
387 std::optional<TmpFile> binaryFile = createTemp(basename, "bin");
388 if (!binaryFile)
389 return failure();
390 TmpFile cubinFile;
391 if (createFatbin) {
392 std::string cubinFilename = (ptxFile->first + ".cubin").str();
393 cubinFile = TmpFile(cubinFilename, llvm::FileRemover(cubinFilename));
394 } else {
395 cubinFile.first = binaryFile->first;
396 }
397
398 std::error_code ec;
399 // Dump the PTX to a temp file.
400 {
401 llvm::raw_fd_ostream ptxStream(ptxFile->first, ec);
402 if (ec)
403 return emitError(loc) << "Couldn't open the file: `" << ptxFile->first
404 << "`, error message: " << ec.message();
405
406 ptxStream << ptxCode;
407 if (ptxStream.has_error())
408 return emitError(loc) << "An error occurred while writing the PTX to: `"
409 << ptxFile->first << "`.";
410
411 ptxStream.flush();
412 }
413
414 // Command redirects.
415 std::optional<StringRef> redirects[] = {
416 std::nullopt,
417 logFile->first,
418 logFile->first,
419 };
420
421 // Get any extra args passed in `targetOptions`.
422 std::pair<llvm::BumpPtrAllocator, SmallVector<const char *>> cmdOpts =
423 targetOptions.tokenizeCmdOptions();
424
425 // Create ptxas args.
426 std::string optLevel = std::to_string(this->optLevel);
427 SmallVector<StringRef, 12> ptxasArgs(
428 {StringRef("ptxas"), StringRef("-arch"), getTarget().getChip(),
429 StringRef(ptxFile->first), StringRef("-o"), StringRef(cubinFile.first),
430 "--opt-level", optLevel});
431
432 bool useFatbin32 = false;
433 for (const auto *cArg : cmdOpts.second) {
434 // All `cmdOpts` are for `ptxas` except `-32` which passes `-32` to
435 // `fatbinary`, indicating a 32-bit target. By default a 64-bit target is
436 // assumed.
437 if (StringRef arg(cArg); arg != "-32")
438 ptxasArgs.push_back(arg);
439 else
440 useFatbin32 = true;
441 }
442
443 // Set optional command line arguments
444 setOptionalCommandlineArguments(getTarget(), ptxasArgs);
445
446 // Create the `fatbinary` args.
447 StringRef chip = getTarget().getChip();
448 // Remove the arch prefix to obtain the compute capability.
449 chip.consume_front("sm_"), chip.consume_front("compute_");
450 // Embed the cubin object.
451 std::string cubinArg =
452 llvm::formatv("--image3=kind=elf,sm={0},file={1}", chip, cubinFile.first)
453 .str();
454 // Embed the PTX file so the driver can JIT if needed.
455 std::string ptxArg =
456 llvm::formatv("--image3=kind=ptx,sm={0},file={1}", chip, ptxFile->first)
457 .str();
458 SmallVector<StringRef, 6> fatbinArgs({StringRef("fatbinary"),
459 useFatbin32 ? "-32" : "-64", cubinArg,
460 ptxArg, "--create", binaryFile->first});
461
462 // Dump tool invocation commands.
463#define DEBUG_TYPE "serialize-to-binary"
464 LDBG() << "Tool invocation for module: " << getOperation().getNameAttr()
465 << "\nptxas executable:" << ptxasCompiler.value()
466 << "\nptxas args: " << llvm::interleaved(ptxasArgs, " ");
467 if (createFatbin)
468 LDBG() << "fatbin args: " << llvm::interleaved(fatbinArgs, " ");
469#undef DEBUG_TYPE
470
471 // Helper function for printing tool error logs.
472 std::string message;
473 auto emitLogError =
474 [&](StringRef toolName) -> FailureOr<SmallVector<char, 0>> {
475 if (message.empty()) {
476 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> toolStderr =
477 llvm::MemoryBuffer::getFile(logFile->first);
478 if (toolStderr)
479 return emitError(loc) << toolName << " invocation failed. Log:\n"
480 << toolStderr->get()->getBuffer();
481 else
482 return emitError(loc) << toolName << " invocation failed.";
483 }
484 return emitError(loc) << toolName
485 << " invocation failed, error message: " << message;
486 };
487
488 // Invoke PTXAS.
489 if (llvm::sys::ExecuteAndWait(ptxasCompiler.value(), ptxasArgs,
490 /*Env=*/std::nullopt,
491 /*Redirects=*/redirects,
492 /*SecondsToWait=*/0,
493 /*MemoryLimit=*/0,
494 /*ErrMsg=*/&message))
495 return emitLogError("`ptxas`");
496
497 if (target.hasFlag("collect-compiler-diagnostics")) {
498 if (auto logBuffer = llvm::MemoryBuffer::getFile(logFile->first))
499 isaCompilerLog = (*logBuffer)->getBuffer().str();
500 }
501#define DEBUG_TYPE "dump-sass"
502 LLVM_DEBUG({
503 std::optional<std::string> nvdisasm = findTool("nvdisasm");
504 SmallVector<StringRef> nvdisasmArgs(
505 {StringRef("nvdisasm"), StringRef(cubinFile.first)});
506 if (llvm::sys::ExecuteAndWait(nvdisasm.value(), nvdisasmArgs,
507 /*Env=*/std::nullopt,
508 /*Redirects=*/redirects,
509 /*SecondsToWait=*/0,
510 /*MemoryLimit=*/0,
511 /*ErrMsg=*/&message))
512 return emitLogError("`nvdisasm`");
513 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> logBuffer =
514 llvm::MemoryBuffer::getFile(logFile->first);
515 if (logBuffer && !(*logBuffer)->getBuffer().empty()) {
516 LDBG() << "Output:\n" << (*logBuffer)->getBuffer();
517 llvm::dbgs().flush();
518 }
519 });
520#undef DEBUG_TYPE
521
522 // Invoke `fatbin`.
523 message.clear();
524 if (createFatbin && llvm::sys::ExecuteAndWait(*fatbinaryTool, fatbinArgs,
525 /*Env=*/std::nullopt,
526 /*Redirects=*/redirects,
527 /*SecondsToWait=*/0,
528 /*MemoryLimit=*/0,
529 /*ErrMsg=*/&message))
530 return emitLogError("`fatbinary`");
531
532// Dump the output of the tools, helpful if the verbose flag was passed.
533#define DEBUG_TYPE "serialize-to-binary"
534 LLVM_DEBUG({
535 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> logBuffer =
536 llvm::MemoryBuffer::getFile(logFile->first);
537 if (logBuffer && !(*logBuffer)->getBuffer().empty()) {
538 LDBG() << "Output:\n" << (*logBuffer)->getBuffer();
539 llvm::dbgs().flush();
540 }
541 });
542#undef DEBUG_TYPE
543
544 // Read the fatbin.
545 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> binaryBuffer =
546 llvm::MemoryBuffer::getFile(binaryFile->first);
547 if (!binaryBuffer)
548 return emitError(loc) << "Couldn't open the file: `" << binaryFile->first
549 << "`, error message: "
550 << binaryBuffer.getError().message();
551
552 StringRef fatbin = (*binaryBuffer)->getBuffer();
553 return SmallVector<char, 0>(fatbin.begin(), fatbin.end());
554}
555
556#if MLIR_ENABLE_NVPTXCOMPILER
557#include "nvPTXCompiler.h"
558
559#define RETURN_ON_NVPTXCOMPILER_ERROR(expr) \
560 do { \
561 if (auto status = (expr)) { \
562 emitError(loc) << llvm::Twine(#expr).concat(" failed with error code ") \
563 << status; \
564 return failure(); \
565 } \
566 } while (false)
567
568#include "nvFatbin.h"
569
570#define RETURN_ON_NVFATBIN_ERROR(expr) \
571 do { \
572 auto result = (expr); \
573 if (result != nvFatbinResult::NVFATBIN_SUCCESS) { \
574 emitError(loc) << llvm::Twine(#expr).concat(" failed with error: ") \
575 << nvFatbinGetErrorString(result); \
576 return failure(); \
577 } \
578 } while (false)
579
580FailureOr<SmallVector<char, 0>>
581NVPTXSerializer::compileToBinaryNVPTX(StringRef ptxCode) {
582 Location loc = getOperation().getLoc();
583 nvPTXCompilerHandle compiler = nullptr;
584 nvPTXCompileResult status;
585 size_t logSize;
586
587 // Create the options.
588 std::string optLevel = std::to_string(this->optLevel);
589 std::pair<llvm::BumpPtrAllocator, SmallVector<const char *>> cmdOpts =
590 targetOptions.tokenizeCmdOptions();
591 cmdOpts.second.insert(
592 cmdOpts.second.begin(),
593 {"-arch", getTarget().getChip().data(), "--opt-level", optLevel.c_str()});
594
595 // Set optional command line arguments
596 setOptionalCommandlineArguments(getTarget(), cmdOpts.second);
597 // Create the compiler handle.
598 RETURN_ON_NVPTXCOMPILER_ERROR(
599 nvPTXCompilerCreate(&compiler, ptxCode.size(), ptxCode.str().c_str()));
600
601 // Try to compile the binary.
602 status = nvPTXCompilerCompile(compiler, cmdOpts.second.size(),
603 cmdOpts.second.data());
604
605 // Check if compilation failed.
606 if (status != NVPTXCOMPILE_SUCCESS) {
607 RETURN_ON_NVPTXCOMPILER_ERROR(
608 nvPTXCompilerGetErrorLogSize(compiler, &logSize));
609 if (logSize != 0) {
610 SmallVector<char> log(logSize + 1, 0);
611 RETURN_ON_NVPTXCOMPILER_ERROR(
612 nvPTXCompilerGetErrorLog(compiler, log.data()));
613 return emitError(loc)
614 << "NVPTX compiler invocation failed, error log: " << log.data();
615 } else {
616 return emitError(loc)
617 << "NVPTX compiler invocation failed with error code: " << status;
618 }
619 }
620
621 // Retrieve the binary.
622 size_t elfSize;
623 RETURN_ON_NVPTXCOMPILER_ERROR(
624 nvPTXCompilerGetCompiledProgramSize(compiler, &elfSize));
625 SmallVector<char, 0> binary(elfSize, 0);
626 RETURN_ON_NVPTXCOMPILER_ERROR(
627 nvPTXCompilerGetCompiledProgram(compiler, (void *)binary.data()));
628
629 // Lambda to fetch info log; returns empty vector on failure or no log.
630 auto fetchInfoLog = [&]() -> SmallVector<char> {
631 size_t size = 0;
632 if (nvPTXCompilerGetInfoLogSize(compiler, &size) != NVPTXCOMPILE_SUCCESS ||
633 size == 0)
634 return {};
635 SmallVector<char> log(size + 1, 0);
636 if (nvPTXCompilerGetInfoLog(compiler, log.data()) != NVPTXCOMPILE_SUCCESS)
637 return {};
638 return log;
639 };
640
641 if (target.hasFlag("collect-compiler-diagnostics")) {
642 if (auto log = fetchInfoLog(); !log.empty())
643 isaCompilerLog = log.data();
644 }
645
646// Dump the log of the compiler, helpful if the verbose flag was passed.
647#define DEBUG_TYPE "serialize-to-binary"
648 LLVM_DEBUG({
649 if (auto log = fetchInfoLog(); !log.empty())
650 LDBG() << "NVPTX compiler invocation for module: "
651 << getOperation().getNameAttr()
652 << "\nArguments: " << llvm::interleaved(cmdOpts.second, " ")
653 << "\nOutput\n"
654 << log.data();
655 });
656#undef DEBUG_TYPE
657 RETURN_ON_NVPTXCOMPILER_ERROR(nvPTXCompilerDestroy(&compiler));
658
659 if (targetOptions.getCompilationTarget() == gpu::CompilationTarget::Fatbin) {
660 bool useFatbin32 = llvm::any_of(cmdOpts.second, [](const char *option) {
661 return llvm::StringRef(option) == "-32";
662 });
663
664 const char *cubinOpts[1] = {useFatbin32 ? "-32" : "-64"};
665 nvFatbinHandle handle;
666
667 auto chip = getTarget().getChip();
668 chip.consume_front("sm_");
669
670 RETURN_ON_NVFATBIN_ERROR(nvFatbinCreate(&handle, cubinOpts, 1));
671 RETURN_ON_NVFATBIN_ERROR(nvFatbinAddCubin(
672 handle, binary.data(), binary.size(), chip.data(), nullptr));
673 RETURN_ON_NVFATBIN_ERROR(nvFatbinAddPTX(
674 handle, ptxCode.data(), ptxCode.size(), chip.data(), nullptr, nullptr));
675
676 size_t fatbinSize;
677 RETURN_ON_NVFATBIN_ERROR(nvFatbinSize(handle, &fatbinSize));
678 SmallVector<char, 0> fatbin(fatbinSize, 0);
679 RETURN_ON_NVFATBIN_ERROR(nvFatbinGet(handle, (void *)fatbin.data()));
680 RETURN_ON_NVFATBIN_ERROR(nvFatbinDestroy(&handle));
681 return fatbin;
682 }
683
684 return binary;
685}
686#endif // MLIR_ENABLE_NVPTXCOMPILER
687
688FailureOr<SmallVector<char, 0>>
689NVPTXSerializer::moduleToObject(llvm::Module &llvmModule) {
690 llvm::Timer moduleToObjectTimer(
691 "moduleToObjectTimer",
692 "Timer for perf llvm-ir -> isa and isa -> binary.");
693 llvm::scope_exit clear([&]() { moduleToObjectTimer.clear(); });
694 // Return LLVM IR if the compilation target is `offload`.
695#define DEBUG_TYPE "serialize-to-llvm"
696 LLVM_DEBUG({
697 LDBG() << "LLVM IR for module: " << getOperation().getNameAttr();
698 LDBG() << llvmModule;
699 });
700#undef DEBUG_TYPE
701 if (targetOptions.getCompilationTarget() == gpu::CompilationTarget::Offload)
703
704#if !LLVM_HAS_NVPTX_TARGET
705 return getOperation()->emitError(
706 "The `NVPTX` target was not built. Please enable it when building LLVM.");
707#endif // LLVM_HAS_NVPTX_TARGET
708
709 // Emit PTX code.
710 FailureOr<llvm::TargetMachine *> targetMachine = getOrCreateTargetMachine();
711 if (failed(targetMachine))
712 return getOperation().emitError()
713 << "Target Machine unavailable for triple " << triple
714 << ", can't optimize with LLVM\n";
715
716 moduleToObjectTimer.startTimer();
717 FailureOr<SmallString<0>> serializedISA =
718 translateModuleToISA(llvmModule, **targetMachine,
719 [&]() { return getOperation().emitError(); });
720 moduleToObjectTimer.stopTimer();
721 llvmToISATimeInMs = moduleToObjectTimer.getTotalTime().getWallTime() * 1000;
722 moduleToObjectTimer.clear();
723 if (failed(serializedISA))
724 return getOperation().emitError()
725 << "Failed translating the module to ISA.";
726
727 if (isaCallback)
728 isaCallback(*serializedISA);
729
730#define DEBUG_TYPE "serialize-to-isa"
731 LDBG() << "PTX for module: " << getOperation().getNameAttr() << "\n"
732 << *serializedISA;
733#undef DEBUG_TYPE
734
735 // Return PTX if the compilation target is `assembly`.
736 if (targetOptions.getCompilationTarget() == gpu::CompilationTarget::Assembly)
737 return SmallVector<char, 0>(serializedISA->begin(), serializedISA->end());
738
739 FailureOr<SmallVector<char, 0>> result;
740 moduleToObjectTimer.startTimer();
741 // Compile to binary.
742#if MLIR_ENABLE_NVPTXCOMPILER
743 result = compileToBinaryNVPTX(*serializedISA);
744#else
745 result = compileToBinary(*serializedISA);
746#endif // MLIR_ENABLE_NVPTXCOMPILER
747
748 moduleToObjectTimer.stopTimer();
749 isaToBinaryTimeInMs = moduleToObjectTimer.getTotalTime().getWallTime() * 1000;
750 moduleToObjectTimer.clear();
751 return result;
752}
753
754std::optional<mlir::gpu::SerializedObject>
755NVVMTargetAttrImpl::serializeToObject(Attribute attribute, Operation *module,
756 const gpu::TargetOptions &options) const {
757 Builder builder(attribute.getContext());
758 assert(module && "The module must be non null.");
759 if (!module)
760 return std::nullopt;
761 if (!mlir::isa<gpu::GPUModuleOp>(module)) {
762 module->emitError("Module must be a GPU module.");
763 return std::nullopt;
764 }
765 NVPTXSerializer serializer(*module, cast<NVVMTargetAttr>(attribute), options);
766 serializer.init();
767 std::optional<SmallVector<char, 0>> result = serializer.run();
768 if (!result)
769 return std::nullopt;
770
771 SmallVector<NamedAttribute, 4> properties;
772 auto llvmToISATimeInMs = serializer.getLLVMIRToISATimeInMs();
773 if (llvmToISATimeInMs.has_value())
774 properties.push_back(builder.getNamedAttr(
775 "LLVMIRToISATimeInMs", builder.getI64IntegerAttr(*llvmToISATimeInMs)));
776 auto isaToBinaryTimeInMs = serializer.getISAToBinaryTimeInMs();
777 if (isaToBinaryTimeInMs.has_value())
778 properties.push_back(
779 builder.getNamedAttr("ISAToBinaryTimeInMs",
780 builder.getI64IntegerAttr(*isaToBinaryTimeInMs)));
781 StringRef isaCompilerLog = serializer.getISACompilerLog();
782 if (!isaCompilerLog.empty())
783 properties.push_back(builder.getNamedAttr(
784 "ISACompilerLog", builder.getStringAttr(isaCompilerLog)));
785
786 return gpu::SerializedObject{std::move(*result),
787 builder.getDictionaryAttr(properties)};
788}
789
790Attribute
791NVVMTargetAttrImpl::createObject(Attribute attribute, Operation *module,
792 const mlir::gpu::SerializedObject &object,
793 const gpu::TargetOptions &options) const {
794 auto target = cast<NVVMTargetAttr>(attribute);
795 gpu::CompilationTarget format = options.getCompilationTarget();
796 DictionaryAttr objectProps;
797 Builder builder(attribute.getContext());
798 SmallVector<NamedAttribute> properties =
799 llvm::to_vector(object.getMetadata().getValue());
800 if (format == gpu::CompilationTarget::Assembly)
801 properties.push_back(
802 builder.getNamedAttr("O", builder.getI32IntegerAttr(target.getO())));
803
804 if (StringRef section = options.getELFSection(); !section.empty())
805 properties.push_back(builder.getNamedAttr(gpu::elfSectionName,
806 builder.getStringAttr(section)));
807
808 if (!properties.empty())
809 objectProps = builder.getDictionaryAttr(properties);
810
811 return builder.getAttr<gpu::ObjectAttr>(
812 attribute, format,
813 builder.getStringAttr(
814 StringRef(object.getObject().data(), object.getObject().size())),
815 objectProps, /*kernels=*/nullptr);
816}
return success()
static void setOptionalCommandlineArguments(NVVMTargetAttr target, SmallVectorImpl< T > &ptxasArgs)
Adds optional command-line arguments to existing arguments.
Definition Target.cpp:337
const unsigned _mlir_embedded_libdevice_size
Definition Target.cpp:56
#define __DEFAULT_CUDATOOLKIT_PATH__
Definition Target.cpp:52
const unsigned char _mlir_embedded_libdevice[]
Definition Target.cpp:55
values clear()
static llvm::ManagedStatic< PassManagerOptions > options
Attributes are known-constant values of operations.
Definition Attributes.h:25
MLIRContext * getContext() const
Return the context this attribute belongs to.
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
bool addExtension(TypeID extensionID, std::unique_ptr< DialectExtensionBase > extension)
Add the given extension to the registry.
The class represents an individual entry of a blob.
LogicalResult loadBitcodeFilesFromList(llvm::LLVMContext &context, ArrayRef< Attribute > librariesToLink, SmallVector< std::unique_ptr< llvm::Module > > &llvmModules, bool failureOnError=true)
Loads multiple bitcode files.
virtual FailureOr< SmallVector< char, 0 > > moduleToObject(llvm::Module &llvmModule)
Serializes the LLVM IR bitcode to an object file, by default it serializes to LLVM bitcode.
Operation & getOperation()
Returns the operation being serialized.
ModuleToObject(Operation &module, StringRef triple, StringRef chip, StringRef features={}, int optLevel=3, function_ref< void(llvm::Module &)> initialLlvmIRCallback={}, function_ref< void(llvm::Module &)> linkedLlvmIRCallback={}, function_ref< void(llvm::Module &)> optimizedLlvmIRCallback={}, function_ref< void(StringRef)> isaCallback={}, const llvm::cl::LibraryOptionsContext *libraryOptions=nullptr)
Operation & module
Module to transform to a binary object.
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
void appendDialectRegistry(const DialectRegistry &registry)
Append the contents of the given dialect registry to the registry associated with this context.
Dialect * getLoadedDialect(StringRef name)
Get a registered IR dialect with the given namespace.
Base class for all NVVM serializations from GPU modules into binary strings.
Definition Utils.h:32
ArrayRef< Attribute > getLibrariesToLink() const
Returns the bitcode libraries to be linked into the gpu module after translation to LLVM IR.
Definition Target.cpp:140
SerializeGPUModuleBase(Operation &module, NVVMTargetAttr target, const gpu::TargetOptions &targetOptions={})
Initializes the toolkitPath with the path in targetOptions or if empty with the path in getCUDAToolki...
Definition Target.cpp:99
NVVMTargetAttr target
NVVM target attribute.
Definition Utils.h:63
std::string toolkitPath
CUDA toolkit path.
Definition Utils.h:66
SmallVector< Attribute > librariesToLink
List of LLVM bitcode to link into after translation to LLVM IR.
Definition Utils.h:71
std::optional< SmallVector< std::unique_ptr< llvm::Module > > > loadBitcodeFiles(llvm::Module &module) override
Loads the bitcode files in librariesToLink.
Definition Target.cpp:198
LogicalResult appendStandardLibs()
Appends nvvm/libdevice.bc into librariesToLink.
Definition Target.cpp:145
static void init()
Initializes the LLVM NVPTX target by safely calling LLVMInitializeNVPTX* methods if available.
Definition Target.cpp:123
StringRef getToolkitPath() const
Returns the CUDA toolkit path.
Definition Target.cpp:138
NVVMTargetAttr getTarget() const
Returns the target attribute.
Definition Target.cpp:136
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
static AsmResourceBlob allocateInferAlign(ArrayRef< T > data, AsmResourceBlob::DeleterFn deleter={}, bool dataIsMutable=false)
Definition AsmState.h:235
This class represents a serialized object (GPU binary) with metadata (e.g.
This class serves as an opaque interface for passing options to the TargetAttrInterface methods.
void registerNVVMTargetInterfaceExternalModels(DialectRegistry &registry)
Registers the TargetAttrInterface for the #nvvm.target attribute in the given registry.
Definition Target.cpp:74
StringRef getCUDAToolkitPath()
Searches & returns the path CUDA toolkit path, the search order is:
Definition Target.cpp:89
constexpr StringLiteral elfSectionName
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
Include the generated interface declarations.
DialectResourceBlobHandle< BuiltinDialect > DenseResourceElementsHandle
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
static ManagerInterface & getManagerInterface(MLIRContext *ctx)