ClangLinkerWrapper.cpp 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442
  1. //===-- clang-linker-wrapper/ClangLinkerWrapper.cpp - wrapper over linker-===//
  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. // This tool works as a wrapper over a linking job. This tool is used to create
  10. // linked device images for offloading. It scans the linker's input for embedded
  11. // device offloading data stored in sections `.llvm.offloading` and extracts it
  12. // as a temporary file. The extracted device files will then be passed to a
  13. // device linking job to create a final device image.
  14. //
  15. //===---------------------------------------------------------------------===//
  16. #include "OffloadWrapper.h"
  17. #include "clang/Basic/Version.h"
  18. #include "llvm/BinaryFormat/Magic.h"
  19. #include "llvm/Bitcode/BitcodeWriter.h"
  20. #include "llvm/CodeGen/CommandFlags.h"
  21. #include "llvm/IR/Constants.h"
  22. #include "llvm/IR/DiagnosticPrinter.h"
  23. #include "llvm/IR/Module.h"
  24. #include "llvm/IRReader/IRReader.h"
  25. #include "llvm/LTO/LTO.h"
  26. #include "llvm/MC/TargetRegistry.h"
  27. #include "llvm/Object/Archive.h"
  28. #include "llvm/Object/ArchiveWriter.h"
  29. #include "llvm/Object/Binary.h"
  30. #include "llvm/Object/ELFObjectFile.h"
  31. #include "llvm/Object/IRObjectFile.h"
  32. #include "llvm/Object/ObjectFile.h"
  33. #include "llvm/Object/OffloadBinary.h"
  34. #include "llvm/Option/ArgList.h"
  35. #include "llvm/Option/OptTable.h"
  36. #include "llvm/Option/Option.h"
  37. #include "llvm/Support/CommandLine.h"
  38. #include "llvm/Support/Errc.h"
  39. #include "llvm/Support/FileOutputBuffer.h"
  40. #include "llvm/Support/FileSystem.h"
  41. #include "llvm/Support/Host.h"
  42. #include "llvm/Support/InitLLVM.h"
  43. #include "llvm/Support/MemoryBuffer.h"
  44. #include "llvm/Support/Parallel.h"
  45. #include "llvm/Support/Path.h"
  46. #include "llvm/Support/Program.h"
  47. #include "llvm/Support/Signals.h"
  48. #include "llvm/Support/SourceMgr.h"
  49. #include "llvm/Support/StringSaver.h"
  50. #include "llvm/Support/TargetSelect.h"
  51. #include "llvm/Support/WithColor.h"
  52. #include "llvm/Support/raw_ostream.h"
  53. #include "llvm/Target/TargetMachine.h"
  54. #include <atomic>
  55. #include <optional>
  56. using namespace llvm;
  57. using namespace llvm::opt;
  58. using namespace llvm::object;
  59. /// Path of the current binary.
  60. static const char *LinkerExecutable;
  61. /// Ssave intermediary results.
  62. static bool SaveTemps = false;
  63. /// Print arguments without executing.
  64. static bool DryRun = false;
  65. /// Print verbose output.
  66. static bool Verbose = false;
  67. /// Filename of the executable being created.
  68. static StringRef ExecutableName;
  69. /// Binary path for the CUDA installation.
  70. static std::string CudaBinaryPath;
  71. /// Mutex lock to protect writes to shared TempFiles in parallel.
  72. static std::mutex TempFilesMutex;
  73. /// Temporary files created by the linker wrapper.
  74. static std::list<SmallString<128>> TempFiles;
  75. /// Codegen flags for LTO backend.
  76. static codegen::RegisterCodeGenFlags CodeGenFlags;
  77. /// Global flag to indicate that the LTO pipeline threw an error.
  78. static std::atomic<bool> LTOError;
  79. using OffloadingImage = OffloadBinary::OffloadingImage;
  80. namespace llvm {
  81. // Provide DenseMapInfo so that OffloadKind can be used in a DenseMap.
  82. template <> struct DenseMapInfo<OffloadKind> {
  83. static inline OffloadKind getEmptyKey() { return OFK_LAST; }
  84. static inline OffloadKind getTombstoneKey() {
  85. return static_cast<OffloadKind>(OFK_LAST + 1);
  86. }
  87. static unsigned getHashValue(const OffloadKind &Val) { return Val; }
  88. static bool isEqual(const OffloadKind &LHS, const OffloadKind &RHS) {
  89. return LHS == RHS;
  90. }
  91. };
  92. } // namespace llvm
  93. namespace {
  94. using std::error_code;
  95. /// Must not overlap with llvm::opt::DriverFlag.
  96. enum WrapperFlags {
  97. WrapperOnlyOption = (1 << 4), // Options only used by the linker wrapper.
  98. DeviceOnlyOption = (1 << 5), // Options only used for device linking.
  99. };
  100. enum ID {
  101. OPT_INVALID = 0, // This is not an option ID.
  102. #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  103. HELPTEXT, METAVAR, VALUES) \
  104. OPT_##ID,
  105. #include "LinkerWrapperOpts.inc"
  106. LastOption
  107. #undef OPTION
  108. };
  109. #define PREFIX(NAME, VALUE) \
  110. static constexpr StringLiteral NAME##_init[] = VALUE; \
  111. static constexpr ArrayRef<StringLiteral> NAME(NAME##_init, \
  112. std::size(NAME##_init) - 1);
  113. #include "LinkerWrapperOpts.inc"
  114. #undef PREFIX
  115. static constexpr OptTable::Info InfoTable[] = {
  116. #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  117. HELPTEXT, METAVAR, VALUES) \
  118. {PREFIX, NAME, HELPTEXT, METAVAR, OPT_##ID, Option::KIND##Class, \
  119. PARAM, FLAGS, OPT_##GROUP, OPT_##ALIAS, ALIASARGS, VALUES},
  120. #include "LinkerWrapperOpts.inc"
  121. #undef OPTION
  122. };
  123. class WrapperOptTable : public opt::GenericOptTable {
  124. public:
  125. WrapperOptTable() : opt::GenericOptTable(InfoTable) {}
  126. };
  127. const OptTable &getOptTable() {
  128. static const WrapperOptTable *Table = []() {
  129. auto Result = std::make_unique<WrapperOptTable>();
  130. return Result.release();
  131. }();
  132. return *Table;
  133. }
  134. void printCommands(ArrayRef<StringRef> CmdArgs) {
  135. if (CmdArgs.empty())
  136. return;
  137. llvm::errs() << " \"" << CmdArgs.front() << "\" ";
  138. for (auto IC = std::next(CmdArgs.begin()), IE = CmdArgs.end(); IC != IE; ++IC)
  139. llvm::errs() << *IC << (std::next(IC) != IE ? " " : "\n");
  140. }
  141. [[noreturn]] void reportError(Error E) {
  142. outs().flush();
  143. logAllUnhandledErrors(std::move(E),
  144. WithColor::error(errs(), LinkerExecutable));
  145. exit(EXIT_FAILURE);
  146. }
  147. /// Create an extra user-specified \p OffloadFile.
  148. /// TODO: We should find a way to wrap these as libraries instead.
  149. Expected<OffloadFile> getInputBitcodeLibrary(StringRef Input) {
  150. auto [Device, Path] = StringRef(Input).split('=');
  151. auto [String, Arch] = Device.rsplit('-');
  152. auto [Kind, Triple] = String.split('-');
  153. llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> ImageOrError =
  154. llvm::MemoryBuffer::getFileOrSTDIN(Path);
  155. if (std::error_code EC = ImageOrError.getError())
  156. return createFileError(Path, EC);
  157. OffloadingImage Image{};
  158. Image.TheImageKind = IMG_Bitcode;
  159. Image.TheOffloadKind = getOffloadKind(Kind);
  160. Image.StringData = {{"triple", Triple}, {"arch", Arch}};
  161. Image.Image = std::move(*ImageOrError);
  162. std::unique_ptr<MemoryBuffer> Binary = OffloadBinary::write(Image);
  163. auto NewBinaryOrErr = OffloadBinary::create(*Binary);
  164. if (!NewBinaryOrErr)
  165. return NewBinaryOrErr.takeError();
  166. return OffloadFile(std::move(*NewBinaryOrErr), std::move(Binary));
  167. }
  168. std::string getMainExecutable(const char *Name) {
  169. void *Ptr = (void *)(intptr_t)&getMainExecutable;
  170. auto COWPath = sys::fs::getMainExecutable(Name, Ptr);
  171. return sys::path::parent_path(COWPath).str();
  172. }
  173. /// Get a temporary filename suitable for output.
  174. Expected<StringRef> createOutputFile(const Twine &Prefix, StringRef Extension) {
  175. std::scoped_lock<decltype(TempFilesMutex)> Lock(TempFilesMutex);
  176. SmallString<128> OutputFile;
  177. if (SaveTemps) {
  178. (Prefix + "." + Extension).toNullTerminatedStringRef(OutputFile);
  179. } else {
  180. if (std::error_code EC =
  181. sys::fs::createTemporaryFile(Prefix, Extension, OutputFile))
  182. return createFileError(OutputFile, EC);
  183. }
  184. TempFiles.emplace_back(std::move(OutputFile));
  185. return TempFiles.back();
  186. }
  187. /// Execute the command \p ExecutablePath with the arguments \p Args.
  188. Error executeCommands(StringRef ExecutablePath, ArrayRef<StringRef> Args) {
  189. if (Verbose || DryRun)
  190. printCommands(Args);
  191. if (!DryRun)
  192. if (sys::ExecuteAndWait(ExecutablePath, Args))
  193. return createStringError(inconvertibleErrorCode(),
  194. "'" + sys::path::filename(ExecutablePath) + "'" +
  195. " failed");
  196. return Error::success();
  197. }
  198. Expected<std::string> findProgram(StringRef Name, ArrayRef<StringRef> Paths) {
  199. ErrorOr<std::string> Path = sys::findProgramByName(Name, Paths);
  200. if (!Path)
  201. Path = sys::findProgramByName(Name);
  202. if (!Path && DryRun)
  203. return Name.str();
  204. if (!Path)
  205. return createStringError(Path.getError(),
  206. "Unable to find '" + Name + "' in path");
  207. return *Path;
  208. }
  209. /// Runs the wrapped linker job with the newly created input.
  210. Error runLinker(ArrayRef<StringRef> Files, const ArgList &Args) {
  211. llvm::TimeTraceScope TimeScope("Execute host linker");
  212. // Render the linker arguments and add the newly created image. We add it
  213. // after the output file to ensure it is linked with the correct libraries.
  214. StringRef LinkerPath = Args.getLastArgValue(OPT_linker_path_EQ);
  215. ArgStringList NewLinkerArgs;
  216. for (const opt::Arg *Arg : Args) {
  217. // Do not forward arguments only intended for the linker wrapper.
  218. if (Arg->getOption().hasFlag(WrapperOnlyOption))
  219. continue;
  220. Arg->render(Args, NewLinkerArgs);
  221. if (Arg->getOption().matches(OPT_o))
  222. llvm::transform(Files, std::back_inserter(NewLinkerArgs),
  223. [&](StringRef Arg) { return Args.MakeArgString(Arg); });
  224. }
  225. SmallVector<StringRef> LinkerArgs({LinkerPath});
  226. for (StringRef Arg : NewLinkerArgs)
  227. LinkerArgs.push_back(Arg);
  228. if (Error Err = executeCommands(LinkerPath, LinkerArgs))
  229. return Err;
  230. return Error::success();
  231. }
  232. void printVersion(raw_ostream &OS) {
  233. OS << clang::getClangToolFullVersion("clang-linker-wrapper") << '\n';
  234. }
  235. namespace nvptx {
  236. Expected<StringRef>
  237. fatbinary(ArrayRef<std::pair<StringRef, StringRef>> InputFiles,
  238. const ArgList &Args) {
  239. llvm::TimeTraceScope TimeScope("NVPTX fatbinary");
  240. // NVPTX uses the fatbinary program to bundle the linked images.
  241. Expected<std::string> FatBinaryPath =
  242. findProgram("fatbinary", {CudaBinaryPath + "/bin"});
  243. if (!FatBinaryPath)
  244. return FatBinaryPath.takeError();
  245. llvm::Triple Triple(
  246. Args.getLastArgValue(OPT_host_triple_EQ, sys::getDefaultTargetTriple()));
  247. // Create a new file to write the linked device image to.
  248. auto TempFileOrErr =
  249. createOutputFile(sys::path::filename(ExecutableName), "fatbin");
  250. if (!TempFileOrErr)
  251. return TempFileOrErr.takeError();
  252. SmallVector<StringRef, 16> CmdArgs;
  253. CmdArgs.push_back(*FatBinaryPath);
  254. CmdArgs.push_back(Triple.isArch64Bit() ? "-64" : "-32");
  255. CmdArgs.push_back("--create");
  256. CmdArgs.push_back(*TempFileOrErr);
  257. for (const auto &[File, Arch] : InputFiles)
  258. CmdArgs.push_back(
  259. Args.MakeArgString("--image=profile=" + Arch + ",file=" + File));
  260. if (Error Err = executeCommands(*FatBinaryPath, CmdArgs))
  261. return std::move(Err);
  262. return *TempFileOrErr;
  263. }
  264. } // namespace nvptx
  265. namespace amdgcn {
  266. Expected<StringRef>
  267. fatbinary(ArrayRef<std::pair<StringRef, StringRef>> InputFiles,
  268. const ArgList &Args) {
  269. llvm::TimeTraceScope TimeScope("AMDGPU Fatbinary");
  270. // AMDGPU uses the clang-offload-bundler to bundle the linked images.
  271. Expected<std::string> OffloadBundlerPath = findProgram(
  272. "clang-offload-bundler", {getMainExecutable("clang-offload-bundler")});
  273. if (!OffloadBundlerPath)
  274. return OffloadBundlerPath.takeError();
  275. llvm::Triple Triple(
  276. Args.getLastArgValue(OPT_host_triple_EQ, sys::getDefaultTargetTriple()));
  277. // Create a new file to write the linked device image to.
  278. auto TempFileOrErr =
  279. createOutputFile(sys::path::filename(ExecutableName), "hipfb");
  280. if (!TempFileOrErr)
  281. return TempFileOrErr.takeError();
  282. BumpPtrAllocator Alloc;
  283. StringSaver Saver(Alloc);
  284. SmallVector<StringRef, 16> CmdArgs;
  285. CmdArgs.push_back(*OffloadBundlerPath);
  286. CmdArgs.push_back("-type=o");
  287. CmdArgs.push_back("-bundle-align=4096");
  288. SmallVector<StringRef> Targets = {"-targets=host-x86_64-unknown-linux"};
  289. for (const auto &[File, Arch] : InputFiles)
  290. Targets.push_back(Saver.save("hipv4-amdgcn-amd-amdhsa--" + Arch));
  291. CmdArgs.push_back(Saver.save(llvm::join(Targets, ",")));
  292. CmdArgs.push_back("-input=/dev/null");
  293. for (const auto &[File, Arch] : InputFiles)
  294. CmdArgs.push_back(Saver.save("-input=" + File));
  295. CmdArgs.push_back(Saver.save("-output=" + *TempFileOrErr));
  296. if (Error Err = executeCommands(*OffloadBundlerPath, CmdArgs))
  297. return std::move(Err);
  298. return *TempFileOrErr;
  299. }
  300. } // namespace amdgcn
  301. namespace generic {
  302. Expected<StringRef> clang(ArrayRef<StringRef> InputFiles, const ArgList &Args) {
  303. llvm::TimeTraceScope TimeScope("Clang");
  304. // Use `clang` to invoke the appropriate device tools.
  305. Expected<std::string> ClangPath =
  306. findProgram("clang", {getMainExecutable("clang")});
  307. if (!ClangPath)
  308. return ClangPath.takeError();
  309. const llvm::Triple Triple(Args.getLastArgValue(OPT_triple_EQ));
  310. StringRef Arch = Args.getLastArgValue(OPT_arch_EQ);
  311. if (Arch.empty())
  312. Arch = "native";
  313. // Create a new file to write the linked device image to. Assume that the
  314. // input filename already has the device and architecture.
  315. auto TempFileOrErr =
  316. createOutputFile(sys::path::filename(ExecutableName) + "." +
  317. Triple.getArchName() + "." + Arch,
  318. "img");
  319. if (!TempFileOrErr)
  320. return TempFileOrErr.takeError();
  321. StringRef OptLevel = Args.getLastArgValue(OPT_opt_level, "O2");
  322. SmallVector<StringRef, 16> CmdArgs{
  323. *ClangPath,
  324. "-o",
  325. *TempFileOrErr,
  326. Args.MakeArgString("--target=" + Triple.getTriple()),
  327. Triple.isAMDGPU() ? Args.MakeArgString("-mcpu=" + Arch)
  328. : Args.MakeArgString("-march=" + Arch),
  329. Args.MakeArgString("-" + OptLevel),
  330. "-Wl,--no-undefined",
  331. };
  332. // If this is CPU offloading we copy the input libraries.
  333. if (!Triple.isAMDGPU() && !Triple.isNVPTX()) {
  334. CmdArgs.push_back("-Bsymbolic");
  335. CmdArgs.push_back("-shared");
  336. ArgStringList LinkerArgs;
  337. for (const opt::Arg *Arg :
  338. Args.filtered(OPT_library, OPT_rpath, OPT_library_path))
  339. Arg->render(Args, LinkerArgs);
  340. llvm::copy(LinkerArgs, std::back_inserter(CmdArgs));
  341. }
  342. if (Args.hasArg(OPT_debug))
  343. CmdArgs.push_back("-g");
  344. if (SaveTemps)
  345. CmdArgs.push_back("-save-temps");
  346. if (Verbose)
  347. CmdArgs.push_back("-v");
  348. if (!CudaBinaryPath.empty())
  349. CmdArgs.push_back(Args.MakeArgString("--cuda-path=" + CudaBinaryPath));
  350. for (StringRef Arg : Args.getAllArgValues(OPT_ptxas_arg))
  351. llvm::copy(SmallVector<StringRef>({"-Xcuda-ptxas", Arg}),
  352. std::back_inserter(CmdArgs));
  353. for (StringRef Arg : Args.getAllArgValues(OPT_linker_arg_EQ))
  354. CmdArgs.push_back(Args.MakeArgString("-Wl," + Arg));
  355. for (StringRef InputFile : InputFiles)
  356. CmdArgs.push_back(InputFile);
  357. if (Error Err = executeCommands(*ClangPath, CmdArgs))
  358. return std::move(Err);
  359. return *TempFileOrErr;
  360. }
  361. } // namespace generic
  362. Expected<StringRef> linkDevice(ArrayRef<StringRef> InputFiles,
  363. const ArgList &Args) {
  364. const llvm::Triple Triple(Args.getLastArgValue(OPT_triple_EQ));
  365. switch (Triple.getArch()) {
  366. case Triple::nvptx:
  367. case Triple::nvptx64:
  368. case Triple::amdgcn:
  369. case Triple::x86:
  370. case Triple::x86_64:
  371. case Triple::aarch64:
  372. case Triple::aarch64_be:
  373. case Triple::ppc64:
  374. case Triple::ppc64le:
  375. return generic::clang(InputFiles, Args);
  376. default:
  377. return createStringError(inconvertibleErrorCode(),
  378. Triple.getArchName() +
  379. " linking is not supported");
  380. }
  381. }
  382. void diagnosticHandler(const DiagnosticInfo &DI) {
  383. std::string ErrStorage;
  384. raw_string_ostream OS(ErrStorage);
  385. DiagnosticPrinterRawOStream DP(OS);
  386. DI.print(DP);
  387. switch (DI.getSeverity()) {
  388. case DS_Error:
  389. WithColor::error(errs(), LinkerExecutable) << ErrStorage << "\n";
  390. LTOError = true;
  391. break;
  392. case DS_Warning:
  393. WithColor::warning(errs(), LinkerExecutable) << ErrStorage << "\n";
  394. break;
  395. case DS_Note:
  396. WithColor::note(errs(), LinkerExecutable) << ErrStorage << "\n";
  397. break;
  398. case DS_Remark:
  399. WithColor::remark(errs()) << ErrStorage << "\n";
  400. break;
  401. }
  402. }
  403. // Get the list of target features from the input file and unify them such that
  404. // if there are multiple +xxx or -xxx features we only keep the last one.
  405. std::vector<std::string> getTargetFeatures(ArrayRef<OffloadFile> InputFiles) {
  406. SmallVector<StringRef> Features;
  407. for (const OffloadFile &File : InputFiles) {
  408. for (auto Arg : llvm::split(File.getBinary()->getString("feature"), ","))
  409. Features.emplace_back(Arg);
  410. }
  411. // Only add a feature if it hasn't been seen before starting from the end.
  412. std::vector<std::string> UnifiedFeatures;
  413. DenseSet<StringRef> UsedFeatures;
  414. for (StringRef Feature : llvm::reverse(Features)) {
  415. if (UsedFeatures.insert(Feature.drop_front()).second)
  416. UnifiedFeatures.push_back(Feature.str());
  417. }
  418. return UnifiedFeatures;
  419. }
  420. template <typename ModuleHook = function_ref<bool(size_t, const Module &)>>
  421. std::unique_ptr<lto::LTO> createLTO(
  422. const ArgList &Args, const std::vector<std::string> &Features,
  423. ModuleHook Hook = [](size_t, const Module &) { return true; }) {
  424. const llvm::Triple Triple(Args.getLastArgValue(OPT_triple_EQ));
  425. StringRef Arch = Args.getLastArgValue(OPT_arch_EQ);
  426. lto::Config Conf;
  427. lto::ThinBackend Backend;
  428. // TODO: Handle index-only thin-LTO
  429. Backend =
  430. lto::createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
  431. Conf.CPU = Arch.str();
  432. Conf.Options = codegen::InitTargetOptionsFromCodeGenFlags(Triple);
  433. StringRef OptLevel = Args.getLastArgValue(OPT_opt_level, "O2");
  434. Conf.MAttrs = Features;
  435. std::optional<CodeGenOpt::Level> CGOptLevelOrNone =
  436. CodeGenOpt::parseLevel(OptLevel[1]);
  437. assert(CGOptLevelOrNone && "Invalid optimization level");
  438. Conf.CGOptLevel = *CGOptLevelOrNone;
  439. Conf.OptLevel = OptLevel[1] - '0';
  440. Conf.DefaultTriple = Triple.getTriple();
  441. LTOError = false;
  442. Conf.DiagHandler = diagnosticHandler;
  443. Conf.PTO.LoopVectorization = Conf.OptLevel > 1;
  444. Conf.PTO.SLPVectorization = Conf.OptLevel > 1;
  445. if (SaveTemps) {
  446. std::string TempName = (sys::path::filename(ExecutableName) + "." +
  447. Triple.getTriple() + "." + Arch)
  448. .str();
  449. Conf.PostInternalizeModuleHook = [=](size_t Task, const Module &M) {
  450. std::string File =
  451. !Task ? TempName + ".postlink.bc"
  452. : TempName + "." + std::to_string(Task) + ".postlink.bc";
  453. error_code EC;
  454. raw_fd_ostream LinkedBitcode(File, EC, sys::fs::OF_None);
  455. if (EC)
  456. reportError(errorCodeToError(EC));
  457. WriteBitcodeToFile(M, LinkedBitcode);
  458. return true;
  459. };
  460. Conf.PreCodeGenModuleHook = [=](size_t Task, const Module &M) {
  461. std::string File =
  462. !Task ? TempName + ".postopt.bc"
  463. : TempName + "." + std::to_string(Task) + ".postopt.bc";
  464. error_code EC;
  465. raw_fd_ostream LinkedBitcode(File, EC, sys::fs::OF_None);
  466. if (EC)
  467. reportError(errorCodeToError(EC));
  468. WriteBitcodeToFile(M, LinkedBitcode);
  469. return true;
  470. };
  471. }
  472. Conf.PostOptModuleHook = Hook;
  473. Conf.CGFileType =
  474. (Triple.isNVPTX() || SaveTemps) ? CGFT_AssemblyFile : CGFT_ObjectFile;
  475. // TODO: Handle remark files
  476. Conf.HasWholeProgramVisibility = Args.hasArg(OPT_whole_program);
  477. return std::make_unique<lto::LTO>(std::move(Conf), Backend);
  478. }
  479. // Returns true if \p S is valid as a C language identifier and will be given
  480. // `__start_` and `__stop_` symbols.
  481. bool isValidCIdentifier(StringRef S) {
  482. return !S.empty() && (isAlpha(S[0]) || S[0] == '_') &&
  483. llvm::all_of(llvm::drop_begin(S),
  484. [](char C) { return C == '_' || isAlnum(C); });
  485. }
  486. Error linkBitcodeFiles(SmallVectorImpl<OffloadFile> &InputFiles,
  487. SmallVectorImpl<StringRef> &OutputFiles,
  488. const ArgList &Args) {
  489. llvm::TimeTraceScope TimeScope("Link bitcode files");
  490. const llvm::Triple Triple(Args.getLastArgValue(OPT_triple_EQ));
  491. StringRef Arch = Args.getLastArgValue(OPT_arch_EQ);
  492. SmallVector<OffloadFile, 4> BitcodeInputFiles;
  493. DenseSet<StringRef> UsedInRegularObj;
  494. DenseSet<StringRef> UsedInSharedLib;
  495. BumpPtrAllocator Alloc;
  496. StringSaver Saver(Alloc);
  497. // Search for bitcode files in the input and create an LTO input file. If it
  498. // is not a bitcode file, scan its symbol table for symbols we need to save.
  499. for (OffloadFile &File : InputFiles) {
  500. MemoryBufferRef Buffer = MemoryBufferRef(File.getBinary()->getImage(), "");
  501. file_magic Type = identify_magic(Buffer.getBuffer());
  502. switch (Type) {
  503. case file_magic::bitcode: {
  504. BitcodeInputFiles.emplace_back(std::move(File));
  505. continue;
  506. }
  507. case file_magic::elf_relocatable:
  508. case file_magic::elf_shared_object: {
  509. Expected<std::unique_ptr<ObjectFile>> ObjFile =
  510. ObjectFile::createObjectFile(Buffer);
  511. if (!ObjFile)
  512. continue;
  513. for (SymbolRef Sym : (*ObjFile)->symbols()) {
  514. Expected<StringRef> Name = Sym.getName();
  515. if (!Name)
  516. return Name.takeError();
  517. // Record if we've seen these symbols in any object or shared libraries.
  518. if ((*ObjFile)->isRelocatableObject())
  519. UsedInRegularObj.insert(Saver.save(*Name));
  520. else
  521. UsedInSharedLib.insert(Saver.save(*Name));
  522. }
  523. continue;
  524. }
  525. default:
  526. continue;
  527. }
  528. }
  529. if (BitcodeInputFiles.empty())
  530. return Error::success();
  531. // Remove all the bitcode files that we moved from the original input.
  532. llvm::erase_if(InputFiles, [](OffloadFile &F) { return !F.getBinary(); });
  533. // LTO Module hook to output bitcode without running the backend.
  534. SmallVector<StringRef, 4> BitcodeOutput;
  535. auto OutputBitcode = [&](size_t, const Module &M) {
  536. auto TempFileOrErr = createOutputFile(sys::path::filename(ExecutableName) +
  537. "-jit-" + Triple.getTriple(),
  538. "bc");
  539. if (!TempFileOrErr)
  540. reportError(TempFileOrErr.takeError());
  541. std::error_code EC;
  542. raw_fd_ostream LinkedBitcode(*TempFileOrErr, EC, sys::fs::OF_None);
  543. if (EC)
  544. reportError(errorCodeToError(EC));
  545. WriteBitcodeToFile(M, LinkedBitcode);
  546. BitcodeOutput.push_back(*TempFileOrErr);
  547. return false;
  548. };
  549. // We assume visibility of the whole program if every input file was bitcode.
  550. auto Features = getTargetFeatures(BitcodeInputFiles);
  551. auto LTOBackend = Args.hasArg(OPT_embed_bitcode)
  552. ? createLTO(Args, Features, OutputBitcode)
  553. : createLTO(Args, Features);
  554. // We need to resolve the symbols so the LTO backend knows which symbols need
  555. // to be kept or can be internalized. This is a simplified symbol resolution
  556. // scheme to approximate the full resolution a linker would do.
  557. uint64_t Idx = 0;
  558. DenseSet<StringRef> PrevailingSymbols;
  559. for (auto &BitcodeInput : BitcodeInputFiles) {
  560. // Get a semi-unique buffer identifier for Thin-LTO.
  561. StringRef Identifier = Saver.save(
  562. std::to_string(Idx++) + "." +
  563. BitcodeInput.getBinary()->getMemoryBufferRef().getBufferIdentifier());
  564. MemoryBufferRef Buffer =
  565. MemoryBufferRef(BitcodeInput.getBinary()->getImage(), Identifier);
  566. Expected<std::unique_ptr<lto::InputFile>> BitcodeFileOrErr =
  567. llvm::lto::InputFile::create(Buffer);
  568. if (!BitcodeFileOrErr)
  569. return BitcodeFileOrErr.takeError();
  570. // Save the input file and the buffer associated with its memory.
  571. const auto Symbols = (*BitcodeFileOrErr)->symbols();
  572. SmallVector<lto::SymbolResolution, 16> Resolutions(Symbols.size());
  573. size_t Idx = 0;
  574. for (auto &Sym : Symbols) {
  575. lto::SymbolResolution &Res = Resolutions[Idx++];
  576. // We will use this as the prevailing symbol definition in LTO unless
  577. // it is undefined or another definition has already been used.
  578. Res.Prevailing =
  579. !Sym.isUndefined() &&
  580. PrevailingSymbols.insert(Saver.save(Sym.getName())).second;
  581. // We need LTO to preseve the following global symbols:
  582. // 1) Symbols used in regular objects.
  583. // 2) Sections that will be given a __start/__stop symbol.
  584. // 3) Prevailing symbols that are needed visible to external libraries.
  585. Res.VisibleToRegularObj =
  586. UsedInRegularObj.contains(Sym.getName()) ||
  587. isValidCIdentifier(Sym.getSectionName()) ||
  588. (Res.Prevailing &&
  589. (Sym.getVisibility() != GlobalValue::HiddenVisibility &&
  590. !Sym.canBeOmittedFromSymbolTable()));
  591. // Identify symbols that must be exported dynamically and can be
  592. // referenced by other files.
  593. Res.ExportDynamic =
  594. Sym.getVisibility() != GlobalValue::HiddenVisibility &&
  595. (UsedInSharedLib.contains(Sym.getName()) ||
  596. !Sym.canBeOmittedFromSymbolTable());
  597. // The final definition will reside in this linkage unit if the symbol is
  598. // defined and local to the module. This only checks for bitcode files,
  599. // full assertion will require complete symbol resolution.
  600. Res.FinalDefinitionInLinkageUnit =
  601. Sym.getVisibility() != GlobalValue::DefaultVisibility &&
  602. (!Sym.isUndefined() && !Sym.isCommon());
  603. // We do not support linker redefined symbols (e.g. --wrap) for device
  604. // image linking, so the symbols will not be changed after LTO.
  605. Res.LinkerRedefined = false;
  606. }
  607. // Add the bitcode file with its resolved symbols to the LTO job.
  608. if (Error Err = LTOBackend->add(std::move(*BitcodeFileOrErr), Resolutions))
  609. return Err;
  610. }
  611. // Run the LTO job to compile the bitcode.
  612. size_t MaxTasks = LTOBackend->getMaxTasks();
  613. SmallVector<StringRef> Files(MaxTasks);
  614. auto AddStream =
  615. [&](size_t Task,
  616. const Twine &ModuleName) -> std::unique_ptr<CachedFileStream> {
  617. int FD = -1;
  618. auto &TempFile = Files[Task];
  619. StringRef Extension = (Triple.isNVPTX() || SaveTemps) ? "s" : "o";
  620. std::string TaskStr = Task ? "." + std::to_string(Task) : "";
  621. auto TempFileOrErr =
  622. createOutputFile(sys::path::filename(ExecutableName) + "." +
  623. Triple.getTriple() + "." + Arch + TaskStr,
  624. Extension);
  625. if (!TempFileOrErr)
  626. reportError(TempFileOrErr.takeError());
  627. TempFile = *TempFileOrErr;
  628. if (std::error_code EC = sys::fs::openFileForWrite(TempFile, FD))
  629. reportError(errorCodeToError(EC));
  630. return std::make_unique<CachedFileStream>(
  631. std::make_unique<llvm::raw_fd_ostream>(FD, true));
  632. };
  633. if (Error Err = LTOBackend->run(AddStream))
  634. return Err;
  635. if (LTOError)
  636. return createStringError(inconvertibleErrorCode(),
  637. "Errors encountered inside the LTO pipeline.");
  638. // If we are embedding bitcode we only need the intermediate output.
  639. bool SingleOutput = Files.size() == 1;
  640. if (Args.hasArg(OPT_embed_bitcode)) {
  641. if (BitcodeOutput.size() != 1 || !SingleOutput)
  642. return createStringError(inconvertibleErrorCode(),
  643. "Cannot embed bitcode with multiple files.");
  644. OutputFiles.push_back(Args.MakeArgString(BitcodeOutput.front()));
  645. return Error::success();
  646. }
  647. // Append the new inputs to the device linker input.
  648. for (StringRef File : Files)
  649. OutputFiles.push_back(File);
  650. return Error::success();
  651. }
  652. Expected<StringRef> writeOffloadFile(const OffloadFile &File) {
  653. const OffloadBinary &Binary = *File.getBinary();
  654. StringRef Prefix =
  655. sys::path::stem(Binary.getMemoryBufferRef().getBufferIdentifier());
  656. StringRef Suffix = getImageKindName(Binary.getImageKind());
  657. auto TempFileOrErr = createOutputFile(
  658. Prefix + "-" + Binary.getTriple() + "-" + Binary.getArch(), Suffix);
  659. if (!TempFileOrErr)
  660. return TempFileOrErr.takeError();
  661. Expected<std::unique_ptr<FileOutputBuffer>> OutputOrErr =
  662. FileOutputBuffer::create(*TempFileOrErr, Binary.getImage().size());
  663. if (!OutputOrErr)
  664. return OutputOrErr.takeError();
  665. std::unique_ptr<FileOutputBuffer> Output = std::move(*OutputOrErr);
  666. llvm::copy(Binary.getImage(), Output->getBufferStart());
  667. if (Error E = Output->commit())
  668. return std::move(E);
  669. return *TempFileOrErr;
  670. }
  671. // Compile the module to an object file using the appropriate target machine for
  672. // the host triple.
  673. Expected<StringRef> compileModule(Module &M) {
  674. llvm::TimeTraceScope TimeScope("Compile module");
  675. std::string Msg;
  676. const Target *T = TargetRegistry::lookupTarget(M.getTargetTriple(), Msg);
  677. if (!T)
  678. return createStringError(inconvertibleErrorCode(), Msg);
  679. auto Options =
  680. codegen::InitTargetOptionsFromCodeGenFlags(Triple(M.getTargetTriple()));
  681. StringRef CPU = "";
  682. StringRef Features = "";
  683. std::unique_ptr<TargetMachine> TM(
  684. T->createTargetMachine(M.getTargetTriple(), CPU, Features, Options,
  685. Reloc::PIC_, M.getCodeModel()));
  686. if (M.getDataLayout().isDefault())
  687. M.setDataLayout(TM->createDataLayout());
  688. int FD = -1;
  689. auto TempFileOrErr = createOutputFile(
  690. sys::path::filename(ExecutableName) + ".image.wrapper", "o");
  691. if (!TempFileOrErr)
  692. return TempFileOrErr.takeError();
  693. if (std::error_code EC = sys::fs::openFileForWrite(*TempFileOrErr, FD))
  694. return errorCodeToError(EC);
  695. auto OS = std::make_unique<llvm::raw_fd_ostream>(FD, true);
  696. legacy::PassManager CodeGenPasses;
  697. TargetLibraryInfoImpl TLII(Triple(M.getTargetTriple()));
  698. CodeGenPasses.add(new TargetLibraryInfoWrapperPass(TLII));
  699. if (TM->addPassesToEmitFile(CodeGenPasses, *OS, nullptr, CGFT_ObjectFile))
  700. return createStringError(inconvertibleErrorCode(),
  701. "Failed to execute host backend");
  702. CodeGenPasses.run(M);
  703. return *TempFileOrErr;
  704. }
  705. /// Creates the object file containing the device image and runtime
  706. /// registration code from the device images stored in \p Images.
  707. Expected<StringRef>
  708. wrapDeviceImages(ArrayRef<std::unique_ptr<MemoryBuffer>> Buffers,
  709. const ArgList &Args, OffloadKind Kind) {
  710. llvm::TimeTraceScope TimeScope("Wrap bundled images");
  711. SmallVector<ArrayRef<char>, 4> BuffersToWrap;
  712. for (const auto &Buffer : Buffers)
  713. BuffersToWrap.emplace_back(
  714. ArrayRef<char>(Buffer->getBufferStart(), Buffer->getBufferSize()));
  715. LLVMContext Context;
  716. Module M("offload.wrapper.module", Context);
  717. M.setTargetTriple(
  718. Args.getLastArgValue(OPT_host_triple_EQ, sys::getDefaultTargetTriple()));
  719. switch (Kind) {
  720. case OFK_OpenMP:
  721. if (Error Err = wrapOpenMPBinaries(M, BuffersToWrap))
  722. return std::move(Err);
  723. break;
  724. case OFK_Cuda:
  725. if (Error Err = wrapCudaBinary(M, BuffersToWrap.front()))
  726. return std::move(Err);
  727. break;
  728. case OFK_HIP:
  729. if (Error Err = wrapHIPBinary(M, BuffersToWrap.front()))
  730. return std::move(Err);
  731. break;
  732. default:
  733. return createStringError(inconvertibleErrorCode(),
  734. getOffloadKindName(Kind) +
  735. " wrapping is not supported");
  736. }
  737. if (Args.hasArg(OPT_print_wrapped_module))
  738. errs() << M;
  739. auto FileOrErr = compileModule(M);
  740. if (!FileOrErr)
  741. return FileOrErr.takeError();
  742. return *FileOrErr;
  743. }
  744. Expected<SmallVector<std::unique_ptr<MemoryBuffer>>>
  745. bundleOpenMP(ArrayRef<OffloadingImage> Images) {
  746. SmallVector<std::unique_ptr<MemoryBuffer>> Buffers;
  747. for (const OffloadingImage &Image : Images)
  748. Buffers.emplace_back(OffloadBinary::write(Image));
  749. return std::move(Buffers);
  750. }
  751. Expected<SmallVector<std::unique_ptr<MemoryBuffer>>>
  752. bundleCuda(ArrayRef<OffloadingImage> Images, const ArgList &Args) {
  753. SmallVector<std::pair<StringRef, StringRef>, 4> InputFiles;
  754. for (const OffloadingImage &Image : Images)
  755. InputFiles.emplace_back(std::make_pair(Image.Image->getBufferIdentifier(),
  756. Image.StringData.lookup("arch")));
  757. Triple TheTriple = Triple(Images.front().StringData.lookup("triple"));
  758. auto FileOrErr = nvptx::fatbinary(InputFiles, Args);
  759. if (!FileOrErr)
  760. return FileOrErr.takeError();
  761. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ImageOrError =
  762. llvm::MemoryBuffer::getFileOrSTDIN(*FileOrErr);
  763. SmallVector<std::unique_ptr<MemoryBuffer>> Buffers;
  764. if (std::error_code EC = ImageOrError.getError())
  765. return createFileError(*FileOrErr, EC);
  766. Buffers.emplace_back(std::move(*ImageOrError));
  767. return std::move(Buffers);
  768. }
  769. Expected<SmallVector<std::unique_ptr<MemoryBuffer>>>
  770. bundleHIP(ArrayRef<OffloadingImage> Images, const ArgList &Args) {
  771. SmallVector<std::pair<StringRef, StringRef>, 4> InputFiles;
  772. for (const OffloadingImage &Image : Images)
  773. InputFiles.emplace_back(std::make_pair(Image.Image->getBufferIdentifier(),
  774. Image.StringData.lookup("arch")));
  775. Triple TheTriple = Triple(Images.front().StringData.lookup("triple"));
  776. auto FileOrErr = amdgcn::fatbinary(InputFiles, Args);
  777. if (!FileOrErr)
  778. return FileOrErr.takeError();
  779. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ImageOrError =
  780. llvm::MemoryBuffer::getFileOrSTDIN(*FileOrErr);
  781. SmallVector<std::unique_ptr<MemoryBuffer>> Buffers;
  782. if (std::error_code EC = ImageOrError.getError())
  783. return createFileError(*FileOrErr, EC);
  784. Buffers.emplace_back(std::move(*ImageOrError));
  785. return std::move(Buffers);
  786. }
  787. /// Transforms the input \p Images into the binary format the runtime expects
  788. /// for the given \p Kind.
  789. Expected<SmallVector<std::unique_ptr<MemoryBuffer>>>
  790. bundleLinkedOutput(ArrayRef<OffloadingImage> Images, const ArgList &Args,
  791. OffloadKind Kind) {
  792. llvm::TimeTraceScope TimeScope("Bundle linked output");
  793. switch (Kind) {
  794. case OFK_OpenMP:
  795. return bundleOpenMP(Images);
  796. case OFK_Cuda:
  797. return bundleCuda(Images, Args);
  798. case OFK_HIP:
  799. return bundleHIP(Images, Args);
  800. default:
  801. return createStringError(inconvertibleErrorCode(),
  802. getOffloadKindName(Kind) +
  803. " bundling is not supported");
  804. }
  805. }
  806. /// Returns a new ArgList containg arguments used for the device linking phase.
  807. DerivedArgList getLinkerArgs(ArrayRef<OffloadFile> Input,
  808. const InputArgList &Args) {
  809. DerivedArgList DAL = DerivedArgList(DerivedArgList(Args));
  810. for (Arg *A : Args)
  811. DAL.append(A);
  812. // Set the subarchitecture and target triple for this compilation.
  813. const OptTable &Tbl = getOptTable();
  814. DAL.AddJoinedArg(nullptr, Tbl.getOption(OPT_arch_EQ),
  815. Args.MakeArgString(Input.front().getBinary()->getArch()));
  816. DAL.AddJoinedArg(nullptr, Tbl.getOption(OPT_triple_EQ),
  817. Args.MakeArgString(Input.front().getBinary()->getTriple()));
  818. // If every input file is bitcode we have whole program visibility as we do
  819. // only support static linking with bitcode.
  820. auto ContainsBitcode = [](const OffloadFile &F) {
  821. return identify_magic(F.getBinary()->getImage()) == file_magic::bitcode;
  822. };
  823. if (llvm::all_of(Input, ContainsBitcode))
  824. DAL.AddFlagArg(nullptr, Tbl.getOption(OPT_whole_program));
  825. // Forward '-Xoffload-linker' options to the appropriate backend.
  826. for (StringRef Arg : Args.getAllArgValues(OPT_device_linker_args_EQ)) {
  827. auto [Triple, Value] = Arg.split('=');
  828. if (Value.empty())
  829. DAL.AddJoinedArg(nullptr, Tbl.getOption(OPT_linker_arg_EQ),
  830. Args.MakeArgString(Triple));
  831. else if (Triple == DAL.getLastArgValue(OPT_triple_EQ))
  832. DAL.AddJoinedArg(nullptr, Tbl.getOption(OPT_linker_arg_EQ),
  833. Args.MakeArgString(Value));
  834. }
  835. return DAL;
  836. }
  837. /// Transforms all the extracted offloading input files into an image that can
  838. /// be registered by the runtime.
  839. Expected<SmallVector<StringRef>>
  840. linkAndWrapDeviceFiles(SmallVectorImpl<OffloadFile> &LinkerInputFiles,
  841. const InputArgList &Args, char **Argv, int Argc) {
  842. llvm::TimeTraceScope TimeScope("Handle all device input");
  843. DenseMap<OffloadFile::TargetID, SmallVector<OffloadFile>> InputMap;
  844. for (auto &File : LinkerInputFiles)
  845. InputMap[File].emplace_back(std::move(File));
  846. LinkerInputFiles.clear();
  847. SmallVector<SmallVector<OffloadFile>> InputsForTarget;
  848. for (auto &[ID, Input] : InputMap)
  849. InputsForTarget.emplace_back(std::move(Input));
  850. InputMap.clear();
  851. std::mutex ImageMtx;
  852. DenseMap<OffloadKind, SmallVector<OffloadingImage>> Images;
  853. auto Err = parallelForEachError(InputsForTarget, [&](auto &Input) -> Error {
  854. llvm::TimeTraceScope TimeScope("Link device input");
  855. // Each thread needs its own copy of the base arguments to maintain
  856. // per-device argument storage of synthetic strings.
  857. const OptTable &Tbl = getOptTable();
  858. BumpPtrAllocator Alloc;
  859. StringSaver Saver(Alloc);
  860. auto BaseArgs =
  861. Tbl.parseArgs(Argc, Argv, OPT_INVALID, Saver, [](StringRef Err) {
  862. reportError(createStringError(inconvertibleErrorCode(), Err));
  863. });
  864. auto LinkerArgs = getLinkerArgs(Input, BaseArgs);
  865. DenseSet<OffloadKind> ActiveOffloadKinds;
  866. for (const auto &File : Input)
  867. if (File.getBinary()->getOffloadKind() != OFK_None)
  868. ActiveOffloadKinds.insert(File.getBinary()->getOffloadKind());
  869. // First link and remove all the input files containing bitcode.
  870. SmallVector<StringRef> InputFiles;
  871. if (Error Err = linkBitcodeFiles(Input, InputFiles, LinkerArgs))
  872. return Err;
  873. // Write any remaining device inputs to an output file for the linker.
  874. for (const OffloadFile &File : Input) {
  875. auto FileNameOrErr = writeOffloadFile(File);
  876. if (!FileNameOrErr)
  877. return FileNameOrErr.takeError();
  878. InputFiles.emplace_back(*FileNameOrErr);
  879. }
  880. // Link the remaining device files using the device linker.
  881. auto OutputOrErr = !Args.hasArg(OPT_embed_bitcode)
  882. ? linkDevice(InputFiles, LinkerArgs)
  883. : InputFiles.front();
  884. if (!OutputOrErr)
  885. return OutputOrErr.takeError();
  886. // Store the offloading image for each linked output file.
  887. for (OffloadKind Kind : ActiveOffloadKinds) {
  888. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileOrErr =
  889. llvm::MemoryBuffer::getFileOrSTDIN(*OutputOrErr);
  890. if (std::error_code EC = FileOrErr.getError()) {
  891. if (DryRun)
  892. FileOrErr = MemoryBuffer::getMemBuffer("");
  893. else
  894. return createFileError(*OutputOrErr, EC);
  895. }
  896. std::scoped_lock<decltype(ImageMtx)> Guard(ImageMtx);
  897. OffloadingImage TheImage{};
  898. TheImage.TheImageKind =
  899. Args.hasArg(OPT_embed_bitcode) ? IMG_Bitcode : IMG_Object;
  900. TheImage.TheOffloadKind = Kind;
  901. TheImage.StringData = {
  902. {"triple",
  903. Args.MakeArgString(LinkerArgs.getLastArgValue(OPT_triple_EQ))},
  904. {"arch",
  905. Args.MakeArgString(LinkerArgs.getLastArgValue(OPT_arch_EQ))}};
  906. TheImage.Image = std::move(*FileOrErr);
  907. Images[Kind].emplace_back(std::move(TheImage));
  908. }
  909. return Error::success();
  910. });
  911. if (Err)
  912. return std::move(Err);
  913. // Create a binary image of each offloading image and embed it into a new
  914. // object file.
  915. SmallVector<StringRef> WrappedOutput;
  916. for (auto &[Kind, Input] : Images) {
  917. // We sort the entries before bundling so they appear in a deterministic
  918. // order in the final binary.
  919. llvm::sort(Input, [](OffloadingImage &A, OffloadingImage &B) {
  920. return A.StringData["triple"] > B.StringData["triple"] ||
  921. A.StringData["arch"] > B.StringData["arch"] ||
  922. A.TheOffloadKind < B.TheOffloadKind;
  923. });
  924. auto BundledImagesOrErr = bundleLinkedOutput(Input, Args, Kind);
  925. if (!BundledImagesOrErr)
  926. return BundledImagesOrErr.takeError();
  927. auto OutputOrErr = wrapDeviceImages(*BundledImagesOrErr, Args, Kind);
  928. if (!OutputOrErr)
  929. return OutputOrErr.takeError();
  930. WrappedOutput.push_back(*OutputOrErr);
  931. }
  932. return WrappedOutput;
  933. }
  934. std::optional<std::string> findFile(StringRef Dir, StringRef Root,
  935. const Twine &Name) {
  936. SmallString<128> Path;
  937. if (Dir.startswith("="))
  938. sys::path::append(Path, Root, Dir.substr(1), Name);
  939. else
  940. sys::path::append(Path, Dir, Name);
  941. if (sys::fs::exists(Path))
  942. return static_cast<std::string>(Path);
  943. return std::nullopt;
  944. }
  945. std::optional<std::string>
  946. findFromSearchPaths(StringRef Name, StringRef Root,
  947. ArrayRef<StringRef> SearchPaths) {
  948. for (StringRef Dir : SearchPaths)
  949. if (std::optional<std::string> File = findFile(Dir, Root, Name))
  950. return File;
  951. return std::nullopt;
  952. }
  953. std::optional<std::string>
  954. searchLibraryBaseName(StringRef Name, StringRef Root,
  955. ArrayRef<StringRef> SearchPaths) {
  956. for (StringRef Dir : SearchPaths) {
  957. if (std::optional<std::string> File =
  958. findFile(Dir, Root, "lib" + Name + ".so"))
  959. return File;
  960. if (std::optional<std::string> File =
  961. findFile(Dir, Root, "lib" + Name + ".a"))
  962. return File;
  963. }
  964. return std::nullopt;
  965. }
  966. /// Search for static libraries in the linker's library path given input like
  967. /// `-lfoo` or `-l:libfoo.a`.
  968. std::optional<std::string> searchLibrary(StringRef Input, StringRef Root,
  969. ArrayRef<StringRef> SearchPaths) {
  970. if (Input.startswith(":"))
  971. return findFromSearchPaths(Input.drop_front(), Root, SearchPaths);
  972. return searchLibraryBaseName(Input, Root, SearchPaths);
  973. }
  974. /// Common redeclaration of needed symbol flags.
  975. enum Symbol : uint32_t {
  976. Sym_None = 0,
  977. Sym_Undefined = 1U << 1,
  978. Sym_Weak = 1U << 2,
  979. };
  980. /// Scan the symbols from a BitcodeFile \p Buffer and record if we need to
  981. /// extract any symbols from it.
  982. Expected<bool> getSymbolsFromBitcode(MemoryBufferRef Buffer, StringSaver &Saver,
  983. DenseMap<StringRef, Symbol> &Syms) {
  984. Expected<IRSymtabFile> IRSymtabOrErr = readIRSymtab(Buffer);
  985. if (!IRSymtabOrErr)
  986. return IRSymtabOrErr.takeError();
  987. bool ShouldExtract = false;
  988. for (unsigned I = 0; I != IRSymtabOrErr->Mods.size(); ++I) {
  989. for (const auto &Sym : IRSymtabOrErr->TheReader.module_symbols(I)) {
  990. if (Sym.isFormatSpecific() || !Sym.isGlobal())
  991. continue;
  992. bool NewSymbol = Syms.count(Sym.getName()) == 0;
  993. auto &OldSym = Syms[Saver.save(Sym.getName())];
  994. // We will extract if it defines a currenlty undefined non-weak symbol.
  995. bool ResolvesStrongReference =
  996. ((OldSym & Sym_Undefined && !(OldSym & Sym_Weak)) &&
  997. !Sym.isUndefined());
  998. // We will extract if it defines a new global symbol visible to the host.
  999. bool NewGlobalSymbol =
  1000. ((NewSymbol || (OldSym & Sym_Undefined)) && !Sym.isUndefined() &&
  1001. !Sym.canBeOmittedFromSymbolTable() &&
  1002. (Sym.getVisibility() != GlobalValue::HiddenVisibility));
  1003. ShouldExtract |= ResolvesStrongReference | NewGlobalSymbol;
  1004. // Update this symbol in the "table" with the new information.
  1005. if (OldSym & Sym_Undefined && !Sym.isUndefined())
  1006. OldSym = static_cast<Symbol>(OldSym & ~Sym_Undefined);
  1007. if (Sym.isUndefined() && NewSymbol)
  1008. OldSym = static_cast<Symbol>(OldSym | Sym_Undefined);
  1009. if (Sym.isWeak())
  1010. OldSym = static_cast<Symbol>(OldSym | Sym_Weak);
  1011. }
  1012. }
  1013. return ShouldExtract;
  1014. }
  1015. /// Scan the symbols from an ObjectFile \p Obj and record if we need to extract
  1016. /// any symbols from it.
  1017. Expected<bool> getSymbolsFromObject(const ObjectFile &Obj, StringSaver &Saver,
  1018. DenseMap<StringRef, Symbol> &Syms) {
  1019. bool ShouldExtract = false;
  1020. for (SymbolRef Sym : Obj.symbols()) {
  1021. auto FlagsOrErr = Sym.getFlags();
  1022. if (!FlagsOrErr)
  1023. return FlagsOrErr.takeError();
  1024. if (!(*FlagsOrErr & SymbolRef::SF_Global) ||
  1025. (*FlagsOrErr & SymbolRef::SF_FormatSpecific))
  1026. continue;
  1027. auto NameOrErr = Sym.getName();
  1028. if (!NameOrErr)
  1029. return NameOrErr.takeError();
  1030. bool NewSymbol = Syms.count(*NameOrErr) == 0;
  1031. auto &OldSym = Syms[Saver.save(*NameOrErr)];
  1032. // We will extract if it defines a currenlty undefined non-weak symbol.
  1033. bool ResolvesStrongReference = (OldSym & Sym_Undefined) &&
  1034. !(OldSym & Sym_Weak) &&
  1035. !(*FlagsOrErr & SymbolRef::SF_Undefined);
  1036. // We will extract if it defines a new global symbol visible to the host.
  1037. bool NewGlobalSymbol = ((NewSymbol || (OldSym & Sym_Undefined)) &&
  1038. !(*FlagsOrErr & SymbolRef::SF_Undefined) &&
  1039. !(*FlagsOrErr & SymbolRef::SF_Hidden));
  1040. ShouldExtract |= ResolvesStrongReference | NewGlobalSymbol;
  1041. // Update this symbol in the "table" with the new information.
  1042. if (OldSym & Sym_Undefined && !(*FlagsOrErr & SymbolRef::SF_Undefined))
  1043. OldSym = static_cast<Symbol>(OldSym & ~Sym_Undefined);
  1044. if (*FlagsOrErr & SymbolRef::SF_Undefined && NewSymbol)
  1045. OldSym = static_cast<Symbol>(OldSym | Sym_Undefined);
  1046. if (*FlagsOrErr & SymbolRef::SF_Weak)
  1047. OldSym = static_cast<Symbol>(OldSym | Sym_Weak);
  1048. }
  1049. return ShouldExtract;
  1050. }
  1051. /// Attempt to 'resolve' symbols found in input files. We use this to
  1052. /// determine if an archive member needs to be extracted. An archive member
  1053. /// will be extracted if any of the following is true.
  1054. /// 1) It defines an undefined symbol in a regular object filie.
  1055. /// 2) It defines a global symbol without hidden visibility that has not
  1056. /// yet been defined.
  1057. Expected<bool> getSymbols(StringRef Image, StringSaver &Saver,
  1058. DenseMap<StringRef, Symbol> &Syms) {
  1059. MemoryBufferRef Buffer = MemoryBufferRef(Image, "");
  1060. switch (identify_magic(Image)) {
  1061. case file_magic::bitcode:
  1062. return getSymbolsFromBitcode(Buffer, Saver, Syms);
  1063. case file_magic::elf_relocatable: {
  1064. Expected<std::unique_ptr<ObjectFile>> ObjFile =
  1065. ObjectFile::createObjectFile(Buffer);
  1066. if (!ObjFile)
  1067. return ObjFile.takeError();
  1068. return getSymbolsFromObject(**ObjFile, Saver, Syms);
  1069. }
  1070. default:
  1071. return false;
  1072. }
  1073. }
  1074. /// Search the input files and libraries for embedded device offloading code
  1075. /// and add it to the list of files to be linked. Files coming from static
  1076. /// libraries are only added to the input if they are used by an existing
  1077. /// input file.
  1078. Expected<SmallVector<OffloadFile>> getDeviceInput(const ArgList &Args) {
  1079. llvm::TimeTraceScope TimeScope("ExtractDeviceCode");
  1080. StringRef Root = Args.getLastArgValue(OPT_sysroot_EQ);
  1081. SmallVector<StringRef> LibraryPaths;
  1082. for (const opt::Arg *Arg : Args.filtered(OPT_library_path))
  1083. LibraryPaths.push_back(Arg->getValue());
  1084. BumpPtrAllocator Alloc;
  1085. StringSaver Saver(Alloc);
  1086. // Try to extract device code from the linker input files.
  1087. SmallVector<OffloadFile> InputFiles;
  1088. DenseMap<OffloadFile::TargetID, DenseMap<StringRef, Symbol>> Syms;
  1089. for (const opt::Arg *Arg : Args.filtered(OPT_INPUT, OPT_library)) {
  1090. std::optional<std::string> Filename =
  1091. Arg->getOption().matches(OPT_library)
  1092. ? searchLibrary(Arg->getValue(), Root, LibraryPaths)
  1093. : std::string(Arg->getValue());
  1094. if (!Filename && Arg->getOption().matches(OPT_library))
  1095. reportError(createStringError(inconvertibleErrorCode(),
  1096. "unable to find library -l%s",
  1097. Arg->getValue()));
  1098. if (!Filename || !sys::fs::exists(*Filename) ||
  1099. sys::fs::is_directory(*Filename))
  1100. continue;
  1101. ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
  1102. MemoryBuffer::getFileOrSTDIN(*Filename);
  1103. if (std::error_code EC = BufferOrErr.getError())
  1104. return createFileError(*Filename, EC);
  1105. MemoryBufferRef Buffer = **BufferOrErr;
  1106. if (identify_magic(Buffer.getBuffer()) == file_magic::elf_shared_object)
  1107. continue;
  1108. SmallVector<OffloadFile> Binaries;
  1109. if (Error Err = extractOffloadBinaries(Buffer, Binaries))
  1110. return std::move(Err);
  1111. // We only extract archive members that are needed.
  1112. bool IsArchive = identify_magic(Buffer.getBuffer()) == file_magic::archive;
  1113. bool Extracted = true;
  1114. while (Extracted) {
  1115. Extracted = false;
  1116. for (OffloadFile &Binary : Binaries) {
  1117. if (!Binary.getBinary())
  1118. continue;
  1119. // If we don't have an object file for this architecture do not
  1120. // extract.
  1121. if (IsArchive && !Syms.count(Binary))
  1122. continue;
  1123. Expected<bool> ExtractOrErr =
  1124. getSymbols(Binary.getBinary()->getImage(), Saver, Syms[Binary]);
  1125. if (!ExtractOrErr)
  1126. return ExtractOrErr.takeError();
  1127. Extracted = IsArchive && *ExtractOrErr;
  1128. if (!IsArchive || Extracted)
  1129. InputFiles.emplace_back(std::move(Binary));
  1130. // If we extracted any files we need to check all the symbols again.
  1131. if (Extracted)
  1132. break;
  1133. }
  1134. }
  1135. }
  1136. for (StringRef Library : Args.getAllArgValues(OPT_bitcode_library_EQ)) {
  1137. auto FileOrErr = getInputBitcodeLibrary(Library);
  1138. if (!FileOrErr)
  1139. return FileOrErr.takeError();
  1140. InputFiles.push_back(std::move(*FileOrErr));
  1141. }
  1142. return std::move(InputFiles);
  1143. }
  1144. } // namespace
  1145. int main(int Argc, char **Argv) {
  1146. InitLLVM X(Argc, Argv);
  1147. InitializeAllTargetInfos();
  1148. InitializeAllTargets();
  1149. InitializeAllTargetMCs();
  1150. InitializeAllAsmParsers();
  1151. InitializeAllAsmPrinters();
  1152. LinkerExecutable = Argv[0];
  1153. sys::PrintStackTraceOnErrorSignal(Argv[0]);
  1154. const OptTable &Tbl = getOptTable();
  1155. BumpPtrAllocator Alloc;
  1156. StringSaver Saver(Alloc);
  1157. auto Args = Tbl.parseArgs(Argc, Argv, OPT_INVALID, Saver, [&](StringRef Err) {
  1158. reportError(createStringError(inconvertibleErrorCode(), Err));
  1159. });
  1160. if (Args.hasArg(OPT_help) || Args.hasArg(OPT_help_hidden)) {
  1161. Tbl.printHelp(
  1162. outs(),
  1163. "clang-linker-wrapper [options] -- <options to passed to the linker>",
  1164. "\nA wrapper utility over the host linker. It scans the input files\n"
  1165. "for sections that require additional processing prior to linking.\n"
  1166. "The will then transparently pass all arguments and input to the\n"
  1167. "specified host linker to create the final binary.\n",
  1168. Args.hasArg(OPT_help_hidden), Args.hasArg(OPT_help_hidden));
  1169. return EXIT_SUCCESS;
  1170. }
  1171. if (Args.hasArg(OPT_v)) {
  1172. printVersion(outs());
  1173. return EXIT_SUCCESS;
  1174. }
  1175. // This forwards '-mllvm' arguments to LLVM if present.
  1176. SmallVector<const char *> NewArgv = {Argv[0]};
  1177. for (const opt::Arg *Arg : Args.filtered(OPT_mllvm))
  1178. NewArgv.push_back(Arg->getValue());
  1179. for (const opt::Arg *Arg : Args.filtered(OPT_offload_opt_eq_minus))
  1180. NewArgv.push_back(Args.MakeArgString(StringRef("-") + Arg->getValue()));
  1181. cl::ParseCommandLineOptions(NewArgv.size(), &NewArgv[0]);
  1182. Verbose = Args.hasArg(OPT_verbose);
  1183. DryRun = Args.hasArg(OPT_dry_run);
  1184. SaveTemps = Args.hasArg(OPT_save_temps);
  1185. ExecutableName = Args.getLastArgValue(OPT_o, "a.out");
  1186. CudaBinaryPath = Args.getLastArgValue(OPT_cuda_path_EQ).str();
  1187. parallel::strategy = hardware_concurrency(1);
  1188. if (auto *Arg = Args.getLastArg(OPT_wrapper_jobs)) {
  1189. unsigned Threads = 0;
  1190. if (!llvm::to_integer(Arg->getValue(), Threads) || Threads == 0)
  1191. reportError(createStringError(
  1192. inconvertibleErrorCode(), "%s: expected a positive integer, got '%s'",
  1193. Arg->getSpelling().data(), Arg->getValue()));
  1194. parallel::strategy = hardware_concurrency(Threads);
  1195. }
  1196. if (Args.hasArg(OPT_wrapper_time_trace_eq)) {
  1197. unsigned Granularity;
  1198. Args.getLastArgValue(OPT_wrapper_time_trace_granularity, "500")
  1199. .getAsInteger(10, Granularity);
  1200. timeTraceProfilerInitialize(Granularity, Argv[0]);
  1201. }
  1202. {
  1203. llvm::TimeTraceScope TimeScope("Execute linker wrapper");
  1204. // Extract the device input files stored in the host fat binary.
  1205. auto DeviceInputFiles = getDeviceInput(Args);
  1206. if (!DeviceInputFiles)
  1207. reportError(DeviceInputFiles.takeError());
  1208. // Link and wrap the device images extracted from the linker input.
  1209. auto FilesOrErr =
  1210. linkAndWrapDeviceFiles(*DeviceInputFiles, Args, Argv, Argc);
  1211. if (!FilesOrErr)
  1212. reportError(FilesOrErr.takeError());
  1213. // Run the host linking job with the rendered arguments.
  1214. if (Error Err = runLinker(*FilesOrErr, Args))
  1215. reportError(std::move(Err));
  1216. }
  1217. if (const opt::Arg *Arg = Args.getLastArg(OPT_wrapper_time_trace_eq)) {
  1218. if (Error Err = timeTraceProfilerWrite(Arg->getValue(), ExecutableName))
  1219. reportError(std::move(Err));
  1220. timeTraceProfilerCleanup();
  1221. }
  1222. // Remove the temporary files created.
  1223. if (!SaveTemps)
  1224. for (const auto &TempFile : TempFiles)
  1225. if (std::error_code EC = sys::fs::remove(TempFile))
  1226. reportError(createFileError(TempFile, EC));
  1227. return EXIT_SUCCESS;
  1228. }