clang 22.0.0git
HIPSPV.cpp
Go to the documentation of this file.
1//===--- HIPSPV.cpp - HIPSPV ToolChain Implementation -----------*- 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 "HIPSPV.h"
10#include "HIPUtility.h"
13#include "clang/Driver/Driver.h"
16#include "llvm/Support/FileSystem.h"
17#include "llvm/Support/Path.h"
18
19using namespace clang::driver;
20using namespace clang::driver::toolchains;
21using namespace clang::driver::tools;
22using namespace clang;
23using namespace llvm::opt;
24
25// Convenience function for creating temporary file for both modes of
26// isSaveTempsEnabled().
27static const char *getTempFile(Compilation &C, StringRef Prefix,
28 StringRef Extension) {
29 if (C.getDriver().isSaveTempsEnabled()) {
30 return C.getArgs().MakeArgString(Prefix + "." + Extension);
31 }
32 auto TmpFile = C.getDriver().GetTemporaryPath(Prefix, Extension);
33 return C.addTempFile(C.getArgs().MakeArgString(TmpFile));
34}
35
36// Locates HIP pass plugin.
37static std::string findPassPlugin(const Driver &D,
38 const llvm::opt::ArgList &Args) {
39 StringRef Path = Args.getLastArgValue(options::OPT_hipspv_pass_plugin_EQ);
40 if (!Path.empty()) {
41 if (llvm::sys::fs::exists(Path))
42 return Path.str();
43 D.Diag(diag::err_drv_no_such_file) << Path;
44 }
45
46 StringRef hipPath = Args.getLastArgValue(options::OPT_hip_path_EQ);
47 if (!hipPath.empty()) {
48 SmallString<128> PluginPath(hipPath);
49 llvm::sys::path::append(PluginPath, "lib", "libLLVMHipSpvPasses.so");
50 if (llvm::sys::fs::exists(PluginPath))
51 return PluginPath.str().str();
52 PluginPath.assign(hipPath);
53 llvm::sys::path::append(PluginPath, "lib", "llvm",
54 "libLLVMHipSpvPasses.so");
55 if (llvm::sys::fs::exists(PluginPath))
56 return PluginPath.str().str();
57 }
58
59 return std::string();
60}
61
62void HIPSPV::Linker::constructLinkAndEmitSpirvCommand(
63 Compilation &C, const JobAction &JA, const InputInfoList &Inputs,
64 const InputInfo &Output, const llvm::opt::ArgList &Args) const {
65
66 assert(!Inputs.empty() && "Must have at least one input.");
67 std::string Name = std::string(llvm::sys::path::stem(Output.getFilename()));
68 const char *TempFile = getTempFile(C, Name + "-link", "bc");
69
70 // Link LLVM bitcode.
71 ArgStringList LinkArgs{};
72
73 for (auto Input : Inputs)
74 LinkArgs.push_back(Input.getFilename());
75
76 // Add static device libraries using the common helper function.
77 // This handles unbundling archives (.a) containing bitcode bundles.
78 StringRef Arch = getToolChain().getTriple().getArchName();
79 StringRef Target =
80 "generic"; // SPIR-V is generic, no specific target ID like -mcpu
81 tools::AddStaticDeviceLibsLinking(C, *this, JA, Inputs, Args, LinkArgs, Arch,
82 Target, /*IsBitCodeSDL=*/true);
83 LinkArgs.append({"-o", TempFile});
84 const char *LlvmLink =
85 Args.MakeArgString(getToolChain().GetProgramPath("llvm-link"));
86 C.addCommand(std::make_unique<Command>(JA, *this, ResponseFileSupport::None(),
87 LlvmLink, LinkArgs, Inputs, Output));
88
89 // Post-link HIP lowering.
90
91 // Run LLVM IR passes to lower/expand/emulate HIP code that does not translate
92 // to SPIR-V (E.g. dynamic shared memory).
93 auto PassPluginPath = findPassPlugin(C.getDriver(), Args);
94 if (!PassPluginPath.empty()) {
95 const char *PassPathCStr = C.getArgs().MakeArgString(PassPluginPath);
96 const char *OptOutput = getTempFile(C, Name + "-lower", "bc");
97 ArgStringList OptArgs{TempFile, "-load-pass-plugin",
98 PassPathCStr, "-passes=hip-post-link-passes",
99 "-o", OptOutput};
100 const char *Opt = Args.MakeArgString(getToolChain().GetProgramPath("opt"));
101 C.addCommand(std::make_unique<Command>(
102 JA, *this, ResponseFileSupport::None(), Opt, OptArgs, Inputs, Output));
103 TempFile = OptOutput;
104 }
105
106 // Emit SPIR-V binary.
107
108 llvm::opt::ArgStringList TrArgs{"--spirv-max-version=1.1",
109 "--spirv-ext=+all"};
110 InputInfo TrInput = InputInfo(types::TY_LLVM_BC, TempFile, "");
111 SPIRV::constructTranslateCommand(C, *this, JA, Output, TrInput, TrArgs);
112}
113
115 const InputInfo &Output,
116 const InputInfoList &Inputs,
117 const ArgList &Args,
118 const char *LinkingOutput) const {
119 if (Inputs.size() > 0 && Inputs[0].getType() == types::TY_Image &&
120 JA.getType() == types::TY_Object)
122 Args, JA, *this);
123
124 if (JA.getType() == types::TY_HIP_FATBIN)
125 return HIP::constructHIPFatbinCommand(C, JA, Output.getFilename(), Inputs,
126 Args, *this);
127
128 constructLinkAndEmitSpirvCommand(C, JA, Inputs, Output, Args);
129}
130
131HIPSPVToolChain::HIPSPVToolChain(const Driver &D, const llvm::Triple &Triple,
132 const ToolChain &HostTC, const ArgList &Args)
133 : ToolChain(D, Triple, Args), HostTC(HostTC) {
134 // Lookup binaries into the driver directory, this is used to
135 // discover the clang-offload-bundler executable.
136 getProgramPaths().push_back(getDriver().Dir);
137}
138
140 const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args,
141 Action::OffloadKind DeviceOffloadingKind) const {
142 HostTC.addClangTargetOptions(DriverArgs, CC1Args, DeviceOffloadingKind);
143
144 assert(DeviceOffloadingKind == Action::OFK_HIP &&
145 "Only HIP offloading kinds are supported for GPUs.");
146
147 CC1Args.append(
148 {"-fcuda-is-device", "-fcuda-allow-variadic-functions",
149 // A crude workaround for llvm-spirv which does not handle the
150 // autovectorized code well (vector reductions, non-i{8,16,32,64} types).
151 // TODO: Allow autovectorization when SPIR-V backend arrives.
152 "-mllvm", "-vectorize-loops=false", "-mllvm", "-vectorize-slp=false"});
153
154 // Default to "hidden" visibility, as object level linking will not be
155 // supported for the foreseeable future.
156 if (!DriverArgs.hasArg(options::OPT_fvisibility_EQ,
157 options::OPT_fvisibility_ms_compat))
158 CC1Args.append(
159 {"-fvisibility=hidden", "-fapply-global-visibility-to-externs"});
160
161 for (const BitCodeLibraryInfo &BCFile :
162 getDeviceLibs(DriverArgs, DeviceOffloadingKind))
163 CC1Args.append(
164 {"-mlink-builtin-bitcode", DriverArgs.MakeArgString(BCFile.Path)});
165}
166
168 assert(getTriple().getArch() == llvm::Triple::spirv64);
169 return new tools::HIPSPV::Linker(*this);
170}
171
172void HIPSPVToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {
173 HostTC.addClangWarningOptions(CC1Args);
174}
175
177HIPSPVToolChain::GetCXXStdlibType(const ArgList &Args) const {
178 return HostTC.GetCXXStdlibType(Args);
179}
180
181void HIPSPVToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
182 ArgStringList &CC1Args) const {
183 HostTC.AddClangSystemIncludeArgs(DriverArgs, CC1Args);
184}
185
187 const ArgList &Args, ArgStringList &CC1Args) const {
188 HostTC.AddClangCXXStdlibIncludeArgs(Args, CC1Args);
189}
190
192 ArgStringList &CC1Args) const {
193 HostTC.AddIAMCUIncludeArgs(Args, CC1Args);
194}
195
196void HIPSPVToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs,
197 ArgStringList &CC1Args) const {
198 if (!DriverArgs.hasFlag(options::OPT_offload_inc, options::OPT_no_offload_inc,
199 true))
200 return;
201
202 StringRef hipPath = DriverArgs.getLastArgValue(options::OPT_hip_path_EQ);
203 if (hipPath.empty()) {
204 getDriver().Diag(diag::err_drv_hipspv_no_hip_path);
205 return;
206 }
207 SmallString<128> P(hipPath);
208 llvm::sys::path::append(P, "include");
209 CC1Args.append({"-isystem", DriverArgs.MakeArgString(P)});
210}
211
214 const llvm::opt::ArgList &DriverArgs,
215 const Action::OffloadKind DeviceOffloadingKind) const {
217 if (!DriverArgs.hasFlag(options::OPT_offloadlib, options::OPT_no_offloadlib,
218 true))
219 return {};
220
221 ArgStringList LibraryPaths;
222 // Find device libraries in --hip-device-lib-path and HIP_DEVICE_LIB_PATH.
223 auto HipDeviceLibPathArgs = DriverArgs.getAllArgValues(
224 // --hip-device-lib-path is alias to this option.
225 clang::driver::options::OPT_rocm_device_lib_path_EQ);
226 for (auto Path : HipDeviceLibPathArgs)
227 LibraryPaths.push_back(DriverArgs.MakeArgString(Path));
228
229 StringRef HipPath = DriverArgs.getLastArgValue(options::OPT_hip_path_EQ);
230 if (!HipPath.empty()) {
231 SmallString<128> Path(HipPath);
232 llvm::sys::path::append(Path, "lib", "hip-device-lib");
233 LibraryPaths.push_back(DriverArgs.MakeArgString(Path));
234 }
235
236 addDirectoryList(DriverArgs, LibraryPaths, "", "HIP_DEVICE_LIB_PATH");
237
238 // Maintain compatability with --hip-device-lib.
239 auto BCLibArgs = DriverArgs.getAllArgValues(options::OPT_hip_device_lib_EQ);
240 if (!BCLibArgs.empty()) {
241 bool Found = false;
242 for (StringRef BCName : BCLibArgs) {
243 StringRef FullName;
244 for (std::string LibraryPath : LibraryPaths) {
245 SmallString<128> Path(LibraryPath);
246 llvm::sys::path::append(Path, BCName);
247 FullName = Path;
248 if (llvm::sys::fs::exists(FullName)) {
249 BCLibs.emplace_back(FullName.str());
250 Found = true;
251 break;
252 }
253 }
254 if (!Found)
255 getDriver().Diag(diag::err_drv_no_such_file) << BCName;
256 }
257 } else {
258 // Search device library named as 'hipspv-<triple>.bc'.
259 auto TT = getTriple().normalize();
260 std::string BCName = "hipspv-" + TT + ".bc";
261 for (auto *LibPath : LibraryPaths) {
262 SmallString<128> Path(LibPath);
263 llvm::sys::path::append(Path, BCName);
264 if (llvm::sys::fs::exists(Path)) {
265 BCLibs.emplace_back(Path.str().str());
266 return BCLibs;
267 }
268 }
269 getDriver().Diag(diag::err_drv_no_hipspv_device_lib)
270 << 1 << ("'" + TT + "' target");
271 return {};
272 }
273
274 return BCLibs;
275}
276
278 // The HIPSPVToolChain only supports sanitizers in the sense that it allows
279 // sanitizer arguments on the command line if they are supported by the host
280 // toolchain. The HIPSPVToolChain will actually ignore any command line
281 // arguments for any of these "supported" sanitizers. That means that no
282 // sanitization of device code is actually supported at this time.
283 //
284 // This behavior is necessary because the host and device toolchains
285 // invocations often share the command line, so the device toolchain must
286 // tolerate flags meant only for the host toolchain.
287 return HostTC.getSupportedSanitizers();
288}
289
291 const ArgList &Args) const {
292 return HostTC.computeMSVCVersion(D, Args);
293}
294
296 llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
297 const llvm::opt::ArgList &Args) const {
298 // Debug info generation is disabled for SPIRV-LLVM-Translator
299 // which currently aborts on the presence of DW_OP_LLVM_convert.
300 // TODO: Enable debug info when the SPIR-V backend arrives.
301 DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
302}
static std::string findPassPlugin(const Driver &D, const llvm::opt::ArgList &Args)
Definition HIPSPV.cpp:37
static const char * getTempFile(Compilation &C, StringRef Prefix, StringRef Extension)
Definition HIPSPV.cpp:27
types::ID getType() const
Definition Action.h:150
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
DiagnosticBuilder Diag(unsigned DiagID) const
Definition Driver.h:169
InputInfo - Wrapper for information about an input source.
Definition InputInfo.h:22
const char * getFilename() const
Definition InputInfo.h:83
llvm::Triple::ArchType getArch() const
Definition ToolChain.h:269
const Driver & getDriver() const
Definition ToolChain.h:253
ToolChain(const Driver &D, const llvm::Triple &T, const llvm::opt::ArgList &Args)
Definition ToolChain.cpp:89
path_list & getProgramPaths()
Definition ToolChain.h:298
const llvm::Triple & getTriple() const
Definition ToolChain.h:255
Tool - Information on a specific compilation tool.
Definition Tool.h:32
const ToolChain & getToolChain() const
Definition Tool.h:52
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 HIPSPV.cpp:139
void AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add the clang cc1 arguments for system include paths.
Definition HIPSPV.cpp:181
void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const override
Add warning options that need to be passed to cc1 for this target.
Definition HIPSPV.cpp:172
Tool * buildLinker() const override
Definition HIPSPV.cpp:167
llvm::SmallVector< BitCodeLibraryInfo, 12 > getDeviceLibs(const llvm::opt::ArgList &Args, const Action::OffloadKind DeviceOffloadKind) const override
Get paths for device libraries.
Definition HIPSPV.cpp:213
HIPSPVToolChain(const Driver &D, const llvm::Triple &Triple, const ToolChain &HostTC, const llvm::opt::ArgList &Args)
Definition HIPSPV.cpp:131
void AddHIPIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add arguments to use system-specific HIP includes.
Definition HIPSPV.cpp:196
CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const override
Definition HIPSPV.cpp:177
void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CC1Args) const override
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
Definition HIPSPV.cpp:186
VersionTuple computeMSVCVersion(const Driver *D, const llvm::opt::ArgList &Args) const override
On Windows, returns the MSVC compatibility version.
Definition HIPSPV.cpp:290
void AddIAMCUIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const override
Add arguments to use MCU GCC toolchain includes.
Definition HIPSPV.cpp:191
void adjustDebugInfoKind(llvm::codegenoptions::DebugInfoKind &DebugInfoKind, const llvm::opt::ArgList &Args) const override
Adjust debug information kind considering all passed options.
Definition HIPSPV.cpp:295
SanitizerMask getSupportedSanitizers() const override
Return sanitizers which are available in this toolchain.
Definition HIPSPV.cpp:277
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 HIPSPV.cpp:114
void constructHIPFatbinCommand(Compilation &C, const JobAction &JA, StringRef OutputFileName, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const Tool &T)
void constructGenerateObjFileFromHIPFatBinary(Compilation &C, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &Args, const JobAction &JA, const Tool &T)
void constructTranslateCommand(Compilation &C, const Tool &T, const JobAction &JA, const InputInfo &Output, const InputInfo &Input, const llvm::opt::ArgStringList &Args)
Definition SPIRV.cpp:20
void AddStaticDeviceLibsLinking(Compilation &C, const Tool &T, const JobAction &JA, const InputInfoList &Inputs, const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CmdArgs, StringRef Arch, StringRef Target, bool isBitCodeSDL)
void addDirectoryList(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const char *ArgName, const char *EnvVar)
EnvVar is split by system delimiter for environment variables.
SmallVector< InputInfo, 4 > InputInfoList
Definition Driver.h:50
The JSON file list parser is used to communicate input to InstallAPI.
static constexpr ResponseFileSupport None()
Returns a ResponseFileSupport indicating that response files are not supported.
Definition Job.h:78