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