1 //===--- HIPAMD.cpp - HIP Tool and ToolChain Implementations ----*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "HIPAMD.h"
10 #include "AMDGPU.h"
11 #include "CommonArgs.h"
12 #include "HIPUtility.h"
13 #include "clang/Basic/Cuda.h"
14 #include "clang/Basic/TargetID.h"
15 #include "clang/Driver/Compilation.h"
16 #include "clang/Driver/Driver.h"
17 #include "clang/Driver/DriverDiagnostic.h"
18 #include "clang/Driver/InputInfo.h"
19 #include "clang/Driver/Options.h"
20 #include "clang/Driver/SanitizerArgs.h"
21 #include "llvm/Support/Alignment.h"
22 #include "llvm/Support/FileSystem.h"
23 #include "llvm/Support/Path.h"
24 #include "llvm/Support/TargetParser.h"
25 
26 using namespace clang::driver;
27 using namespace clang::driver::toolchains;
28 using namespace clang::driver::tools;
29 using namespace clang;
30 using namespace llvm::opt;
31 
32 #if defined(_WIN32) || defined(_WIN64)
33 #define NULL_FILE "nul"
34 #else
35 #define NULL_FILE "/dev/null"
36 #endif
37 
38 static bool shouldSkipSanitizeOption(const ToolChain &TC,
39                                      const llvm::opt::ArgList &DriverArgs,
40                                      StringRef TargetID,
41                                      const llvm::opt::Arg *A) {
42   // For actions without targetID, do nothing.
43   if (TargetID.empty())
44     return false;
45   Option O = A->getOption();
46   if (!O.matches(options::OPT_fsanitize_EQ))
47     return false;
48 
49   if (!DriverArgs.hasFlag(options::OPT_fgpu_sanitize,
50                           options::OPT_fno_gpu_sanitize))
51     return true;
52 
53   auto &Diags = TC.getDriver().getDiags();
54 
55   // For simplicity, we only allow -fsanitize=address
56   SanitizerMask K = parseSanitizerValue(A->getValue(), /*AllowGroups=*/false);
57   if (K != SanitizerKind::Address)
58     return true;
59 
60   llvm::StringMap<bool> FeatureMap;
61   auto OptionalGpuArch = parseTargetID(TC.getTriple(), TargetID, &FeatureMap);
62 
63   assert(OptionalGpuArch && "Invalid Target ID");
64   (void)OptionalGpuArch;
65   auto Loc = FeatureMap.find("xnack");
66   if (Loc == FeatureMap.end() || !Loc->second) {
67     Diags.Report(
68         clang::diag::warn_drv_unsupported_option_for_offload_arch_req_feature)
69         << A->getAsString(DriverArgs) << TargetID << "xnack+";
70     return true;
71   }
72   return false;
73 }
74 
75 void AMDGCN::Linker::constructLldCommand(Compilation &C, const JobAction &JA,
76                                          const InputInfoList &Inputs,
77                                          const InputInfo &Output,
78                                          const llvm::opt::ArgList &Args) const {
79   // Construct lld command.
80   // The output from ld.lld is an HSA code object file.
81   ArgStringList LldArgs{"-flavor", "gnu", "--no-undefined", "-shared",
82                         "-plugin-opt=-amdgpu-internalize-symbols"};
83 
84   auto &TC = getToolChain();
85   auto &D = TC.getDriver();
86   assert(!Inputs.empty() && "Must have at least one input.");
87   bool IsThinLTO = D.getLTOMode(/*IsOffload=*/true) == LTOK_Thin;
88   addLTOOptions(TC, Args, LldArgs, Output, Inputs[0], IsThinLTO);
89 
90   // Extract all the -m options
91   std::vector<llvm::StringRef> Features;
92   amdgpu::getAMDGPUTargetFeatures(D, TC.getTriple(), Args, Features);
93 
94   // Add features to mattr such as cumode
95   std::string MAttrString = "-plugin-opt=-mattr=";
96   for (auto OneFeature : unifyTargetFeatures(Features)) {
97     MAttrString.append(Args.MakeArgString(OneFeature));
98     if (OneFeature != Features.back())
99       MAttrString.append(",");
100   }
101   if (!Features.empty())
102     LldArgs.push_back(Args.MakeArgString(MAttrString));
103 
104   // ToDo: Remove this option after AMDGPU backend supports ISA-level linking.
105   // Since AMDGPU backend currently does not support ISA-level linking, all
106   // called functions need to be imported.
107   if (IsThinLTO)
108     LldArgs.push_back(Args.MakeArgString("-plugin-opt=-force-import-all"));
109 
110   for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
111     LldArgs.push_back(
112         Args.MakeArgString(Twine("-plugin-opt=") + A->getValue(0)));
113   }
114 
115   if (C.getDriver().isSaveTempsEnabled())
116     LldArgs.push_back("-save-temps");
117 
118   addLinkerCompressDebugSectionsOption(TC, Args, LldArgs);
119 
120   LldArgs.append({"-o", Output.getFilename()});
121   for (auto Input : Inputs)
122     LldArgs.push_back(Input.getFilename());
123 
124   // Look for archive of bundled bitcode in arguments, and add temporary files
125   // for the extracted archive of bitcode to inputs.
126   auto TargetID = Args.getLastArgValue(options::OPT_mcpu_EQ);
127   AddStaticDeviceLibsLinking(C, *this, JA, Inputs, Args, LldArgs, "amdgcn",
128                              TargetID,
129                              /*IsBitCodeSDL=*/true,
130                              /*PostClangLink=*/false);
131 
132   const char *Lld = Args.MakeArgString(getToolChain().GetProgramPath("lld"));
133   C.addCommand(std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),
134                                          Lld, LldArgs, Inputs, Output));
135 }
136 
137 // For amdgcn the inputs of the linker job are device bitcode and output is
138 // object file. It calls llvm-link, opt, llc, then lld steps.
139 void AMDGCN::Linker::ConstructJob(Compilation &C, const JobAction &JA,
140                                   const InputInfo &Output,
141                                   const InputInfoList &Inputs,
142                                   const ArgList &Args,
143                                   const char *LinkingOutput) const {
144   if (Inputs.size() > 0 &&
145       Inputs[0].getType() == types::TY_Image &&
146       JA.getType() == types::TY_Object)
147     return HIP::constructGenerateObjFileFromHIPFatBinary(C, Output, Inputs,
148                                                          Args, JA, *this);
149 
150   if (JA.getType() == types::TY_HIP_FATBIN)
151     return HIP::constructHIPFatbinCommand(C, JA, Output.getFilename(), Inputs,
152                                           Args, *this);
153 
154   return constructLldCommand(C, JA, Inputs, Output, Args);
155 }
156 
157 HIPAMDToolChain::HIPAMDToolChain(const Driver &D, const llvm::Triple &Triple,
158                                  const ToolChain &HostTC, const ArgList &Args)
159     : ROCMToolChain(D, Triple, Args), HostTC(HostTC) {
160   // Lookup binaries into the driver directory, this is used to
161   // discover the clang-offload-bundler executable.
162   getProgramPaths().push_back(getDriver().Dir);
163 
164   // Diagnose unsupported sanitizer options only once.
165   if (!Args.hasFlag(options::OPT_fgpu_sanitize, options::OPT_fno_gpu_sanitize))
166     return;
167   for (auto A : Args.filtered(options::OPT_fsanitize_EQ)) {
168     SanitizerMask K = parseSanitizerValue(A->getValue(), /*AllowGroups=*/false);
169     if (K != SanitizerKind::Address)
170       D.getDiags().Report(clang::diag::warn_drv_unsupported_option_for_target)
171           << A->getAsString(Args) << getTriple().str();
172   }
173 }
174 
175 void HIPAMDToolChain::addClangTargetOptions(
176     const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
177     Action::OffloadKind DeviceOffloadingKind) const {
178   HostTC.addClangTargetOptions(DriverArgs, CC1Args, DeviceOffloadingKind);
179 
180   assert(DeviceOffloadingKind == Action::OFK_HIP &&
181          "Only HIP offloading kinds are supported for GPUs.");
182 
183   CC1Args.push_back("-fcuda-is-device");
184 
185   if (DriverArgs.hasFlag(options::OPT_fcuda_approx_transcendentals,
186                          options::OPT_fno_cuda_approx_transcendentals, false))
187     CC1Args.push_back("-fcuda-approx-transcendentals");
188 
189   if (!DriverArgs.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
190                           false))
191     CC1Args.append({"-mllvm", "-amdgpu-internalize-symbols"});
192 
193   StringRef MaxThreadsPerBlock =
194       DriverArgs.getLastArgValue(options::OPT_gpu_max_threads_per_block_EQ);
195   if (!MaxThreadsPerBlock.empty()) {
196     std::string ArgStr =
197         std::string("--gpu-max-threads-per-block=") + MaxThreadsPerBlock.str();
198     CC1Args.push_back(DriverArgs.MakeArgStringRef(ArgStr));
199   }
200 
201   CC1Args.push_back("-fcuda-allow-variadic-functions");
202 
203   // Default to "hidden" visibility, as object level linking will not be
204   // supported for the foreseeable future.
205   if (!DriverArgs.hasArg(options::OPT_fvisibility_EQ,
206                          options::OPT_fvisibility_ms_compat)) {
207     CC1Args.append({"-fvisibility", "hidden"});
208     CC1Args.push_back("-fapply-global-visibility-to-externs");
209   }
210 
211   llvm::for_each(getHIPDeviceLibs(DriverArgs), [&](auto BCFile) {
212     CC1Args.push_back(BCFile.ShouldInternalize ? "-mlink-builtin-bitcode"
213                                                : "-mlink-bitcode-file");
214     CC1Args.push_back(DriverArgs.MakeArgString(BCFile.Path));
215   });
216 }
217 
218 llvm::opt::DerivedArgList *
219 HIPAMDToolChain::TranslateArgs(const llvm::opt::DerivedArgList &Args,
220                                StringRef BoundArch,
221                                Action::OffloadKind DeviceOffloadKind) const {
222   DerivedArgList *DAL =
223       HostTC.TranslateArgs(Args, BoundArch, DeviceOffloadKind);
224   if (!DAL)
225     DAL = new DerivedArgList(Args.getBaseArgs());
226 
227   const OptTable &Opts = getDriver().getOpts();
228 
229   for (Arg *A : Args) {
230     if (!shouldSkipArgument(A) &&
231         !shouldSkipSanitizeOption(*this, Args, BoundArch, A))
232       DAL->append(A);
233   }
234 
235   if (!BoundArch.empty()) {
236     DAL->eraseArg(options::OPT_mcpu_EQ);
237     DAL->AddJoinedArg(nullptr, Opts.getOption(options::OPT_mcpu_EQ), BoundArch);
238     checkTargetID(*DAL);
239   }
240 
241   return DAL;
242 }
243 
244 Tool *HIPAMDToolChain::buildLinker() const {
245   assert(getTriple().getArch() == llvm::Triple::amdgcn);
246   return new tools::AMDGCN::Linker(*this);
247 }
248 
249 void HIPAMDToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {
250   HostTC.addClangWarningOptions(CC1Args);
251 }
252 
253 ToolChain::CXXStdlibType
254 HIPAMDToolChain::GetCXXStdlibType(const ArgList &Args) const {
255   return HostTC.GetCXXStdlibType(Args);
256 }
257 
258 void HIPAMDToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
259                                                 ArgStringList &CC1Args) const {
260   HostTC.AddClangSystemIncludeArgs(DriverArgs, CC1Args);
261 }
262 
263 void HIPAMDToolChain::AddClangCXXStdlibIncludeArgs(
264     const ArgList &Args, ArgStringList &CC1Args) const {
265   HostTC.AddClangCXXStdlibIncludeArgs(Args, CC1Args);
266 }
267 
268 void HIPAMDToolChain::AddIAMCUIncludeArgs(const ArgList &Args,
269                                           ArgStringList &CC1Args) const {
270   HostTC.AddIAMCUIncludeArgs(Args, CC1Args);
271 }
272 
273 void HIPAMDToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs,
274                                         ArgStringList &CC1Args) const {
275   RocmInstallation.AddHIPIncludeArgs(DriverArgs, CC1Args);
276 }
277 
278 SanitizerMask HIPAMDToolChain::getSupportedSanitizers() const {
279   // The HIPAMDToolChain only supports sanitizers in the sense that it allows
280   // sanitizer arguments on the command line if they are supported by the host
281   // toolchain. The HIPAMDToolChain will actually ignore any command line
282   // arguments for any of these "supported" sanitizers. That means that no
283   // sanitization of device code is actually supported at this time.
284   //
285   // This behavior is necessary because the host and device toolchains
286   // invocations often share the command line, so the device toolchain must
287   // tolerate flags meant only for the host toolchain.
288   return HostTC.getSupportedSanitizers();
289 }
290 
291 VersionTuple HIPAMDToolChain::computeMSVCVersion(const Driver *D,
292                                                  const ArgList &Args) const {
293   return HostTC.computeMSVCVersion(D, Args);
294 }
295 
296 llvm::SmallVector<ToolChain::BitCodeLibraryInfo, 12>
297 HIPAMDToolChain::getHIPDeviceLibs(const llvm::opt::ArgList &DriverArgs) const {
298   llvm::SmallVector<BitCodeLibraryInfo, 12> BCLibs;
299   if (DriverArgs.hasArg(options::OPT_nogpulib))
300     return {};
301   ArgStringList LibraryPaths;
302 
303   // Find in --hip-device-lib-path and HIP_LIBRARY_PATH.
304   for (auto Path : RocmInstallation.getRocmDeviceLibPathArg())
305     LibraryPaths.push_back(DriverArgs.MakeArgString(Path));
306 
307   addDirectoryList(DriverArgs, LibraryPaths, "", "HIP_DEVICE_LIB_PATH");
308 
309   // Maintain compatability with --hip-device-lib.
310   auto BCLibArgs = DriverArgs.getAllArgValues(options::OPT_hip_device_lib_EQ);
311   if (!BCLibArgs.empty()) {
312     llvm::for_each(BCLibArgs, [&](StringRef BCName) {
313       StringRef FullName;
314       for (std::string LibraryPath : LibraryPaths) {
315         SmallString<128> Path(LibraryPath);
316         llvm::sys::path::append(Path, BCName);
317         FullName = Path;
318         if (llvm::sys::fs::exists(FullName)) {
319           BCLibs.push_back(FullName);
320           return;
321         }
322       }
323       getDriver().Diag(diag::err_drv_no_such_file) << BCName;
324     });
325   } else {
326     if (!RocmInstallation.hasDeviceLibrary()) {
327       getDriver().Diag(diag::err_drv_no_rocm_device_lib) << 0;
328       return {};
329     }
330     StringRef GpuArch = getGPUArch(DriverArgs);
331     assert(!GpuArch.empty() && "Must have an explicit GPU arch.");
332 
333     // If --hip-device-lib is not set, add the default bitcode libraries.
334     if (DriverArgs.hasFlag(options::OPT_fgpu_sanitize,
335                            options::OPT_fno_gpu_sanitize) &&
336         getSanitizerArgs(DriverArgs).needsAsanRt()) {
337       auto AsanRTL = RocmInstallation.getAsanRTLPath();
338       if (AsanRTL.empty()) {
339         unsigned DiagID = getDriver().getDiags().getCustomDiagID(
340             DiagnosticsEngine::Error,
341             "AMDGPU address sanitizer runtime library (asanrtl) is not found. "
342             "Please install ROCm device library which supports address "
343             "sanitizer");
344         getDriver().Diag(DiagID);
345         return {};
346       } else
347         BCLibs.push_back({AsanRTL.str(), /*ShouldInternalize=*/false});
348     }
349 
350     // Add the HIP specific bitcode library.
351     BCLibs.push_back(RocmInstallation.getHIPPath());
352 
353     // Add common device libraries like ocml etc.
354     for (auto N : getCommonDeviceLibNames(DriverArgs, GpuArch.str()))
355       BCLibs.push_back(StringRef(N));
356 
357     // Add instrument lib.
358     auto InstLib =
359         DriverArgs.getLastArgValue(options::OPT_gpu_instrument_lib_EQ);
360     if (InstLib.empty())
361       return BCLibs;
362     if (llvm::sys::fs::exists(InstLib))
363       BCLibs.push_back(InstLib);
364     else
365       getDriver().Diag(diag::err_drv_no_such_file) << InstLib;
366   }
367 
368   return BCLibs;
369 }
370 
371 void HIPAMDToolChain::checkTargetID(
372     const llvm::opt::ArgList &DriverArgs) const {
373   auto PTID = getParsedTargetID(DriverArgs);
374   if (PTID.OptionalTargetID && !PTID.OptionalGPUArch) {
375     getDriver().Diag(clang::diag::err_drv_bad_target_id)
376         << PTID.OptionalTargetID.getValue();
377   }
378 }
379