ClangNvlinkWrapper.cpp 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. //===-- clang-nvlink-wrapper/ClangNvlinkWrapper.cpp - wrapper over nvlink-===//
  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
  10. /// This tool works as a wrapper over nvlink program. It transparently passes
  11. /// every input option and objects to nvlink except archive files. It reads
  12. /// each input archive file to extract archived cubin files as temporary files.
  13. /// These temp (*.cubin) files are passed to nvlink, because nvlink does not
  14. /// support linking of archive files implicitly.
  15. ///
  16. /// During linking of heterogeneous device archive libraries, the
  17. /// clang-offload-bundler creates a device specific archive of cubin files.
  18. /// Such an archive is then passed to this tool to extract cubin files before
  19. /// passing to nvlink.
  20. ///
  21. /// Example:
  22. /// clang-nvlink-wrapper -o a.out-openmp-nvptx64 /tmp/libTest-nvptx-sm_50.a
  23. ///
  24. /// 1. Extract (libTest-nvptx-sm_50.a) => /tmp/a.cubin /tmp/b.cubin
  25. /// 2. nvlink -o a.out-openmp-nvptx64 /tmp/a.cubin /tmp/b.cubin
  26. //===---------------------------------------------------------------------===//
  27. #include "clang/Basic/Version.h"
  28. #include "llvm/Object/Archive.h"
  29. #include "llvm/Support/CommandLine.h"
  30. #include "llvm/Support/Errc.h"
  31. #include "llvm/Support/FileSystem.h"
  32. #include "llvm/Support/MemoryBuffer.h"
  33. #include "llvm/Support/Path.h"
  34. #include "llvm/Support/Program.h"
  35. #include "llvm/Support/Signals.h"
  36. #include "llvm/Support/StringSaver.h"
  37. #include "llvm/Support/WithColor.h"
  38. #include "llvm/Support/raw_ostream.h"
  39. using namespace llvm;
  40. static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);
  41. // Mark all our options with this category, everything else (except for -help)
  42. // will be hidden.
  43. static cl::OptionCategory
  44. ClangNvlinkWrapperCategory("clang-nvlink-wrapper options");
  45. static cl::opt<std::string> NvlinkUserPath("nvlink-path",
  46. cl::desc("Path of nvlink binary"),
  47. cl::cat(ClangNvlinkWrapperCategory));
  48. // Do not parse nvlink options
  49. static cl::list<std::string>
  50. NVArgs(cl::Sink, cl::desc("<options to be passed to nvlink>..."));
  51. static bool isEmptyFile(StringRef Filename) {
  52. ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
  53. MemoryBuffer::getFileOrSTDIN(Filename, false, false);
  54. if (std::error_code EC = BufOrErr.getError())
  55. return false;
  56. return (*BufOrErr)->getBuffer().empty();
  57. }
  58. static Error runNVLink(std::string NVLinkPath,
  59. SmallVectorImpl<std::string> &Args) {
  60. std::vector<StringRef> NVLArgs;
  61. NVLArgs.push_back(NVLinkPath);
  62. StringRef Output = *(llvm::find(Args, "-o") + 1);
  63. for (auto &Arg : Args) {
  64. if (!(sys::fs::exists(Arg) && Arg != Output && isEmptyFile(Arg)))
  65. NVLArgs.push_back(Arg);
  66. }
  67. if (sys::ExecuteAndWait(NVLinkPath, NVLArgs))
  68. return createStringError(inconvertibleErrorCode(), "'nvlink' failed");
  69. return Error::success();
  70. }
  71. static Error extractArchiveFiles(StringRef Filename,
  72. SmallVectorImpl<std::string> &Args,
  73. SmallVectorImpl<std::string> &TmpFiles) {
  74. std::vector<std::unique_ptr<MemoryBuffer>> ArchiveBuffers;
  75. ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
  76. MemoryBuffer::getFileOrSTDIN(Filename, false, false);
  77. if (std::error_code EC = BufOrErr.getError())
  78. return createFileError(Filename, EC);
  79. ArchiveBuffers.push_back(std::move(*BufOrErr));
  80. Expected<std::unique_ptr<llvm::object::Archive>> LibOrErr =
  81. object::Archive::create(ArchiveBuffers.back()->getMemBufferRef());
  82. if (!LibOrErr)
  83. return LibOrErr.takeError();
  84. auto Archive = std::move(*LibOrErr);
  85. Error Err = Error::success();
  86. auto ChildEnd = Archive->child_end();
  87. for (auto ChildIter = Archive->child_begin(Err); ChildIter != ChildEnd;
  88. ++ChildIter) {
  89. if (Err)
  90. return Err;
  91. auto ChildNameOrErr = (*ChildIter).getName();
  92. if (!ChildNameOrErr)
  93. return ChildNameOrErr.takeError();
  94. StringRef ChildName = sys::path::filename(ChildNameOrErr.get());
  95. auto ChildBufferRefOrErr = (*ChildIter).getMemoryBufferRef();
  96. if (!ChildBufferRefOrErr)
  97. return ChildBufferRefOrErr.takeError();
  98. auto ChildBuffer =
  99. MemoryBuffer::getMemBuffer(ChildBufferRefOrErr.get(), false);
  100. auto ChildNameSplit = ChildName.split('.');
  101. SmallString<16> Path;
  102. int FileDesc;
  103. if (std::error_code EC = sys::fs::createTemporaryFile(
  104. (ChildNameSplit.first), (ChildNameSplit.second), FileDesc, Path))
  105. return createFileError(ChildName, EC);
  106. std::string TmpFileName(Path.str());
  107. Args.push_back(TmpFileName);
  108. TmpFiles.push_back(TmpFileName);
  109. std::error_code EC;
  110. raw_fd_ostream OS(Path.c_str(), EC, sys::fs::OF_None);
  111. if (EC)
  112. return createFileError(TmpFileName, errc::io_error);
  113. OS << ChildBuffer->getBuffer();
  114. OS.close();
  115. }
  116. return Err;
  117. }
  118. static Error cleanupTmpFiles(SmallVectorImpl<std::string> &TmpFiles) {
  119. for (auto &TmpFile : TmpFiles) {
  120. if (std::error_code EC = sys::fs::remove(TmpFile))
  121. return createFileError(TmpFile, errc::no_such_file_or_directory);
  122. }
  123. return Error::success();
  124. }
  125. static void PrintVersion(raw_ostream &OS) {
  126. OS << clang::getClangToolFullVersion("clang-nvlink-wrapper") << '\n';
  127. }
  128. int main(int argc, const char **argv) {
  129. sys::PrintStackTraceOnErrorSignal(argv[0]);
  130. cl::SetVersionPrinter(PrintVersion);
  131. cl::HideUnrelatedOptions(ClangNvlinkWrapperCategory);
  132. cl::ParseCommandLineOptions(
  133. argc, argv,
  134. "A wrapper tool over nvlink program. It transparently passes every \n"
  135. "input option and objects to nvlink except archive files and path of \n"
  136. "nvlink binary. It reads each input archive file to extract archived \n"
  137. "cubin files as temporary files.\n");
  138. if (Help) {
  139. cl::PrintHelpMessage();
  140. return 0;
  141. }
  142. auto reportError = [argv](Error E) {
  143. logAllUnhandledErrors(std::move(E), WithColor::error(errs(), argv[0]));
  144. exit(1);
  145. };
  146. std::string NvlinkPath;
  147. SmallVector<const char *, 0> Argv(argv, argv + argc);
  148. SmallVector<std::string, 0> ArgvSubst;
  149. SmallVector<std::string, 0> TmpFiles;
  150. BumpPtrAllocator Alloc;
  151. StringSaver Saver(Alloc);
  152. cl::ExpandResponseFiles(Saver, cl::TokenizeGNUCommandLine, Argv);
  153. for (const std::string &Arg : NVArgs) {
  154. if (sys::path::extension(Arg) == ".a") {
  155. if (Error Err = extractArchiveFiles(Arg, ArgvSubst, TmpFiles))
  156. reportError(std::move(Err));
  157. } else {
  158. ArgvSubst.push_back(Arg);
  159. }
  160. }
  161. NvlinkPath = NvlinkUserPath;
  162. // If user hasn't specified nvlink binary then search it in PATH
  163. if (NvlinkPath.empty()) {
  164. ErrorOr<std::string> NvlinkPathErr = sys::findProgramByName("nvlink");
  165. if (!NvlinkPathErr) {
  166. reportError(createStringError(NvlinkPathErr.getError(),
  167. "unable to find 'nvlink' in path"));
  168. }
  169. NvlinkPath = NvlinkPathErr.get();
  170. }
  171. if (Error Err = runNVLink(NvlinkPath, ArgvSubst))
  172. reportError(std::move(Err));
  173. if (Error Err = cleanupTmpFiles(TmpFiles))
  174. reportError(std::move(Err));
  175. return 0;
  176. }