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