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