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"
32#if defined(_WIN32) || defined(_WIN64)
33#define NULL_FILE "nul"
35#define NULL_FILE "/dev/null"
39const unsigned HIPCodeObjectAlign = 4096;
45 return HasTargetID ? (
T.getArchName() +
"-" +
T.getVendorName() +
"-" +
46 T.getOSName() +
"-" +
T.getEnvironmentName())
56 const llvm::opt::ArgList &Args_)
58 DiagID(C.getDriver().getDiags().getCustomDiagID(
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)) {
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
79 return GPUBinHandleSymbols;
88 bool IsMSVC = Triple.isWindowsMSVCEnvironment();
89 llvm::StringRef Ext = IsMSVC ?
".lib" :
".a";
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());
96 LibNames.push_back(
Value);
98 for (
const auto *Arg : Args.filtered(options::OPT_L)) {
99 auto Path = Arg->getValue();
100 LibPaths.push_back(
Path);
102 llvm::errs() <<
"HIP fatbin symbol search uses library path: " <<
Path
106 auto ProcessLib = [&](llvm::StringRef LibName,
bool IsExact) {
108 IsExact ? Twine(LibName).str()
109 : IsMSVC ? (Twine(LibName) + Ext).str()
110 : (Twine(
"lib") + LibName + Ext).str());
113 for (
const auto Path : LibPaths) {
115 llvm::sys::path::append(FullPath, FullLibName);
117 if (llvm::sys::fs::exists(FullPath)) {
119 llvm::errs() <<
"HIP fatbin symbol search found library: "
121 auto BufferOrErr = llvm::MemoryBuffer::getFile(FullPath);
123 errorHandler(llvm::errorCodeToError(BufferOrErr.getError()));
126 processInput(BufferOrErr.get()->getMemBufferRef());
131 if (!
Found && Verbose)
132 llvm::errs() <<
"HIP fatbin symbol search could not find library: "
133 << FullLibName <<
"\n";
136 for (
const auto LibName : ExactLibNames)
137 ProcessLib(LibName,
true);
139 for (
const auto LibName : LibNames)
140 ProcessLib(LibName,
false);
145 const llvm::opt::ArgList &Args;
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";
156 void populateSymbols() {
157 std::deque<const Action *> WorkList;
158 std::set<const Action *>
Visited;
160 for (
const auto &
Action : C.getActions())
161 WorkList.push_back(
Action);
163 while (!WorkList.empty()) {
164 const Action *CurrentAction = WorkList.front();
165 WorkList.pop_front();
167 if (!CurrentAction || !
Visited.insert(CurrentAction).second)
170 if (
const auto *IA = dyn_cast<InputAction>(CurrentAction)) {
171 std::string ID = IA->getId().str();
173 ID = llvm::utohexstr(llvm::MD5Hash(ID),
true);
174 FatBinSymbols.insert((FatBinPrefix + Twine(
'_') + ID).str());
175 GPUBinHandleSymbols.insert(
176 (GPUBinHandlePrefix + Twine(
'_') + ID).str());
179 if (IA->getInputArg().getNumValues() == 0)
181 const char *
Filename = IA->getInputArg().getValue();
184 auto BufferOrErr = llvm::MemoryBuffer::getFile(
Filename);
191 processInput(BufferOrErr.get()->getMemBufferRef());
193 WorkList.insert(WorkList.end(), CurrentAction->
getInputs().begin(),
198 void processInput(
const llvm::MemoryBufferRef &Buffer) {
200 auto ObjFileOrErr = llvm::object::ObjectFile::createObjectFile(Buffer);
202 processSymbols(**ObjFileOrErr);
207 llvm::consumeError(ObjFileOrErr.takeError());
208 auto ArchiveOrErr = llvm::object::Archive::create(Buffer);
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();
215 processInput(*ChildBufOrErr);
217 errorHandler(ChildBufOrErr.takeError());
221 errorHandler(std::move(Err));
226 llvm::consumeError(ArchiveOrErr.takeError());
229 void processSymbols(
const llvm::object::ObjectFile &Obj) {
230 for (
const auto &Symbol : Obj.symbols()) {
231 auto FlagOrErr = Symbol.getFlags();
233 errorHandler(FlagOrErr.takeError());
237 auto NameOrErr = Symbol.getName();
239 errorHandler(NameOrErr.takeError());
242 llvm::StringRef Name = *NameOrErr;
245 FlagOrErr.get() & llvm::object::SymbolRef::SF_Undefined;
246 bool isFatBinSymbol = Name.starts_with(FatBinPrefix);
247 bool isGPUBinHandleSymbol = Name.starts_with(GPUBinHandlePrefix);
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());
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());
272 void errorHandler(llvm::Error Err) {
275 C.getDriver().Diag(DiagID) << llvm::toString(std::move(Err));
282 llvm::StringRef OutputFileName,
284 const llvm::opt::ArgList &Args,
288 ArgStringList BundlerArgs;
289 BundlerArgs.push_back(Args.MakeArgString(
"-type=o"));
290 BundlerArgs.push_back(
291 Args.MakeArgString(
"-bundle-align=" + Twine(HIPCodeObjectAlign)));
295 std::string BundlerTargetArg =
"-targets=host-x86_64-unknown-linux";
300 std::string OffloadKind =
"hip";
301 auto &TT =
T.getToolChain().getTriple();
303 OffloadKind = OffloadKind +
"v4";
304 for (
const auto &II : Inputs) {
305 const auto *A = II.getAction();
306 auto ArchStr = llvm::StringRef(A->getOffloadingArch());
309 if (!ArchStr.empty())
310 BundlerTargetArg +=
"-" + ArchStr.str();
312 BundlerArgs.push_back(Args.MakeArgString(BundlerTargetArg));
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));
322 std::string Output = std::string(OutputFileName);
323 auto *BundlerOutputArg =
324 Args.MakeArgString(std::string(
"-output=").append(Output));
325 BundlerArgs.push_back(BundlerOutputArg);
329 const char *Bundler = Args.MakeArgString(
330 T.getToolChain().GetProgramPath(
"clang-offload-bundler"));
331 C.addCommand(std::make_unique<Command>(
333 InputInfo(&JA, Args.MakeArgString(Output))));
344 std::string Name = std::string(llvm::sys::path::stem(Output.
getFilename()));
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");
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));
363 std::string ObjBuffer;
364 llvm::raw_string_ostream ObjStream(ObjBuffer);
371 std::string PrimaryHipFatbinSymbol;
372 std::string PrimaryGpuBinHandleSymbol;
373 bool FoundPrimaryHipFatbinSymbol =
false;
374 bool FoundPrimaryGpuBinHandleSymbol =
false;
376 std::vector<std::string> AliasHipFatbinSymbols;
377 std::vector<std::string> AliasGpuBinHandleSymbols;
381 for (
const auto &Symbol : Symbols.getFatBinSymbols()) {
382 if (!FoundPrimaryHipFatbinSymbol) {
383 PrimaryHipFatbinSymbol = Symbol;
384 FoundPrimaryHipFatbinSymbol =
true;
386 AliasHipFatbinSymbols.push_back(Symbol);
389 for (
const auto &Symbol : Symbols.getGPUBinHandleSymbols()) {
390 if (!FoundPrimaryGpuBinHandleSymbol) {
391 PrimaryGpuBinHandleSymbol = Symbol;
392 FoundPrimaryGpuBinHandleSymbol =
true;
394 AliasGpuBinHandleSymbols.push_back(Symbol);
401 ObjStream <<
"# HIP Object Generator\n";
402 ObjStream <<
"# *** Automatically generated by Clang ***\n";
403 if (FoundPrimaryGpuBinHandleSymbol) {
405 if (HostTriple.isWindowsMSVCEnvironment())
406 ObjStream <<
" .section .hip_gpubin_handle,\"dw\"\n";
408 ObjStream <<
" .protected " << PrimaryGpuBinHandleSymbol <<
"\n";
409 ObjStream <<
" .type " << PrimaryGpuBinHandleSymbol <<
",@object\n";
410 ObjStream <<
" .section .hip_gpubin_handle,\"aw\"\n";
412 ObjStream <<
" .globl " << PrimaryGpuBinHandleSymbol <<
"\n";
413 ObjStream <<
" .p2align 3\n";
414 ObjStream << PrimaryGpuBinHandleSymbol <<
":\n";
415 ObjStream <<
" .zero 8\n";
418 for (
const auto &AliasSymbol : AliasGpuBinHandleSymbols) {
419 ObjStream <<
" .globl " << AliasSymbol <<
"\n";
420 ObjStream <<
" .set " << AliasSymbol <<
"," << PrimaryGpuBinHandleSymbol
424 if (FoundPrimaryHipFatbinSymbol) {
426 if (HostTriple.isWindowsMSVCEnvironment())
427 ObjStream <<
" .section .hip_fatbin,\"dw\"\n";
429 ObjStream <<
" .protected " << PrimaryHipFatbinSymbol <<
"\n";
430 ObjStream <<
" .type " << PrimaryHipFatbinSymbol <<
",@object\n";
431 ObjStream <<
" .section .hip_fatbin,\"a\",@progbits\n";
433 ObjStream <<
" .globl " << PrimaryHipFatbinSymbol <<
"\n";
434 ObjStream <<
" .p2align " << llvm::Log2(llvm::Align(HIPCodeObjectAlign))
437 for (
const auto &AliasSymbol : AliasHipFatbinSymbols) {
438 ObjStream <<
" .globl " << AliasSymbol <<
"\n";
439 ObjStream <<
" .set " << AliasSymbol <<
"," << PrimaryHipFatbinSymbol
442 ObjStream << PrimaryHipFatbinSymbol <<
":\n";
443 ObjStream <<
" .incbin ";
444 llvm::sys::printArg(ObjStream, BundleFile,
true);
447 if (HostTriple.isOSLinux() && HostTriple.isOSBinFormatELF())
448 ObjStream <<
" .section .note.GNU-stack, \"\", @progbits\n";
453 if (
C.getArgs().hasArg(options::OPT_fhip_dump_offload_linker_script))
454 llvm::errs() << ObjBuffer;
458 llvm::raw_fd_ostream Objf(McinFile, EC, llvm::sys::fs::OF_None);
461 C.getDriver().Diag(clang::diag::err_unable_to_make_temp) << EC.message();
467 ArgStringList McArgs{
"-triple", Args.MakeArgString(HostTriple.normalize()),
469 McinFile,
"--filetype=obj"};
470 const char *Mc = Args.MakeArgString(TC.
GetProgramPath(
"llvm-mc"));
472 McArgs, Inputs, Output));
static std::string normalizeForBundler(const llvm::Triple &T, bool HasTargetID)
llvm::DenseSet< const void * > Visited
const std::set< std::string > & getGPUBinHandleSymbols() const
void processStaticLibraries()
HIPUndefinedFatBinSymbols(const Compilation &C, const llvm::opt::ArgList &Args_)
const std::set< std::string > & getFatBinSymbols() const
Concrete class used by the front-end to report problems and issues.
Action - Represent an abstract compilation step to perform.
Compilation - A set of tasks to perform for a single driver invocation.
const Driver & getDriver() const
std::string getTargetTriple() const
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.