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