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