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