clang 20.0.0git
HIPUtility.cpp
Go to the documentation of this file.
1//===--- HIPUtility.cpp - Common HIP Tool Chain Utilities -------*- 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 "HIPUtility.h"
10#include "Clang.h"
11#include "CommonArgs.h"
14#include "llvm/ADT/StringExtras.h"
15#include "llvm/ADT/StringRef.h"
16#include "llvm/Object/Archive.h"
17#include "llvm/Object/ObjectFile.h"
18#include "llvm/Support/MD5.h"
19#include "llvm/Support/MemoryBuffer.h"
20#include "llvm/Support/Path.h"
21#include "llvm/Support/raw_ostream.h"
22#include "llvm/TargetParser/Triple.h"
23#include <deque>
24#include <set>
25
26using namespace clang;
27using namespace clang::driver;
28using namespace clang::driver::tools;
29using namespace llvm::opt;
30using llvm::dyn_cast;
31
32#if defined(_WIN32) || defined(_WIN64)
33#define NULL_FILE "nul"
34#else
35#define NULL_FILE "/dev/null"
36#endif
37
38namespace {
39const unsigned HIPCodeObjectAlign = 4096;
40} // namespace
41
42// Constructs a triple string for clang offload bundler.
43static std::string normalizeForBundler(const llvm::Triple &T,
44 bool HasTargetID) {
45 return HasTargetID ? (T.getArchName() + "-" + T.getVendorName() + "-" +
46 T.getOSName() + "-" + T.getEnvironmentName())
47 .str()
48 : T.normalize();
49}
50
51// Collect undefined __hip_fatbin* and __hip_gpubin_handle* symbols from all
52// input object or archive files.
54public:
56 const llvm::opt::ArgList &Args_)
57 : C(C), Args(Args_),
58 DiagID(C.getDriver().getDiags().getCustomDiagID(
59 DiagnosticsEngine::Error,
60 "Error collecting HIP undefined fatbin symbols: %0")),
61 Quiet(C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)),
62 Verbose(C.getArgs().hasArg(options::OPT_v)) {
63 populateSymbols();
65 if (Verbose) {
66 for (const auto &Name : FatBinSymbols)
67 llvm::errs() << "Found undefined HIP fatbin symbol: " << Name << "\n";
68 for (const auto &Name : GPUBinHandleSymbols)
69 llvm::errs() << "Found undefined HIP gpubin handle symbol: " << Name
70 << "\n";
71 }
72 }
73
74 const std::set<std::string> &getFatBinSymbols() const {
75 return FatBinSymbols;
76 }
77
78 const std::set<std::string> &getGPUBinHandleSymbols() const {
79 return GPUBinHandleSymbols;
80 }
81
82 // Collect symbols from static libraries specified by -l options.
87 llvm::Triple Triple(C.getDriver().getTargetTriple());
88 bool IsMSVC = Triple.isWindowsMSVCEnvironment();
89 llvm::StringRef Ext = IsMSVC ? ".lib" : ".a";
90
91 for (const auto *Arg : Args.filtered(options::OPT_l)) {
92 llvm::StringRef Value = Arg->getValue();
93 if (Value.starts_with(":"))
94 ExactLibNames.push_back(Value.drop_front());
95 else
96 LibNames.push_back(Value);
97 }
98 for (const auto *Arg : Args.filtered(options::OPT_L)) {
99 auto Path = Arg->getValue();
100 LibPaths.push_back(Path);
101 if (Verbose)
102 llvm::errs() << "HIP fatbin symbol search uses library path: " << Path
103 << "\n";
104 }
105
106 auto ProcessLib = [&](llvm::StringRef LibName, bool IsExact) {
107 llvm::SmallString<256> FullLibName(
108 IsExact ? Twine(LibName).str()
109 : IsMSVC ? (Twine(LibName) + Ext).str()
110 : (Twine("lib") + LibName + Ext).str());
111
112 bool Found = false;
113 for (const auto Path : LibPaths) {
114 llvm::SmallString<256> FullPath = Path;
115 llvm::sys::path::append(FullPath, FullLibName);
116
117 if (llvm::sys::fs::exists(FullPath)) {
118 if (Verbose)
119 llvm::errs() << "HIP fatbin symbol search found library: "
120 << FullPath << "\n";
121 auto BufferOrErr = llvm::MemoryBuffer::getFile(FullPath);
122 if (!BufferOrErr) {
123 errorHandler(llvm::errorCodeToError(BufferOrErr.getError()));
124 continue;
125 }
126 processInput(BufferOrErr.get()->getMemBufferRef());
127 Found = true;
128 break;
129 }
130 }
131 if (!Found && Verbose)
132 llvm::errs() << "HIP fatbin symbol search could not find library: "
133 << FullLibName << "\n";
134 };
135
136 for (const auto LibName : ExactLibNames)
137 ProcessLib(LibName, true);
138
139 for (const auto LibName : LibNames)
140 ProcessLib(LibName, false);
141 }
142
143private:
144 const Compilation &C;
145 const llvm::opt::ArgList &Args;
146 unsigned DiagID;
147 bool Quiet;
148 bool Verbose;
149 std::set<std::string> FatBinSymbols;
150 std::set<std::string> GPUBinHandleSymbols;
151 std::set<std::string> DefinedFatBinSymbols;
152 std::set<std::string> DefinedGPUBinHandleSymbols;
153 const std::string FatBinPrefix = "__hip_fatbin";
154 const std::string GPUBinHandlePrefix = "__hip_gpubin_handle";
155
156 void populateSymbols() {
157 std::deque<const Action *> WorkList;
158 std::set<const Action *> Visited;
159
160 for (const auto &Action : C.getActions())
161 WorkList.push_back(Action);
162
163 while (!WorkList.empty()) {
164 const Action *CurrentAction = WorkList.front();
165 WorkList.pop_front();
166
167 if (!CurrentAction || !Visited.insert(CurrentAction).second)
168 continue;
169
170 if (const auto *IA = dyn_cast<InputAction>(CurrentAction)) {
171 std::string ID = IA->getId().str();
172 if (!ID.empty()) {
173 ID = llvm::utohexstr(llvm::MD5Hash(ID), /*LowerCase=*/true);
174 FatBinSymbols.insert((FatBinPrefix + Twine('_') + ID).str());
175 GPUBinHandleSymbols.insert(
176 (GPUBinHandlePrefix + Twine('_') + ID).str());
177 continue;
178 }
179 if (IA->getInputArg().getNumValues() == 0)
180 continue;
181 const char *Filename = IA->getInputArg().getValue();
182 if (!Filename)
183 continue;
184 auto BufferOrErr = llvm::MemoryBuffer::getFile(Filename);
185 // Input action could be options to linker, therefore, ignore it
186 // if cannot read it. If it turns out to be a file that cannot be read,
187 // the error will be caught by the linker.
188 if (!BufferOrErr)
189 continue;
190
191 processInput(BufferOrErr.get()->getMemBufferRef());
192 } else
193 WorkList.insert(WorkList.end(), CurrentAction->getInputs().begin(),
194 CurrentAction->getInputs().end());
195 }
196 }
197
198 void processInput(const llvm::MemoryBufferRef &Buffer) {
199 // Try processing as object file first.
200 auto ObjFileOrErr = llvm::object::ObjectFile::createObjectFile(Buffer);
201 if (ObjFileOrErr) {
202 processSymbols(**ObjFileOrErr);
203 return;
204 }
205
206 // Then try processing as archive files.
207 llvm::consumeError(ObjFileOrErr.takeError());
208 auto ArchiveOrErr = llvm::object::Archive::create(Buffer);
209 if (ArchiveOrErr) {
210 llvm::Error Err = llvm::Error::success();
211 llvm::object::Archive &Archive = *ArchiveOrErr.get();
212 for (auto &Child : Archive.children(Err)) {
213 auto ChildBufOrErr = Child.getMemoryBufferRef();
214 if (ChildBufOrErr)
215 processInput(*ChildBufOrErr);
216 else
217 errorHandler(ChildBufOrErr.takeError());
218 }
219
220 if (Err)
221 errorHandler(std::move(Err));
222 return;
223 }
224
225 // Ignore other files.
226 llvm::consumeError(ArchiveOrErr.takeError());
227 }
228
229 void processSymbols(const llvm::object::ObjectFile &Obj) {
230 for (const auto &Symbol : Obj.symbols()) {
231 auto FlagOrErr = Symbol.getFlags();
232 if (!FlagOrErr) {
233 errorHandler(FlagOrErr.takeError());
234 continue;
235 }
236
237 auto NameOrErr = Symbol.getName();
238 if (!NameOrErr) {
239 errorHandler(NameOrErr.takeError());
240 continue;
241 }
242 llvm::StringRef Name = *NameOrErr;
243
244 bool isUndefined =
245 FlagOrErr.get() & llvm::object::SymbolRef::SF_Undefined;
246 bool isFatBinSymbol = Name.starts_with(FatBinPrefix);
247 bool isGPUBinHandleSymbol = Name.starts_with(GPUBinHandlePrefix);
248
249 // Handling for defined symbols
250 if (!isUndefined) {
251 if (isFatBinSymbol) {
252 DefinedFatBinSymbols.insert(Name.str());
253 FatBinSymbols.erase(Name.str());
254 } else if (isGPUBinHandleSymbol) {
255 DefinedGPUBinHandleSymbols.insert(Name.str());
256 GPUBinHandleSymbols.erase(Name.str());
257 }
258 continue;
259 }
260
261 // Add undefined symbols if they are not in the defined sets
262 if (isFatBinSymbol &&
263 DefinedFatBinSymbols.find(Name.str()) == DefinedFatBinSymbols.end())
264 FatBinSymbols.insert(Name.str());
265 else if (isGPUBinHandleSymbol &&
266 DefinedGPUBinHandleSymbols.find(Name.str()) ==
267 DefinedGPUBinHandleSymbols.end())
268 GPUBinHandleSymbols.insert(Name.str());
269 }
270 }
271
272 void errorHandler(llvm::Error Err) {
273 if (Quiet)
274 return;
275 C.getDriver().Diag(DiagID) << llvm::toString(std::move(Err));
276 }
277};
278
279// Construct a clang-offload-bundler command to bundle code objects for
280// different devices into a HIP fat binary.
282 llvm::StringRef OutputFileName,
283 const InputInfoList &Inputs,
284 const llvm::opt::ArgList &Args,
285 const Tool &T) {
286 // Construct clang-offload-bundler command to bundle object files for
287 // for different GPU archs.
288 ArgStringList BundlerArgs;
289 BundlerArgs.push_back(Args.MakeArgString("-type=o"));
290 BundlerArgs.push_back(
291 Args.MakeArgString("-bundle-align=" + Twine(HIPCodeObjectAlign)));
292
293 // ToDo: Remove the dummy host binary entry which is required by
294 // clang-offload-bundler.
295 std::string BundlerTargetArg = "-targets=host-x86_64-unknown-linux";
296 // AMDGCN:
297 // For code object version 2 and 3, the offload kind in bundle ID is 'hip'
298 // for backward compatibility. For code object version 4 and greater, the
299 // offload kind in bundle ID is 'hipv4'.
300 std::string OffloadKind = "hip";
301 auto &TT = T.getToolChain().getTriple();
302 if (TT.isAMDGCN() && getAMDGPUCodeObjectVersion(C.getDriver(), Args) >= 4)
303 OffloadKind = OffloadKind + "v4";
304 for (const auto &II : Inputs) {
305 const auto *A = II.getAction();
306 auto ArchStr = llvm::StringRef(A->getOffloadingArch());
307 BundlerTargetArg +=
308 "," + OffloadKind + "-" + normalizeForBundler(TT, !ArchStr.empty());
309 if (!ArchStr.empty())
310 BundlerTargetArg += "-" + ArchStr.str();
311 }
312 BundlerArgs.push_back(Args.MakeArgString(BundlerTargetArg));
313
314 // Use a NULL file as input for the dummy host binary entry
315 std::string BundlerInputArg = "-input=" NULL_FILE;
316 BundlerArgs.push_back(Args.MakeArgString(BundlerInputArg));
317 for (const auto &II : Inputs) {
318 BundlerInputArg = std::string("-input=") + II.getFilename();
319 BundlerArgs.push_back(Args.MakeArgString(BundlerInputArg));
320 }
321
322 std::string Output = std::string(OutputFileName);
323 auto *BundlerOutputArg =
324 Args.MakeArgString(std::string("-output=").append(Output));
325 BundlerArgs.push_back(BundlerOutputArg);
326
327 addOffloadCompressArgs(Args, BundlerArgs);
328
329 const char *Bundler = Args.MakeArgString(
330 T.getToolChain().GetProgramPath("clang-offload-bundler"));
331 C.addCommand(std::make_unique<Command>(
332 JA, T, ResponseFileSupport::None(), Bundler, BundlerArgs, Inputs,
333 InputInfo(&JA, Args.MakeArgString(Output))));
334}
335
336/// Add Generated HIP Object File which has device images embedded into the
337/// host to the argument list for linking. Using MC directives, embed the
338/// device code and also define symbols required by the code generation so that
339/// the image can be retrieved at runtime.
341 Compilation &C, const InputInfo &Output, const InputInfoList &Inputs,
342 const ArgList &Args, const JobAction &JA, const Tool &T) {
343 const ToolChain &TC = T.getToolChain();
344 std::string Name = std::string(llvm::sys::path::stem(Output.getFilename()));
345
346 // Create Temp Object File Generator,
347 // Offload Bundled file and Bundled Object file.
348 // Keep them if save-temps is enabled.
349 const char *McinFile;
350 const char *BundleFile;
351 if (C.getDriver().isSaveTempsEnabled()) {
352 McinFile = C.getArgs().MakeArgString(Name + ".mcin");
353 BundleFile = C.getArgs().MakeArgString(Name + ".hipfb");
354 } else {
355 auto TmpNameMcin = C.getDriver().GetTemporaryPath(Name, "mcin");
356 McinFile = C.addTempFile(C.getArgs().MakeArgString(TmpNameMcin));
357 auto TmpNameFb = C.getDriver().GetTemporaryPath(Name, "hipfb");
358 BundleFile = C.addTempFile(C.getArgs().MakeArgString(TmpNameFb));
359 }
360 HIP::constructHIPFatbinCommand(C, JA, BundleFile, Inputs, Args, T);
361
362 // Create a buffer to write the contents of the temp obj generator.
363 std::string ObjBuffer;
364 llvm::raw_string_ostream ObjStream(ObjBuffer);
365
366 auto HostTriple =
367 C.getSingleOffloadToolChain<Action::OFK_Host>()->getTriple();
368
369 HIPUndefinedFatBinSymbols Symbols(C, Args);
370
371 std::string PrimaryHipFatbinSymbol;
372 std::string PrimaryGpuBinHandleSymbol;
373 bool FoundPrimaryHipFatbinSymbol = false;
374 bool FoundPrimaryGpuBinHandleSymbol = false;
375
376 std::vector<std::string> AliasHipFatbinSymbols;
377 std::vector<std::string> AliasGpuBinHandleSymbols;
378
379 // Iterate through symbols to find the primary ones and collect others for
380 // aliasing
381 for (const auto &Symbol : Symbols.getFatBinSymbols()) {
382 if (!FoundPrimaryHipFatbinSymbol) {
383 PrimaryHipFatbinSymbol = Symbol;
384 FoundPrimaryHipFatbinSymbol = true;
385 } else
386 AliasHipFatbinSymbols.push_back(Symbol);
387 }
388
389 for (const auto &Symbol : Symbols.getGPUBinHandleSymbols()) {
390 if (!FoundPrimaryGpuBinHandleSymbol) {
391 PrimaryGpuBinHandleSymbol = Symbol;
392 FoundPrimaryGpuBinHandleSymbol = true;
393 } else
394 AliasGpuBinHandleSymbols.push_back(Symbol);
395 }
396
397 // Add MC directives to embed target binaries. We ensure that each
398 // section and image is 16-byte aligned. This is not mandatory, but
399 // increases the likelihood of data to be aligned with a cache block
400 // in several main host machines.
401 ObjStream << "# HIP Object Generator\n";
402 ObjStream << "# *** Automatically generated by Clang ***\n";
403 if (FoundPrimaryGpuBinHandleSymbol) {
404 // Define the first gpubin handle symbol
405 if (HostTriple.isWindowsMSVCEnvironment())
406 ObjStream << " .section .hip_gpubin_handle,\"dw\"\n";
407 else {
408 ObjStream << " .protected " << PrimaryGpuBinHandleSymbol << "\n";
409 ObjStream << " .type " << PrimaryGpuBinHandleSymbol << ",@object\n";
410 ObjStream << " .section .hip_gpubin_handle,\"aw\"\n";
411 }
412 ObjStream << " .globl " << PrimaryGpuBinHandleSymbol << "\n";
413 ObjStream << " .p2align 3\n"; // Align 8
414 ObjStream << PrimaryGpuBinHandleSymbol << ":\n";
415 ObjStream << " .zero 8\n"; // Size 8
416
417 // Generate alias directives for other gpubin handle symbols
418 for (const auto &AliasSymbol : AliasGpuBinHandleSymbols) {
419 ObjStream << " .globl " << AliasSymbol << "\n";
420 ObjStream << " .set " << AliasSymbol << "," << PrimaryGpuBinHandleSymbol
421 << "\n";
422 }
423 }
424 if (FoundPrimaryHipFatbinSymbol) {
425 // Define the first fatbin symbol
426 if (HostTriple.isWindowsMSVCEnvironment())
427 ObjStream << " .section .hip_fatbin,\"dw\"\n";
428 else {
429 ObjStream << " .protected " << PrimaryHipFatbinSymbol << "\n";
430 ObjStream << " .type " << PrimaryHipFatbinSymbol << ",@object\n";
431 ObjStream << " .section .hip_fatbin,\"a\",@progbits\n";
432 }
433 ObjStream << " .globl " << PrimaryHipFatbinSymbol << "\n";
434 ObjStream << " .p2align " << llvm::Log2(llvm::Align(HIPCodeObjectAlign))
435 << "\n";
436 // Generate alias directives for other fatbin symbols
437 for (const auto &AliasSymbol : AliasHipFatbinSymbols) {
438 ObjStream << " .globl " << AliasSymbol << "\n";
439 ObjStream << " .set " << AliasSymbol << "," << PrimaryHipFatbinSymbol
440 << "\n";
441 }
442 ObjStream << PrimaryHipFatbinSymbol << ":\n";
443 ObjStream << " .incbin ";
444 llvm::sys::printArg(ObjStream, BundleFile, /*Quote=*/true);
445 ObjStream << "\n";
446 }
447 if (HostTriple.isOSLinux() && HostTriple.isOSBinFormatELF())
448 ObjStream << " .section .note.GNU-stack, \"\", @progbits\n";
449 ObjStream.flush();
450
451 // Dump the contents of the temp object file gen if the user requested that.
452 // We support this option to enable testing of behavior with -###.
453 if (C.getArgs().hasArg(options::OPT_fhip_dump_offload_linker_script))
454 llvm::errs() << ObjBuffer;
455
456 // Open script file and write the contents.
457 std::error_code EC;
458 llvm::raw_fd_ostream Objf(McinFile, EC, llvm::sys::fs::OF_None);
459
460 if (EC) {
461 C.getDriver().Diag(clang::diag::err_unable_to_make_temp) << EC.message();
462 return;
463 }
464
465 Objf << ObjBuffer;
466
467 ArgStringList McArgs{"-triple", Args.MakeArgString(HostTriple.normalize()),
468 "-o", Output.getFilename(),
469 McinFile, "--filetype=obj"};
470 const char *Mc = Args.MakeArgString(TC.GetProgramPath("llvm-mc"));
471 C.addCommand(std::make_unique<Command>(JA, T, ResponseFileSupport::None(), Mc,
472 McArgs, Inputs, Output));
473}
IndirectLocalPath & Path
StringRef Filename
Definition: Format.cpp:3001
#define NULL_FILE
Definition: HIPUtility.cpp:35
static std::string normalizeForBundler(const llvm::Triple &T, bool HasTargetID)
Definition: HIPUtility.cpp:43
llvm::DenseSet< const void * > Visited
Definition: HTMLLogger.cpp:146
const std::set< std::string > & getGPUBinHandleSymbols() const
Definition: HIPUtility.cpp:78
HIPUndefinedFatBinSymbols(const Compilation &C, const llvm::opt::ArgList &Args_)
Definition: HIPUtility.cpp:55
const std::set< std::string > & getFatBinSymbols() const
Definition: HIPUtility.cpp:74
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
Action - Represent an abstract compilation step to perform.
Definition: Action.h:47
ActionList & getInputs()
Definition: Action.h:150
Compilation - A set of tasks to perform for a single driver invocation.
Definition: Compilation.h:45
const Driver & getDriver() const
Definition: Compilation.h:141
std::string getTargetTriple() const
Definition: Driver.h:420
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
std::string GetProgramPath(const char *Name) const
Definition: ToolChain.cpp:903
Tool - Information on a specific compilation tool.
Definition: Tool.h:32
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 addOffloadCompressArgs(const llvm::opt::ArgList &TCArgs, llvm::opt::ArgStringList &CmdArgs)
unsigned getAMDGPUCodeObjectVersion(const Driver &D, const llvm::opt::ArgList &Args)
The JSON file list parser is used to communicate input to InstallAPI.
const FunctionProtoType * T
static constexpr ResponseFileSupport None()
Returns a ResponseFileSupport indicating that response files are not supported.
Definition: Job.h:78