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 "CommonArgs.h"
11 #include "InputInfo.h"
12 #include "clang/Driver/Compilation.h"
13 #include "clang/Driver/DriverDiagnostic.h"
14 #include "llvm/Option/ArgList.h"
15 #include "llvm/Support/Path.h"
16 #include "llvm/Support/VirtualFileSystem.h"
17 
18 using namespace clang::driver;
19 using namespace clang::driver::tools;
20 using namespace clang::driver::toolchains;
21 using namespace clang;
22 using namespace llvm::opt;
23 
24 void RocmInstallationDetector::scanLibDevicePath() {
25   assert(!LibDevicePath.empty());
26 
27   const StringRef Suffix(".bc");
28 
29   std::error_code EC;
30   for (llvm::sys::fs::directory_iterator LI(LibDevicePath, EC), LE;
31        !EC && LI != LE; LI = LI.increment(EC)) {
32     StringRef FilePath = LI->path();
33     StringRef FileName = llvm::sys::path::filename(FilePath);
34     if (!FileName.endswith(Suffix))
35       continue;
36 
37     StringRef BaseName = FileName.drop_back(Suffix.size());
38 
39     if (BaseName == "ocml") {
40       OCML = FilePath;
41     } else if (BaseName == "ockl") {
42       OCKL = FilePath;
43     } else if (BaseName == "opencl") {
44       OpenCL = FilePath;
45     } else if (BaseName == "hip") {
46       HIP = FilePath;
47     } else if (BaseName == "oclc_finite_only_off") {
48       FiniteOnly.Off = FilePath;
49     } else if (BaseName == "oclc_finite_only_on") {
50       FiniteOnly.On = FilePath;
51     } else if (BaseName == "oclc_daz_opt_on") {
52       DenormalsAreZero.On = FilePath;
53     } else if (BaseName == "oclc_daz_opt_off") {
54       DenormalsAreZero.Off = FilePath;
55     } else if (BaseName == "oclc_correctly_rounded_sqrt_on") {
56       CorrectlyRoundedSqrt.On = FilePath;
57     } else if (BaseName == "oclc_correctly_rounded_sqrt_off") {
58       CorrectlyRoundedSqrt.Off = FilePath;
59     } else if (BaseName == "oclc_unsafe_math_on") {
60       UnsafeMath.On = FilePath;
61     } else if (BaseName == "oclc_unsafe_math_off") {
62       UnsafeMath.Off = FilePath;
63     } else if (BaseName == "oclc_wavefrontsize64_on") {
64       WavefrontSize64.On = FilePath;
65     } else if (BaseName == "oclc_wavefrontsize64_off") {
66       WavefrontSize64.Off = FilePath;
67     } else {
68       // Process all bitcode filenames that look like
69       // ocl_isa_version_XXX.amdgcn.bc
70       const StringRef DeviceLibPrefix = "oclc_isa_version_";
71       if (!BaseName.startswith(DeviceLibPrefix))
72         continue;
73 
74       StringRef IsaVersionNumber =
75         BaseName.drop_front(DeviceLibPrefix.size());
76 
77       llvm::Twine GfxName = Twine("gfx") + IsaVersionNumber;
78       SmallString<8> Tmp;
79       LibDeviceMap.insert(
80         std::make_pair(GfxName.toStringRef(Tmp), FilePath.str()));
81     }
82   }
83 }
84 
85 RocmInstallationDetector::RocmInstallationDetector(
86     const Driver &D, const llvm::Triple &HostTriple,
87     const llvm::opt::ArgList &Args)
88     : D(D) {
89   struct Candidate {
90     std::string Path;
91     bool StrictChecking;
92 
93     Candidate(std::string Path, bool StrictChecking = false)
94         : Path(Path), StrictChecking(StrictChecking) {}
95   };
96 
97   SmallVector<Candidate, 4> Candidates;
98 
99   if (Args.hasArg(clang::driver::options::OPT_rocm_path_EQ)) {
100     Candidates.emplace_back(
101         Args.getLastArgValue(clang::driver::options::OPT_rocm_path_EQ).str());
102   } else {
103     // Try to find relative to the compiler binary.
104     const char *InstallDir = D.getInstalledDir();
105 
106     // Check both a normal Unix prefix position of the clang binary, as well as
107     // the Windows-esque layout the ROCm packages use with the host architecture
108     // subdirectory of bin.
109 
110     // Strip off directory (usually bin)
111     StringRef ParentDir = llvm::sys::path::parent_path(InstallDir);
112     StringRef ParentName = llvm::sys::path::filename(ParentDir);
113 
114     // Some builds use bin/{host arch}, so go up again.
115     if (ParentName == "bin") {
116       ParentDir = llvm::sys::path::parent_path(ParentDir);
117       ParentName = llvm::sys::path::filename(ParentDir);
118     }
119 
120     if (ParentName == "llvm") {
121       // Some versions of the rocm llvm package install to /opt/rocm/llvm/bin
122       Candidates.emplace_back(llvm::sys::path::parent_path(ParentDir).str(),
123                               /*StrictChecking=*/true);
124     }
125 
126     Candidates.emplace_back(D.SysRoot + "/opt/rocm");
127   }
128 
129   bool NoBuiltinLibs = Args.hasArg(options::OPT_nogpulib);
130 
131   assert(LibDevicePath.empty());
132 
133   if (Args.hasArg(clang::driver::options::OPT_hip_device_lib_path_EQ)) {
134     LibDevicePath
135       = Args.getLastArgValue(clang::driver::options::OPT_hip_device_lib_path_EQ);
136   } else if (const char *LibPathEnv = ::getenv("HIP_DEVICE_LIB_PATH")) {
137     LibDevicePath = LibPathEnv;
138   }
139 
140   if (!LibDevicePath.empty()) {
141     // Maintain compatability with HIP flag/envvar pointing directly at the
142     // bitcode library directory. This points directly at the library path instead
143     // of the rocm root installation.
144     if (!D.getVFS().exists(LibDevicePath))
145       return;
146 
147     scanLibDevicePath();
148     IsValid = allGenericLibsValid() && !LibDeviceMap.empty();
149     return;
150   }
151 
152   for (const auto &Candidate : Candidates) {
153     InstallPath = Candidate.Path;
154     if (InstallPath.empty() || !D.getVFS().exists(InstallPath))
155       continue;
156 
157     // The install path situation in old versions of ROCm is a real mess, and
158     // use a different install layout. Multiple copies of the device libraries
159     // exist for each frontend project, and differ depending on which build
160     // system produced the packages. Standalone OpenCL builds also have a
161     // different directory structure from the ROCm OpenCL package.
162     //
163     // The desired structure is (${ROCM_ROOT} or
164     // ${OPENCL_ROOT})/amdgcn/bitcode/*, so try to detect this layout.
165 
166     // BinPath = InstallPath + "/bin";
167     llvm::sys::path::append(IncludePath, InstallPath, "include");
168     llvm::sys::path::append(LibDevicePath, InstallPath, "amdgcn", "bitcode");
169 
170     auto &FS = D.getVFS();
171 
172     // We don't need the include path for OpenCL, since clang already ships with
173     // the default header.
174 
175     bool CheckLibDevice = (!NoBuiltinLibs || Candidate.StrictChecking);
176     if (CheckLibDevice && !FS.exists(LibDevicePath))
177       continue;
178 
179     scanLibDevicePath();
180 
181     if (!NoBuiltinLibs) {
182       // Check that the required non-target libraries are all available.
183       if (!allGenericLibsValid())
184         continue;
185 
186       // Check that we have found at least one libdevice that we can link in if
187       // -nobuiltinlib hasn't been specified.
188       if (LibDeviceMap.empty())
189         continue;
190     }
191 
192     IsValid = true;
193     break;
194   }
195 }
196 
197 void RocmInstallationDetector::print(raw_ostream &OS) const {
198   if (isValid())
199     OS << "Found ROCm installation: " << InstallPath << '\n';
200 }
201 
202 void amdgpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,
203                                   const InputInfo &Output,
204                                   const InputInfoList &Inputs,
205                                   const ArgList &Args,
206                                   const char *LinkingOutput) const {
207 
208   std::string Linker = getToolChain().GetProgramPath(getShortName());
209   ArgStringList CmdArgs;
210   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
211   CmdArgs.push_back("-shared");
212   CmdArgs.push_back("-o");
213   CmdArgs.push_back(Output.getFilename());
214   C.addCommand(std::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
215                                           CmdArgs, Inputs));
216 }
217 
218 void amdgpu::getAMDGPUTargetFeatures(const Driver &D,
219                                      const llvm::opt::ArgList &Args,
220                                      std::vector<StringRef> &Features) {
221   if (const Arg *dAbi = Args.getLastArg(options::OPT_mamdgpu_debugger_abi))
222     D.Diag(diag::err_drv_clang_unsupported) << dAbi->getAsString(Args);
223 
224   if (Args.getLastArg(options::OPT_mwavefrontsize64)) {
225     Features.push_back("-wavefrontsize16");
226     Features.push_back("-wavefrontsize32");
227     Features.push_back("+wavefrontsize64");
228   }
229   if (Args.getLastArg(options::OPT_mno_wavefrontsize64)) {
230     Features.push_back("-wavefrontsize16");
231     Features.push_back("+wavefrontsize32");
232     Features.push_back("-wavefrontsize64");
233   }
234 
235   handleTargetFeaturesGroup(
236     Args, Features, options::OPT_m_amdgpu_Features_Group);
237 }
238 
239 /// AMDGPU Toolchain
240 AMDGPUToolChain::AMDGPUToolChain(const Driver &D, const llvm::Triple &Triple,
241                                  const ArgList &Args)
242     : Generic_ELF(D, Triple, Args),
243       OptionsDefault({{options::OPT_O, "3"},
244                       {options::OPT_cl_std_EQ, "CL1.2"}}) {}
245 
246 Tool *AMDGPUToolChain::buildLinker() const {
247   return new tools::amdgpu::Linker(*this);
248 }
249 
250 DerivedArgList *
251 AMDGPUToolChain::TranslateArgs(const DerivedArgList &Args, StringRef BoundArch,
252                                Action::OffloadKind DeviceOffloadKind) const {
253 
254   DerivedArgList *DAL =
255       Generic_ELF::TranslateArgs(Args, BoundArch, DeviceOffloadKind);
256 
257   // Do nothing if not OpenCL (-x cl)
258   if (!Args.getLastArgValue(options::OPT_x).equals("cl"))
259     return DAL;
260 
261   if (!DAL)
262     DAL = new DerivedArgList(Args.getBaseArgs());
263   for (auto *A : Args)
264     DAL->append(A);
265 
266   const OptTable &Opts = getDriver().getOpts();
267 
268   // Phase 1 (.cl -> .bc)
269   if (Args.hasArg(options::OPT_c) && Args.hasArg(options::OPT_emit_llvm)) {
270     DAL->AddFlagArg(nullptr, Opts.getOption(getTriple().isArch64Bit()
271                                                 ? options::OPT_m64
272                                                 : options::OPT_m32));
273 
274     // Have to check OPT_O4, OPT_O0 & OPT_Ofast separately
275     // as they defined that way in Options.td
276     if (!Args.hasArg(options::OPT_O, options::OPT_O0, options::OPT_O4,
277                      options::OPT_Ofast))
278       DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_O),
279                         getOptionDefault(options::OPT_O));
280   }
281 
282   return DAL;
283 }
284 
285 bool AMDGPUToolChain::getDefaultDenormsAreZeroForTarget(
286     llvm::AMDGPU::GPUKind Kind) {
287 
288   // Assume nothing without a specific target.
289   if (Kind == llvm::AMDGPU::GK_NONE)
290     return false;
291 
292   const unsigned ArchAttr = llvm::AMDGPU::getArchAttrAMDGCN(Kind);
293 
294   // Default to enabling f32 denormals by default on subtargets where fma is
295   // fast with denormals
296   const bool BothDenormAndFMAFast =
297       (ArchAttr & llvm::AMDGPU::FEATURE_FAST_FMA_F32) &&
298       (ArchAttr & llvm::AMDGPU::FEATURE_FAST_DENORMAL_F32);
299   return !BothDenormAndFMAFast;
300 }
301 
302 llvm::DenormalMode AMDGPUToolChain::getDefaultDenormalModeForType(
303     const llvm::opt::ArgList &DriverArgs, const JobAction &JA,
304     const llvm::fltSemantics *FPType) const {
305   // Denormals should always be enabled for f16 and f64.
306   if (!FPType || FPType != &llvm::APFloat::IEEEsingle())
307     return llvm::DenormalMode::getIEEE();
308 
309   if (JA.getOffloadingDeviceKind() == Action::OFK_HIP ||
310       JA.getOffloadingDeviceKind() == Action::OFK_Cuda) {
311     auto Kind = llvm::AMDGPU::parseArchAMDGCN(JA.getOffloadingArch());
312     if (FPType && FPType == &llvm::APFloat::IEEEsingle() &&
313         DriverArgs.hasFlag(options::OPT_fcuda_flush_denormals_to_zero,
314                            options::OPT_fno_cuda_flush_denormals_to_zero,
315                            getDefaultDenormsAreZeroForTarget(Kind)))
316       return llvm::DenormalMode::getPreserveSign();
317 
318     return llvm::DenormalMode::getIEEE();
319   }
320 
321   const StringRef GpuArch = DriverArgs.getLastArgValue(options::OPT_mcpu_EQ);
322   auto Kind = llvm::AMDGPU::parseArchAMDGCN(GpuArch);
323 
324   // TODO: There are way too many flags that change this. Do we need to check
325   // them all?
326   bool DAZ = DriverArgs.hasArg(options::OPT_cl_denorms_are_zero) ||
327              getDefaultDenormsAreZeroForTarget(Kind);
328 
329   // Outputs are flushed to zero (FTZ), preserving sign. Denormal inputs are
330   // also implicit treated as zero (DAZ).
331   return DAZ ? llvm::DenormalMode::getPreserveSign() :
332                llvm::DenormalMode::getIEEE();
333 }
334 
335 bool AMDGPUToolChain::isWave64(const llvm::opt::ArgList &DriverArgs,
336                                llvm::AMDGPU::GPUKind Kind) {
337   const unsigned ArchAttr = llvm::AMDGPU::getArchAttrAMDGCN(Kind);
338   static bool HasWave32 = (ArchAttr & llvm::AMDGPU::FEATURE_WAVE32);
339 
340   return !HasWave32 || DriverArgs.hasFlag(
341     options::OPT_mwavefrontsize64, options::OPT_mno_wavefrontsize64, false);
342 }
343 
344 
345 /// ROCM Toolchain
346 ROCMToolChain::ROCMToolChain(const Driver &D, const llvm::Triple &Triple,
347                              const ArgList &Args)
348   : AMDGPUToolChain(D, Triple, Args),
349     RocmInstallation(D, Triple, Args) { }
350 
351 void AMDGPUToolChain::addClangTargetOptions(
352     const llvm::opt::ArgList &DriverArgs,
353     llvm::opt::ArgStringList &CC1Args,
354     Action::OffloadKind DeviceOffloadingKind) const {
355   // Default to "hidden" visibility, as object level linking will not be
356   // supported for the foreseeable future.
357   if (!DriverArgs.hasArg(options::OPT_fvisibility_EQ,
358                          options::OPT_fvisibility_ms_compat)) {
359     CC1Args.push_back("-fvisibility");
360     CC1Args.push_back("hidden");
361     CC1Args.push_back("-fapply-global-visibility-to-externs");
362   }
363 }
364 
365 void ROCMToolChain::addClangTargetOptions(
366     const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
367     Action::OffloadKind DeviceOffloadingKind) const {
368   AMDGPUToolChain::addClangTargetOptions(DriverArgs, CC1Args,
369                                          DeviceOffloadingKind);
370 
371   // For the OpenCL case where there is no offload target, accept -nostdlib to
372   // disable bitcode linking.
373   if (DeviceOffloadingKind == Action::OFK_None &&
374       DriverArgs.hasArg(options::OPT_nostdlib))
375     return;
376 
377   if (DriverArgs.hasArg(options::OPT_nogpulib))
378     return;
379 
380   if (!RocmInstallation.isValid()) {
381     getDriver().Diag(diag::err_drv_no_rocm_installation);
382     return;
383   }
384 
385   // Get the device name and canonicalize it
386   const StringRef GpuArch = DriverArgs.getLastArgValue(options::OPT_mcpu_EQ);
387   auto Kind = llvm::AMDGPU::parseArchAMDGCN(GpuArch);
388   const StringRef CanonArch = llvm::AMDGPU::getArchNameAMDGCN(Kind);
389   std::string LibDeviceFile = RocmInstallation.getLibDeviceFile(CanonArch);
390   if (LibDeviceFile.empty()) {
391     getDriver().Diag(diag::err_drv_no_rocm_device_lib) << GpuArch;
392     return;
393   }
394 
395   bool Wave64 = isWave64(DriverArgs, Kind);
396 
397   // TODO: There are way too many flags that change this. Do we need to check
398   // them all?
399   bool DAZ = DriverArgs.hasArg(options::OPT_cl_denorms_are_zero) ||
400              getDefaultDenormsAreZeroForTarget(Kind);
401   bool FiniteOnly = DriverArgs.hasArg(options::OPT_cl_finite_math_only);
402 
403   bool UnsafeMathOpt =
404       DriverArgs.hasArg(options::OPT_cl_unsafe_math_optimizations);
405   bool FastRelaxedMath = DriverArgs.hasArg(options::OPT_cl_fast_relaxed_math);
406   bool CorrectSqrt =
407       DriverArgs.hasArg(options::OPT_cl_fp32_correctly_rounded_divide_sqrt);
408 
409   // Add the OpenCL specific bitcode library.
410   CC1Args.push_back("-mlink-builtin-bitcode");
411   CC1Args.push_back(DriverArgs.MakeArgString(RocmInstallation.getOpenCLPath()));
412 
413   // Add the generic set of libraries.
414   RocmInstallation.addCommonBitcodeLibCC1Args(
415       DriverArgs, CC1Args, LibDeviceFile, Wave64, DAZ, FiniteOnly,
416       UnsafeMathOpt, FastRelaxedMath, CorrectSqrt);
417 }
418 
419 void RocmInstallationDetector::addCommonBitcodeLibCC1Args(
420     const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
421     StringRef LibDeviceFile, bool Wave64, bool DAZ, bool FiniteOnly,
422     bool UnsafeMathOpt, bool FastRelaxedMath, bool CorrectSqrt) const {
423   static const char LinkBitcodeFlag[] = "-mlink-builtin-bitcode";
424 
425   CC1Args.push_back(LinkBitcodeFlag);
426   CC1Args.push_back(DriverArgs.MakeArgString(getOCMLPath()));
427 
428   CC1Args.push_back(LinkBitcodeFlag);
429   CC1Args.push_back(DriverArgs.MakeArgString(getOCKLPath()));
430 
431   CC1Args.push_back(LinkBitcodeFlag);
432   CC1Args.push_back(DriverArgs.MakeArgString(getDenormalsAreZeroPath(DAZ)));
433 
434   CC1Args.push_back(LinkBitcodeFlag);
435   CC1Args.push_back(DriverArgs.MakeArgString(
436       getUnsafeMathPath(UnsafeMathOpt || FastRelaxedMath)));
437 
438   CC1Args.push_back(LinkBitcodeFlag);
439   CC1Args.push_back(DriverArgs.MakeArgString(
440       getFiniteOnlyPath(FiniteOnly || FastRelaxedMath)));
441 
442   CC1Args.push_back(LinkBitcodeFlag);
443   CC1Args.push_back(
444       DriverArgs.MakeArgString(getCorrectlyRoundedSqrtPath(CorrectSqrt)));
445 
446   CC1Args.push_back(LinkBitcodeFlag);
447   CC1Args.push_back(DriverArgs.MakeArgString(getWavefrontSize64Path(Wave64)));
448 
449   CC1Args.push_back(LinkBitcodeFlag);
450   CC1Args.push_back(DriverArgs.MakeArgString(LibDeviceFile));
451 }
452