xref: /openbsd-src/gnu/llvm/clang/lib/Driver/ToolChains/HIPSPV.cpp (revision 12c855180aad702bbcca06e0398d774beeafb155)
1*12c85518Srobert //===--- HIPSPV.cpp - HIPSPV ToolChain Implementation -----------*- C++ -*-===//
2*12c85518Srobert //
3*12c85518Srobert // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*12c85518Srobert // See https://llvm.org/LICENSE.txt for license information.
5*12c85518Srobert // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*12c85518Srobert //
7*12c85518Srobert //===----------------------------------------------------------------------===//
8*12c85518Srobert 
9*12c85518Srobert #include "HIPSPV.h"
10*12c85518Srobert #include "CommonArgs.h"
11*12c85518Srobert #include "HIPUtility.h"
12*12c85518Srobert #include "clang/Driver/Compilation.h"
13*12c85518Srobert #include "clang/Driver/Driver.h"
14*12c85518Srobert #include "clang/Driver/DriverDiagnostic.h"
15*12c85518Srobert #include "clang/Driver/InputInfo.h"
16*12c85518Srobert #include "clang/Driver/Options.h"
17*12c85518Srobert #include "llvm/Support/FileSystem.h"
18*12c85518Srobert #include "llvm/Support/Path.h"
19*12c85518Srobert 
20*12c85518Srobert using namespace clang::driver;
21*12c85518Srobert using namespace clang::driver::toolchains;
22*12c85518Srobert using namespace clang::driver::tools;
23*12c85518Srobert using namespace clang;
24*12c85518Srobert using namespace llvm::opt;
25*12c85518Srobert 
26*12c85518Srobert // Convenience function for creating temporary file for both modes of
27*12c85518Srobert // isSaveTempsEnabled().
getTempFile(Compilation & C,StringRef Prefix,StringRef Extension)28*12c85518Srobert static const char *getTempFile(Compilation &C, StringRef Prefix,
29*12c85518Srobert                                StringRef Extension) {
30*12c85518Srobert   if (C.getDriver().isSaveTempsEnabled()) {
31*12c85518Srobert     return C.getArgs().MakeArgString(Prefix + "." + Extension);
32*12c85518Srobert   }
33*12c85518Srobert   auto TmpFile = C.getDriver().GetTemporaryPath(Prefix, Extension);
34*12c85518Srobert   return C.addTempFile(C.getArgs().MakeArgString(TmpFile));
35*12c85518Srobert }
36*12c85518Srobert 
37*12c85518Srobert // Locates HIP pass plugin.
findPassPlugin(const Driver & D,const llvm::opt::ArgList & Args)38*12c85518Srobert static std::string findPassPlugin(const Driver &D,
39*12c85518Srobert                                   const llvm::opt::ArgList &Args) {
40*12c85518Srobert   StringRef Path = Args.getLastArgValue(options::OPT_hipspv_pass_plugin_EQ);
41*12c85518Srobert   if (!Path.empty()) {
42*12c85518Srobert     if (llvm::sys::fs::exists(Path))
43*12c85518Srobert       return Path.str();
44*12c85518Srobert     D.Diag(diag::err_drv_no_such_file) << Path;
45*12c85518Srobert   }
46*12c85518Srobert 
47*12c85518Srobert   StringRef hipPath = Args.getLastArgValue(options::OPT_hip_path_EQ);
48*12c85518Srobert   if (!hipPath.empty()) {
49*12c85518Srobert     SmallString<128> PluginPath(hipPath);
50*12c85518Srobert     llvm::sys::path::append(PluginPath, "lib", "libLLVMHipSpvPasses.so");
51*12c85518Srobert     if (llvm::sys::fs::exists(PluginPath))
52*12c85518Srobert       return PluginPath.str().str();
53*12c85518Srobert     PluginPath.assign(hipPath);
54*12c85518Srobert     llvm::sys::path::append(PluginPath, "lib", "llvm",
55*12c85518Srobert                             "libLLVMHipSpvPasses.so");
56*12c85518Srobert     if (llvm::sys::fs::exists(PluginPath))
57*12c85518Srobert       return PluginPath.str().str();
58*12c85518Srobert   }
59*12c85518Srobert 
60*12c85518Srobert   return std::string();
61*12c85518Srobert }
62*12c85518Srobert 
constructLinkAndEmitSpirvCommand(Compilation & C,const JobAction & JA,const InputInfoList & Inputs,const InputInfo & Output,const llvm::opt::ArgList & Args) const63*12c85518Srobert void HIPSPV::Linker::constructLinkAndEmitSpirvCommand(
64*12c85518Srobert     Compilation &C, const JobAction &JA, const InputInfoList &Inputs,
65*12c85518Srobert     const InputInfo &Output, const llvm::opt::ArgList &Args) const {
66*12c85518Srobert 
67*12c85518Srobert   assert(!Inputs.empty() && "Must have at least one input.");
68*12c85518Srobert   std::string Name = std::string(llvm::sys::path::stem(Output.getFilename()));
69*12c85518Srobert   const char *TempFile = getTempFile(C, Name + "-link", "bc");
70*12c85518Srobert 
71*12c85518Srobert   // Link LLVM bitcode.
72*12c85518Srobert   ArgStringList LinkArgs{};
73*12c85518Srobert   for (auto Input : Inputs)
74*12c85518Srobert     LinkArgs.push_back(Input.getFilename());
75*12c85518Srobert   LinkArgs.append({"-o", TempFile});
76*12c85518Srobert   const char *LlvmLink =
77*12c85518Srobert       Args.MakeArgString(getToolChain().GetProgramPath("llvm-link"));
78*12c85518Srobert   C.addCommand(std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),
79*12c85518Srobert                                          LlvmLink, LinkArgs, Inputs, Output));
80*12c85518Srobert 
81*12c85518Srobert   // Post-link HIP lowering.
82*12c85518Srobert 
83*12c85518Srobert   // Run LLVM IR passes to lower/expand/emulate HIP code that does not translate
84*12c85518Srobert   // to SPIR-V (E.g. dynamic shared memory).
85*12c85518Srobert   auto PassPluginPath = findPassPlugin(C.getDriver(), Args);
86*12c85518Srobert   if (!PassPluginPath.empty()) {
87*12c85518Srobert     const char *PassPathCStr = C.getArgs().MakeArgString(PassPluginPath);
88*12c85518Srobert     const char *OptOutput = getTempFile(C, Name + "-lower", "bc");
89*12c85518Srobert     ArgStringList OptArgs{TempFile,     "-load-pass-plugin",
90*12c85518Srobert                           PassPathCStr, "-passes=hip-post-link-passes",
91*12c85518Srobert                           "-o",         OptOutput};
92*12c85518Srobert     const char *Opt = Args.MakeArgString(getToolChain().GetProgramPath("opt"));
93*12c85518Srobert     C.addCommand(std::make_unique<Command>(
94*12c85518Srobert         JA, *this, ResponseFileSupport::None(), Opt, OptArgs, Inputs, Output));
95*12c85518Srobert     TempFile = OptOutput;
96*12c85518Srobert   }
97*12c85518Srobert 
98*12c85518Srobert   // Emit SPIR-V binary.
99*12c85518Srobert 
100*12c85518Srobert   llvm::opt::ArgStringList TrArgs{"--spirv-max-version=1.1",
101*12c85518Srobert                                   "--spirv-ext=+all"};
102*12c85518Srobert   InputInfo TrInput = InputInfo(types::TY_LLVM_BC, TempFile, "");
103*12c85518Srobert   SPIRV::constructTranslateCommand(C, *this, JA, Output, TrInput, TrArgs);
104*12c85518Srobert }
105*12c85518Srobert 
ConstructJob(Compilation & C,const JobAction & JA,const InputInfo & Output,const InputInfoList & Inputs,const ArgList & Args,const char * LinkingOutput) const106*12c85518Srobert void HIPSPV::Linker::ConstructJob(Compilation &C, const JobAction &JA,
107*12c85518Srobert                                   const InputInfo &Output,
108*12c85518Srobert                                   const InputInfoList &Inputs,
109*12c85518Srobert                                   const ArgList &Args,
110*12c85518Srobert                                   const char *LinkingOutput) const {
111*12c85518Srobert   if (Inputs.size() > 0 && Inputs[0].getType() == types::TY_Image &&
112*12c85518Srobert       JA.getType() == types::TY_Object)
113*12c85518Srobert     return HIP::constructGenerateObjFileFromHIPFatBinary(C, Output, Inputs,
114*12c85518Srobert                                                          Args, JA, *this);
115*12c85518Srobert 
116*12c85518Srobert   if (JA.getType() == types::TY_HIP_FATBIN)
117*12c85518Srobert     return HIP::constructHIPFatbinCommand(C, JA, Output.getFilename(), Inputs,
118*12c85518Srobert                                           Args, *this);
119*12c85518Srobert 
120*12c85518Srobert   constructLinkAndEmitSpirvCommand(C, JA, Inputs, Output, Args);
121*12c85518Srobert }
122*12c85518Srobert 
HIPSPVToolChain(const Driver & D,const llvm::Triple & Triple,const ToolChain & HostTC,const ArgList & Args)123*12c85518Srobert HIPSPVToolChain::HIPSPVToolChain(const Driver &D, const llvm::Triple &Triple,
124*12c85518Srobert                                  const ToolChain &HostTC, const ArgList &Args)
125*12c85518Srobert     : ToolChain(D, Triple, Args), HostTC(HostTC) {
126*12c85518Srobert   // Lookup binaries into the driver directory, this is used to
127*12c85518Srobert   // discover the clang-offload-bundler executable.
128*12c85518Srobert   getProgramPaths().push_back(getDriver().Dir);
129*12c85518Srobert }
130*12c85518Srobert 
addClangTargetOptions(const llvm::opt::ArgList & DriverArgs,llvm::opt::ArgStringList & CC1Args,Action::OffloadKind DeviceOffloadingKind) const131*12c85518Srobert void HIPSPVToolChain::addClangTargetOptions(
132*12c85518Srobert     const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
133*12c85518Srobert     Action::OffloadKind DeviceOffloadingKind) const {
134*12c85518Srobert   HostTC.addClangTargetOptions(DriverArgs, CC1Args, DeviceOffloadingKind);
135*12c85518Srobert 
136*12c85518Srobert   assert(DeviceOffloadingKind == Action::OFK_HIP &&
137*12c85518Srobert          "Only HIP offloading kinds are supported for GPUs.");
138*12c85518Srobert 
139*12c85518Srobert   CC1Args.append(
140*12c85518Srobert       {"-fcuda-is-device", "-fcuda-allow-variadic-functions",
141*12c85518Srobert        // A crude workaround for llvm-spirv which does not handle the
142*12c85518Srobert        // autovectorized code well (vector reductions, non-i{8,16,32,64} types).
143*12c85518Srobert        // TODO: Allow autovectorization when SPIR-V backend arrives.
144*12c85518Srobert        "-mllvm", "-vectorize-loops=false", "-mllvm", "-vectorize-slp=false"});
145*12c85518Srobert 
146*12c85518Srobert   if (DriverArgs.hasFlag(options::OPT_fcuda_approx_transcendentals,
147*12c85518Srobert                          options::OPT_fno_cuda_approx_transcendentals, false))
148*12c85518Srobert     CC1Args.push_back("-fcuda-approx-transcendentals");
149*12c85518Srobert 
150*12c85518Srobert   // Default to "hidden" visibility, as object level linking will not be
151*12c85518Srobert   // supported for the foreseeable future.
152*12c85518Srobert   if (!DriverArgs.hasArg(options::OPT_fvisibility_EQ,
153*12c85518Srobert                          options::OPT_fvisibility_ms_compat))
154*12c85518Srobert     CC1Args.append(
155*12c85518Srobert         {"-fvisibility=hidden", "-fapply-global-visibility-to-externs"});
156*12c85518Srobert 
157*12c85518Srobert   llvm::for_each(getDeviceLibs(DriverArgs),
158*12c85518Srobert                  [&](const BitCodeLibraryInfo &BCFile) {
159*12c85518Srobert                    CC1Args.append({"-mlink-builtin-bitcode",
160*12c85518Srobert                                    DriverArgs.MakeArgString(BCFile.Path)});
161*12c85518Srobert                  });
162*12c85518Srobert }
163*12c85518Srobert 
buildLinker() const164*12c85518Srobert Tool *HIPSPVToolChain::buildLinker() const {
165*12c85518Srobert   assert(getTriple().getArch() == llvm::Triple::spirv64);
166*12c85518Srobert   return new tools::HIPSPV::Linker(*this);
167*12c85518Srobert }
168*12c85518Srobert 
addClangWarningOptions(ArgStringList & CC1Args) const169*12c85518Srobert void HIPSPVToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {
170*12c85518Srobert   HostTC.addClangWarningOptions(CC1Args);
171*12c85518Srobert }
172*12c85518Srobert 
173*12c85518Srobert ToolChain::CXXStdlibType
GetCXXStdlibType(const ArgList & Args) const174*12c85518Srobert HIPSPVToolChain::GetCXXStdlibType(const ArgList &Args) const {
175*12c85518Srobert   return HostTC.GetCXXStdlibType(Args);
176*12c85518Srobert }
177*12c85518Srobert 
AddClangSystemIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const178*12c85518Srobert void HIPSPVToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
179*12c85518Srobert                                                 ArgStringList &CC1Args) const {
180*12c85518Srobert   HostTC.AddClangSystemIncludeArgs(DriverArgs, CC1Args);
181*12c85518Srobert }
182*12c85518Srobert 
AddClangCXXStdlibIncludeArgs(const ArgList & Args,ArgStringList & CC1Args) const183*12c85518Srobert void HIPSPVToolChain::AddClangCXXStdlibIncludeArgs(
184*12c85518Srobert     const ArgList &Args, ArgStringList &CC1Args) const {
185*12c85518Srobert   HostTC.AddClangCXXStdlibIncludeArgs(Args, CC1Args);
186*12c85518Srobert }
187*12c85518Srobert 
AddIAMCUIncludeArgs(const ArgList & Args,ArgStringList & CC1Args) const188*12c85518Srobert void HIPSPVToolChain::AddIAMCUIncludeArgs(const ArgList &Args,
189*12c85518Srobert                                           ArgStringList &CC1Args) const {
190*12c85518Srobert   HostTC.AddIAMCUIncludeArgs(Args, CC1Args);
191*12c85518Srobert }
192*12c85518Srobert 
AddHIPIncludeArgs(const ArgList & DriverArgs,ArgStringList & CC1Args) const193*12c85518Srobert void HIPSPVToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs,
194*12c85518Srobert                                         ArgStringList &CC1Args) const {
195*12c85518Srobert   if (DriverArgs.hasArg(options::OPT_nogpuinc))
196*12c85518Srobert     return;
197*12c85518Srobert 
198*12c85518Srobert   StringRef hipPath = DriverArgs.getLastArgValue(options::OPT_hip_path_EQ);
199*12c85518Srobert   if (hipPath.empty()) {
200*12c85518Srobert     getDriver().Diag(diag::err_drv_hipspv_no_hip_path) << 1 << "'-nogpuinc'";
201*12c85518Srobert     return;
202*12c85518Srobert   }
203*12c85518Srobert   SmallString<128> P(hipPath);
204*12c85518Srobert   llvm::sys::path::append(P, "include");
205*12c85518Srobert   CC1Args.append({"-isystem", DriverArgs.MakeArgString(P)});
206*12c85518Srobert }
207*12c85518Srobert 
208*12c85518Srobert llvm::SmallVector<ToolChain::BitCodeLibraryInfo, 12>
getDeviceLibs(const llvm::opt::ArgList & DriverArgs) const209*12c85518Srobert HIPSPVToolChain::getDeviceLibs(const llvm::opt::ArgList &DriverArgs) const {
210*12c85518Srobert   llvm::SmallVector<ToolChain::BitCodeLibraryInfo, 12> BCLibs;
211*12c85518Srobert   if (DriverArgs.hasArg(options::OPT_nogpulib))
212*12c85518Srobert     return {};
213*12c85518Srobert 
214*12c85518Srobert   ArgStringList LibraryPaths;
215*12c85518Srobert   // Find device libraries in --hip-device-lib-path and HIP_DEVICE_LIB_PATH.
216*12c85518Srobert   auto HipDeviceLibPathArgs = DriverArgs.getAllArgValues(
217*12c85518Srobert       // --hip-device-lib-path is alias to this option.
218*12c85518Srobert       clang::driver::options::OPT_rocm_device_lib_path_EQ);
219*12c85518Srobert   for (auto Path : HipDeviceLibPathArgs)
220*12c85518Srobert     LibraryPaths.push_back(DriverArgs.MakeArgString(Path));
221*12c85518Srobert 
222*12c85518Srobert   StringRef HipPath = DriverArgs.getLastArgValue(options::OPT_hip_path_EQ);
223*12c85518Srobert   if (!HipPath.empty()) {
224*12c85518Srobert     SmallString<128> Path(HipPath);
225*12c85518Srobert     llvm::sys::path::append(Path, "lib", "hip-device-lib");
226*12c85518Srobert     LibraryPaths.push_back(DriverArgs.MakeArgString(Path));
227*12c85518Srobert   }
228*12c85518Srobert 
229*12c85518Srobert   addDirectoryList(DriverArgs, LibraryPaths, "", "HIP_DEVICE_LIB_PATH");
230*12c85518Srobert 
231*12c85518Srobert   // Maintain compatability with --hip-device-lib.
232*12c85518Srobert   auto BCLibArgs = DriverArgs.getAllArgValues(options::OPT_hip_device_lib_EQ);
233*12c85518Srobert   if (!BCLibArgs.empty()) {
234*12c85518Srobert     llvm::for_each(BCLibArgs, [&](StringRef BCName) {
235*12c85518Srobert       StringRef FullName;
236*12c85518Srobert       for (std::string LibraryPath : LibraryPaths) {
237*12c85518Srobert         SmallString<128> Path(LibraryPath);
238*12c85518Srobert         llvm::sys::path::append(Path, BCName);
239*12c85518Srobert         FullName = Path;
240*12c85518Srobert         if (llvm::sys::fs::exists(FullName)) {
241*12c85518Srobert           BCLibs.emplace_back(FullName.str());
242*12c85518Srobert           return;
243*12c85518Srobert         }
244*12c85518Srobert       }
245*12c85518Srobert       getDriver().Diag(diag::err_drv_no_such_file) << BCName;
246*12c85518Srobert     });
247*12c85518Srobert   } else {
248*12c85518Srobert     // Search device library named as 'hipspv-<triple>.bc'.
249*12c85518Srobert     auto TT = getTriple().normalize();
250*12c85518Srobert     std::string BCName = "hipspv-" + TT + ".bc";
251*12c85518Srobert     for (auto *LibPath : LibraryPaths) {
252*12c85518Srobert       SmallString<128> Path(LibPath);
253*12c85518Srobert       llvm::sys::path::append(Path, BCName);
254*12c85518Srobert       if (llvm::sys::fs::exists(Path)) {
255*12c85518Srobert         BCLibs.emplace_back(Path.str().str());
256*12c85518Srobert         return BCLibs;
257*12c85518Srobert       }
258*12c85518Srobert     }
259*12c85518Srobert     getDriver().Diag(diag::err_drv_no_hipspv_device_lib)
260*12c85518Srobert         << 1 << ("'" + TT + "' target");
261*12c85518Srobert     return {};
262*12c85518Srobert   }
263*12c85518Srobert 
264*12c85518Srobert   return BCLibs;
265*12c85518Srobert }
266*12c85518Srobert 
getSupportedSanitizers() const267*12c85518Srobert SanitizerMask HIPSPVToolChain::getSupportedSanitizers() const {
268*12c85518Srobert   // The HIPSPVToolChain only supports sanitizers in the sense that it allows
269*12c85518Srobert   // sanitizer arguments on the command line if they are supported by the host
270*12c85518Srobert   // toolchain. The HIPSPVToolChain will actually ignore any command line
271*12c85518Srobert   // arguments for any of these "supported" sanitizers. That means that no
272*12c85518Srobert   // sanitization of device code is actually supported at this time.
273*12c85518Srobert   //
274*12c85518Srobert   // This behavior is necessary because the host and device toolchains
275*12c85518Srobert   // invocations often share the command line, so the device toolchain must
276*12c85518Srobert   // tolerate flags meant only for the host toolchain.
277*12c85518Srobert   return HostTC.getSupportedSanitizers();
278*12c85518Srobert }
279*12c85518Srobert 
computeMSVCVersion(const Driver * D,const ArgList & Args) const280*12c85518Srobert VersionTuple HIPSPVToolChain::computeMSVCVersion(const Driver *D,
281*12c85518Srobert                                                  const ArgList &Args) const {
282*12c85518Srobert   return HostTC.computeMSVCVersion(D, Args);
283*12c85518Srobert }
284*12c85518Srobert 
adjustDebugInfoKind(codegenoptions::DebugInfoKind & DebugInfoKind,const llvm::opt::ArgList & Args) const285*12c85518Srobert void HIPSPVToolChain::adjustDebugInfoKind(
286*12c85518Srobert     codegenoptions::DebugInfoKind &DebugInfoKind,
287*12c85518Srobert     const llvm::opt::ArgList &Args) const {
288*12c85518Srobert   // Debug info generation is disabled for SPIRV-LLVM-Translator
289*12c85518Srobert   // which currently aborts on the presence of DW_OP_LLVM_convert.
290*12c85518Srobert   // TODO: Enable debug info when the SPIR-V backend arrives.
291*12c85518Srobert   DebugInfoKind = codegenoptions::NoDebugInfo;
292*12c85518Srobert }
293