1 //===--- Cuda.cpp - Cuda Tool and ToolChain Implementations -----*- 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 #include "Cuda.h"
10 #include "CommonArgs.h"
11 #include "clang/Basic/Cuda.h"
12 #include "clang/Config/config.h"
13 #include "clang/Driver/Compilation.h"
14 #include "clang/Driver/Distro.h"
15 #include "clang/Driver/Driver.h"
16 #include "clang/Driver/DriverDiagnostic.h"
17 #include "clang/Driver/InputInfo.h"
18 #include "clang/Driver/Options.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Option/ArgList.h"
22 #include "llvm/Support/FileSystem.h"
23 #include "llvm/Support/Host.h"
24 #include "llvm/Support/Path.h"
25 #include "llvm/Support/Process.h"
26 #include "llvm/Support/Program.h"
27 #include "llvm/Support/TargetParser.h"
28 #include "llvm/Support/VirtualFileSystem.h"
29 #include <system_error>
30 
31 using namespace clang::driver;
32 using namespace clang::driver::toolchains;
33 using namespace clang::driver::tools;
34 using namespace clang;
35 using namespace llvm::opt;
36 
37 namespace {
38 
39 CudaVersion getCudaVersion(uint32_t raw_version) {
40   if (raw_version < 7050)
41     return CudaVersion::CUDA_70;
42   if (raw_version < 8000)
43     return CudaVersion::CUDA_75;
44   if (raw_version < 9000)
45     return CudaVersion::CUDA_80;
46   if (raw_version < 9010)
47     return CudaVersion::CUDA_90;
48   if (raw_version < 9020)
49     return CudaVersion::CUDA_91;
50   if (raw_version < 10000)
51     return CudaVersion::CUDA_92;
52   if (raw_version < 10010)
53     return CudaVersion::CUDA_100;
54   if (raw_version < 10020)
55     return CudaVersion::CUDA_101;
56   if (raw_version < 11000)
57     return CudaVersion::CUDA_102;
58   if (raw_version < 11010)
59     return CudaVersion::CUDA_110;
60   if (raw_version < 11020)
61     return CudaVersion::CUDA_111;
62   if (raw_version < 11030)
63     return CudaVersion::CUDA_112;
64   if (raw_version < 11040)
65     return CudaVersion::CUDA_113;
66   if (raw_version < 11050)
67     return CudaVersion::CUDA_114;
68   return CudaVersion::NEW;
69 }
70 
71 CudaVersion parseCudaHFile(llvm::StringRef Input) {
72   // Helper lambda which skips the words if the line starts with them or returns
73   // None otherwise.
74   auto StartsWithWords =
75       [](llvm::StringRef Line,
76          const SmallVector<StringRef, 3> words) -> llvm::Optional<StringRef> {
77     for (StringRef word : words) {
78       if (!Line.consume_front(word))
79         return {};
80       Line = Line.ltrim();
81     }
82     return Line;
83   };
84 
85   Input = Input.ltrim();
86   while (!Input.empty()) {
87     if (auto Line =
88             StartsWithWords(Input.ltrim(), {"#", "define", "CUDA_VERSION"})) {
89       uint32_t RawVersion;
90       Line->consumeInteger(10, RawVersion);
91       return getCudaVersion(RawVersion);
92     }
93     // Find next non-empty line.
94     Input = Input.drop_front(Input.find_first_of("\n\r")).ltrim();
95   }
96   return CudaVersion::UNKNOWN;
97 }
98 } // namespace
99 
100 void CudaInstallationDetector::WarnIfUnsupportedVersion() {
101   if (Version > CudaVersion::PARTIALLY_SUPPORTED) {
102     std::string VersionString = CudaVersionToString(Version);
103     if (!VersionString.empty())
104       VersionString.insert(0, " ");
105     D.Diag(diag::warn_drv_new_cuda_version)
106         << VersionString
107         << (CudaVersion::PARTIALLY_SUPPORTED != CudaVersion::FULLY_SUPPORTED)
108         << CudaVersionToString(CudaVersion::PARTIALLY_SUPPORTED);
109   } else if (Version > CudaVersion::FULLY_SUPPORTED)
110     D.Diag(diag::warn_drv_partially_supported_cuda_version)
111         << CudaVersionToString(Version);
112 }
113 
114 CudaInstallationDetector::CudaInstallationDetector(
115     const Driver &D, const llvm::Triple &HostTriple,
116     const llvm::opt::ArgList &Args)
117     : D(D) {
118   struct Candidate {
119     std::string Path;
120     bool StrictChecking;
121 
122     Candidate(std::string Path, bool StrictChecking = false)
123         : Path(Path), StrictChecking(StrictChecking) {}
124   };
125   SmallVector<Candidate, 4> Candidates;
126 
127   // In decreasing order so we prefer newer versions to older versions.
128   std::initializer_list<const char *> Versions = {"8.0", "7.5", "7.0"};
129   auto &FS = D.getVFS();
130 
131   if (Args.hasArg(clang::driver::options::OPT_cuda_path_EQ)) {
132     Candidates.emplace_back(
133         Args.getLastArgValue(clang::driver::options::OPT_cuda_path_EQ).str());
134   } else if (HostTriple.isOSWindows()) {
135     for (const char *Ver : Versions)
136       Candidates.emplace_back(
137           D.SysRoot + "/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v" +
138           Ver);
139   } else {
140     if (!Args.hasArg(clang::driver::options::OPT_cuda_path_ignore_env)) {
141       // Try to find ptxas binary. If the executable is located in a directory
142       // called 'bin/', its parent directory might be a good guess for a valid
143       // CUDA installation.
144       // However, some distributions might installs 'ptxas' to /usr/bin. In that
145       // case the candidate would be '/usr' which passes the following checks
146       // because '/usr/include' exists as well. To avoid this case, we always
147       // check for the directory potentially containing files for libdevice,
148       // even if the user passes -nocudalib.
149       if (llvm::ErrorOr<std::string> ptxas =
150               llvm::sys::findProgramByName("ptxas")) {
151         SmallString<256> ptxasAbsolutePath;
152         llvm::sys::fs::real_path(*ptxas, ptxasAbsolutePath);
153 
154         StringRef ptxasDir = llvm::sys::path::parent_path(ptxasAbsolutePath);
155         if (llvm::sys::path::filename(ptxasDir) == "bin")
156           Candidates.emplace_back(
157               std::string(llvm::sys::path::parent_path(ptxasDir)),
158               /*StrictChecking=*/true);
159       }
160     }
161 
162     Candidates.emplace_back(D.SysRoot + "/usr/local/cuda");
163     for (const char *Ver : Versions)
164       Candidates.emplace_back(D.SysRoot + "/usr/local/cuda-" + Ver);
165 
166     Distro Dist(FS, llvm::Triple(llvm::sys::getProcessTriple()));
167     if (Dist.IsDebian() || Dist.IsUbuntu())
168       // Special case for Debian to have nvidia-cuda-toolkit work
169       // out of the box. More info on http://bugs.debian.org/882505
170       Candidates.emplace_back(D.SysRoot + "/usr/lib/cuda");
171   }
172 
173   bool NoCudaLib = Args.hasArg(options::OPT_nogpulib);
174 
175   for (const auto &Candidate : Candidates) {
176     InstallPath = Candidate.Path;
177     if (InstallPath.empty() || !FS.exists(InstallPath))
178       continue;
179 
180     BinPath = InstallPath + "/bin";
181     IncludePath = InstallPath + "/include";
182     LibDevicePath = InstallPath + "/nvvm/libdevice";
183 
184     if (!(FS.exists(IncludePath) && FS.exists(BinPath)))
185       continue;
186     bool CheckLibDevice = (!NoCudaLib || Candidate.StrictChecking);
187     if (CheckLibDevice && !FS.exists(LibDevicePath))
188       continue;
189 
190     // On Linux, we have both lib and lib64 directories, and we need to choose
191     // based on our triple.  On MacOS, we have only a lib directory.
192     //
193     // It's sufficient for our purposes to be flexible: If both lib and lib64
194     // exist, we choose whichever one matches our triple.  Otherwise, if only
195     // lib exists, we use it.
196     if (HostTriple.isArch64Bit() && FS.exists(InstallPath + "/lib64"))
197       LibPath = InstallPath + "/lib64";
198     else if (FS.exists(InstallPath + "/lib"))
199       LibPath = InstallPath + "/lib";
200     else
201       continue;
202 
203     Version = CudaVersion::UNKNOWN;
204     if (auto CudaHFile = FS.getBufferForFile(InstallPath + "/include/cuda.h"))
205       Version = parseCudaHFile((*CudaHFile)->getBuffer());
206     // As the last resort, make an educated guess between CUDA-7.0, which had
207     // old-style libdevice bitcode, and an unknown recent CUDA version.
208     if (Version == CudaVersion::UNKNOWN) {
209       Version = FS.exists(LibDevicePath + "/libdevice.10.bc")
210                     ? CudaVersion::NEW
211                     : CudaVersion::CUDA_70;
212     }
213 
214     if (Version >= CudaVersion::CUDA_90) {
215       // CUDA-9+ uses single libdevice file for all GPU variants.
216       std::string FilePath = LibDevicePath + "/libdevice.10.bc";
217       if (FS.exists(FilePath)) {
218         for (int Arch = (int)CudaArch::SM_30, E = (int)CudaArch::LAST; Arch < E;
219              ++Arch) {
220           CudaArch GpuArch = static_cast<CudaArch>(Arch);
221           if (!IsNVIDIAGpuArch(GpuArch))
222             continue;
223           std::string GpuArchName(CudaArchToString(GpuArch));
224           LibDeviceMap[GpuArchName] = FilePath;
225         }
226       }
227     } else {
228       std::error_code EC;
229       for (llvm::vfs::directory_iterator LI = FS.dir_begin(LibDevicePath, EC),
230                                          LE;
231            !EC && LI != LE; LI = LI.increment(EC)) {
232         StringRef FilePath = LI->path();
233         StringRef FileName = llvm::sys::path::filename(FilePath);
234         // Process all bitcode filenames that look like
235         // libdevice.compute_XX.YY.bc
236         const StringRef LibDeviceName = "libdevice.";
237         if (!(FileName.startswith(LibDeviceName) && FileName.endswith(".bc")))
238           continue;
239         StringRef GpuArch = FileName.slice(
240             LibDeviceName.size(), FileName.find('.', LibDeviceName.size()));
241         LibDeviceMap[GpuArch] = FilePath.str();
242         // Insert map entries for specific devices with this compute
243         // capability. NVCC's choice of the libdevice library version is
244         // rather peculiar and depends on the CUDA version.
245         if (GpuArch == "compute_20") {
246           LibDeviceMap["sm_20"] = std::string(FilePath);
247           LibDeviceMap["sm_21"] = std::string(FilePath);
248           LibDeviceMap["sm_32"] = std::string(FilePath);
249         } else if (GpuArch == "compute_30") {
250           LibDeviceMap["sm_30"] = std::string(FilePath);
251           if (Version < CudaVersion::CUDA_80) {
252             LibDeviceMap["sm_50"] = std::string(FilePath);
253             LibDeviceMap["sm_52"] = std::string(FilePath);
254             LibDeviceMap["sm_53"] = std::string(FilePath);
255           }
256           LibDeviceMap["sm_60"] = std::string(FilePath);
257           LibDeviceMap["sm_61"] = std::string(FilePath);
258           LibDeviceMap["sm_62"] = std::string(FilePath);
259         } else if (GpuArch == "compute_35") {
260           LibDeviceMap["sm_35"] = std::string(FilePath);
261           LibDeviceMap["sm_37"] = std::string(FilePath);
262         } else if (GpuArch == "compute_50") {
263           if (Version >= CudaVersion::CUDA_80) {
264             LibDeviceMap["sm_50"] = std::string(FilePath);
265             LibDeviceMap["sm_52"] = std::string(FilePath);
266             LibDeviceMap["sm_53"] = std::string(FilePath);
267           }
268         }
269       }
270     }
271 
272     // Check that we have found at least one libdevice that we can link in if
273     // -nocudalib hasn't been specified.
274     if (LibDeviceMap.empty() && !NoCudaLib)
275       continue;
276 
277     IsValid = true;
278     break;
279   }
280 }
281 
282 void CudaInstallationDetector::AddCudaIncludeArgs(
283     const ArgList &DriverArgs, ArgStringList &CC1Args) const {
284   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
285     // Add cuda_wrappers/* to our system include path.  This lets us wrap
286     // standard library headers.
287     SmallString<128> P(D.ResourceDir);
288     llvm::sys::path::append(P, "include");
289     llvm::sys::path::append(P, "cuda_wrappers");
290     CC1Args.push_back("-internal-isystem");
291     CC1Args.push_back(DriverArgs.MakeArgString(P));
292   }
293 
294   if (DriverArgs.hasArg(options::OPT_nogpuinc))
295     return;
296 
297   if (!isValid()) {
298     D.Diag(diag::err_drv_no_cuda_installation);
299     return;
300   }
301 
302   CC1Args.push_back("-internal-isystem");
303   CC1Args.push_back(DriverArgs.MakeArgString(getIncludePath()));
304   CC1Args.push_back("-include");
305   CC1Args.push_back("__clang_cuda_runtime_wrapper.h");
306 }
307 
308 void CudaInstallationDetector::CheckCudaVersionSupportsArch(
309     CudaArch Arch) const {
310   if (Arch == CudaArch::UNKNOWN || Version == CudaVersion::UNKNOWN ||
311       ArchsWithBadVersion[(int)Arch])
312     return;
313 
314   auto MinVersion = MinVersionForCudaArch(Arch);
315   auto MaxVersion = MaxVersionForCudaArch(Arch);
316   if (Version < MinVersion || Version > MaxVersion) {
317     ArchsWithBadVersion[(int)Arch] = true;
318     D.Diag(diag::err_drv_cuda_version_unsupported)
319         << CudaArchToString(Arch) << CudaVersionToString(MinVersion)
320         << CudaVersionToString(MaxVersion) << InstallPath
321         << CudaVersionToString(Version);
322   }
323 }
324 
325 void CudaInstallationDetector::print(raw_ostream &OS) const {
326   if (isValid())
327     OS << "Found CUDA installation: " << InstallPath << ", version "
328        << CudaVersionToString(Version) << "\n";
329 }
330 
331 namespace {
332 /// Debug info level for the NVPTX devices. We may need to emit different debug
333 /// info level for the host and for the device itselfi. This type controls
334 /// emission of the debug info for the devices. It either prohibits disable info
335 /// emission completely, or emits debug directives only, or emits same debug
336 /// info as for the host.
337 enum DeviceDebugInfoLevel {
338   DisableDebugInfo,        /// Do not emit debug info for the devices.
339   DebugDirectivesOnly,     /// Emit only debug directives.
340   EmitSameDebugInfoAsHost, /// Use the same debug info level just like for the
341                            /// host.
342 };
343 } // anonymous namespace
344 
345 /// Define debug info level for the NVPTX devices. If the debug info for both
346 /// the host and device are disabled (-g0/-ggdb0 or no debug options at all). If
347 /// only debug directives are requested for the both host and device
348 /// (-gline-directvies-only), or the debug info only for the device is disabled
349 /// (optimization is on and --cuda-noopt-device-debug was not specified), the
350 /// debug directves only must be emitted for the device. Otherwise, use the same
351 /// debug info level just like for the host (with the limitations of only
352 /// supported DWARF2 standard).
353 static DeviceDebugInfoLevel mustEmitDebugInfo(const ArgList &Args) {
354   const Arg *A = Args.getLastArg(options::OPT_O_Group);
355   bool IsDebugEnabled = !A || A->getOption().matches(options::OPT_O0) ||
356                         Args.hasFlag(options::OPT_cuda_noopt_device_debug,
357                                      options::OPT_no_cuda_noopt_device_debug,
358                                      /*Default=*/false);
359   if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
360     const Option &Opt = A->getOption();
361     if (Opt.matches(options::OPT_gN_Group)) {
362       if (Opt.matches(options::OPT_g0) || Opt.matches(options::OPT_ggdb0))
363         return DisableDebugInfo;
364       if (Opt.matches(options::OPT_gline_directives_only))
365         return DebugDirectivesOnly;
366     }
367     return IsDebugEnabled ? EmitSameDebugInfoAsHost : DebugDirectivesOnly;
368   }
369   return willEmitRemarks(Args) ? DebugDirectivesOnly : DisableDebugInfo;
370 }
371 
372 void NVPTX::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
373                                     const InputInfo &Output,
374                                     const InputInfoList &Inputs,
375                                     const ArgList &Args,
376                                     const char *LinkingOutput) const {
377   const auto &TC =
378       static_cast<const toolchains::CudaToolChain &>(getToolChain());
379   assert(TC.getTriple().isNVPTX() && "Wrong platform");
380 
381   StringRef GPUArchName;
382   // If this is an OpenMP action we need to extract the device architecture
383   // from the -march=arch option. This option may come from -Xopenmp-target
384   // flag or the default value.
385   if (JA.isDeviceOffloading(Action::OFK_OpenMP)) {
386     GPUArchName = Args.getLastArgValue(options::OPT_march_EQ);
387     assert(!GPUArchName.empty() && "Must have an architecture passed in.");
388   } else
389     GPUArchName = JA.getOffloadingArch();
390 
391   // Obtain architecture from the action.
392   CudaArch gpu_arch = StringToCudaArch(GPUArchName);
393   assert(gpu_arch != CudaArch::UNKNOWN &&
394          "Device action expected to have an architecture.");
395 
396   // Check that our installation's ptxas supports gpu_arch.
397   if (!Args.hasArg(options::OPT_no_cuda_version_check)) {
398     TC.CudaInstallation.CheckCudaVersionSupportsArch(gpu_arch);
399   }
400 
401   ArgStringList CmdArgs;
402   CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-m64" : "-m32");
403   DeviceDebugInfoLevel DIKind = mustEmitDebugInfo(Args);
404   if (DIKind == EmitSameDebugInfoAsHost) {
405     // ptxas does not accept -g option if optimization is enabled, so
406     // we ignore the compiler's -O* options if we want debug info.
407     CmdArgs.push_back("-g");
408     CmdArgs.push_back("--dont-merge-basicblocks");
409     CmdArgs.push_back("--return-at-end");
410   } else if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
411     // Map the -O we received to -O{0,1,2,3}.
412     //
413     // TODO: Perhaps we should map host -O2 to ptxas -O3. -O3 is ptxas's
414     // default, so it may correspond more closely to the spirit of clang -O2.
415 
416     // -O3 seems like the least-bad option when -Osomething is specified to
417     // clang but it isn't handled below.
418     StringRef OOpt = "3";
419     if (A->getOption().matches(options::OPT_O4) ||
420         A->getOption().matches(options::OPT_Ofast))
421       OOpt = "3";
422     else if (A->getOption().matches(options::OPT_O0))
423       OOpt = "0";
424     else if (A->getOption().matches(options::OPT_O)) {
425       // -Os, -Oz, and -O(anything else) map to -O2, for lack of better options.
426       OOpt = llvm::StringSwitch<const char *>(A->getValue())
427                  .Case("1", "1")
428                  .Case("2", "2")
429                  .Case("3", "3")
430                  .Case("s", "2")
431                  .Case("z", "2")
432                  .Default("2");
433     }
434     CmdArgs.push_back(Args.MakeArgString(llvm::Twine("-O") + OOpt));
435   } else {
436     // If no -O was passed, pass -O0 to ptxas -- no opt flag should correspond
437     // to no optimizations, but ptxas's default is -O3.
438     CmdArgs.push_back("-O0");
439   }
440   if (DIKind == DebugDirectivesOnly)
441     CmdArgs.push_back("-lineinfo");
442 
443   // Pass -v to ptxas if it was passed to the driver.
444   if (Args.hasArg(options::OPT_v))
445     CmdArgs.push_back("-v");
446 
447   CmdArgs.push_back("--gpu-name");
448   CmdArgs.push_back(Args.MakeArgString(CudaArchToString(gpu_arch)));
449   CmdArgs.push_back("--output-file");
450   CmdArgs.push_back(Args.MakeArgString(TC.getInputFilename(Output)));
451   for (const auto& II : Inputs)
452     CmdArgs.push_back(Args.MakeArgString(II.getFilename()));
453 
454   for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
455     CmdArgs.push_back(Args.MakeArgString(A));
456 
457   bool Relocatable = false;
458   if (JA.isOffloading(Action::OFK_OpenMP))
459     // In OpenMP we need to generate relocatable code.
460     Relocatable = Args.hasFlag(options::OPT_fopenmp_relocatable_target,
461                                options::OPT_fnoopenmp_relocatable_target,
462                                /*Default=*/true);
463   else if (JA.isOffloading(Action::OFK_Cuda))
464     Relocatable = Args.hasFlag(options::OPT_fgpu_rdc,
465                                options::OPT_fno_gpu_rdc, /*Default=*/false);
466 
467   if (Relocatable)
468     CmdArgs.push_back("-c");
469 
470   const char *Exec;
471   if (Arg *A = Args.getLastArg(options::OPT_ptxas_path_EQ))
472     Exec = A->getValue();
473   else
474     Exec = Args.MakeArgString(TC.GetProgramPath("ptxas"));
475   C.addCommand(std::make_unique<Command>(
476       JA, *this,
477       ResponseFileSupport{ResponseFileSupport::RF_Full, llvm::sys::WEM_UTF8,
478                           "--options-file"},
479       Exec, CmdArgs, Inputs, Output));
480 }
481 
482 static bool shouldIncludePTX(const ArgList &Args, const char *gpu_arch) {
483   bool includePTX = true;
484   for (Arg *A : Args) {
485     if (!(A->getOption().matches(options::OPT_cuda_include_ptx_EQ) ||
486           A->getOption().matches(options::OPT_no_cuda_include_ptx_EQ)))
487       continue;
488     A->claim();
489     const StringRef ArchStr = A->getValue();
490     if (ArchStr == "all" || ArchStr == gpu_arch) {
491       includePTX = A->getOption().matches(options::OPT_cuda_include_ptx_EQ);
492       continue;
493     }
494   }
495   return includePTX;
496 }
497 
498 // All inputs to this linker must be from CudaDeviceActions, as we need to look
499 // at the Inputs' Actions in order to figure out which GPU architecture they
500 // correspond to.
501 void NVPTX::Linker::ConstructJob(Compilation &C, const JobAction &JA,
502                                  const InputInfo &Output,
503                                  const InputInfoList &Inputs,
504                                  const ArgList &Args,
505                                  const char *LinkingOutput) const {
506   const auto &TC =
507       static_cast<const toolchains::CudaToolChain &>(getToolChain());
508   assert(TC.getTriple().isNVPTX() && "Wrong platform");
509 
510   ArgStringList CmdArgs;
511   if (TC.CudaInstallation.version() <= CudaVersion::CUDA_100)
512     CmdArgs.push_back("--cuda");
513   CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-64" : "-32");
514   CmdArgs.push_back(Args.MakeArgString("--create"));
515   CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
516   if (mustEmitDebugInfo(Args) == EmitSameDebugInfoAsHost)
517     CmdArgs.push_back("-g");
518 
519   for (const auto& II : Inputs) {
520     auto *A = II.getAction();
521     assert(A->getInputs().size() == 1 &&
522            "Device offload action is expected to have a single input");
523     const char *gpu_arch_str = A->getOffloadingArch();
524     assert(gpu_arch_str &&
525            "Device action expected to have associated a GPU architecture!");
526     CudaArch gpu_arch = StringToCudaArch(gpu_arch_str);
527 
528     if (II.getType() == types::TY_PP_Asm &&
529         !shouldIncludePTX(Args, gpu_arch_str))
530       continue;
531     // We need to pass an Arch of the form "sm_XX" for cubin files and
532     // "compute_XX" for ptx.
533     const char *Arch = (II.getType() == types::TY_PP_Asm)
534                            ? CudaArchToVirtualArchString(gpu_arch)
535                            : gpu_arch_str;
536     CmdArgs.push_back(Args.MakeArgString(llvm::Twine("--image=profile=") +
537                                          Arch + ",file=" + II.getFilename()));
538   }
539 
540   for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_fatbinary))
541     CmdArgs.push_back(Args.MakeArgString(A));
542 
543   const char *Exec = Args.MakeArgString(TC.GetProgramPath("fatbinary"));
544   C.addCommand(std::make_unique<Command>(
545       JA, *this,
546       ResponseFileSupport{ResponseFileSupport::RF_Full, llvm::sys::WEM_UTF8,
547                           "--options-file"},
548       Exec, CmdArgs, Inputs, Output));
549 }
550 
551 void NVPTX::OpenMPLinker::ConstructJob(Compilation &C, const JobAction &JA,
552                                        const InputInfo &Output,
553                                        const InputInfoList &Inputs,
554                                        const ArgList &Args,
555                                        const char *LinkingOutput) const {
556   const auto &TC =
557       static_cast<const toolchains::CudaToolChain &>(getToolChain());
558   assert(TC.getTriple().isNVPTX() && "Wrong platform");
559 
560   ArgStringList CmdArgs;
561 
562   // OpenMP uses nvlink to link cubin files. The result will be embedded in the
563   // host binary by the host linker.
564   assert(!JA.isHostOffloading(Action::OFK_OpenMP) &&
565          "CUDA toolchain not expected for an OpenMP host device.");
566 
567   if (Output.isFilename()) {
568     CmdArgs.push_back("-o");
569     CmdArgs.push_back(Output.getFilename());
570   } else
571     assert(Output.isNothing() && "Invalid output.");
572   if (mustEmitDebugInfo(Args) == EmitSameDebugInfoAsHost)
573     CmdArgs.push_back("-g");
574 
575   if (Args.hasArg(options::OPT_v))
576     CmdArgs.push_back("-v");
577 
578   StringRef GPUArch =
579       Args.getLastArgValue(options::OPT_march_EQ);
580   assert(!GPUArch.empty() && "At least one GPU Arch required for ptxas.");
581 
582   CmdArgs.push_back("-arch");
583   CmdArgs.push_back(Args.MakeArgString(GPUArch));
584 
585   // Add paths specified in LIBRARY_PATH environment variable as -L options.
586   addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
587 
588   // Add paths for the default clang library path.
589   SmallString<256> DefaultLibPath =
590       llvm::sys::path::parent_path(TC.getDriver().Dir);
591   llvm::sys::path::append(DefaultLibPath, "lib" CLANG_LIBDIR_SUFFIX);
592   CmdArgs.push_back(Args.MakeArgString(Twine("-L") + DefaultLibPath));
593 
594   for (const auto &II : Inputs) {
595     if (II.getType() == types::TY_LLVM_IR ||
596         II.getType() == types::TY_LTO_IR ||
597         II.getType() == types::TY_LTO_BC ||
598         II.getType() == types::TY_LLVM_BC) {
599       C.getDriver().Diag(diag::err_drv_no_linker_llvm_support)
600           << getToolChain().getTripleString();
601       continue;
602     }
603 
604     // Currently, we only pass the input files to the linker, we do not pass
605     // any libraries that may be valid only for the host.
606     if (!II.isFilename())
607       continue;
608 
609     const char *CubinF = C.addTempFile(
610         C.getArgs().MakeArgString(getToolChain().getInputFilename(II)));
611 
612     CmdArgs.push_back(CubinF);
613   }
614 
615   const char *Exec =
616       Args.MakeArgString(getToolChain().GetProgramPath("nvlink"));
617   C.addCommand(std::make_unique<Command>(
618       JA, *this,
619       ResponseFileSupport{ResponseFileSupport::RF_Full, llvm::sys::WEM_UTF8,
620                           "--options-file"},
621       Exec, CmdArgs, Inputs, Output));
622 }
623 
624 /// CUDA toolchain.  Our assembler is ptxas, and our "linker" is fatbinary,
625 /// which isn't properly a linker but nonetheless performs the step of stitching
626 /// together object files from the assembler into a single blob.
627 
628 CudaToolChain::CudaToolChain(const Driver &D, const llvm::Triple &Triple,
629                              const ToolChain &HostTC, const ArgList &Args,
630                              const Action::OffloadKind OK)
631     : ToolChain(D, Triple, Args), HostTC(HostTC),
632       CudaInstallation(D, HostTC.getTriple(), Args), OK(OK) {
633   if (CudaInstallation.isValid()) {
634     CudaInstallation.WarnIfUnsupportedVersion();
635     getProgramPaths().push_back(std::string(CudaInstallation.getBinPath()));
636   }
637   // Lookup binaries into the driver directory, this is used to
638   // discover the clang-offload-bundler executable.
639   getProgramPaths().push_back(getDriver().Dir);
640 }
641 
642 std::string CudaToolChain::getInputFilename(const InputInfo &Input) const {
643   // Only object files are changed, for example assembly files keep their .s
644   // extensions. CUDA also continues to use .o as they don't use nvlink but
645   // fatbinary.
646   if (!(OK == Action::OFK_OpenMP && Input.getType() == types::TY_Object))
647     return ToolChain::getInputFilename(Input);
648 
649   // Replace extension for object files with cubin because nvlink relies on
650   // these particular file names.
651   SmallString<256> Filename(ToolChain::getInputFilename(Input));
652   llvm::sys::path::replace_extension(Filename, "cubin");
653   return std::string(Filename.str());
654 }
655 
656 void CudaToolChain::addClangTargetOptions(
657     const llvm::opt::ArgList &DriverArgs,
658     llvm::opt::ArgStringList &CC1Args,
659     Action::OffloadKind DeviceOffloadingKind) const {
660   HostTC.addClangTargetOptions(DriverArgs, CC1Args, DeviceOffloadingKind);
661 
662   StringRef GpuArch = DriverArgs.getLastArgValue(options::OPT_march_EQ);
663   assert(!GpuArch.empty() && "Must have an explicit GPU arch.");
664   assert((DeviceOffloadingKind == Action::OFK_OpenMP ||
665           DeviceOffloadingKind == Action::OFK_Cuda) &&
666          "Only OpenMP or CUDA offloading kinds are supported for NVIDIA GPUs.");
667 
668   if (DeviceOffloadingKind == Action::OFK_Cuda) {
669     CC1Args.append(
670         {"-fcuda-is-device", "-mllvm", "-enable-memcpyopt-without-libcalls"});
671 
672     if (DriverArgs.hasFlag(options::OPT_fcuda_approx_transcendentals,
673                            options::OPT_fno_cuda_approx_transcendentals, false))
674       CC1Args.push_back("-fcuda-approx-transcendentals");
675   }
676 
677   if (DriverArgs.hasArg(options::OPT_nogpulib))
678     return;
679 
680   if (DeviceOffloadingKind == Action::OFK_OpenMP &&
681       DriverArgs.hasArg(options::OPT_S))
682     return;
683 
684   std::string LibDeviceFile = CudaInstallation.getLibDeviceFile(GpuArch);
685   if (LibDeviceFile.empty()) {
686     getDriver().Diag(diag::err_drv_no_cuda_libdevice) << GpuArch;
687     return;
688   }
689 
690   CC1Args.push_back("-mlink-builtin-bitcode");
691   CC1Args.push_back(DriverArgs.MakeArgString(LibDeviceFile));
692 
693   clang::CudaVersion CudaInstallationVersion = CudaInstallation.version();
694 
695   // New CUDA versions often introduce new instructions that are only supported
696   // by new PTX version, so we need to raise PTX level to enable them in NVPTX
697   // back-end.
698   const char *PtxFeature = nullptr;
699   switch (CudaInstallationVersion) {
700 #define CASE_CUDA_VERSION(CUDA_VER, PTX_VER)                                   \
701   case CudaVersion::CUDA_##CUDA_VER:                                           \
702     PtxFeature = "+ptx" #PTX_VER;                                              \
703     break;
704     CASE_CUDA_VERSION(114, 74);
705     CASE_CUDA_VERSION(113, 73);
706     CASE_CUDA_VERSION(112, 72);
707     CASE_CUDA_VERSION(111, 71);
708     CASE_CUDA_VERSION(110, 70);
709     CASE_CUDA_VERSION(102, 65);
710     CASE_CUDA_VERSION(101, 64);
711     CASE_CUDA_VERSION(100, 63);
712     CASE_CUDA_VERSION(92, 61);
713     CASE_CUDA_VERSION(91, 61);
714     CASE_CUDA_VERSION(90, 60);
715 #undef CASE_CUDA_VERSION
716   default:
717     PtxFeature = "+ptx42";
718   }
719   CC1Args.append({"-target-feature", PtxFeature});
720   if (DriverArgs.hasFlag(options::OPT_fcuda_short_ptr,
721                          options::OPT_fno_cuda_short_ptr, false))
722     CC1Args.append({"-mllvm", "--nvptx-short-ptr"});
723 
724   if (CudaInstallationVersion >= CudaVersion::UNKNOWN)
725     CC1Args.push_back(
726         DriverArgs.MakeArgString(Twine("-target-sdk-version=") +
727                                  CudaVersionToString(CudaInstallationVersion)));
728 
729   if (DeviceOffloadingKind == Action::OFK_OpenMP) {
730     if (CudaInstallationVersion < CudaVersion::CUDA_92) {
731       getDriver().Diag(
732           diag::err_drv_omp_offload_target_cuda_version_not_support)
733           << CudaVersionToString(CudaInstallationVersion);
734       return;
735     }
736 
737     std::string BitcodeSuffix;
738     if (DriverArgs.hasFlag(options::OPT_fopenmp_target_new_runtime,
739                            options::OPT_fno_openmp_target_new_runtime, false))
740       BitcodeSuffix = "new-nvptx-" + GpuArch.str();
741     else
742       BitcodeSuffix = "nvptx-" + GpuArch.str();
743 
744     addOpenMPDeviceRTL(getDriver(), DriverArgs, CC1Args, BitcodeSuffix,
745                        getTriple());
746   }
747 }
748 
749 llvm::DenormalMode CudaToolChain::getDefaultDenormalModeForType(
750     const llvm::opt::ArgList &DriverArgs, const JobAction &JA,
751     const llvm::fltSemantics *FPType) const {
752   if (JA.getOffloadingDeviceKind() == Action::OFK_Cuda) {
753     if (FPType && FPType == &llvm::APFloat::IEEEsingle() &&
754         DriverArgs.hasFlag(options::OPT_fgpu_flush_denormals_to_zero,
755                            options::OPT_fno_gpu_flush_denormals_to_zero, false))
756       return llvm::DenormalMode::getPreserveSign();
757   }
758 
759   assert(JA.getOffloadingDeviceKind() != Action::OFK_Host);
760   return llvm::DenormalMode::getIEEE();
761 }
762 
763 bool CudaToolChain::supportsDebugInfoOption(const llvm::opt::Arg *A) const {
764   const Option &O = A->getOption();
765   return (O.matches(options::OPT_gN_Group) &&
766           !O.matches(options::OPT_gmodules)) ||
767          O.matches(options::OPT_g_Flag) ||
768          O.matches(options::OPT_ggdbN_Group) || O.matches(options::OPT_ggdb) ||
769          O.matches(options::OPT_gdwarf) || O.matches(options::OPT_gdwarf_2) ||
770          O.matches(options::OPT_gdwarf_3) || O.matches(options::OPT_gdwarf_4) ||
771          O.matches(options::OPT_gdwarf_5) ||
772          O.matches(options::OPT_gcolumn_info);
773 }
774 
775 void CudaToolChain::adjustDebugInfoKind(
776     codegenoptions::DebugInfoKind &DebugInfoKind, const ArgList &Args) const {
777   switch (mustEmitDebugInfo(Args)) {
778   case DisableDebugInfo:
779     DebugInfoKind = codegenoptions::NoDebugInfo;
780     break;
781   case DebugDirectivesOnly:
782     DebugInfoKind = codegenoptions::DebugDirectivesOnly;
783     break;
784   case EmitSameDebugInfoAsHost:
785     // Use same debug info level as the host.
786     break;
787   }
788 }
789 
790 void CudaToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
791                                        ArgStringList &CC1Args) const {
792   // Check our CUDA version if we're going to include the CUDA headers.
793   if (!DriverArgs.hasArg(options::OPT_nogpuinc) &&
794       !DriverArgs.hasArg(options::OPT_no_cuda_version_check)) {
795     StringRef Arch = DriverArgs.getLastArgValue(options::OPT_march_EQ);
796     assert(!Arch.empty() && "Must have an explicit GPU arch.");
797     CudaInstallation.CheckCudaVersionSupportsArch(StringToCudaArch(Arch));
798   }
799   CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
800 }
801 
802 llvm::opt::DerivedArgList *
803 CudaToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
804                              StringRef BoundArch,
805                              Action::OffloadKind DeviceOffloadKind) const {
806   DerivedArgList *DAL =
807       HostTC.TranslateArgs(Args, BoundArch, DeviceOffloadKind);
808   if (!DAL)
809     DAL = new DerivedArgList(Args.getBaseArgs());
810 
811   const OptTable &Opts = getDriver().getOpts();
812 
813   // For OpenMP device offloading, append derived arguments. Make sure
814   // flags are not duplicated.
815   // Also append the compute capability.
816   if (DeviceOffloadKind == Action::OFK_OpenMP) {
817     for (Arg *A : Args) {
818       bool IsDuplicate = false;
819       for (Arg *DALArg : *DAL) {
820         if (A == DALArg) {
821           IsDuplicate = true;
822           break;
823         }
824       }
825       if (!IsDuplicate)
826         DAL->append(A);
827     }
828 
829     StringRef Arch = DAL->getLastArgValue(options::OPT_march_EQ);
830     if (Arch.empty())
831       DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ),
832                         CLANG_OPENMP_NVPTX_DEFAULT_ARCH);
833 
834     return DAL;
835   }
836 
837   for (Arg *A : Args) {
838     DAL->append(A);
839   }
840 
841   if (!BoundArch.empty()) {
842     DAL->eraseArg(options::OPT_march_EQ);
843     DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ), BoundArch);
844   }
845   return DAL;
846 }
847 
848 Tool *CudaToolChain::buildAssembler() const {
849   return new tools::NVPTX::Assembler(*this);
850 }
851 
852 Tool *CudaToolChain::buildLinker() const {
853   if (OK == Action::OFK_OpenMP)
854     return new tools::NVPTX::OpenMPLinker(*this);
855   return new tools::NVPTX::Linker(*this);
856 }
857 
858 void CudaToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {
859   HostTC.addClangWarningOptions(CC1Args);
860 }
861 
862 ToolChain::CXXStdlibType
863 CudaToolChain::GetCXXStdlibType(const ArgList &Args) const {
864   return HostTC.GetCXXStdlibType(Args);
865 }
866 
867 void CudaToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
868                                               ArgStringList &CC1Args) const {
869   HostTC.AddClangSystemIncludeArgs(DriverArgs, CC1Args);
870 }
871 
872 void CudaToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &Args,
873                                                  ArgStringList &CC1Args) const {
874   HostTC.AddClangCXXStdlibIncludeArgs(Args, CC1Args);
875 }
876 
877 void CudaToolChain::AddIAMCUIncludeArgs(const ArgList &Args,
878                                         ArgStringList &CC1Args) const {
879   HostTC.AddIAMCUIncludeArgs(Args, CC1Args);
880 }
881 
882 SanitizerMask CudaToolChain::getSupportedSanitizers() const {
883   // The CudaToolChain only supports sanitizers in the sense that it allows
884   // sanitizer arguments on the command line if they are supported by the host
885   // toolchain. The CudaToolChain will actually ignore any command line
886   // arguments for any of these "supported" sanitizers. That means that no
887   // sanitization of device code is actually supported at this time.
888   //
889   // This behavior is necessary because the host and device toolchains
890   // invocations often share the command line, so the device toolchain must
891   // tolerate flags meant only for the host toolchain.
892   return HostTC.getSupportedSanitizers();
893 }
894 
895 VersionTuple CudaToolChain::computeMSVCVersion(const Driver *D,
896                                                const ArgList &Args) const {
897   return HostTC.computeMSVCVersion(D, Args);
898 }
899