1 //===--- Cuda.cpp - Cuda Tool and ToolChain Implementations -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 #include "CommonArgs.h"
12 #include "InputInfo.h"
13 #include "clang/Basic/Cuda.h"
14 #include "clang/Config/config.h"
15 #include "clang/Driver/Compilation.h"
16 #include "clang/Driver/Distro.h"
17 #include "clang/Driver/Driver.h"
18 #include "clang/Driver/DriverDiagnostic.h"
19 #include "clang/Driver/Options.h"
20 #include "llvm/Option/ArgList.h"
21 #include "llvm/Support/FileSystem.h"
22 #include "llvm/Support/Path.h"
23 #include "llvm/Support/Process.h"
24 #include "llvm/Support/Program.h"
25 #include "llvm/Support/VirtualFileSystem.h"
26 #include <system_error>
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;
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(llvm::StringRef V) {
37 if (!V.startswith("CUDA Version "))
38 return CudaVersion::UNKNOWN;
39 V = V.substr(strlen("CUDA Version "));
40 int Major = -1, Minor = -1;
41 auto First = V.split('.');
42 auto Second = First.second.split('.');
43 if (First.first.getAsInteger(10, Major) ||
44 Second.first.getAsInteger(10, Minor))
45 return CudaVersion::UNKNOWN;
47 if (Major == 7 && Minor == 0) {
48 // This doesn't appear to ever happen -- version.txt doesn't exist in the
49 // CUDA 7 installs I've seen. But no harm in checking.
50 return CudaVersion::CUDA_70;
52 if (Major == 7 && Minor == 5)
53 return CudaVersion::CUDA_75;
54 if (Major == 8 && Minor == 0)
55 return CudaVersion::CUDA_80;
56 if (Major == 9 && Minor == 0)
57 return CudaVersion::CUDA_90;
58 if (Major == 9 && Minor == 1)
59 return CudaVersion::CUDA_91;
60 if (Major == 9 && Minor == 2)
61 return CudaVersion::CUDA_92;
62 if (Major == 10 && Minor == 0)
63 return CudaVersion::CUDA_100;
64 return CudaVersion::UNKNOWN;
67 CudaInstallationDetector::CudaInstallationDetector(
68 const Driver &D, const llvm::Triple &HostTriple,
69 const llvm::opt::ArgList &Args)
75 Candidate(std::string Path, bool StrictChecking = false)
76 : Path(Path), StrictChecking(StrictChecking) {}
78 SmallVector<Candidate, 4> Candidates;
80 // In decreasing order so we prefer newer versions to older versions.
81 std::initializer_list<const char *> Versions = {"8.0", "7.5", "7.0"};
83 if (Args.hasArg(clang::driver::options::OPT_cuda_path_EQ)) {
84 Candidates.emplace_back(
85 Args.getLastArgValue(clang::driver::options::OPT_cuda_path_EQ).str());
86 } else if (HostTriple.isOSWindows()) {
87 for (const char *Ver : Versions)
88 Candidates.emplace_back(
89 D.SysRoot + "/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v" +
92 if (!Args.hasArg(clang::driver::options::OPT_cuda_path_ignore_env)) {
93 // Try to find ptxas binary. If the executable is located in a directory
94 // called 'bin/', its parent directory might be a good guess for a valid
96 // However, some distributions might installs 'ptxas' to /usr/bin. In that
97 // case the candidate would be '/usr' which passes the following checks
98 // because '/usr/include' exists as well. To avoid this case, we always
99 // check for the directory potentially containing files for libdevice,
100 // even if the user passes -nocudalib.
101 if (llvm::ErrorOr<std::string> ptxas =
102 llvm::sys::findProgramByName("ptxas")) {
103 SmallString<256> ptxasAbsolutePath;
104 llvm::sys::fs::real_path(*ptxas, ptxasAbsolutePath);
106 StringRef ptxasDir = llvm::sys::path::parent_path(ptxasAbsolutePath);
107 if (llvm::sys::path::filename(ptxasDir) == "bin")
108 Candidates.emplace_back(llvm::sys::path::parent_path(ptxasDir),
109 /*StrictChecking=*/true);
113 Candidates.emplace_back(D.SysRoot + "/usr/local/cuda");
114 for (const char *Ver : Versions)
115 Candidates.emplace_back(D.SysRoot + "/usr/local/cuda-" + Ver);
117 if (Distro(D.getVFS()).IsDebian() || Distro(D.getVFS()).IsUbuntu())
118 // Special case for Debian to have nvidia-cuda-toolkit work
119 // out of the box. More info on http://bugs.debian.org/882505
120 Candidates.emplace_back(D.SysRoot + "/usr/lib/cuda");
123 bool NoCudaLib = Args.hasArg(options::OPT_nocudalib);
125 for (const auto &Candidate : Candidates) {
126 InstallPath = Candidate.Path;
127 if (InstallPath.empty() || !D.getVFS().exists(InstallPath))
130 BinPath = InstallPath + "/bin";
131 IncludePath = InstallPath + "/include";
132 LibDevicePath = InstallPath + "/nvvm/libdevice";
134 auto &FS = D.getVFS();
135 if (!(FS.exists(IncludePath) && FS.exists(BinPath)))
137 bool CheckLibDevice = (!NoCudaLib || Candidate.StrictChecking);
138 if (CheckLibDevice && !FS.exists(LibDevicePath))
141 // On Linux, we have both lib and lib64 directories, and we need to choose
142 // based on our triple. On MacOS, we have only a lib directory.
144 // It's sufficient for our purposes to be flexible: If both lib and lib64
145 // exist, we choose whichever one matches our triple. Otherwise, if only
146 // lib exists, we use it.
147 if (HostTriple.isArch64Bit() && FS.exists(InstallPath + "/lib64"))
148 LibPath = InstallPath + "/lib64";
149 else if (FS.exists(InstallPath + "/lib"))
150 LibPath = InstallPath + "/lib";
154 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> VersionFile =
155 FS.getBufferForFile(InstallPath + "/version.txt");
157 // CUDA 7.0 doesn't have a version.txt, so guess that's our version if
158 // version.txt isn't present.
159 Version = CudaVersion::CUDA_70;
161 Version = ParseCudaVersionFile((*VersionFile)->getBuffer());
164 if (Version >= CudaVersion::CUDA_90) {
165 // CUDA-9+ uses single libdevice file for all GPU variants.
166 std::string FilePath = LibDevicePath + "/libdevice.10.bc";
167 if (FS.exists(FilePath)) {
168 for (const char *GpuArchName :
169 {"sm_30", "sm_32", "sm_35", "sm_37", "sm_50", "sm_52", "sm_53",
170 "sm_60", "sm_61", "sm_62", "sm_70", "sm_72", "sm_75"}) {
171 const CudaArch GpuArch = StringToCudaArch(GpuArchName);
172 if (Version >= MinVersionForCudaArch(GpuArch) &&
173 Version <= MaxVersionForCudaArch(GpuArch))
174 LibDeviceMap[GpuArchName] = FilePath;
179 for (llvm::sys::fs::directory_iterator LI(LibDevicePath, EC), LE;
180 !EC && LI != LE; LI = LI.increment(EC)) {
181 StringRef FilePath = LI->path();
182 StringRef FileName = llvm::sys::path::filename(FilePath);
183 // Process all bitcode filenames that look like
184 // libdevice.compute_XX.YY.bc
185 const StringRef LibDeviceName = "libdevice.";
186 if (!(FileName.startswith(LibDeviceName) && FileName.endswith(".bc")))
188 StringRef GpuArch = FileName.slice(
189 LibDeviceName.size(), FileName.find('.', LibDeviceName.size()));
190 LibDeviceMap[GpuArch] = FilePath.str();
191 // Insert map entries for specific devices with this compute
192 // capability. NVCC's choice of the libdevice library version is
193 // rather peculiar and depends on the CUDA version.
194 if (GpuArch == "compute_20") {
195 LibDeviceMap["sm_20"] = FilePath;
196 LibDeviceMap["sm_21"] = FilePath;
197 LibDeviceMap["sm_32"] = FilePath;
198 } else if (GpuArch == "compute_30") {
199 LibDeviceMap["sm_30"] = FilePath;
200 if (Version < CudaVersion::CUDA_80) {
201 LibDeviceMap["sm_50"] = FilePath;
202 LibDeviceMap["sm_52"] = FilePath;
203 LibDeviceMap["sm_53"] = FilePath;
205 LibDeviceMap["sm_60"] = FilePath;
206 LibDeviceMap["sm_61"] = FilePath;
207 LibDeviceMap["sm_62"] = FilePath;
208 } else if (GpuArch == "compute_35") {
209 LibDeviceMap["sm_35"] = FilePath;
210 LibDeviceMap["sm_37"] = FilePath;
211 } else if (GpuArch == "compute_50") {
212 if (Version >= CudaVersion::CUDA_80) {
213 LibDeviceMap["sm_50"] = FilePath;
214 LibDeviceMap["sm_52"] = FilePath;
215 LibDeviceMap["sm_53"] = FilePath;
221 // Check that we have found at least one libdevice that we can link in if
222 // -nocudalib hasn't been specified.
223 if (LibDeviceMap.empty() && !NoCudaLib)
231 void CudaInstallationDetector::AddCudaIncludeArgs(
232 const ArgList &DriverArgs, ArgStringList &CC1Args) const {
233 if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
234 // Add cuda_wrappers/* to our system include path. This lets us wrap
235 // standard library headers.
236 SmallString<128> P(D.ResourceDir);
237 llvm::sys::path::append(P, "include");
238 llvm::sys::path::append(P, "cuda_wrappers");
239 CC1Args.push_back("-internal-isystem");
240 CC1Args.push_back(DriverArgs.MakeArgString(P));
243 if (DriverArgs.hasArg(options::OPT_nocudainc))
247 D.Diag(diag::err_drv_no_cuda_installation);
251 CC1Args.push_back("-internal-isystem");
252 CC1Args.push_back(DriverArgs.MakeArgString(getIncludePath()));
253 CC1Args.push_back("-include");
254 CC1Args.push_back("__clang_cuda_runtime_wrapper.h");
257 void CudaInstallationDetector::CheckCudaVersionSupportsArch(
258 CudaArch Arch) const {
259 if (Arch == CudaArch::UNKNOWN || Version == CudaVersion::UNKNOWN ||
260 ArchsWithBadVersion.count(Arch) > 0)
263 auto MinVersion = MinVersionForCudaArch(Arch);
264 auto MaxVersion = MaxVersionForCudaArch(Arch);
265 if (Version < MinVersion || Version > MaxVersion) {
266 ArchsWithBadVersion.insert(Arch);
267 D.Diag(diag::err_drv_cuda_version_unsupported)
268 << CudaArchToString(Arch) << CudaVersionToString(MinVersion)
269 << CudaVersionToString(MaxVersion) << InstallPath
270 << CudaVersionToString(Version);
274 void CudaInstallationDetector::print(raw_ostream &OS) const {
276 OS << "Found CUDA installation: " << InstallPath << ", version "
277 << CudaVersionToString(Version) << "\n";
281 /// Debug info level for the NVPTX devices. We may need to emit different debug
282 /// info level for the host and for the device itselfi. This type controls
283 /// emission of the debug info for the devices. It either prohibits disable info
284 /// emission completely, or emits debug directives only, or emits same debug
285 /// info as for the host.
286 enum DeviceDebugInfoLevel {
287 DisableDebugInfo, /// Do not emit debug info for the devices.
288 DebugDirectivesOnly, /// Emit only debug directives.
289 EmitSameDebugInfoAsHost, /// Use the same debug info level just like for the
292 } // anonymous namespace
294 /// Define debug info level for the NVPTX devices. If the debug info for both
295 /// the host and device are disabled (-g0/-ggdb0 or no debug options at all). If
296 /// only debug directives are requested for the both host and device
297 /// (-gline-directvies-only), or the debug info only for the device is disabled
298 /// (optimization is on and --cuda-noopt-device-debug was not specified), the
299 /// debug directves only must be emitted for the device. Otherwise, use the same
300 /// debug info level just like for the host (with the limitations of only
301 /// supported DWARF2 standard).
302 static DeviceDebugInfoLevel mustEmitDebugInfo(const ArgList &Args) {
303 const Arg *A = Args.getLastArg(options::OPT_O_Group);
304 bool IsDebugEnabled = !A || A->getOption().matches(options::OPT_O0) ||
305 Args.hasFlag(options::OPT_cuda_noopt_device_debug,
306 options::OPT_no_cuda_noopt_device_debug,
308 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
309 const Option &Opt = A->getOption();
310 if (Opt.matches(options::OPT_gN_Group)) {
311 if (Opt.matches(options::OPT_g0) || Opt.matches(options::OPT_ggdb0))
312 return DisableDebugInfo;
313 if (Opt.matches(options::OPT_gline_directives_only))
314 return DebugDirectivesOnly;
316 return IsDebugEnabled ? EmitSameDebugInfoAsHost : DebugDirectivesOnly;
318 return DisableDebugInfo;
321 void NVPTX::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
322 const InputInfo &Output,
323 const InputInfoList &Inputs,
325 const char *LinkingOutput) const {
327 static_cast<const toolchains::CudaToolChain &>(getToolChain());
328 assert(TC.getTriple().isNVPTX() && "Wrong platform");
330 StringRef GPUArchName;
331 // If this is an OpenMP action we need to extract the device architecture
332 // from the -march=arch option. This option may come from -Xopenmp-target
333 // flag or the default value.
334 if (JA.isDeviceOffloading(Action::OFK_OpenMP)) {
335 GPUArchName = Args.getLastArgValue(options::OPT_march_EQ);
336 assert(!GPUArchName.empty() && "Must have an architecture passed in.");
338 GPUArchName = JA.getOffloadingArch();
340 // Obtain architecture from the action.
341 CudaArch gpu_arch = StringToCudaArch(GPUArchName);
342 assert(gpu_arch != CudaArch::UNKNOWN &&
343 "Device action expected to have an architecture.");
345 // Check that our installation's ptxas supports gpu_arch.
346 if (!Args.hasArg(options::OPT_no_cuda_version_check)) {
347 TC.CudaInstallation.CheckCudaVersionSupportsArch(gpu_arch);
350 ArgStringList CmdArgs;
351 CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-m64" : "-m32");
352 DeviceDebugInfoLevel DIKind = mustEmitDebugInfo(Args);
353 if (DIKind == EmitSameDebugInfoAsHost) {
354 // ptxas does not accept -g option if optimization is enabled, so
355 // we ignore the compiler's -O* options if we want debug info.
356 CmdArgs.push_back("-g");
357 CmdArgs.push_back("--dont-merge-basicblocks");
358 CmdArgs.push_back("--return-at-end");
359 } else if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
360 // Map the -O we received to -O{0,1,2,3}.
362 // TODO: Perhaps we should map host -O2 to ptxas -O3. -O3 is ptxas's
363 // default, so it may correspond more closely to the spirit of clang -O2.
365 // -O3 seems like the least-bad option when -Osomething is specified to
366 // clang but it isn't handled below.
367 StringRef OOpt = "3";
368 if (A->getOption().matches(options::OPT_O4) ||
369 A->getOption().matches(options::OPT_Ofast))
371 else if (A->getOption().matches(options::OPT_O0))
373 else if (A->getOption().matches(options::OPT_O)) {
374 // -Os, -Oz, and -O(anything else) map to -O2, for lack of better options.
375 OOpt = llvm::StringSwitch<const char *>(A->getValue())
383 CmdArgs.push_back(Args.MakeArgString(llvm::Twine("-O") + OOpt));
385 // If no -O was passed, pass -O0 to ptxas -- no opt flag should correspond
386 // to no optimizations, but ptxas's default is -O3.
387 CmdArgs.push_back("-O0");
389 if (DIKind == DebugDirectivesOnly)
390 CmdArgs.push_back("-lineinfo");
392 // Pass -v to ptxas if it was passed to the driver.
393 if (Args.hasArg(options::OPT_v))
394 CmdArgs.push_back("-v");
396 CmdArgs.push_back("--gpu-name");
397 CmdArgs.push_back(Args.MakeArgString(CudaArchToString(gpu_arch)));
398 CmdArgs.push_back("--output-file");
399 CmdArgs.push_back(Args.MakeArgString(TC.getInputFilename(Output)));
400 for (const auto& II : Inputs)
401 CmdArgs.push_back(Args.MakeArgString(II.getFilename()));
403 for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
404 CmdArgs.push_back(Args.MakeArgString(A));
406 bool Relocatable = false;
407 if (JA.isOffloading(Action::OFK_OpenMP))
408 // In OpenMP we need to generate relocatable code.
409 Relocatable = Args.hasFlag(options::OPT_fopenmp_relocatable_target,
410 options::OPT_fnoopenmp_relocatable_target,
412 else if (JA.isOffloading(Action::OFK_Cuda))
413 Relocatable = Args.hasFlag(options::OPT_fgpu_rdc,
414 options::OPT_fno_gpu_rdc, /*Default=*/false);
417 CmdArgs.push_back("-c");
420 if (Arg *A = Args.getLastArg(options::OPT_ptxas_path_EQ))
421 Exec = A->getValue();
423 Exec = Args.MakeArgString(TC.GetProgramPath("ptxas"));
424 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
427 static bool shouldIncludePTX(const ArgList &Args, const char *gpu_arch) {
428 bool includePTX = true;
429 for (Arg *A : Args) {
430 if (!(A->getOption().matches(options::OPT_cuda_include_ptx_EQ) ||
431 A->getOption().matches(options::OPT_no_cuda_include_ptx_EQ)))
434 const StringRef ArchStr = A->getValue();
435 if (ArchStr == "all" || ArchStr == gpu_arch) {
436 includePTX = A->getOption().matches(options::OPT_cuda_include_ptx_EQ);
443 // All inputs to this linker must be from CudaDeviceActions, as we need to look
444 // at the Inputs' Actions in order to figure out which GPU architecture they
446 void NVPTX::Linker::ConstructJob(Compilation &C, const JobAction &JA,
447 const InputInfo &Output,
448 const InputInfoList &Inputs,
450 const char *LinkingOutput) const {
452 static_cast<const toolchains::CudaToolChain &>(getToolChain());
453 assert(TC.getTriple().isNVPTX() && "Wrong platform");
455 ArgStringList CmdArgs;
456 CmdArgs.push_back("--cuda");
457 CmdArgs.push_back(TC.getTriple().isArch64Bit() ? "-64" : "-32");
458 CmdArgs.push_back(Args.MakeArgString("--create"));
459 CmdArgs.push_back(Args.MakeArgString(Output.getFilename()));
460 if (mustEmitDebugInfo(Args) == EmitSameDebugInfoAsHost)
461 CmdArgs.push_back("-g");
463 for (const auto& II : Inputs) {
464 auto *A = II.getAction();
465 assert(A->getInputs().size() == 1 &&
466 "Device offload action is expected to have a single input");
467 const char *gpu_arch_str = A->getOffloadingArch();
468 assert(gpu_arch_str &&
469 "Device action expected to have associated a GPU architecture!");
470 CudaArch gpu_arch = StringToCudaArch(gpu_arch_str);
472 if (II.getType() == types::TY_PP_Asm &&
473 !shouldIncludePTX(Args, gpu_arch_str))
475 // We need to pass an Arch of the form "sm_XX" for cubin files and
476 // "compute_XX" for ptx.
478 (II.getType() == types::TY_PP_Asm)
479 ? CudaVirtualArchToString(VirtualArchForCudaArch(gpu_arch))
481 CmdArgs.push_back(Args.MakeArgString(llvm::Twine("--image=profile=") +
482 Arch + ",file=" + II.getFilename()));
485 for (const auto& A : Args.getAllArgValues(options::OPT_Xcuda_fatbinary))
486 CmdArgs.push_back(Args.MakeArgString(A));
488 const char *Exec = Args.MakeArgString(TC.GetProgramPath("fatbinary"));
489 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
492 void NVPTX::OpenMPLinker::ConstructJob(Compilation &C, const JobAction &JA,
493 const InputInfo &Output,
494 const InputInfoList &Inputs,
496 const char *LinkingOutput) const {
498 static_cast<const toolchains::CudaToolChain &>(getToolChain());
499 assert(TC.getTriple().isNVPTX() && "Wrong platform");
501 ArgStringList CmdArgs;
503 // OpenMP uses nvlink to link cubin files. The result will be embedded in the
504 // host binary by the host linker.
505 assert(!JA.isHostOffloading(Action::OFK_OpenMP) &&
506 "CUDA toolchain not expected for an OpenMP host device.");
508 if (Output.isFilename()) {
509 CmdArgs.push_back("-o");
510 CmdArgs.push_back(Output.getFilename());
512 assert(Output.isNothing() && "Invalid output.");
513 if (mustEmitDebugInfo(Args) == EmitSameDebugInfoAsHost)
514 CmdArgs.push_back("-g");
516 if (Args.hasArg(options::OPT_v))
517 CmdArgs.push_back("-v");
520 Args.getLastArgValue(options::OPT_march_EQ);
521 assert(!GPUArch.empty() && "At least one GPU Arch required for ptxas.");
523 CmdArgs.push_back("-arch");
524 CmdArgs.push_back(Args.MakeArgString(GPUArch));
526 // Assume that the directory specified with --libomptarget_nvptx_path
527 // contains the static library libomptarget-nvptx.a.
528 if (const Arg *A = Args.getLastArg(options::OPT_libomptarget_nvptx_path_EQ))
529 CmdArgs.push_back(Args.MakeArgString(Twine("-L") + A->getValue()));
531 // Add paths specified in LIBRARY_PATH environment variable as -L options.
532 addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
534 // Add paths for the default clang library path.
535 SmallString<256> DefaultLibPath =
536 llvm::sys::path::parent_path(TC.getDriver().Dir);
537 llvm::sys::path::append(DefaultLibPath, "lib" CLANG_LIBDIR_SUFFIX);
538 CmdArgs.push_back(Args.MakeArgString(Twine("-L") + DefaultLibPath));
540 // Add linking against library implementing OpenMP calls on NVPTX target.
541 CmdArgs.push_back("-lomptarget-nvptx");
543 for (const auto &II : Inputs) {
544 if (II.getType() == types::TY_LLVM_IR ||
545 II.getType() == types::TY_LTO_IR ||
546 II.getType() == types::TY_LTO_BC ||
547 II.getType() == types::TY_LLVM_BC) {
548 C.getDriver().Diag(diag::err_drv_no_linker_llvm_support)
549 << getToolChain().getTripleString();
553 // Currently, we only pass the input files to the linker, we do not pass
554 // any libraries that may be valid only for the host.
555 if (!II.isFilename())
558 const char *CubinF = C.addTempFile(
559 C.getArgs().MakeArgString(getToolChain().getInputFilename(II)));
561 CmdArgs.push_back(CubinF);
564 AddOpenMPLinkerScript(getToolChain(), C, Output, Inputs, Args, CmdArgs, JA);
567 Args.MakeArgString(getToolChain().GetProgramPath("nvlink"));
568 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
571 /// CUDA toolchain. Our assembler is ptxas, and our "linker" is fatbinary,
572 /// which isn't properly a linker but nonetheless performs the step of stitching
573 /// together object files from the assembler into a single blob.
575 CudaToolChain::CudaToolChain(const Driver &D, const llvm::Triple &Triple,
576 const ToolChain &HostTC, const ArgList &Args,
577 const Action::OffloadKind OK)
578 : ToolChain(D, Triple, Args), HostTC(HostTC),
579 CudaInstallation(D, HostTC.getTriple(), Args), OK(OK) {
580 if (CudaInstallation.isValid())
581 getProgramPaths().push_back(CudaInstallation.getBinPath());
582 // Lookup binaries into the driver directory, this is used to
583 // discover the clang-offload-bundler executable.
584 getProgramPaths().push_back(getDriver().Dir);
587 std::string CudaToolChain::getInputFilename(const InputInfo &Input) const {
588 // Only object files are changed, for example assembly files keep their .s
589 // extensions. CUDA also continues to use .o as they don't use nvlink but
591 if (!(OK == Action::OFK_OpenMP && Input.getType() == types::TY_Object))
592 return ToolChain::getInputFilename(Input);
594 // Replace extension for object files with cubin because nvlink relies on
595 // these particular file names.
596 SmallString<256> Filename(ToolChain::getInputFilename(Input));
597 llvm::sys::path::replace_extension(Filename, "cubin");
598 return Filename.str();
601 void CudaToolChain::addClangTargetOptions(
602 const llvm::opt::ArgList &DriverArgs,
603 llvm::opt::ArgStringList &CC1Args,
604 Action::OffloadKind DeviceOffloadingKind) const {
605 HostTC.addClangTargetOptions(DriverArgs, CC1Args, DeviceOffloadingKind);
607 StringRef GpuArch = DriverArgs.getLastArgValue(options::OPT_march_EQ);
608 assert(!GpuArch.empty() && "Must have an explicit GPU arch.");
609 assert((DeviceOffloadingKind == Action::OFK_OpenMP ||
610 DeviceOffloadingKind == Action::OFK_Cuda) &&
611 "Only OpenMP or CUDA offloading kinds are supported for NVIDIA GPUs.");
613 if (DeviceOffloadingKind == Action::OFK_Cuda) {
614 CC1Args.push_back("-fcuda-is-device");
616 if (DriverArgs.hasFlag(options::OPT_fcuda_flush_denormals_to_zero,
617 options::OPT_fno_cuda_flush_denormals_to_zero, false))
618 CC1Args.push_back("-fcuda-flush-denormals-to-zero");
620 if (DriverArgs.hasFlag(options::OPT_fcuda_approx_transcendentals,
621 options::OPT_fno_cuda_approx_transcendentals, false))
622 CC1Args.push_back("-fcuda-approx-transcendentals");
624 if (DriverArgs.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
626 CC1Args.push_back("-fgpu-rdc");
629 if (DriverArgs.hasArg(options::OPT_nocudalib))
632 std::string LibDeviceFile = CudaInstallation.getLibDeviceFile(GpuArch);
634 if (LibDeviceFile.empty()) {
635 if (DeviceOffloadingKind == Action::OFK_OpenMP &&
636 DriverArgs.hasArg(options::OPT_S))
639 getDriver().Diag(diag::err_drv_no_cuda_libdevice) << GpuArch;
643 CC1Args.push_back("-mlink-builtin-bitcode");
644 CC1Args.push_back(DriverArgs.MakeArgString(LibDeviceFile));
646 // Libdevice in CUDA-7.0 requires PTX version that's more recent than LLVM
647 // defaults to. Use PTX4.2 by default, which is the PTX version that came with
649 const char *PtxFeature = "+ptx42";
650 // TODO(tra): CUDA-10+ needs PTX 6.3 to support new features. However that
651 // requires fair amount of work on LLVM side. We'll keep using PTX 6.1 until
652 // all prerequisites are in place.
653 if (CudaInstallation.version() >= CudaVersion::CUDA_91) {
654 // CUDA-9.1 uses new instructions that are only available in PTX6.1+
655 PtxFeature = "+ptx61";
656 } else if (CudaInstallation.version() >= CudaVersion::CUDA_90) {
657 // CUDA-9.0 uses new instructions that are only available in PTX6.0+
658 PtxFeature = "+ptx60";
660 CC1Args.append({"-target-feature", PtxFeature});
661 if (DriverArgs.hasFlag(options::OPT_fcuda_short_ptr,
662 options::OPT_fno_cuda_short_ptr, false))
663 CC1Args.append({"-mllvm", "--nvptx-short-ptr"});
665 if (DeviceOffloadingKind == Action::OFK_OpenMP) {
666 SmallVector<StringRef, 8> LibraryPaths;
668 if (const Arg *A = DriverArgs.getLastArg(options::OPT_libomptarget_nvptx_path_EQ))
669 LibraryPaths.push_back(A->getValue());
671 // Add user defined library paths from LIBRARY_PATH.
672 llvm::Optional<std::string> LibPath =
673 llvm::sys::Process::GetEnv("LIBRARY_PATH");
675 SmallVector<StringRef, 8> Frags;
676 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
677 llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
678 for (StringRef Path : Frags)
679 LibraryPaths.emplace_back(Path.trim());
682 // Add path to lib / lib64 folder.
683 SmallString<256> DefaultLibPath =
684 llvm::sys::path::parent_path(getDriver().Dir);
685 llvm::sys::path::append(DefaultLibPath, Twine("lib") + CLANG_LIBDIR_SUFFIX);
686 LibraryPaths.emplace_back(DefaultLibPath.c_str());
688 std::string LibOmpTargetName =
689 "libomptarget-nvptx-" + GpuArch.str() + ".bc";
690 bool FoundBCLibrary = false;
691 for (StringRef LibraryPath : LibraryPaths) {
692 SmallString<128> LibOmpTargetFile(LibraryPath);
693 llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
694 if (llvm::sys::fs::exists(LibOmpTargetFile)) {
695 CC1Args.push_back("-mlink-builtin-bitcode");
696 CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
697 FoundBCLibrary = true;
702 getDriver().Diag(diag::warn_drv_omp_offload_target_missingbcruntime)
707 bool CudaToolChain::supportsDebugInfoOption(const llvm::opt::Arg *A) const {
708 const Option &O = A->getOption();
709 return (O.matches(options::OPT_gN_Group) &&
710 !O.matches(options::OPT_gmodules)) ||
711 O.matches(options::OPT_g_Flag) ||
712 O.matches(options::OPT_ggdbN_Group) || O.matches(options::OPT_ggdb) ||
713 O.matches(options::OPT_gdwarf) || O.matches(options::OPT_gdwarf_2) ||
714 O.matches(options::OPT_gdwarf_3) || O.matches(options::OPT_gdwarf_4) ||
715 O.matches(options::OPT_gdwarf_5) ||
716 O.matches(options::OPT_gcolumn_info);
719 void CudaToolChain::adjustDebugInfoKind(
720 codegenoptions::DebugInfoKind &DebugInfoKind, const ArgList &Args) const {
721 switch (mustEmitDebugInfo(Args)) {
722 case DisableDebugInfo:
723 DebugInfoKind = codegenoptions::NoDebugInfo;
725 case DebugDirectivesOnly:
726 DebugInfoKind = codegenoptions::DebugDirectivesOnly;
728 case EmitSameDebugInfoAsHost:
729 // Use same debug info level as the host.
734 void CudaToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
735 ArgStringList &CC1Args) const {
736 // Check our CUDA version if we're going to include the CUDA headers.
737 if (!DriverArgs.hasArg(options::OPT_nocudainc) &&
738 !DriverArgs.hasArg(options::OPT_no_cuda_version_check)) {
739 StringRef Arch = DriverArgs.getLastArgValue(options::OPT_march_EQ);
740 assert(!Arch.empty() && "Must have an explicit GPU arch.");
741 CudaInstallation.CheckCudaVersionSupportsArch(StringToCudaArch(Arch));
743 CudaInstallation.AddCudaIncludeArgs(DriverArgs, CC1Args);
746 llvm::opt::DerivedArgList *
747 CudaToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
749 Action::OffloadKind DeviceOffloadKind) const {
750 DerivedArgList *DAL =
751 HostTC.TranslateArgs(Args, BoundArch, DeviceOffloadKind);
753 DAL = new DerivedArgList(Args.getBaseArgs());
755 const OptTable &Opts = getDriver().getOpts();
757 // For OpenMP device offloading, append derived arguments. Make sure
758 // flags are not duplicated.
759 // Also append the compute capability.
760 if (DeviceOffloadKind == Action::OFK_OpenMP) {
761 for (Arg *A : Args) {
762 bool IsDuplicate = false;
763 for (Arg *DALArg : *DAL) {
773 StringRef Arch = DAL->getLastArgValue(options::OPT_march_EQ);
775 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ),
776 CLANG_OPENMP_NVPTX_DEFAULT_ARCH);
781 for (Arg *A : Args) {
782 if (A->getOption().matches(options::OPT_Xarch__)) {
783 // Skip this argument unless the architecture matches BoundArch
784 if (BoundArch.empty() || A->getValue(0) != BoundArch)
787 unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
788 unsigned Prev = Index;
789 std::unique_ptr<Arg> XarchArg(Opts.ParseOneArg(Args, Index));
791 // If the argument parsing failed or more than one argument was
792 // consumed, the -Xarch_ argument's parameter tried to consume
793 // extra arguments. Emit an error and ignore.
795 // We also want to disallow any options which would alter the
796 // driver behavior; that isn't going to work in our model. We
797 // use isDriverOption() as an approximation, although things
798 // like -O4 are going to slip through.
799 if (!XarchArg || Index > Prev + 1) {
800 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
801 << A->getAsString(Args);
803 } else if (XarchArg->getOption().hasFlag(options::DriverOption)) {
804 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver)
805 << A->getAsString(Args);
808 XarchArg->setBaseArg(A);
809 A = XarchArg.release();
810 DAL->AddSynthesizedArg(A);
815 if (!BoundArch.empty()) {
816 DAL->eraseArg(options::OPT_march_EQ);
817 DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_march_EQ), BoundArch);
822 Tool *CudaToolChain::buildAssembler() const {
823 return new tools::NVPTX::Assembler(*this);
826 Tool *CudaToolChain::buildLinker() const {
827 if (OK == Action::OFK_OpenMP)
828 return new tools::NVPTX::OpenMPLinker(*this);
829 return new tools::NVPTX::Linker(*this);
832 void CudaToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {
833 HostTC.addClangWarningOptions(CC1Args);
836 ToolChain::CXXStdlibType
837 CudaToolChain::GetCXXStdlibType(const ArgList &Args) const {
838 return HostTC.GetCXXStdlibType(Args);
841 void CudaToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
842 ArgStringList &CC1Args) const {
843 HostTC.AddClangSystemIncludeArgs(DriverArgs, CC1Args);
846 void CudaToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &Args,
847 ArgStringList &CC1Args) const {
848 HostTC.AddClangCXXStdlibIncludeArgs(Args, CC1Args);
851 void CudaToolChain::AddIAMCUIncludeArgs(const ArgList &Args,
852 ArgStringList &CC1Args) const {
853 HostTC.AddIAMCUIncludeArgs(Args, CC1Args);
856 SanitizerMask CudaToolChain::getSupportedSanitizers() const {
857 // The CudaToolChain only supports sanitizers in the sense that it allows
858 // sanitizer arguments on the command line if they are supported by the host
859 // toolchain. The CudaToolChain will actually ignore any command line
860 // arguments for any of these "supported" sanitizers. That means that no
861 // sanitization of device code is actually supported at this time.
863 // This behavior is necessary because the host and device toolchains
864 // invocations often share the command line, so the device toolchain must
865 // tolerate flags meant only for the host toolchain.
866 return HostTC.getSupportedSanitizers();
869 VersionTuple CudaToolChain::computeMSVCVersion(const Driver *D,
870 const ArgList &Args) const {
871 return HostTC.computeMSVCVersion(D, Args);