1//===--- AMDGPU.cpp - AMDGPU 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 "AMDGPU.h"
10#include "clang/Basic/TargetID.h"
11#include "clang/Config/config.h"
12#include "clang/Driver/CommonArgs.h"
13#include "clang/Driver/Compilation.h"
14#include "clang/Driver/Driver.h"
15#include "clang/Driver/InputInfo.h"
16#include "clang/Driver/SanitizerArgs.h"
17#include "clang/Options/Options.h"
18#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/Option/ArgList.h"
21#include "llvm/Support/Error.h"
22#include "llvm/Support/LineIterator.h"
23#include "llvm/Support/Path.h"
24#include "llvm/Support/Process.h"
25#include "llvm/Support/VirtualFileSystem.h"
26#include "llvm/TargetParser/AMDGPUTargetParser.h"
27#include "llvm/TargetParser/Host.h"
28#include <optional>
29#include <system_error>
30
31using namespace clang::driver;
32using namespace clang::driver::tools;
33using namespace clang::driver::toolchains;
34using namespace clang;
35using namespace llvm::opt;
36
37RocmInstallationDetector::CommonBitcodeLibsPreferences::
38 CommonBitcodeLibsPreferences(const Driver &D,
39 const llvm::opt::ArgList &DriverArgs,
40 StringRef GPUArch,
41 const Action::OffloadKind DeviceOffloadingKind,
42 const bool NeedsASanRT)
43 : ABIVer(DeviceLibABIVersion::fromCodeObjectVersion(
44 CodeObjectVersion: tools::getAMDGPUCodeObjectVersion(D, Args: DriverArgs))) {
45 const auto Kind = llvm::AMDGPU::parseArchAMDGCN(CPU: GPUArch);
46 const unsigned ArchAttr = llvm::AMDGPU::getArchAttrAMDGCN(AK: Kind);
47
48 IsOpenMP = DeviceOffloadingKind == Action::OFK_OpenMP;
49
50 const bool HasWave32 = (ArchAttr & llvm::AMDGPU::FEATURE_WAVE32);
51 Wave64 =
52 !HasWave32 || DriverArgs.hasFlag(Pos: options::OPT_mwavefrontsize64,
53 Neg: options::OPT_mno_wavefrontsize64, Default: false);
54
55 const bool IsKnownOffloading = DeviceOffloadingKind == Action::OFK_OpenMP ||
56 DeviceOffloadingKind == Action::OFK_HIP;
57
58 // Default to enabling f32 denormals on subtargets where fma is fast with
59 // denormals
60 const bool DefaultDAZ =
61 (Kind == llvm::AMDGPU::GK_NONE)
62 ? false
63 : !((ArchAttr & llvm::AMDGPU::FEATURE_FAST_FMA_F32) &&
64 (ArchAttr & llvm::AMDGPU::FEATURE_FAST_DENORMAL_F32));
65 // TODO: There are way too many flags that change this. Do we need to
66 // check them all?
67 DAZ = IsKnownOffloading
68 ? DriverArgs.hasFlag(Pos: options::OPT_fgpu_flush_denormals_to_zero,
69 Neg: options::OPT_fno_gpu_flush_denormals_to_zero,
70 Default: DefaultDAZ)
71 : DriverArgs.hasArg(Ids: options::OPT_cl_denorms_are_zero) || DefaultDAZ;
72
73 FiniteOnly = DriverArgs.hasArg(Ids: options::OPT_cl_finite_math_only) ||
74 DriverArgs.hasFlag(Pos: options::OPT_ffinite_math_only,
75 Neg: options::OPT_fno_finite_math_only, Default: false);
76
77 UnsafeMathOpt =
78 DriverArgs.hasArg(Ids: options::OPT_cl_unsafe_math_optimizations) ||
79 DriverArgs.hasFlag(Pos: options::OPT_funsafe_math_optimizations,
80 Neg: options::OPT_fno_unsafe_math_optimizations, Default: false);
81
82 FastRelaxedMath = DriverArgs.hasArg(Ids: options::OPT_cl_fast_relaxed_math) ||
83 DriverArgs.hasFlag(Pos: options::OPT_ffast_math,
84 Neg: options::OPT_fno_fast_math, Default: false);
85
86 // GPU Sanitizer currently only supports ASan and is enabled through host
87 // ASan.
88 GPUSan = (DriverArgs.hasFlag(Pos: options::OPT_fgpu_sanitize,
89 Neg: options::OPT_fno_gpu_sanitize, Default: true) &&
90 NeedsASanRT);
91}
92
93void RocmInstallationDetector::scanLibDevicePath(llvm::StringRef Path) {
94 assert(!Path.empty());
95
96 const StringRef Suffix(".bc");
97 const StringRef Suffix2(".amdgcn.bc");
98
99 std::error_code EC;
100 for (llvm::vfs::directory_iterator LI = D.getVFS().dir_begin(Dir: Path, EC), LE;
101 !EC && LI != LE; LI = LI.increment(EC)) {
102 StringRef FilePath = LI->path();
103 StringRef FileName = llvm::sys::path::filename(path: FilePath);
104 if (!FileName.ends_with(Suffix))
105 continue;
106
107 StringRef BaseName;
108 if (FileName.ends_with(Suffix: Suffix2))
109 BaseName = FileName.drop_back(N: Suffix2.size());
110 else if (FileName.ends_with(Suffix))
111 BaseName = FileName.drop_back(N: Suffix.size());
112
113 const StringRef ABIVersionPrefix = "oclc_abi_version_";
114 if (BaseName == "ocml") {
115 OCML = FilePath;
116 } else if (BaseName == "ockl") {
117 OCKL = FilePath;
118 } else if (BaseName == "opencl") {
119 OpenCL = FilePath;
120 } else if (BaseName == "asanrtl") {
121 AsanRTL = FilePath;
122 } else if (BaseName == "oclc_finite_only_off") {
123 FiniteOnly.Off = FilePath;
124 } else if (BaseName == "oclc_finite_only_on") {
125 FiniteOnly.On = FilePath;
126 } else if (BaseName == "oclc_unsafe_math_on") {
127 UnsafeMath.On = FilePath;
128 } else if (BaseName == "oclc_unsafe_math_off") {
129 UnsafeMath.Off = FilePath;
130 } else if (BaseName == "oclc_wavefrontsize64_on") {
131 WavefrontSize64.On = FilePath;
132 } else if (BaseName == "oclc_wavefrontsize64_off") {
133 WavefrontSize64.Off = FilePath;
134 } else if (BaseName.starts_with(Prefix: ABIVersionPrefix)) {
135 unsigned ABIVersionNumber;
136 if (BaseName.drop_front(N: ABIVersionPrefix.size())
137 .getAsInteger(/*Redex=*/Radix: 0, Result&: ABIVersionNumber))
138 continue;
139 ABIVersionMap[ABIVersionNumber] = FilePath.str();
140 } else {
141 // Process all bitcode filenames that look like
142 // ocl_isa_version_XXX.amdgcn.bc
143 const StringRef DeviceLibPrefix = "oclc_isa_version_";
144 if (!BaseName.starts_with(Prefix: DeviceLibPrefix))
145 continue;
146
147 StringRef IsaVersionNumber =
148 BaseName.drop_front(N: DeviceLibPrefix.size());
149
150 llvm::Twine GfxName = Twine("gfx") + IsaVersionNumber;
151 SmallString<8> Tmp;
152 LibDeviceMap.insert(KV: {GfxName.toStringRef(Out&: Tmp), FilePath.str()});
153 }
154 }
155}
156
157// Parse and extract version numbers from `.hipVersion`. Return `true` if
158// the parsing fails.
159bool RocmInstallationDetector::parseHIPVersionFile(llvm::StringRef V) {
160 SmallVector<StringRef, 4> VersionParts;
161 V.split(A&: VersionParts, Separator: '\n');
162 unsigned Major = ~0U;
163 unsigned Minor = ~0U;
164 for (auto Part : VersionParts) {
165 auto Splits = Part.rtrim().split(Separator: '=');
166 if (Splits.first == "HIP_VERSION_MAJOR") {
167 if (Splits.second.getAsInteger(Radix: 0, Result&: Major))
168 return true;
169 } else if (Splits.first == "HIP_VERSION_MINOR") {
170 if (Splits.second.getAsInteger(Radix: 0, Result&: Minor))
171 return true;
172 } else if (Splits.first == "HIP_VERSION_PATCH")
173 VersionPatch = Splits.second.str();
174 }
175 if (Major == ~0U || Minor == ~0U)
176 return true;
177 VersionMajorMinor = llvm::VersionTuple(Major, Minor);
178 DetectedVersion =
179 (Twine(Major) + "." + Twine(Minor) + "." + VersionPatch).str();
180 return false;
181}
182
183/// \returns a list of candidate directories for ROCm installation, which is
184/// cached and populated only once.
185const SmallVectorImpl<RocmInstallationDetector::Candidate> &
186RocmInstallationDetector::getInstallationPathCandidates() {
187
188 // Return the cached candidate list if it has already been populated.
189 if (!ROCmSearchDirs.empty())
190 return ROCmSearchDirs;
191
192 auto DoPrintROCmSearchDirs = [&]() {
193 if (PrintROCmSearchDirs)
194 for (auto Cand : ROCmSearchDirs) {
195 llvm::errs() << "ROCm installation search path: " << Cand.Path << '\n';
196 }
197 };
198
199 // For candidate specified by --rocm-path we do not do strict check, i.e.,
200 // checking existence of HIP version file and device library files.
201 if (!RocmPathArg.empty()) {
202 ROCmSearchDirs.emplace_back(Args: RocmPathArg.str());
203 DoPrintROCmSearchDirs();
204 return ROCmSearchDirs;
205 } else if (std::optional<std::string> RocmPathEnv =
206 llvm::sys::Process::GetEnv(name: "ROCM_PATH")) {
207 if (!RocmPathEnv->empty()) {
208 ROCmSearchDirs.emplace_back(Args: std::move(*RocmPathEnv));
209 DoPrintROCmSearchDirs();
210 return ROCmSearchDirs;
211 }
212 }
213
214 // Try to find relative to the compiler binary.
215 StringRef InstallDir = D.Dir;
216
217 // Check both a normal Unix prefix position of the clang binary, as well as
218 // the Windows-esque layout the ROCm packages use with the host architecture
219 // subdirectory of bin.
220 auto DeduceROCmPath = [](StringRef ClangPath) {
221 // Strip off directory (usually bin)
222 StringRef ParentDir = llvm::sys::path::parent_path(path: ClangPath);
223 StringRef ParentName = llvm::sys::path::filename(path: ParentDir);
224
225 // Some builds use bin/{host arch}, so go up again.
226 if (ParentName == "bin") {
227 ParentDir = llvm::sys::path::parent_path(path: ParentDir);
228 ParentName = llvm::sys::path::filename(path: ParentDir);
229 }
230
231 // Some versions of the rocm llvm package install to /opt/rocm/llvm/bin
232 // Some versions of the aomp package install to /opt/rocm/aomp/bin
233 if (ParentName == "llvm" || ParentName.starts_with(Prefix: "aomp")) {
234 ParentDir = llvm::sys::path::parent_path(path: ParentDir);
235 ParentName = llvm::sys::path::filename(path: ParentDir);
236
237 // Some versions of the rocm llvm package install to
238 // /opt/rocm/lib/llvm/bin, so also back up if within the lib dir still
239 if (ParentName == "lib")
240 ParentDir = llvm::sys::path::parent_path(path: ParentDir);
241 }
242
243 return Candidate(ParentDir.str(), /*StrictChecking=*/true);
244 };
245
246 // Deduce ROCm path by the path used to invoke clang. Do not resolve symbolic
247 // link of clang itself.
248 ROCmSearchDirs.emplace_back(Args: DeduceROCmPath(InstallDir));
249
250 // Deduce ROCm path by the real path of the invoked clang, resolving symbolic
251 // link of clang itself.
252 llvm::SmallString<256> RealClangPath;
253 llvm::sys::fs::real_path(path: D.getDriverProgramPath(), output&: RealClangPath);
254 auto ParentPath = llvm::sys::path::parent_path(path: RealClangPath);
255 if (ParentPath != InstallDir)
256 ROCmSearchDirs.emplace_back(Args: DeduceROCmPath(ParentPath));
257
258 // Device library may be installed in clang or resource directory.
259 auto ClangRoot = llvm::sys::path::parent_path(path: InstallDir);
260 auto RealClangRoot = llvm::sys::path::parent_path(path: ParentPath);
261 ROCmSearchDirs.emplace_back(Args: ClangRoot.str(), /*StrictChecking=*/Args: true);
262 if (RealClangRoot != ClangRoot)
263 ROCmSearchDirs.emplace_back(Args: RealClangRoot.str(), /*StrictChecking=*/Args: true);
264 ROCmSearchDirs.emplace_back(Args: D.ResourceDir,
265 /*StrictChecking=*/Args: true);
266
267 ROCmSearchDirs.emplace_back(Args: D.SysRoot + "/opt/rocm",
268 /*StrictChecking=*/Args: true);
269
270 // Find the latest /opt/rocm-{release} directory.
271 std::error_code EC;
272 std::string LatestROCm;
273 llvm::VersionTuple LatestVer;
274 // Get ROCm version from ROCm directory name.
275 auto GetROCmVersion = [](StringRef DirName) {
276 llvm::VersionTuple V;
277 std::string VerStr = DirName.drop_front(N: strlen(s: "rocm-")).str();
278 // The ROCm directory name follows the format of
279 // rocm-{major}.{minor}.{subMinor}[-{build}]
280 llvm::replace(Range&: VerStr, OldValue: '-', NewValue: '.');
281 V.tryParse(string: VerStr);
282 return V;
283 };
284 for (llvm::vfs::directory_iterator
285 File = D.getVFS().dir_begin(Dir: D.SysRoot + "/opt", EC),
286 FileEnd;
287 File != FileEnd && !EC; File.increment(EC)) {
288 llvm::StringRef FileName = llvm::sys::path::filename(path: File->path());
289 if (!FileName.starts_with(Prefix: "rocm-"))
290 continue;
291 if (LatestROCm.empty()) {
292 LatestROCm = FileName.str();
293 LatestVer = GetROCmVersion(LatestROCm);
294 continue;
295 }
296 auto Ver = GetROCmVersion(FileName);
297 if (LatestVer < Ver) {
298 LatestROCm = FileName.str();
299 LatestVer = Ver;
300 }
301 }
302 if (!LatestROCm.empty())
303 ROCmSearchDirs.emplace_back(Args: D.SysRoot + "/opt/" + LatestROCm,
304 /*StrictChecking=*/Args: true);
305
306 ROCmSearchDirs.emplace_back(Args: D.SysRoot + "/usr/local",
307 /*StrictChecking=*/Args: true);
308 ROCmSearchDirs.emplace_back(Args: D.SysRoot + "/usr",
309 /*StrictChecking=*/Args: true);
310
311 DoPrintROCmSearchDirs();
312 return ROCmSearchDirs;
313}
314
315RocmInstallationDetector::RocmInstallationDetector(
316 const Driver &D, const llvm::Triple &HostTriple,
317 const llvm::opt::ArgList &Args, bool DetectHIPRuntime)
318 : D(D) {
319 Verbose = Args.hasArg(Ids: options::OPT_v);
320 RocmPathArg = Args.getLastArgValue(Id: options::OPT_rocm_path_EQ);
321 PrintROCmSearchDirs = Args.hasArg(Ids: options::OPT_print_rocm_search_dirs);
322 RocmDeviceLibPathArg =
323 Args.getAllArgValues(Id: options::OPT_rocm_device_lib_path_EQ);
324 HIPPathArg = Args.getLastArgValue(Id: options::OPT_hip_path_EQ);
325 HIPStdParPathArg = Args.getLastArgValue(Id: options::OPT_hipstdpar_path_EQ);
326 HasHIPStdParLibrary =
327 !HIPStdParPathArg.empty() && D.getVFS().exists(Path: HIPStdParPathArg +
328 "/hipstdpar_lib.hpp");
329 HIPRocThrustPathArg =
330 Args.getLastArgValue(Id: options::OPT_hipstdpar_thrust_path_EQ);
331 HasRocThrustLibrary = !HIPRocThrustPathArg.empty() &&
332 D.getVFS().exists(Path: HIPRocThrustPathArg + "/thrust");
333 HIPRocPrimPathArg = Args.getLastArgValue(Id: options::OPT_hipstdpar_prim_path_EQ);
334 HasRocPrimLibrary = !HIPRocPrimPathArg.empty() &&
335 D.getVFS().exists(Path: HIPRocPrimPathArg + "/rocprim");
336
337 if (auto *A = Args.getLastArg(Ids: options::OPT_hip_version_EQ)) {
338 HIPVersionArg = A->getValue();
339 unsigned Major = ~0U;
340 unsigned Minor = ~0U;
341 SmallVector<StringRef, 3> Parts;
342 HIPVersionArg.split(A&: Parts, Separator: '.');
343 if (!Parts.empty())
344 Parts[0].getAsInteger(Radix: 0, Result&: Major);
345 if (Parts.size() > 1)
346 Parts[1].getAsInteger(Radix: 0, Result&: Minor);
347 if (Parts.size() > 2)
348 VersionPatch = Parts[2].str();
349 if (VersionPatch.empty())
350 VersionPatch = "0";
351 if (Major != ~0U && Minor == ~0U)
352 Minor = 0;
353 if (Major == ~0U || Minor == ~0U)
354 D.Diag(DiagID: diag::err_drv_invalid_value)
355 << A->getAsString(Args) << HIPVersionArg;
356
357 VersionMajorMinor = llvm::VersionTuple(Major, Minor);
358 DetectedVersion =
359 (Twine(Major) + "." + Twine(Minor) + "." + VersionPatch).str();
360 } else {
361 VersionPatch = DefaultVersionPatch;
362 VersionMajorMinor =
363 llvm::VersionTuple(DefaultVersionMajor, DefaultVersionMinor);
364 DetectedVersion = (Twine(DefaultVersionMajor) + "." +
365 Twine(DefaultVersionMinor) + "." + VersionPatch)
366 .str();
367 }
368
369 if (DetectHIPRuntime)
370 detectHIPRuntime();
371}
372
373void RocmInstallationDetector::detectDeviceLibrary() {
374 assert(LibDevicePath.empty());
375
376 if (!RocmDeviceLibPathArg.empty())
377 LibDevicePath = RocmDeviceLibPathArg.back();
378 else if (std::optional<std::string> LibPathEnv =
379 llvm::sys::Process::GetEnv(name: "HIP_DEVICE_LIB_PATH"))
380 LibDevicePath = std::move(*LibPathEnv);
381
382 auto &FS = D.getVFS();
383 if (!LibDevicePath.empty()) {
384 // Maintain compatability with HIP flag/envvar pointing directly at the
385 // bitcode library directory. This points directly at the library path instead
386 // of the rocm root installation.
387 if (!FS.exists(Path: LibDevicePath))
388 return;
389
390 scanLibDevicePath(Path: LibDevicePath);
391 HasDeviceLibrary = allGenericLibsValid() && !LibDeviceMap.empty();
392 return;
393 }
394
395 // Check device library exists at the given path.
396 auto CheckDeviceLib = [&](StringRef Path, bool StrictChecking) {
397 bool CheckLibDevice = (!NoBuiltinLibs || StrictChecking);
398 if (CheckLibDevice && !FS.exists(Path))
399 return false;
400
401 scanLibDevicePath(Path);
402
403 if (!NoBuiltinLibs) {
404 // Check that the required non-target libraries are all available.
405 if (!allGenericLibsValid())
406 return false;
407
408 // Check that we have found at least one libdevice that we can link in
409 // if -nobuiltinlib hasn't been specified.
410 if (LibDeviceMap.empty())
411 return false;
412 }
413 return true;
414 };
415
416 // Find device libraries in <LLVM_DIR>/lib/clang/<ver>/lib/amdgcn/bitcode
417 LibDevicePath = D.ResourceDir;
418 llvm::sys::path::append(path&: LibDevicePath, CLANG_INSTALL_LIBDIR_BASENAME,
419 b: "amdgcn", c: "bitcode");
420 HasDeviceLibrary = CheckDeviceLib(LibDevicePath, true);
421 if (HasDeviceLibrary)
422 return;
423
424 // Find device libraries in a legacy ROCm directory structure
425 // ${ROCM_ROOT}/amdgcn/bitcode/*
426 auto &ROCmDirs = getInstallationPathCandidates();
427 for (const auto &Candidate : ROCmDirs) {
428 LibDevicePath = Candidate.Path;
429 llvm::sys::path::append(path&: LibDevicePath, a: "amdgcn", b: "bitcode");
430 HasDeviceLibrary = CheckDeviceLib(LibDevicePath, Candidate.StrictChecking);
431 if (HasDeviceLibrary)
432 return;
433 }
434}
435
436void RocmInstallationDetector::detectHIPRuntime() {
437 SmallVector<Candidate, 4> HIPSearchDirs;
438 if (!HIPPathArg.empty())
439 HIPSearchDirs.emplace_back(Args: HIPPathArg.str());
440 else if (std::optional<std::string> HIPPathEnv =
441 llvm::sys::Process::GetEnv(name: "HIP_PATH")) {
442 if (!HIPPathEnv->empty())
443 HIPSearchDirs.emplace_back(Args: std::move(*HIPPathEnv));
444 }
445 if (HIPSearchDirs.empty())
446 HIPSearchDirs.append(RHS: getInstallationPathCandidates());
447 auto &FS = D.getVFS();
448
449 for (const auto &Candidate : HIPSearchDirs) {
450 InstallPath = Candidate.Path;
451 if (InstallPath.empty() || !FS.exists(Path: InstallPath))
452 continue;
453
454 BinPath = InstallPath;
455 llvm::sys::path::append(path&: BinPath, a: "bin");
456 IncludePath = InstallPath;
457 llvm::sys::path::append(path&: IncludePath, a: "include");
458 LibPath = InstallPath;
459 llvm::sys::path::append(path&: LibPath, a: "lib");
460 SharePath = InstallPath;
461 llvm::sys::path::append(path&: SharePath, a: "share");
462
463 // Get parent of InstallPath and append "share"
464 SmallString<0> ParentSharePath = llvm::sys::path::parent_path(path: InstallPath);
465 llvm::sys::path::append(path&: ParentSharePath, a: "share");
466
467 auto Append = [](SmallString<0> &path, const Twine &a, const Twine &b = "",
468 const Twine &c = "", const Twine &d = "") {
469 SmallString<0> newpath = path;
470 llvm::sys::path::append(path&: newpath, a, b, c, d);
471 return newpath;
472 };
473 // If HIP version file can be found and parsed, use HIP version from there.
474 std::vector<SmallString<0>> VersionFilePaths = {
475 Append(SharePath, "hip", "version"),
476 InstallPath != D.SysRoot + "/usr/local"
477 ? Append(ParentSharePath, "hip", "version")
478 : SmallString<0>(),
479 Append(BinPath, ".hipVersion")};
480
481 for (const auto &VersionFilePath : VersionFilePaths) {
482 if (VersionFilePath.empty())
483 continue;
484 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> VersionFile =
485 FS.getBufferForFile(Name: VersionFilePath);
486 if (!VersionFile)
487 continue;
488 if (HIPVersionArg.empty() && VersionFile)
489 if (parseHIPVersionFile(V: (*VersionFile)->getBuffer()))
490 continue;
491
492 HasHIPRuntime = true;
493 return;
494 }
495 // Otherwise, if -rocm-path is specified (no strict checking), use the
496 // default HIP version or specified by --hip-version.
497 if (!Candidate.StrictChecking) {
498 HasHIPRuntime = true;
499 return;
500 }
501 }
502 HasHIPRuntime = false;
503}
504
505void RocmInstallationDetector::print(raw_ostream &OS) const {
506 if (hasHIPRuntime())
507 OS << "Found HIP installation: " << InstallPath << ", version "
508 << DetectedVersion << '\n';
509}
510
511void RocmInstallationDetector::AddHIPIncludeArgs(const ArgList &DriverArgs,
512 ArgStringList &CC1Args) const {
513 bool UsesRuntimeWrapper = VersionMajorMinor > llvm::VersionTuple(3, 5) &&
514 !DriverArgs.hasArg(Ids: options::OPT_nohipwrapperinc);
515 bool HasHipStdPar = DriverArgs.hasArg(Ids: options::OPT_hipstdpar);
516
517 if (!DriverArgs.hasArg(Ids: options::OPT_nobuiltininc)) {
518 // HIP header includes standard library wrapper headers under clang
519 // cuda_wrappers directory. Since these wrapper headers include_next
520 // standard C++ headers, whereas libc++ headers include_next other clang
521 // headers. The include paths have to follow this order:
522 // - wrapper include path
523 // - standard C++ include path
524 // - other clang include path
525 // Since standard C++ and other clang include paths are added in other
526 // places after this function, here we only need to make sure wrapper
527 // include path is added.
528 //
529 // ROCm 3.5 does not fully support the wrapper headers. Therefore it needs
530 // a workaround.
531 SmallString<128> P(D.ResourceDir);
532 if (UsesRuntimeWrapper)
533 llvm::sys::path::append(path&: P, a: "include", b: "cuda_wrappers");
534 CC1Args.push_back(Elt: "-internal-isystem");
535 CC1Args.push_back(Elt: DriverArgs.MakeArgString(Str: P));
536 }
537
538 const auto HandleHipStdPar = [=, &DriverArgs, &CC1Args]() {
539 StringRef Inc = getIncludePath();
540 auto &FS = D.getVFS();
541
542 if (!hasHIPStdParLibrary())
543 if (!HIPStdParPathArg.empty() ||
544 !FS.exists(Path: Inc + "/thrust/system/hip/hipstdpar/hipstdpar_lib.hpp")) {
545 D.Diag(DiagID: diag::err_drv_no_hipstdpar_lib);
546 return;
547 }
548 if (!HasRocThrustLibrary && !FS.exists(Path: Inc + "/thrust")) {
549 D.Diag(DiagID: diag::err_drv_no_hipstdpar_thrust_lib);
550 return;
551 }
552 if (!HasRocPrimLibrary && !FS.exists(Path: Inc + "/rocprim")) {
553 D.Diag(DiagID: diag::err_drv_no_hipstdpar_prim_lib);
554 return;
555 }
556 const char *ThrustPath;
557 if (HasRocThrustLibrary)
558 ThrustPath = DriverArgs.MakeArgString(Str: HIPRocThrustPathArg);
559 else
560 ThrustPath = DriverArgs.MakeArgString(Str: Inc + "/thrust");
561
562 const char *HIPStdParPath;
563 if (hasHIPStdParLibrary())
564 HIPStdParPath = DriverArgs.MakeArgString(Str: HIPStdParPathArg);
565 else
566 HIPStdParPath = DriverArgs.MakeArgString(Str: StringRef(ThrustPath) +
567 "/system/hip/hipstdpar");
568
569 const char *PrimPath;
570 if (HasRocPrimLibrary)
571 PrimPath = DriverArgs.MakeArgString(Str: HIPRocPrimPathArg);
572 else
573 PrimPath = DriverArgs.MakeArgString(Str: getIncludePath() + "/rocprim");
574
575 CC1Args.append(IL: {"-idirafter", ThrustPath, "-idirafter", PrimPath,
576 "-idirafter", HIPStdParPath, "-include",
577 "hipstdpar_lib.hpp"});
578 };
579
580 if (!DriverArgs.hasFlag(Pos: options::OPT_offload_inc, Neg: options::OPT_no_offload_inc,
581 Default: true)) {
582 if (HasHipStdPar)
583 HandleHipStdPar();
584
585 return;
586 }
587
588 if (!hasHIPRuntime()) {
589 D.Diag(DiagID: diag::err_drv_no_hip_runtime);
590 return;
591 }
592
593 CC1Args.push_back(Elt: "-idirafter");
594 CC1Args.push_back(Elt: DriverArgs.MakeArgString(Str: getIncludePath()));
595 if (UsesRuntimeWrapper)
596 CC1Args.append(IL: {"-include", "__clang_hip_runtime_wrapper.h"});
597 if (HasHipStdPar)
598 HandleHipStdPar();
599}
600
601void amdgpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,
602 const InputInfo &Output,
603 const InputInfoList &Inputs,
604 const ArgList &Args,
605 const char *LinkingOutput) const {
606 std::string Linker = getToolChain().GetLinkerPath();
607 ArgStringList CmdArgs;
608 if (!Args.hasArg(Ids: options::OPT_r)) {
609 CmdArgs.push_back(Elt: "--no-undefined");
610 CmdArgs.push_back(Elt: "-shared");
611 }
612
613 if (auto LTO = getToolChain().getLTOMode(Args); LTO != LTOK_None) {
614 addLTOOptions(ToolChain: getToolChain(), Args, CmdArgs, Output, Inputs,
615 IsThinLTO: LTO == LTOK_Thin);
616 } else if (Args.hasArg(Ids: options::OPT_mcpu_EQ)) {
617 CmdArgs.push_back(Elt: Args.MakeArgString(
618 Str: "-plugin-opt=mcpu=" +
619 getProcessorFromTargetID(T: getToolChain().getTriple(),
620 OffloadArch: Args.getLastArgValue(Id: options::OPT_mcpu_EQ))));
621 }
622 addLinkerCompressDebugSectionsOption(TC: getToolChain(), Args, CmdArgs);
623 getToolChain().AddFilePathLibArgs(Args, CmdArgs);
624 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_L);
625 AddLinkerInputs(TC: getToolChain(), Inputs, Args, CmdArgs, JA);
626
627 // Always pass the target-id features to the LTO job.
628 std::vector<StringRef> Features;
629 getAMDGPUTargetFeatures(D: C.getDriver(), Triple: getToolChain().getEffectiveTriple(),
630 Args, Features);
631 if (!Features.empty()) {
632 CmdArgs.push_back(
633 Elt: Args.MakeArgString(Str: "-plugin-opt=-mattr=" + llvm::join(R&: Features, Separator: ",")));
634 }
635
636 getToolChain().addProfileRTLibs(Args, CmdArgs);
637 addSanitizerRuntimes(TC: getToolChain(), Args, CmdArgs);
638
639 if (Args.hasArg(Ids: options::OPT_stdlib))
640 CmdArgs.append(IL: {"-lc", "-lm"});
641 if (Args.hasArg(Ids: options::OPT_startfiles)) {
642 std::optional<std::string> IncludePath = getToolChain().getStdlibPath();
643 if (!IncludePath)
644 IncludePath = "/lib";
645 SmallString<128> P(*IncludePath);
646 llvm::sys::path::append(path&: P, a: "crt1.o");
647 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
648 }
649
650 CmdArgs.push_back(Elt: "-o");
651 CmdArgs.push_back(Elt: Output.getFilename());
652 C.addCommand(Cmd: std::make_unique<Command>(
653 args: JA, args: *this, args: ResponseFileSupport::AtFileCurCP(), args: Args.MakeArgString(Str: Linker),
654 args&: CmdArgs, args: Inputs, args: Output));
655}
656
657void amdgpu::getAMDGPUTargetFeatures(const Driver &D,
658 const llvm::Triple &Triple,
659 const llvm::opt::ArgList &Args,
660 std::vector<StringRef> &Features) {
661 if (Args.hasFlag(Pos: options::OPT_mwavefrontsize64,
662 Neg: options::OPT_mno_wavefrontsize64, Default: false))
663 Features.push_back(x: "+wavefrontsize64");
664
665 if (Args.hasFlag(Pos: options::OPT_mamdgpu_precise_memory_op,
666 Neg: options::OPT_mno_amdgpu_precise_memory_op, Default: false))
667 Features.push_back(x: "+precise-memory");
668
669 handleTargetFeaturesGroup(D, Triple, Args, Features,
670 Group: options::OPT_m_amdgpu_Features_Group);
671}
672
673/// AMDGPU Toolchain
674AMDGPUToolChain::AMDGPUToolChain(const Driver &D, const llvm::Triple &Triple,
675 const ArgList &Args)
676 : Generic_ELF(D, Triple, Args),
677 OptionsDefault(
678 {{options::OPT_O, "3"}, {options::OPT_cl_std_EQ, "CL1.2"}}) {
679 loadMultilibsFromYAML(Args, D);
680
681 // Check code object version options. Emit warnings for legacy options
682 // and errors for the last invalid code object version options.
683 // It is done here to avoid repeated warning or error messages for
684 // each tool invocation.
685 checkAMDGPUCodeObjectVersion(D, Args);
686}
687
688Tool *AMDGPUToolChain::buildLinker() const {
689 return new tools::amdgpu::Linker(*this);
690}
691
692DerivedArgList *
693AMDGPUToolChain::TranslateArgs(const DerivedArgList &Args, BoundArch BA,
694 Action::OffloadKind DeviceOffloadKind) const {
695 DerivedArgList *DAL = Generic_ELF::TranslateArgs(Args, BA, DeviceOffloadKind);
696 if (!DAL) {
697 DAL = new DerivedArgList(Args.getBaseArgs());
698 for (Arg *A : Args)
699 DAL->append(A);
700 }
701
702 const OptTable &Opts = getDriver().getOpts();
703
704 if (DeviceOffloadKind == Action::OFK_None) {
705 // AMDGPU is intended to use `-mcpu` but we accept `-march` for legacy.
706 if (Arg *A = DAL->getLastArg(Ids: options::OPT_march_EQ)) {
707 DAL->eraseArg(Id: options::OPT_march_EQ);
708 if (!DAL->hasArg(Ids: options::OPT_mcpu_EQ))
709 DAL->AddJoinedArg(BaseArg: A, Opt: Opts.getOption(Opt: options::OPT_mcpu_EQ),
710 Value: A->getValue());
711 }
712 }
713
714 // Replace -mcpu=native with detected GPU.
715 Arg *LastMCPUArg = DAL->getLastArg(Ids: options::OPT_mcpu_EQ);
716 if (LastMCPUArg && StringRef(LastMCPUArg->getValue()) == "native") {
717 DAL->eraseArg(Id: options::OPT_mcpu_EQ);
718 auto GPUsOrErr = getSystemGPUArchs(Args);
719 if (!GPUsOrErr) {
720 getDriver().Diag(DiagID: diag::err_drv_undetermined_gpu_arch)
721 << getArchName() << llvm::toString(E: GPUsOrErr.takeError()) << "-mcpu";
722 } else {
723 auto &GPUs = *GPUsOrErr;
724 if (!llvm::all_equal(Range&: GPUs))
725 getDriver().Diag(DiagID: diag::warn_drv_multi_gpu_arch)
726 << getArchName() << llvm::join(R&: GPUs, Separator: ", ") << "-mcpu";
727 DAL->AddJoinedArg(BaseArg: nullptr, Opt: Opts.getOption(Opt: options::OPT_mcpu_EQ),
728 Value: Args.MakeArgString(Str: GPUs.front()));
729 }
730 }
731
732 if (!BA.empty()) {
733 DAL->eraseArg(Id: options::OPT_mcpu_EQ);
734 DAL->AddJoinedArg(BaseArg: nullptr, Opt: Opts.getOption(Opt: options::OPT_mcpu_EQ),
735 Value: BA.ArchName);
736 }
737
738 AMDGPUToolChain::ParsedTargetIDType PTID = checkTargetID(DriverArgs: *DAL);
739
740 // Synthesize feature flags for target ID modifiers (xnack, sramecc).
741 if (PTID.OptionalFeatureMap) {
742 const llvm::StringMap<bool> &FeatureMap = *PTID.OptionalFeatureMap;
743
744 auto XnackIt = FeatureMap.find(Key: "xnack");
745 if (XnackIt != FeatureMap.end()) {
746 DAL->AddFlagArg(BaseArg: nullptr,
747 Opt: Opts.getOption(Opt: XnackIt->second ? options::OPT_mxnack
748 : options::OPT_mno_xnack));
749 }
750
751 auto SrameccIt = FeatureMap.find(Key: "sramecc");
752 if (SrameccIt != FeatureMap.end()) {
753 DAL->AddFlagArg(BaseArg: nullptr, Opt: Opts.getOption(Opt: SrameccIt->second
754 ? options::OPT_msramecc
755 : options::OPT_mno_sramecc));
756 }
757 }
758
759 if (Args.getLastArgValue(Id: options::OPT_x) != "cl")
760 return DAL;
761
762 // Phase 1 (.cl -> .bc)
763 if (Args.hasArg(Ids: options::OPT_c) && Args.hasArg(Ids: options::OPT_emit_llvm)) {
764 // Have to check OPT_O4, OPT_O0 & OPT_Ofast separately
765 // as they defined that way in Options.td
766 if (!Args.hasArg(Ids: options::OPT_O, Ids: options::OPT_O0, Ids: options::OPT_O4,
767 Ids: options::OPT_Ofast))
768 DAL->AddJoinedArg(BaseArg: nullptr, Opt: Opts.getOption(Opt: options::OPT_O),
769 Value: getOptionDefault(OptID: options::OPT_O));
770 }
771
772 return DAL;
773}
774
775bool AMDGPUToolChain::getDefaultDenormsAreZeroForTarget(
776 llvm::AMDGPU::GPUKind Kind) {
777
778 // Assume nothing without a specific target.
779 if (Kind == llvm::AMDGPU::GK_NONE)
780 return false;
781
782 const unsigned ArchAttr = llvm::AMDGPU::getArchAttrAMDGCN(AK: Kind);
783
784 // Default to enabling f32 denormals by default on subtargets where fma is
785 // fast with denormals
786 const bool BothDenormAndFMAFast =
787 (ArchAttr & llvm::AMDGPU::FEATURE_FAST_FMA_F32) &&
788 (ArchAttr & llvm::AMDGPU::FEATURE_FAST_DENORMAL_F32);
789 return !BothDenormAndFMAFast;
790}
791
792llvm::DenormalMode AMDGPUToolChain::getDefaultDenormalModeForType(
793 const llvm::opt::ArgList &DriverArgs, const JobAction &JA,
794 const llvm::fltSemantics *FPType) const {
795 // Denormals should always be enabled for f16 and f64.
796 if (!FPType || FPType != &llvm::APFloat::IEEEsingle())
797 return llvm::DenormalMode::getIEEE();
798
799 if (JA.getOffloadingDeviceKind() == Action::OFK_HIP ||
800 JA.getOffloadingDeviceKind() == Action::OFK_Cuda) {
801 BoundArch BA = JA.getOffloadingArch();
802 // FIXME: Missing conversion from OffloadArch to GPUKind
803 auto Arch = getProcessorFromTargetID(T: getTriple(), OffloadArch: BA.ArchName);
804 auto Kind = llvm::AMDGPU::parseArchAMDGCN(CPU: Arch);
805 if (FPType && FPType == &llvm::APFloat::IEEEsingle() &&
806 DriverArgs.hasFlag(Pos: options::OPT_fgpu_flush_denormals_to_zero,
807 Neg: options::OPT_fno_gpu_flush_denormals_to_zero,
808 Default: getDefaultDenormsAreZeroForTarget(Kind)))
809 return llvm::DenormalMode::getPreserveSign();
810
811 return llvm::DenormalMode::getIEEE();
812 }
813
814 const StringRef GpuArch = getGPUArch(DriverArgs);
815 auto Kind = llvm::AMDGPU::parseArchAMDGCN(CPU: GpuArch);
816
817 // TODO: There are way too many flags that change this. Do we need to check
818 // them all?
819 bool DAZ = DriverArgs.hasArg(Ids: options::OPT_cl_denorms_are_zero) ||
820 getDefaultDenormsAreZeroForTarget(Kind);
821
822 // Outputs are flushed to zero (FTZ), preserving sign. Denormal inputs are
823 // also implicit treated as zero (DAZ).
824 return DAZ ? llvm::DenormalMode::getPreserveSign() :
825 llvm::DenormalMode::getIEEE();
826}
827
828bool AMDGPUToolChain::isWave64(const llvm::opt::ArgList &DriverArgs,
829 llvm::AMDGPU::GPUKind Kind) {
830 const unsigned ArchAttr = llvm::AMDGPU::getArchAttrAMDGCN(AK: Kind);
831 bool HasWave32 = (ArchAttr & llvm::AMDGPU::FEATURE_WAVE32);
832
833 return !HasWave32 || DriverArgs.hasFlag(
834 Pos: options::OPT_mwavefrontsize64, Neg: options::OPT_mno_wavefrontsize64, Default: false);
835}
836
837
838/// ROCM Toolchain
839ROCMToolChain::ROCMToolChain(const Driver &D, const llvm::Triple &Triple,
840 const ArgList &Args)
841 : AMDGPUToolChain(D, Triple, Args) {
842 if (Triple.getEnvironment() != llvm::Triple::LLVM)
843 RocmInstallation->detectDeviceLibrary();
844}
845
846DerivedArgList *
847ROCMToolChain::TranslateArgs(const DerivedArgList &Args, BoundArch BA,
848 Action::OffloadKind DeviceOffloadKind) const {
849 DerivedArgList *DAL =
850 AMDGPUToolChain::TranslateArgs(Args, BA, DeviceOffloadKind);
851
852 // Filter out sanitizer coverage options that are not supported for AMDGPU.
853 for (Arg *A : Args) {
854 // Sanitizer coverage is currently not supported for AMDGPU.
855 if (A->getOption().matches(ID: options::OPT_fsan_cov_Group)) {
856 // Upgrade to error if the option was explicitly specified for device
857 bool IsExplicitDevice =
858 A->getBaseArg().getOption().matches(ID: options::OPT_Xarch_device);
859 getDriver().Diag(DiagID: IsExplicitDevice
860 ? diag::err_drv_unsupported_option_for_target
861 : diag::warn_drv_unsupported_option_for_target)
862 << A->getAsString(Args) << getTriple().str();
863 }
864 }
865
866 return DAL;
867}
868
869void AMDGPUToolChain::addClangTargetOptions(
870 const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
871 BoundArch BA, Action::OffloadKind DeviceOffloadingKind) const {
872 // Default to "hidden" visibility, as object level linking will not be
873 // supported for the foreseeable future.
874 // TODO: remove the SPIR-V bypass once it can encode (hidden) visibility.
875 if (!DriverArgs.hasArg(Ids: options::OPT_fvisibility_EQ,
876 Ids: options::OPT_fvisibility_ms_compat) &&
877 !getEffectiveTriple().isSPIRV() && !getDriver().IsFlangMode()) {
878 CC1Args.push_back(Elt: "-fvisibility=hidden");
879 CC1Args.push_back(Elt: "-fapply-global-visibility-to-externs");
880 }
881
882 // For SPIR-V we want to retain the pristine output of Clang CodeGen, since
883 // optimizations might lose structure / information that is necessary for
884 // generating optimal concrete AMDGPU code.
885 // TODO: using the below option is a temporary placeholder until Clang
886 // provides the required functionality, which essentially boils down to
887 // -O0 being refactored / reworked to not imply optnone / remove TBAA.
888 // Once that is added, we should pivot to that functionality, being
889 // mindful to not corrupt the user provided and subsequently embedded
890 // command-line (i.e. if the user asks for -O3 this is what the
891 // finalisation should use).
892 if (getTriple().isSPIRV() &&
893 !DriverArgs.hasArg(Ids: options::OPT_disable_llvm_optzns))
894 CC1Args.push_back(Elt: "-disable-llvm-optzns");
895
896 if (DeviceOffloadingKind == Action::OFK_None)
897 addOpenCLBuiltinsLib(D: getDriver(), TT: getTriple(), DriverArgs, CC1Args);
898}
899
900void AMDGPUToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {
901 // AMDGPU does not support atomic lib call. Treat atomic alignment
902 // warnings as errors.
903 CC1Args.push_back(Elt: "-Werror=atomic-alignment");
904}
905
906void AMDGPUToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
907 ArgStringList &CC1Args) const {
908 if (DriverArgs.hasArg(Ids: options::OPT_nostdinc) ||
909 DriverArgs.hasArg(Ids: options::OPT_nostdlibinc))
910 return;
911
912 // Add multilib variant include paths in priority order.
913 for (const Multilib &M : getOrderedMultilibs()) {
914 if (M.isDefault())
915 continue;
916 if (std::optional<std::string> StdlibIncDir = getStdlibIncludePath()) {
917 SmallString<128> Dir(*StdlibIncDir);
918 llvm::sys::path::append(path&: Dir, a: M.includeSuffix());
919 if (getDriver().getVFS().exists(Path: Dir))
920 addSystemInclude(DriverArgs, CC1Args, Path: Dir);
921 }
922 }
923
924 if (std::optional<std::string> Path = getStdlibIncludePath())
925 addSystemInclude(DriverArgs, CC1Args, Path: *Path);
926}
927
928StringRef
929AMDGPUToolChain::getGPUArch(const llvm::opt::ArgList &DriverArgs) const {
930 return getProcessorFromTargetID(
931 T: getTriple(), OffloadArch: DriverArgs.getLastArgValue(Id: options::OPT_mcpu_EQ));
932}
933
934AMDGPUToolChain::ParsedTargetIDType
935AMDGPUToolChain::getParsedTargetID(const llvm::opt::ArgList &DriverArgs) const {
936 StringRef TargetID = DriverArgs.getLastArgValue(Id: options::OPT_mcpu_EQ);
937 if (TargetID.empty())
938 return {};
939
940 llvm::StringMap<bool> FeatureMap;
941 auto OptionalGpuArch = parseTargetID(T: getTriple(), OffloadArch: TargetID, FeatureMap: &FeatureMap);
942 if (!OptionalGpuArch)
943 return {.OptionalTargetID: TargetID.str(), .OptionalGPUArch: std::nullopt, .OptionalFeatureMap: std::nullopt};
944
945 return {.OptionalTargetID: TargetID.str(), .OptionalGPUArch: OptionalGpuArch->str(), .OptionalFeatureMap: FeatureMap};
946}
947
948AMDGPUToolChain::ParsedTargetIDType
949AMDGPUToolChain::checkTargetID(const llvm::opt::ArgList &DriverArgs) const {
950 auto PTID = getParsedTargetID(DriverArgs);
951 if (PTID.OptionalTargetID && !PTID.OptionalGPUArch) {
952 getDriver().Diag(DiagID: clang::diag::err_drv_bad_target_id)
953 << *PTID.OptionalTargetID;
954 }
955 return PTID;
956}
957
958Expected<SmallVector<std::string>>
959AMDGPUToolChain::getSystemGPUArchs(const ArgList &Args) const {
960 // Detect AMD GPUs availible on the system.
961 std::string Program;
962 if (Arg *A = Args.getLastArg(Ids: options::OPT_offload_arch_tool_EQ))
963 Program = A->getValue();
964 else
965 Program = GetProgramPath(Name: "amdgpu-arch");
966
967 auto StdoutOrErr = getDriver().executeProgram(Args: {Program});
968 if (!StdoutOrErr)
969 return StdoutOrErr.takeError();
970
971 SmallVector<std::string, 1> GPUArchs;
972 for (StringRef Arch : llvm::split(Str: (*StdoutOrErr)->getBuffer(), Separator: "\n"))
973 if (!Arch.empty())
974 GPUArchs.push_back(Elt: Arch.str());
975
976 if (GPUArchs.empty())
977 return llvm::createStringError(EC: std::error_code(),
978 S: "No AMD GPU detected in the system");
979
980 return std::move(GPUArchs);
981}
982
983void ROCMToolChain::addClangTargetOptions(
984 const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
985 BoundArch BA, Action::OffloadKind DeviceOffloadingKind) const {
986 AMDGPUToolChain::addClangTargetOptions(DriverArgs, CC1Args, BA,
987 DeviceOffloadingKind);
988
989 // For the OpenCL case where there is no offload target, accept -nostdlib to
990 // disable bitcode linking.
991 if (DeviceOffloadingKind == Action::OFK_None &&
992 DriverArgs.hasArg(Ids: options::OPT_nostdlib))
993 return;
994
995 if (!DriverArgs.hasFlag(Pos: options::OPT_offloadlib, Neg: options::OPT_no_offloadlib,
996 Default: true))
997 return;
998
999 // For SPIR-V (SPIRVAMDToolChain) we must not link any device libraries so we
1000 // skip it.
1001 const llvm::Triple &TT = this->getEffectiveTriple();
1002 if (TT.isSPIRV())
1003 return;
1004
1005 // With an LLVM environment, only use libraries provided by the resource
1006 // directory.
1007 if (TT.getEnvironment() == llvm::Triple::LLVM)
1008 return;
1009
1010 // Get the device name and canonicalize it. For offload compilation,
1011 // BoundArch contains the full target ID. For non-offload (OpenCL),
1012 // fall back to -mcpu.
1013 StringRef TargetID =
1014 BA ? BA.ArchName : DriverArgs.getLastArgValue(Id: options::OPT_mcpu_EQ);
1015 StringRef GpuArch = getProcessorFromTargetID(T: getTriple(), OffloadArch: TargetID);
1016
1017 StringRef LibDeviceFile = RocmInstallation->getLibDeviceFile(Gpu: GpuArch);
1018
1019 auto ABIVer = DeviceLibABIVersion::fromCodeObjectVersion(
1020 CodeObjectVersion: getAMDGPUCodeObjectVersion(D: getDriver(), Args: DriverArgs));
1021 if (!RocmInstallation->checkCommonBitcodeLibs(GPUArch: GpuArch, LibDeviceFile, ABIVer))
1022 return;
1023
1024 // Add the OpenCL specific bitcode library.
1025 llvm::SmallVector<BitCodeLibraryInfo, 12> BCLibs;
1026 BCLibs.emplace_back(Args: RocmInstallation->getOpenCLPath().str());
1027
1028 // Add the generic set of libraries.
1029 BCLibs.append(RHS: RocmInstallation->getCommonBitcodeLibs(
1030 DriverArgs, LibDeviceFile, GPUArch: GpuArch, DeviceOffloadingKind,
1031 NeedsASanRT: getSanitizerArgs(JobArgs: DriverArgs, BA: BoundArch{TargetID}, DeviceOffloadKind: DeviceOffloadingKind)
1032 .needsAsanRt()));
1033
1034 for (auto [BCFile, Internalize] : BCLibs) {
1035 if (Internalize)
1036 CC1Args.push_back(Elt: "-mlink-builtin-bitcode");
1037 else
1038 CC1Args.push_back(Elt: "-mlink-bitcode-file");
1039 CC1Args.push_back(Elt: DriverArgs.MakeArgString(Str: BCFile));
1040 }
1041}
1042
1043bool RocmInstallationDetector::checkCommonBitcodeLibs(
1044 StringRef GPUArch, StringRef LibDeviceFile,
1045 DeviceLibABIVersion ABIVer) const {
1046 if (!hasDeviceLibrary()) {
1047 D.Diag(DiagID: diag::err_drv_no_rocm_device_lib) << 0;
1048 return false;
1049 }
1050 if (LibDeviceFile.empty()) {
1051 D.Diag(DiagID: diag::err_drv_no_rocm_device_lib) << 1 << GPUArch;
1052 return false;
1053 }
1054 if (ABIVer.requiresLibrary() && getABIVersionPath(ABIVer).empty()) {
1055 // Starting from COV6, we will report minimum ROCm version requirement in
1056 // the error message.
1057 if (ABIVer.getAsCodeObjectVersion() < 6)
1058 D.Diag(DiagID: diag::err_drv_no_rocm_device_lib) << 2 << ABIVer.toString() << 0;
1059 else
1060 D.Diag(DiagID: diag::err_drv_no_rocm_device_lib)
1061 << 2 << ABIVer.toString() << 1 << "6.3";
1062 return false;
1063 }
1064 return true;
1065}
1066
1067llvm::SmallVector<ToolChain::BitCodeLibraryInfo, 12>
1068RocmInstallationDetector::getCommonBitcodeLibs(
1069 const llvm::opt::ArgList &DriverArgs, StringRef LibDeviceFile,
1070 StringRef GPUArch, const Action::OffloadKind DeviceOffloadingKind,
1071 const bool NeedsASanRT) const {
1072 llvm::SmallVector<ToolChain::BitCodeLibraryInfo, 12> BCLibs;
1073
1074 CommonBitcodeLibsPreferences Pref{D, DriverArgs, GPUArch,
1075 DeviceOffloadingKind, NeedsASanRT};
1076
1077 auto AddBCLib = [&](ToolChain::BitCodeLibraryInfo BCLib,
1078 bool Internalize = true) {
1079 if (!BCLib.Path.empty()) {
1080 BCLib.ShouldInternalize = Internalize;
1081 BCLibs.emplace_back(Args&: BCLib);
1082 }
1083 };
1084 auto AddSanBCLibs = [&]() {
1085 if (Pref.GPUSan)
1086 AddBCLib(getAsanRTLPath(), false);
1087 };
1088
1089 AddSanBCLibs();
1090 AddBCLib(getOCMLPath());
1091 if (!Pref.IsOpenMP)
1092 AddBCLib(getOCKLPath());
1093 else if (Pref.GPUSan && Pref.IsOpenMP)
1094 AddBCLib(getOCKLPath());
1095 AddBCLib(getUnsafeMathPath(Enabled: Pref.UnsafeMathOpt || Pref.FastRelaxedMath));
1096 AddBCLib(getFiniteOnlyPath(Enabled: Pref.FiniteOnly || Pref.FastRelaxedMath));
1097 AddBCLib(getWavefrontSize64Path(Enabled: Pref.Wave64));
1098 AddBCLib(LibDeviceFile);
1099 auto ABIVerPath = getABIVersionPath(ABIVer: Pref.ABIVer);
1100 if (!ABIVerPath.empty())
1101 AddBCLib(ABIVerPath);
1102
1103 return BCLibs;
1104}
1105
1106llvm::SmallVector<ToolChain::BitCodeLibraryInfo, 12>
1107ROCMToolChain::getCommonDeviceLibNames(
1108 const llvm::opt::ArgList &DriverArgs, llvm::StringRef TargetID,
1109 llvm::StringRef GPUArch, Action::OffloadKind DeviceOffloadingKind) const {
1110 auto Kind = llvm::AMDGPU::parseArchAMDGCN(CPU: GPUArch);
1111 const StringRef CanonArch = llvm::AMDGPU::getArchNameAMDGCN(AK: Kind);
1112
1113 StringRef LibDeviceFile = RocmInstallation->getLibDeviceFile(Gpu: CanonArch);
1114 auto ABIVer = DeviceLibABIVersion::fromCodeObjectVersion(
1115 CodeObjectVersion: getAMDGPUCodeObjectVersion(D: getDriver(), Args: DriverArgs));
1116 if (!RocmInstallation->checkCommonBitcodeLibs(GPUArch: CanonArch, LibDeviceFile,
1117 ABIVer))
1118 return {};
1119
1120 return RocmInstallation->getCommonBitcodeLibs(
1121 DriverArgs, LibDeviceFile, GPUArch, DeviceOffloadingKind,
1122 NeedsASanRT: getSanitizerArgs(JobArgs: DriverArgs, BA: BoundArch(TargetID), DeviceOffloadKind: DeviceOffloadingKind)
1123 .needsAsanRt());
1124}
1125
1126static bool isXnackAvailable(const llvm::Triple &TT, llvm::StringRef TargetID) {
1127 // Arch-specific check - only report as supported if arch has xnack+
1128 llvm::StringRef Processor = getProcessorFromTargetID(T: TT, OffloadArch: TargetID);
1129 auto ProcKind = TT.isAMDGCN() ? llvm::AMDGPU::parseArchAMDGCN(CPU: Processor)
1130 : llvm::AMDGPU::parseArchR600(CPU: Processor);
1131 auto Features = TT.isAMDGCN() ? llvm::AMDGPU::getArchAttrAMDGCN(AK: ProcKind)
1132 : llvm::AMDGPU::getArchAttrR600(AK: ProcKind);
1133
1134 // If processor has xnack but doesn't support on/off modes, xnack is always on
1135 bool XnackAlwaysOn = (Features & llvm::AMDGPU::FEATURE_XNACK) &&
1136 !(Features & llvm::AMDGPU::FEATURE_XNACK_ON_OFF_MODES);
1137 if (XnackAlwaysOn)
1138 return true;
1139
1140 // Otherwise, check if xnack+ is explicitly enabled in the target ID
1141 llvm::StringMap<bool> FeatureMap;
1142 auto OptionalGpuArch = parseTargetID(T: TT, OffloadArch: TargetID, FeatureMap: &FeatureMap);
1143 if (!OptionalGpuArch)
1144 return false;
1145 auto Loc = FeatureMap.find(Key: "xnack");
1146 return (Loc != FeatureMap.end() && Loc->second);
1147}
1148
1149SanitizerMask AMDGPUToolChain::getSupportedSanitizers(
1150 BoundArch BA, Action::OffloadKind DeviceOffloadKind) const {
1151 SanitizerMask SupportedMask =
1152 ToolChain::getSupportedSanitizers(BA, DeviceOffloadKind);
1153
1154 // Address sanitizer is potentially supported, but depends on the exact target
1155 // arch xnack support.
1156 if (!BA || isXnackAvailable(TT: getTriple(), TargetID: BA.ArchName))
1157 SupportedMask |= SanitizerKind::Address;
1158
1159 return SupportedMask;
1160}
1161
1162StringRef AMDGPUToolChain::getSanitizerRequirement(SanitizerMask Kinds,
1163 BoundArch BA) const {
1164 // Address sanitizer requires xnack+ feature
1165 if ((Kinds & SanitizerKind::Address) && BA &&
1166 !isXnackAvailable(TT: getTriple(), TargetID: BA.ArchName)) {
1167 return "xnack+";
1168 }
1169 return "";
1170}
1171