Cuda.cpp 34 KB

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