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