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.<triple>.<arch>`
12 // and extracts it as a temporary file. The extracted device files will then be
13 // passed to a device linking job to create a final device image.
14 //
15 //===---------------------------------------------------------------------===//
16 
17 #include "OffloadWrapper.h"
18 #include "clang/Basic/Version.h"
19 #include "llvm/BinaryFormat/Magic.h"
20 #include "llvm/Bitcode/BitcodeWriter.h"
21 #include "llvm/CodeGen/CommandFlags.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DiagnosticPrinter.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IRReader/IRReader.h"
26 #include "llvm/LTO/LTO.h"
27 #include "llvm/MC/TargetRegistry.h"
28 #include "llvm/Object/Archive.h"
29 #include "llvm/Object/ArchiveWriter.h"
30 #include "llvm/Object/Binary.h"
31 #include "llvm/Object/ObjectFile.h"
32 #include "llvm/Object/OffloadBinary.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Errc.h"
35 #include "llvm/Support/FileOutputBuffer.h"
36 #include "llvm/Support/FileSystem.h"
37 #include "llvm/Support/Host.h"
38 #include "llvm/Support/InitLLVM.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/Path.h"
41 #include "llvm/Support/Program.h"
42 #include "llvm/Support/Signals.h"
43 #include "llvm/Support/SourceMgr.h"
44 #include "llvm/Support/StringSaver.h"
45 #include "llvm/Support/TargetSelect.h"
46 #include "llvm/Support/WithColor.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Target/TargetMachine.h"
49 
50 using namespace llvm;
51 using namespace llvm::object;
52 
53 static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);
54 
55 enum DebugKind {
56   NoDebugInfo,
57   DirectivesOnly,
58   FullDebugInfo,
59 };
60 
61 // Mark all our options with this category, everything else (except for -help)
62 // will be hidden.
63 static cl::OptionCategory
64     ClangLinkerWrapperCategory("clang-linker-wrapper options");
65 
66 static cl::opt<bool> StripSections(
67     "strip-sections", cl::ZeroOrMore,
68     cl::desc("Strip offloading sections from the host object file."),
69     cl::init(false), cl::cat(ClangLinkerWrapperCategory));
70 
71 static cl::opt<std::string> LinkerUserPath("linker-path", cl::Required,
72                                            cl::desc("Path of linker binary"),
73                                            cl::cat(ClangLinkerWrapperCategory));
74 
75 static cl::opt<std::string>
76     TargetFeatures("target-feature", cl::ZeroOrMore,
77                    cl::desc("Target features for triple"),
78                    cl::cat(ClangLinkerWrapperCategory));
79 
80 static cl::opt<std::string> OptLevel("opt-level", cl::ZeroOrMore,
81                                      cl::desc("Optimization level for LTO"),
82                                      cl::init("O2"),
83                                      cl::cat(ClangLinkerWrapperCategory));
84 
85 static cl::list<std::string>
86     BitcodeLibraries("target-library", cl::ZeroOrMore,
87                      cl::desc("Path for the target bitcode library"),
88                      cl::cat(ClangLinkerWrapperCategory));
89 
90 static cl::opt<bool> EmbedBitcode(
91     "target-embed-bc", cl::ZeroOrMore,
92     cl::desc("Embed linked bitcode instead of an executable device image"),
93     cl::init(false), cl::cat(ClangLinkerWrapperCategory));
94 
95 static cl::opt<bool> DryRun(
96     "dry-run", cl::ZeroOrMore,
97     cl::desc("List the linker commands to be run without executing them"),
98     cl::init(false), cl::cat(ClangLinkerWrapperCategory));
99 
100 static cl::opt<bool>
101     PrintWrappedModule("print-wrapped-module", cl::ZeroOrMore,
102                        cl::desc("Print the wrapped module's IR for testing"),
103                        cl::init(false), cl::cat(ClangLinkerWrapperCategory));
104 
105 static cl::opt<std::string>
106     HostTriple("host-triple", cl::ZeroOrMore,
107                cl::desc("Triple to use for the host compilation"),
108                cl::init(sys::getDefaultTargetTriple()),
109                cl::cat(ClangLinkerWrapperCategory));
110 
111 static cl::list<std::string>
112     PtxasArgs("ptxas-args", cl::ZeroOrMore,
113               cl::desc("Argument to pass to the ptxas invocation"),
114               cl::cat(ClangLinkerWrapperCategory));
115 
116 static cl::opt<bool> Verbose("v", cl::ZeroOrMore,
117                              cl::desc("Verbose output from tools"),
118                              cl::init(false),
119                              cl::cat(ClangLinkerWrapperCategory));
120 
121 static cl::opt<DebugKind> DebugInfo(
122     cl::desc("Choose debugging level:"), cl::init(NoDebugInfo),
123     cl::values(clEnumValN(NoDebugInfo, "g0", "No debug information"),
124                clEnumValN(DirectivesOnly, "gline-directives-only",
125                           "Direction information"),
126                clEnumValN(FullDebugInfo, "g", "Full debugging support")));
127 
128 static cl::opt<bool> SaveTemps("save-temps", cl::ZeroOrMore,
129                                cl::desc("Save intermediary results."),
130                                cl::cat(ClangLinkerWrapperCategory));
131 
132 static cl::opt<std::string> CudaPath("cuda-path", cl::ZeroOrMore,
133                                      cl::desc("Save intermediary results."),
134                                      cl::cat(ClangLinkerWrapperCategory));
135 
136 // Do not parse linker options.
137 static cl::list<std::string>
138     HostLinkerArgs(cl::Positional,
139                    cl::desc("<options to be passed to linker>..."));
140 
141 /// Path of the current binary.
142 static const char *LinkerExecutable;
143 
144 /// Filename of the executable being created.
145 static StringRef ExecutableName;
146 
147 /// System root if passed in to the linker via. '--sysroot='.
148 static StringRef Sysroot = "";
149 
150 /// Binary path for the CUDA installation.
151 static std::string CudaBinaryPath;
152 
153 /// Temporary files created by the linker wrapper.
154 static SmallVector<std::string, 16> TempFiles;
155 
156 /// Codegen flags for LTO backend.
157 static codegen::RegisterCodeGenFlags CodeGenFlags;
158 
159 /// Magic section string that marks the existence of offloading data. The
160 /// section will contain one or more offloading binaries stored contiguously.
161 #define OFFLOAD_SECTION_MAGIC_STR ".llvm.offloading"
162 
163 /// Information for a device offloading file extracted from the host.
164 struct DeviceFile {
165   DeviceFile(StringRef Kind, StringRef TheTriple, StringRef Arch,
166              StringRef Filename)
167       : Kind(Kind), TheTriple(TheTriple), Arch(Arch), Filename(Filename) {}
168 
169   std::string Kind;
170   std::string TheTriple;
171   std::string Arch;
172   std::string Filename;
173 };
174 
175 namespace llvm {
176 /// Helper that allows DeviceFile to be used as a key in a DenseMap.
177 template <> struct DenseMapInfo<DeviceFile> {
178   static DeviceFile getEmptyKey() {
179     return {DenseMapInfo<StringRef>::getEmptyKey(),
180             DenseMapInfo<StringRef>::getEmptyKey(),
181             DenseMapInfo<StringRef>::getEmptyKey(),
182             DenseMapInfo<StringRef>::getEmptyKey()};
183   }
184   static DeviceFile getTombstoneKey() {
185     return {DenseMapInfo<StringRef>::getTombstoneKey(),
186             DenseMapInfo<StringRef>::getTombstoneKey(),
187             DenseMapInfo<StringRef>::getTombstoneKey(),
188             DenseMapInfo<StringRef>::getTombstoneKey()};
189   }
190   static unsigned getHashValue(const DeviceFile &I) {
191     return DenseMapInfo<StringRef>::getHashValue(I.TheTriple) ^
192            DenseMapInfo<StringRef>::getHashValue(I.Arch);
193   }
194   static bool isEqual(const DeviceFile &LHS, const DeviceFile &RHS) {
195     return LHS.TheTriple == RHS.TheTriple && LHS.Arch == RHS.Arch;
196   }
197 };
198 } // namespace llvm
199 
200 namespace {
201 
202 Expected<Optional<std::string>>
203 extractFromBuffer(std::unique_ptr<MemoryBuffer> Buffer,
204                   SmallVectorImpl<DeviceFile> &DeviceFiles);
205 
206 void printCommands(ArrayRef<StringRef> CmdArgs) {
207   if (CmdArgs.empty())
208     return;
209 
210   llvm::errs() << " \"" << CmdArgs.front() << "\" ";
211   for (auto IC = std::next(CmdArgs.begin()), IE = CmdArgs.end(); IC != IE; ++IC)
212     llvm::errs() << *IC << (std::next(IC) != IE ? " " : "\n");
213 }
214 
215 std::string getMainExecutable(const char *Name) {
216   void *Ptr = (void *)(intptr_t)&getMainExecutable;
217   auto COWPath = sys::fs::getMainExecutable(Name, Ptr);
218   return sys::path::parent_path(COWPath).str();
219 }
220 
221 /// Extract the device file from the string '<kind>-<triple>-<arch>=<library>'.
222 DeviceFile getBitcodeLibrary(StringRef LibraryStr) {
223   auto DeviceAndPath = StringRef(LibraryStr).split('=');
224   auto StringAndArch = DeviceAndPath.first.rsplit('-');
225   auto KindAndTriple = StringAndArch.first.split('-');
226   return DeviceFile(KindAndTriple.first, KindAndTriple.second,
227                     StringAndArch.second, DeviceAndPath.second);
228 }
229 
230 /// Get a temporary filename suitable for output.
231 Error createOutputFile(const Twine &Prefix, StringRef Extension,
232                        SmallString<128> &NewFilename) {
233   if (!SaveTemps) {
234     if (std::error_code EC =
235             sys::fs::createTemporaryFile(Prefix, Extension, NewFilename))
236       return createFileError(NewFilename, EC);
237     TempFiles.push_back(static_cast<std::string>(NewFilename));
238   } else {
239     const Twine &Filename = Prefix + "." + Extension;
240     Filename.toNullTerminatedStringRef(NewFilename);
241   }
242 
243   return Error::success();
244 }
245 
246 /// Execute the command \p ExecutablePath with the arguments \p Args.
247 Error executeCommands(StringRef ExecutablePath, ArrayRef<StringRef> Args) {
248   if (Verbose || DryRun)
249     printCommands(Args);
250 
251   if (!DryRun)
252     if (sys::ExecuteAndWait(ExecutablePath, Args))
253       return createStringError(inconvertibleErrorCode(),
254                                "'" + sys::path::filename(ExecutablePath) + "'" +
255                                    " failed");
256   return Error::success();
257 }
258 
259 Expected<std::string> findProgram(StringRef Name, ArrayRef<StringRef> Paths) {
260 
261   ErrorOr<std::string> Path = sys::findProgramByName(Name, Paths);
262   if (!Path)
263     Path = sys::findProgramByName(Name);
264   if (!Path && DryRun)
265     return Name.str();
266   if (!Path)
267     return createStringError(Path.getError(),
268                              "Unable to find '" + Name + "' in path");
269   return *Path;
270 }
271 
272 Error runLinker(std::string &LinkerPath, SmallVectorImpl<std::string> &Args) {
273   std::vector<StringRef> LinkerArgs;
274   LinkerArgs.push_back(LinkerPath);
275   for (auto &Arg : Args)
276     LinkerArgs.push_back(Arg);
277 
278   if (Error Err = executeCommands(LinkerPath, LinkerArgs))
279     return Err;
280   return Error::success();
281 }
282 
283 void PrintVersion(raw_ostream &OS) {
284   OS << clang::getClangToolFullVersion("clang-linker-wrapper") << '\n';
285 }
286 
287 void removeFromCompilerUsed(Module &M, GlobalValue &Value) {
288   GlobalVariable *GV = M.getGlobalVariable("llvm.compiler.used");
289   Type *Int8PtrTy = Type::getInt8PtrTy(M.getContext());
290   Constant *ValueToRemove =
291       ConstantExpr::getPointerBitCastOrAddrSpaceCast(&Value, Int8PtrTy);
292   SmallPtrSet<Constant *, 16> InitAsSet;
293   SmallVector<Constant *, 16> Init;
294   if (GV) {
295     if (GV->hasInitializer()) {
296       auto *CA = cast<ConstantArray>(GV->getInitializer());
297       for (auto &Op : CA->operands()) {
298         Constant *C = cast_or_null<Constant>(Op);
299         if (C != ValueToRemove && InitAsSet.insert(C).second)
300           Init.push_back(C);
301       }
302     }
303     GV->eraseFromParent();
304   }
305 
306   if (Init.empty())
307     return;
308 
309   ArrayType *ATy = ArrayType::get(Int8PtrTy, Init.size());
310   GV = new llvm::GlobalVariable(M, ATy, false, GlobalValue::AppendingLinkage,
311                                 ConstantArray::get(ATy, Init),
312                                 "llvm.compiler.used");
313   GV->setSection("llvm.metadata");
314 }
315 
316 /// Attempts to extract all the embedded device images contained inside the
317 /// buffer \p Contents. The buffer is expected to contain a valid offloading
318 /// binary format.
319 Error extractOffloadFiles(StringRef Contents, StringRef Prefix,
320                           SmallVectorImpl<DeviceFile> &DeviceFiles) {
321   uint64_t Offset = 0;
322   // There could be multiple offloading binaries stored at this section.
323   while (Offset < Contents.size()) {
324     std::unique_ptr<MemoryBuffer> Buffer =
325         MemoryBuffer::getMemBuffer(Contents.drop_front(Offset), "",
326                                    /*RequiresNullTerminator*/ false);
327     auto BinaryOrErr = OffloadBinary::create(*Buffer);
328     if (!BinaryOrErr)
329       return BinaryOrErr.takeError();
330     OffloadBinary &Binary = **BinaryOrErr;
331 
332     if (Binary.getVersion() != 1)
333       return createStringError(inconvertibleErrorCode(),
334                                "Incompatible device image version");
335 
336     StringRef Kind = getOffloadKindName(Binary.getOffloadKind());
337     StringRef Suffix = getImageKindName(Binary.getImageKind());
338 
339     SmallString<128> TempFile;
340     if (Error Err =
341             createOutputFile(Prefix + "-" + Kind + "-" + Binary.getTriple() +
342                                  "-" + Binary.getArch(),
343                              Suffix, TempFile))
344       return Err;
345 
346     Expected<std::unique_ptr<FileOutputBuffer>> OutputOrErr =
347         FileOutputBuffer::create(TempFile, Binary.getImage().size());
348     if (!OutputOrErr)
349       return OutputOrErr.takeError();
350     std::unique_ptr<FileOutputBuffer> Output = std::move(*OutputOrErr);
351     std::copy(Binary.getImage().bytes_begin(), Binary.getImage().bytes_end(),
352               Output->getBufferStart());
353     if (Error E = Output->commit())
354       return E;
355 
356     DeviceFiles.emplace_back(Kind, Binary.getTriple(), Binary.getArch(),
357                              TempFile);
358 
359     Offset += Binary.getSize();
360   }
361 
362   return Error::success();
363 }
364 
365 Expected<Optional<std::string>>
366 extractFromBinary(const ObjectFile &Obj,
367                   SmallVectorImpl<DeviceFile> &DeviceFiles) {
368   StringRef Extension = sys::path::extension(Obj.getFileName()).drop_front();
369   StringRef Prefix = sys::path::stem(Obj.getFileName());
370   SmallVector<StringRef, 4> ToBeStripped;
371 
372   // Extract offloading binaries from sections with the name `.llvm.offloading`.
373   for (const SectionRef &Sec : Obj.sections()) {
374     Expected<StringRef> Name = Sec.getName();
375     if (!Name || !Name->equals(OFFLOAD_SECTION_MAGIC_STR))
376       continue;
377 
378     Expected<StringRef> Contents = Sec.getContents();
379     if (!Contents)
380       return Contents.takeError();
381 
382     if (Error Err = extractOffloadFiles(*Contents, Prefix, DeviceFiles))
383       return std::move(Err);
384 
385     ToBeStripped.push_back(*Name);
386   }
387 
388   if (ToBeStripped.empty() || !StripSections)
389     return None;
390 
391   // If the object file to strip doesn't exist we need to write it so we can
392   // pass it to llvm-strip.
393   SmallString<128> StripFile = Obj.getFileName();
394   if (!sys::fs::exists(StripFile)) {
395     SmallString<128> TempFile;
396     if (Error Err = createOutputFile(
397             sys::path::stem(StripFile),
398             sys::path::extension(StripFile).drop_front(), TempFile))
399       return std::move(Err);
400 
401     auto Contents = Obj.getMemoryBufferRef().getBuffer();
402     Expected<std::unique_ptr<FileOutputBuffer>> OutputOrErr =
403         FileOutputBuffer::create(TempFile, Contents.size());
404     if (!OutputOrErr)
405       return OutputOrErr.takeError();
406     std::unique_ptr<FileOutputBuffer> Output = std::move(*OutputOrErr);
407     std::copy(Contents.begin(), Contents.end(), Output->getBufferStart());
408     if (Error E = Output->commit())
409       return std::move(E);
410     StripFile = TempFile;
411   }
412 
413   // We will use llvm-strip to remove the now unneeded section containing the
414   // offloading code.
415   Expected<std::string> StripPath =
416       findProgram("llvm-strip", {getMainExecutable("llvm-strip")});
417   if (!StripPath)
418     return StripPath.takeError();
419 
420   SmallString<128> TempFile;
421   if (Error Err = createOutputFile(Prefix + "-host", Extension, TempFile))
422     return std::move(Err);
423 
424   SmallVector<StringRef, 8> StripArgs;
425   StripArgs.push_back(*StripPath);
426   StripArgs.push_back("--no-strip-all");
427   StripArgs.push_back(StripFile);
428   for (auto &Section : ToBeStripped) {
429     StripArgs.push_back("--remove-section");
430     StripArgs.push_back(Section);
431   }
432   StripArgs.push_back("-o");
433   StripArgs.push_back(TempFile);
434 
435   if (Error Err = executeCommands(*StripPath, StripArgs))
436     return std::move(Err);
437 
438   return static_cast<std::string>(TempFile);
439 }
440 
441 Expected<Optional<std::string>>
442 extractFromBitcode(std::unique_ptr<MemoryBuffer> Buffer,
443                    SmallVectorImpl<DeviceFile> &DeviceFiles) {
444   LLVMContext Context;
445   SMDiagnostic Err;
446   std::unique_ptr<Module> M = getLazyIRModule(std::move(Buffer), Err, Context);
447   if (!M)
448     return createStringError(inconvertibleErrorCode(),
449                              "Failed to create module");
450 
451   StringRef Extension = sys::path::extension(M->getName()).drop_front();
452   StringRef Prefix =
453       sys::path::stem(M->getName()).take_until([](char C) { return C == '-'; });
454 
455   SmallVector<GlobalVariable *, 4> ToBeDeleted;
456 
457   // Extract offloading data from globals with the `.llvm.offloading` section
458   // name.
459   for (GlobalVariable &GV : M->globals()) {
460     if (!GV.hasSection() || !GV.getSection().equals(OFFLOAD_SECTION_MAGIC_STR))
461       continue;
462 
463     auto *CDS = dyn_cast<ConstantDataSequential>(GV.getInitializer());
464     if (!CDS)
465       continue;
466 
467     StringRef Contents = CDS->getAsString();
468 
469     if (Error Err = extractOffloadFiles(Contents, Prefix, DeviceFiles))
470       return std::move(Err);
471 
472     ToBeDeleted.push_back(&GV);
473   }
474 
475   if (ToBeDeleted.empty() || !StripSections)
476     return None;
477 
478   // We need to materialize the lazy module before we make any changes.
479   if (Error Err = M->materializeAll())
480     return std::move(Err);
481 
482   // Remove the global from the module and write it to a new file.
483   for (GlobalVariable *GV : ToBeDeleted) {
484     removeFromCompilerUsed(*M, *GV);
485     GV->eraseFromParent();
486   }
487 
488   SmallString<128> TempFile;
489   if (Error Err = createOutputFile(Prefix + "-host", Extension, TempFile))
490     return std::move(Err);
491 
492   std::error_code EC;
493   raw_fd_ostream HostOutput(TempFile, EC, sys::fs::OF_None);
494   if (EC)
495     return createFileError(TempFile, EC);
496   WriteBitcodeToFile(*M, HostOutput);
497   return static_cast<std::string>(TempFile);
498 }
499 
500 Expected<Optional<std::string>>
501 extractFromArchive(const Archive &Library,
502                    SmallVectorImpl<DeviceFile> &DeviceFiles) {
503   bool NewMembers = false;
504   SmallVector<NewArchiveMember, 8> Members;
505 
506   // Try to extract device code from each file stored in the static archive.
507   // Save the stripped archive members to create a new host archive with the
508   // offloading code removed.
509   Error Err = Error::success();
510   for (auto Child : Library.children(Err)) {
511     auto ChildBufferRefOrErr = Child.getMemoryBufferRef();
512     if (!ChildBufferRefOrErr)
513       return ChildBufferRefOrErr.takeError();
514     std::unique_ptr<MemoryBuffer> ChildBuffer =
515         MemoryBuffer::getMemBuffer(*ChildBufferRefOrErr, false);
516 
517     auto FileOrErr = extractFromBuffer(std::move(ChildBuffer), DeviceFiles);
518     if (!FileOrErr)
519       return FileOrErr.takeError();
520 
521     // If we created a new stripped host file, use it to create a new archive
522     // member, otherwise use the old member.
523     if (!FileOrErr->hasValue()) {
524       Expected<NewArchiveMember> NewMember =
525           NewArchiveMember::getOldMember(Child, true);
526       if (!NewMember)
527         return NewMember.takeError();
528       Members.push_back(std::move(*NewMember));
529     } else {
530       Expected<NewArchiveMember> NewMember =
531           NewArchiveMember::getFile(**FileOrErr, true);
532       if (!NewMember)
533         return NewMember.takeError();
534       Members.push_back(std::move(*NewMember));
535       NewMembers = true;
536 
537       // We no longer need the stripped file, remove it.
538       if (std::error_code EC = sys::fs::remove(**FileOrErr))
539         return createFileError(**FileOrErr, EC);
540     }
541   }
542 
543   if (Err)
544     return std::move(Err);
545 
546   if (!NewMembers || !StripSections)
547     return None;
548 
549   // Create a new static library using the stripped host files.
550   SmallString<128> TempFile;
551   StringRef Prefix = sys::path::stem(Library.getFileName());
552   if (Error Err = createOutputFile(Prefix + "-host", "a", TempFile))
553     return std::move(Err);
554 
555   std::unique_ptr<MemoryBuffer> Buffer =
556       MemoryBuffer::getMemBuffer(Library.getMemoryBufferRef(), false);
557   if (Error Err = writeArchive(TempFile, Members, true, Library.kind(), true,
558                                Library.isThin(), std::move(Buffer)))
559     return std::move(Err);
560 
561   return static_cast<std::string>(TempFile);
562 }
563 
564 /// Extracts embedded device offloading code from a memory \p Buffer to a list
565 /// of \p DeviceFiles. If device code was extracted a new file with the embedded
566 /// device code stripped from the buffer will be returned.
567 Expected<Optional<std::string>>
568 extractFromBuffer(std::unique_ptr<MemoryBuffer> Buffer,
569                   SmallVectorImpl<DeviceFile> &DeviceFiles) {
570   file_magic Type = identify_magic(Buffer->getBuffer());
571   switch (Type) {
572   case file_magic::bitcode:
573     return extractFromBitcode(std::move(Buffer), DeviceFiles);
574   case file_magic::elf_relocatable:
575   case file_magic::macho_object:
576   case file_magic::coff_object: {
577     Expected<std::unique_ptr<ObjectFile>> ObjFile =
578         ObjectFile::createObjectFile(*Buffer, Type);
579     if (!ObjFile)
580       return ObjFile.takeError();
581     return extractFromBinary(*ObjFile->get(), DeviceFiles);
582   }
583   case file_magic::archive: {
584     Expected<std::unique_ptr<llvm::object::Archive>> LibFile =
585         object::Archive::create(*Buffer);
586     if (!LibFile)
587       return LibFile.takeError();
588     return extractFromArchive(*LibFile->get(), DeviceFiles);
589   }
590   default:
591     return None;
592   }
593 }
594 
595 // TODO: Move these to a separate file.
596 namespace nvptx {
597 Expected<std::string> assemble(StringRef InputFile, Triple TheTriple,
598                                StringRef Arch, bool RDC = true) {
599   // NVPTX uses the ptxas binary to create device object files.
600   Expected<std::string> PtxasPath = findProgram("ptxas", {CudaBinaryPath});
601   if (!PtxasPath)
602     return PtxasPath.takeError();
603 
604   // Create a new file to write the linked device image to.
605   SmallString<128> TempFile;
606   if (Error Err =
607           createOutputFile(sys::path::filename(ExecutableName) + "-device-" +
608                                TheTriple.getArchName() + "-" + Arch,
609                            "cubin", TempFile))
610     return std::move(Err);
611 
612   SmallVector<StringRef, 16> CmdArgs;
613   std::string Opt = "-" + OptLevel;
614   CmdArgs.push_back(*PtxasPath);
615   CmdArgs.push_back(TheTriple.isArch64Bit() ? "-m64" : "-m32");
616   if (Verbose)
617     CmdArgs.push_back("-v");
618   if (DebugInfo == DirectivesOnly && OptLevel[1] == '0')
619     CmdArgs.push_back("-lineinfo");
620   else if (DebugInfo == FullDebugInfo && OptLevel[1] == '0')
621     CmdArgs.push_back("-g");
622   for (auto &Arg : PtxasArgs)
623     CmdArgs.push_back(Arg);
624   CmdArgs.push_back("-o");
625   CmdArgs.push_back(TempFile);
626   CmdArgs.push_back(Opt);
627   CmdArgs.push_back("--gpu-name");
628   CmdArgs.push_back(Arch);
629   if (RDC)
630     CmdArgs.push_back("-c");
631 
632   CmdArgs.push_back(InputFile);
633 
634   if (Verbose)
635     printCommands(CmdArgs);
636 
637   if (Error Err = executeCommands(*PtxasPath, CmdArgs))
638     return std::move(Err);
639 
640   return static_cast<std::string>(TempFile);
641 }
642 
643 Expected<std::string> link(ArrayRef<std::string> InputFiles, Triple TheTriple,
644                            StringRef Arch) {
645   // NVPTX uses the nvlink binary to link device object files.
646   Expected<std::string> NvlinkPath = findProgram("nvlink", {CudaBinaryPath});
647   if (!NvlinkPath)
648     return NvlinkPath.takeError();
649 
650   // Create a new file to write the linked device image to.
651   SmallString<128> TempFile;
652   if (Error Err =
653           createOutputFile(sys::path::filename(ExecutableName) + "-device-" +
654                                TheTriple.getArchName() + "-" + Arch,
655                            "out", TempFile))
656     return std::move(Err);
657 
658   SmallVector<StringRef, 16> CmdArgs;
659   CmdArgs.push_back(*NvlinkPath);
660   CmdArgs.push_back(TheTriple.isArch64Bit() ? "-m64" : "-m32");
661   if (Verbose)
662     CmdArgs.push_back("-v");
663   if (DebugInfo != NoDebugInfo)
664     CmdArgs.push_back("-g");
665   CmdArgs.push_back("-o");
666   CmdArgs.push_back(TempFile);
667   CmdArgs.push_back("-arch");
668   CmdArgs.push_back(Arch);
669 
670   // Add extracted input files.
671   for (StringRef Input : InputFiles)
672     CmdArgs.push_back(Input);
673 
674   if (Verbose)
675     printCommands(CmdArgs);
676 
677   if (Error Err = executeCommands(*NvlinkPath, CmdArgs))
678     return std::move(Err);
679 
680   return static_cast<std::string>(TempFile);
681 }
682 } // namespace nvptx
683 namespace amdgcn {
684 Expected<std::string> link(ArrayRef<std::string> InputFiles, Triple TheTriple,
685                            StringRef Arch) {
686   // AMDGPU uses lld to link device object files.
687   Expected<std::string> LLDPath = findProgram("lld", {CudaBinaryPath});
688   if (!LLDPath)
689     return LLDPath.takeError();
690 
691   // Create a new file to write the linked device image to.
692   SmallString<128> TempFile;
693   if (Error Err = createOutputFile(sys::path::filename(ExecutableName) + "-" +
694                                        TheTriple.getArchName() + "-" + Arch,
695                                    "out", TempFile))
696     return std::move(Err);
697 
698   SmallVector<StringRef, 16> CmdArgs;
699   CmdArgs.push_back(*LLDPath);
700   CmdArgs.push_back("-flavor");
701   CmdArgs.push_back("gnu");
702   CmdArgs.push_back("--no-undefined");
703   CmdArgs.push_back("-shared");
704   CmdArgs.push_back("-o");
705   CmdArgs.push_back(TempFile);
706 
707   // Add extracted input files.
708   for (StringRef Input : InputFiles)
709     CmdArgs.push_back(Input);
710 
711   if (Verbose)
712     printCommands(CmdArgs);
713 
714   if (Error Err = executeCommands(*LLDPath, CmdArgs))
715     return std::move(Err);
716 
717   return static_cast<std::string>(TempFile);
718 }
719 } // namespace amdgcn
720 
721 namespace generic {
722 
723 const char *getLDMOption(const llvm::Triple &T) {
724   switch (T.getArch()) {
725   case llvm::Triple::x86:
726     if (T.isOSIAMCU())
727       return "elf_iamcu";
728     return "elf_i386";
729   case llvm::Triple::aarch64:
730     return "aarch64linux";
731   case llvm::Triple::aarch64_be:
732     return "aarch64linuxb";
733   case llvm::Triple::ppc64:
734     return "elf64ppc";
735   case llvm::Triple::ppc64le:
736     return "elf64lppc";
737   case llvm::Triple::x86_64:
738     if (T.isX32())
739       return "elf32_x86_64";
740     return "elf_x86_64";
741   case llvm::Triple::ve:
742     return "elf64ve";
743   default:
744     return nullptr;
745   }
746 }
747 
748 Expected<std::string> link(ArrayRef<std::string> InputFiles, Triple TheTriple,
749                            StringRef Arch) {
750   // Create a new file to write the linked device image to.
751   SmallString<128> TempFile;
752   if (Error Err = createOutputFile(sys::path::filename(ExecutableName) + "-" +
753                                        TheTriple.getArchName() + "-" + Arch,
754                                    "out", TempFile))
755     return std::move(Err);
756 
757   // Use the host linker to perform generic offloading. Use the same libraries
758   // and paths as the host application does.
759   SmallVector<StringRef, 16> CmdArgs;
760   CmdArgs.push_back(LinkerUserPath);
761   CmdArgs.push_back("-m");
762   CmdArgs.push_back(getLDMOption(TheTriple));
763   CmdArgs.push_back("-shared");
764   for (auto AI = HostLinkerArgs.begin(), AE = HostLinkerArgs.end(); AI != AE;
765        ++AI) {
766     StringRef Arg = *AI;
767     if (Arg.startswith("-L"))
768       CmdArgs.push_back(Arg);
769     else if (Arg.startswith("-l"))
770       CmdArgs.push_back(Arg);
771     else if (Arg.startswith("--as-needed"))
772       CmdArgs.push_back(Arg);
773     else if (Arg.startswith("--no-as-needed"))
774       CmdArgs.push_back(Arg);
775     else if (Arg.startswith("-rpath")) {
776       CmdArgs.push_back(Arg);
777       CmdArgs.push_back(*std::next(AI));
778     } else if (Arg.startswith("-dynamic-linker")) {
779       CmdArgs.push_back(Arg);
780       CmdArgs.push_back(*std::next(AI));
781     }
782   }
783   CmdArgs.push_back("-Bsymbolic");
784   CmdArgs.push_back("-o");
785   CmdArgs.push_back(TempFile);
786 
787   // Add extracted input files.
788   for (StringRef Input : InputFiles)
789     CmdArgs.push_back(Input);
790 
791   if (Verbose)
792     printCommands(CmdArgs);
793 
794   if (Error Err = executeCommands(LinkerUserPath, CmdArgs))
795     return std::move(Err);
796 
797   return static_cast<std::string>(TempFile);
798 }
799 } // namespace generic
800 
801 Expected<std::string> linkDevice(ArrayRef<std::string> InputFiles,
802                                  Triple TheTriple, StringRef Arch) {
803   switch (TheTriple.getArch()) {
804   case Triple::nvptx:
805   case Triple::nvptx64:
806     return nvptx::link(InputFiles, TheTriple, Arch);
807   case Triple::amdgcn:
808     return amdgcn::link(InputFiles, TheTriple, Arch);
809   case Triple::x86:
810   case Triple::x86_64:
811   case Triple::aarch64:
812   case Triple::aarch64_be:
813   case Triple::ppc64:
814   case Triple::ppc64le:
815     return generic::link(InputFiles, TheTriple, Arch);
816   default:
817     return createStringError(inconvertibleErrorCode(),
818                              TheTriple.getArchName() +
819                                  " linking is not supported");
820   }
821 }
822 
823 void diagnosticHandler(const DiagnosticInfo &DI) {
824   std::string ErrStorage;
825   raw_string_ostream OS(ErrStorage);
826   DiagnosticPrinterRawOStream DP(OS);
827   DI.print(DP);
828 
829   switch (DI.getSeverity()) {
830   case DS_Error:
831     WithColor::error(errs(), LinkerExecutable) << ErrStorage << "\n";
832     break;
833   case DS_Warning:
834     WithColor::warning(errs(), LinkerExecutable) << ErrStorage << "\n";
835     break;
836   case DS_Note:
837     WithColor::note(errs(), LinkerExecutable) << ErrStorage << "\n";
838     break;
839   case DS_Remark:
840     WithColor::remark(errs()) << ErrStorage << "\n";
841     break;
842   }
843 }
844 
845 // Get the target features passed in from the driver as <triple>=<features>.
846 std::vector<std::string> getTargetFeatures(const Triple &TheTriple) {
847   std::vector<std::string> Features;
848   auto TargetAndFeatures = StringRef(TargetFeatures).split('=');
849   if (TargetAndFeatures.first != TheTriple.getTriple())
850     return Features;
851 
852   for (auto Feature : llvm::split(TargetAndFeatures.second, ','))
853     Features.push_back(Feature.str());
854   return Features;
855 }
856 
857 CodeGenOpt::Level getCGOptLevel(unsigned OptLevel) {
858   switch (OptLevel) {
859   case 0:
860     return CodeGenOpt::None;
861   case 1:
862     return CodeGenOpt::Less;
863   case 2:
864     return CodeGenOpt::Default;
865   case 3:
866     return CodeGenOpt::Aggressive;
867   }
868   llvm_unreachable("Invalid optimization level");
869 }
870 
871 template <typename ModuleHook = function_ref<bool(size_t, const Module &)>>
872 std::unique_ptr<lto::LTO> createLTO(
873     const Triple &TheTriple, StringRef Arch, bool WholeProgram,
874     ModuleHook Hook = [](size_t, const Module &) { return true; }) {
875   lto::Config Conf;
876   lto::ThinBackend Backend;
877   // TODO: Handle index-only thin-LTO
878   Backend =
879       lto::createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
880 
881   Conf.CPU = Arch.str();
882   Conf.Options = codegen::InitTargetOptionsFromCodeGenFlags(TheTriple);
883 
884   Conf.MAttrs = getTargetFeatures(TheTriple);
885   Conf.CGOptLevel = getCGOptLevel(OptLevel[1] - '0');
886   Conf.OptLevel = OptLevel[1] - '0';
887   if (Conf.OptLevel > 0)
888     Conf.UseDefaultPipeline = true;
889   Conf.DefaultTriple = TheTriple.getTriple();
890   Conf.DiagHandler = diagnosticHandler;
891 
892   Conf.PTO.LoopVectorization = Conf.OptLevel > 1;
893   Conf.PTO.SLPVectorization = Conf.OptLevel > 1;
894 
895   if (SaveTemps) {
896     auto HandleError = [&](Error Err) {
897       logAllUnhandledErrors(std::move(Err),
898                             WithColor::error(errs(), LinkerExecutable));
899       exit(1);
900     };
901     Conf.PostInternalizeModuleHook = [&](size_t, const Module &M) {
902       SmallString<128> TempFile;
903       if (Error Err = createOutputFile(sys::path::filename(ExecutableName) +
904                                            "-device-" + TheTriple.getTriple(),
905                                        "bc", TempFile))
906         HandleError(std::move(Err));
907 
908       std::error_code EC;
909       raw_fd_ostream LinkedBitcode(TempFile, EC, sys::fs::OF_None);
910       if (EC)
911         HandleError(errorCodeToError(EC));
912       WriteBitcodeToFile(M, LinkedBitcode);
913       return true;
914     };
915   }
916   Conf.PostOptModuleHook = Hook;
917   if (TheTriple.isNVPTX())
918     Conf.CGFileType = CGFT_AssemblyFile;
919   else
920     Conf.CGFileType = CGFT_ObjectFile;
921 
922   // TODO: Handle remark files
923   Conf.HasWholeProgramVisibility = WholeProgram;
924 
925   return std::make_unique<lto::LTO>(std::move(Conf), Backend);
926 }
927 
928 // Returns true if \p S is valid as a C language identifier and will be given
929 // `__start_` and `__stop_` symbols.
930 bool isValidCIdentifier(StringRef S) {
931   return !S.empty() && (isAlpha(S[0]) || S[0] == '_') &&
932          std::all_of(S.begin() + 1, S.end(),
933                      [](char C) { return C == '_' || isAlnum(C); });
934 }
935 
936 Error linkBitcodeFiles(SmallVectorImpl<std::string> &InputFiles,
937                        const Triple &TheTriple, StringRef Arch,
938                        bool &WholeProgram) {
939   SmallVector<std::unique_ptr<MemoryBuffer>, 4> SavedBuffers;
940   SmallVector<std::unique_ptr<lto::InputFile>, 4> BitcodeFiles;
941   SmallVector<std::string, 4> NewInputFiles;
942   DenseSet<StringRef> UsedInRegularObj;
943   DenseSet<StringRef> UsedInSharedLib;
944   BumpPtrAllocator Alloc;
945   StringSaver Saver(Alloc);
946 
947   // Search for bitcode files in the input and create an LTO input file. If it
948   // is not a bitcode file, scan its symbol table for symbols we need to
949   // save.
950   for (StringRef File : InputFiles) {
951     ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
952         MemoryBuffer::getFileOrSTDIN(File);
953     if (std::error_code EC = BufferOrErr.getError())
954       return createFileError(File, EC);
955 
956     file_magic Type = identify_magic((*BufferOrErr)->getBuffer());
957     if (Type != file_magic::bitcode) {
958       Expected<std::unique_ptr<ObjectFile>> ObjFile =
959           ObjectFile::createObjectFile(**BufferOrErr, Type);
960       if (!ObjFile)
961         return ObjFile.takeError();
962 
963       NewInputFiles.push_back(File.str());
964       for (auto &Sym : (*ObjFile)->symbols()) {
965         Expected<StringRef> Name = Sym.getName();
966         if (!Name)
967           return Name.takeError();
968 
969         // Record if we've seen these symbols in any object or shared libraries.
970         if ((*ObjFile)->isRelocatableObject())
971           UsedInRegularObj.insert(Saver.save(*Name));
972         else
973           UsedInSharedLib.insert(Saver.save(*Name));
974       }
975     } else {
976       Expected<std::unique_ptr<lto::InputFile>> InputFileOrErr =
977           llvm::lto::InputFile::create(**BufferOrErr);
978       if (!InputFileOrErr)
979         return InputFileOrErr.takeError();
980 
981       // Save the input file and the buffer associated with its memory.
982       BitcodeFiles.push_back(std::move(*InputFileOrErr));
983       SavedBuffers.push_back(std::move(*BufferOrErr));
984     }
985   }
986 
987   if (BitcodeFiles.empty())
988     return Error::success();
989 
990   auto HandleError = [&](Error Err) {
991     logAllUnhandledErrors(std::move(Err),
992                           WithColor::error(errs(), LinkerExecutable));
993     exit(1);
994   };
995 
996   // LTO Module hook to output bitcode without running the backend.
997   auto OutputBitcode = [&](size_t Task, const Module &M) {
998     SmallString<128> TempFile;
999     if (Error Err = createOutputFile(sys::path::filename(ExecutableName) +
1000                                          "-jit-" + TheTriple.getTriple(),
1001                                      "bc", TempFile))
1002       HandleError(std::move(Err));
1003 
1004     std::error_code EC;
1005     raw_fd_ostream LinkedBitcode(TempFile, EC, sys::fs::OF_None);
1006     if (EC)
1007       HandleError(errorCodeToError(EC));
1008     WriteBitcodeToFile(M, LinkedBitcode);
1009     NewInputFiles.push_back(static_cast<std::string>(TempFile));
1010     return false;
1011   };
1012 
1013   // We assume visibility of the whole program if every input file was bitcode.
1014   WholeProgram = BitcodeFiles.size() == InputFiles.size();
1015   auto LTOBackend =
1016       (EmbedBitcode) ? createLTO(TheTriple, Arch, WholeProgram, OutputBitcode)
1017                      : createLTO(TheTriple, Arch, WholeProgram);
1018 
1019   // We need to resolve the symbols so the LTO backend knows which symbols need
1020   // to be kept or can be internalized. This is a simplified symbol resolution
1021   // scheme to approximate the full resolution a linker would do.
1022   DenseSet<StringRef> PrevailingSymbols;
1023   for (auto &BitcodeFile : BitcodeFiles) {
1024     const auto Symbols = BitcodeFile->symbols();
1025     SmallVector<lto::SymbolResolution, 16> Resolutions(Symbols.size());
1026     size_t Idx = 0;
1027     for (auto &Sym : Symbols) {
1028       lto::SymbolResolution &Res = Resolutions[Idx++];
1029 
1030       // We will use this as the prevailing symbol definition in LTO unless
1031       // it is undefined or another definition has already been used.
1032       Res.Prevailing =
1033           !Sym.isUndefined() &&
1034           PrevailingSymbols.insert(Saver.save(Sym.getName())).second;
1035 
1036       // We need LTO to preseve the following global symbols:
1037       // 1) Symbols used in regular objects.
1038       // 2) Sections that will be given a __start/__stop symbol.
1039       // 3) Prevailing symbols that are needed visible to external libraries.
1040       Res.VisibleToRegularObj =
1041           UsedInRegularObj.contains(Sym.getName()) ||
1042           isValidCIdentifier(Sym.getSectionName()) ||
1043           (Res.Prevailing &&
1044            (Sym.getVisibility() != GlobalValue::HiddenVisibility &&
1045             !Sym.canBeOmittedFromSymbolTable()));
1046 
1047       // Identify symbols that must be exported dynamically and can be
1048       // referenced by other files.
1049       Res.ExportDynamic =
1050           Sym.getVisibility() != GlobalValue::HiddenVisibility &&
1051           (UsedInSharedLib.contains(Sym.getName()) ||
1052            !Sym.canBeOmittedFromSymbolTable());
1053 
1054       // The final definition will reside in this linkage unit if the symbol is
1055       // defined and local to the module. This only checks for bitcode files,
1056       // full assertion will require complete symbol resolution.
1057       Res.FinalDefinitionInLinkageUnit =
1058           Sym.getVisibility() != GlobalValue::DefaultVisibility &&
1059           (!Sym.isUndefined() && !Sym.isCommon());
1060 
1061       // We do not support linker redefined symbols (e.g. --wrap) for device
1062       // image linking, so the symbols will not be changed after LTO.
1063       Res.LinkerRedefined = false;
1064     }
1065 
1066     // Add the bitcode file with its resolved symbols to the LTO job.
1067     if (Error Err = LTOBackend->add(std::move(BitcodeFile), Resolutions))
1068       return Err;
1069   }
1070 
1071   // Run the LTO job to compile the bitcode.
1072   size_t MaxTasks = LTOBackend->getMaxTasks();
1073   std::vector<SmallString<128>> Files(MaxTasks);
1074   auto AddStream = [&](size_t Task) -> std::unique_ptr<CachedFileStream> {
1075     int FD = -1;
1076     auto &TempFile = Files[Task];
1077     StringRef Extension = (TheTriple.isNVPTX()) ? "s" : "o";
1078     if (Error Err = createOutputFile(sys::path::filename(ExecutableName) +
1079                                          "-device-" + TheTriple.getTriple(),
1080                                      Extension, TempFile))
1081       HandleError(std::move(Err));
1082     if (std::error_code EC = sys::fs::openFileForWrite(TempFile, FD))
1083       HandleError(errorCodeToError(EC));
1084     return std::make_unique<CachedFileStream>(
1085         std::make_unique<llvm::raw_fd_ostream>(FD, true));
1086   };
1087 
1088   if (Error Err = LTOBackend->run(AddStream))
1089     return Err;
1090 
1091   // Is we are compiling for NVPTX we need to run the assembler first.
1092   if (TheTriple.isNVPTX() && !EmbedBitcode) {
1093     for (auto &File : Files) {
1094       auto FileOrErr = nvptx::assemble(File, TheTriple, Arch, !WholeProgram);
1095       if (!FileOrErr)
1096         return FileOrErr.takeError();
1097       File = *FileOrErr;
1098     }
1099   }
1100 
1101   // Append the new inputs to the device linker input.
1102   for (auto &File : Files)
1103     NewInputFiles.push_back(static_cast<std::string>(File));
1104   InputFiles = NewInputFiles;
1105 
1106   return Error::success();
1107 }
1108 
1109 /// Runs the appropriate linking action on all the device files specified in \p
1110 /// DeviceFiles. The linked device images are returned in \p LinkedImages.
1111 Error linkDeviceFiles(ArrayRef<DeviceFile> DeviceFiles,
1112                       SmallVectorImpl<std::string> &LinkedImages) {
1113   // Get the list of inputs for a specific device.
1114   DenseMap<DeviceFile, SmallVector<std::string, 4>> LinkerInputMap;
1115   for (auto &File : DeviceFiles)
1116     LinkerInputMap[File].push_back(File.Filename);
1117 
1118   // Try to link each device toolchain.
1119   for (auto &LinkerInput : LinkerInputMap) {
1120     DeviceFile &File = LinkerInput.getFirst();
1121     Triple TheTriple = Triple(File.TheTriple);
1122     bool WholeProgram = false;
1123 
1124     // Run LTO on any bitcode files and replace the input with the result.
1125     if (Error Err = linkBitcodeFiles(LinkerInput.getSecond(), TheTriple,
1126                                      File.Arch, WholeProgram))
1127       return Err;
1128 
1129     // If we are embedding bitcode for JIT, skip the final device linking.
1130     if (EmbedBitcode) {
1131       assert(!LinkerInput.getSecond().empty() && "No bitcode image to embed");
1132       LinkedImages.push_back(LinkerInput.getSecond().front());
1133       continue;
1134     }
1135 
1136     // If we performed LTO on NVPTX and had whole program visibility, we can use
1137     // CUDA in non-RDC mode.
1138     if (WholeProgram && TheTriple.isNVPTX()) {
1139       assert(!LinkerInput.getSecond().empty() && "No non-RDC image to embed");
1140       LinkedImages.push_back(LinkerInput.getSecond().front());
1141       continue;
1142     }
1143 
1144     auto ImageOrErr = linkDevice(LinkerInput.getSecond(), TheTriple, File.Arch);
1145     if (!ImageOrErr)
1146       return ImageOrErr.takeError();
1147 
1148     LinkedImages.push_back(*ImageOrErr);
1149   }
1150   return Error::success();
1151 }
1152 
1153 // Compile the module to an object file using the appropriate target machine for
1154 // the host triple.
1155 Expected<std::string> compileModule(Module &M) {
1156   std::string Msg;
1157   const Target *T = TargetRegistry::lookupTarget(M.getTargetTriple(), Msg);
1158   if (!T)
1159     return createStringError(inconvertibleErrorCode(), Msg);
1160 
1161   auto Options =
1162       codegen::InitTargetOptionsFromCodeGenFlags(Triple(M.getTargetTriple()));
1163   StringRef CPU = "";
1164   StringRef Features = "";
1165   std::unique_ptr<TargetMachine> TM(T->createTargetMachine(
1166       HostTriple, CPU, Features, Options, Reloc::PIC_, M.getCodeModel()));
1167 
1168   if (M.getDataLayout().isDefault())
1169     M.setDataLayout(TM->createDataLayout());
1170 
1171   SmallString<128> ObjectFile;
1172   int FD = -1;
1173   if (Error Err = createOutputFile(sys::path::filename(ExecutableName) +
1174                                        "offload-wrapper",
1175                                    "o", ObjectFile))
1176     return std::move(Err);
1177   if (std::error_code EC = sys::fs::openFileForWrite(ObjectFile, FD))
1178     return errorCodeToError(EC);
1179 
1180   auto OS = std::make_unique<llvm::raw_fd_ostream>(FD, true);
1181 
1182   legacy::PassManager CodeGenPasses;
1183   TargetLibraryInfoImpl TLII(Triple(M.getTargetTriple()));
1184   CodeGenPasses.add(new TargetLibraryInfoWrapperPass(TLII));
1185   if (TM->addPassesToEmitFile(CodeGenPasses, *OS, nullptr, CGFT_ObjectFile))
1186     return createStringError(inconvertibleErrorCode(),
1187                              "Failed to execute host backend");
1188   CodeGenPasses.run(M);
1189 
1190   return static_cast<std::string>(ObjectFile);
1191 }
1192 
1193 /// Creates the object file containing the device image and runtime registration
1194 /// code from the device images stored in \p Images.
1195 Expected<std::string> wrapDeviceImages(ArrayRef<std::string> Images) {
1196   SmallVector<std::unique_ptr<MemoryBuffer>, 4> SavedBuffers;
1197   SmallVector<ArrayRef<char>, 4> ImagesToWrap;
1198 
1199   for (StringRef ImageFilename : Images) {
1200     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> ImageOrError =
1201         llvm::MemoryBuffer::getFileOrSTDIN(ImageFilename);
1202     if (std::error_code EC = ImageOrError.getError())
1203       return createFileError(ImageFilename, EC);
1204     ImagesToWrap.emplace_back((*ImageOrError)->getBufferStart(),
1205                               (*ImageOrError)->getBufferSize());
1206     SavedBuffers.emplace_back(std::move(*ImageOrError));
1207   }
1208 
1209   LLVMContext Context;
1210   Module M("offload.wrapper.module", Context);
1211   M.setTargetTriple(HostTriple);
1212   if (Error Err = wrapBinaries(M, ImagesToWrap))
1213     return std::move(Err);
1214 
1215   if (PrintWrappedModule)
1216     llvm::errs() << M;
1217 
1218   return compileModule(M);
1219 }
1220 
1221 Optional<std::string> findFile(StringRef Dir, const Twine &Name) {
1222   SmallString<128> Path;
1223   if (Dir.startswith("="))
1224     sys::path::append(Path, Sysroot, Dir.substr(1), Name);
1225   else
1226     sys::path::append(Path, Dir, Name);
1227 
1228   if (sys::fs::exists(Path))
1229     return static_cast<std::string>(Path);
1230   return None;
1231 }
1232 
1233 Optional<std::string> findFromSearchPaths(StringRef Name,
1234                                           ArrayRef<StringRef> SearchPaths) {
1235   for (StringRef Dir : SearchPaths)
1236     if (Optional<std::string> File = findFile(Dir, Name))
1237       return File;
1238   return None;
1239 }
1240 
1241 Optional<std::string> searchLibraryBaseName(StringRef Name,
1242                                             ArrayRef<StringRef> SearchPaths) {
1243   for (StringRef Dir : SearchPaths) {
1244     if (Optional<std::string> File = findFile(Dir, "lib" + Name + ".so"))
1245       return None;
1246     if (Optional<std::string> File = findFile(Dir, "lib" + Name + ".a"))
1247       return File;
1248   }
1249   return None;
1250 }
1251 
1252 /// Search for static libraries in the linker's library path given input like
1253 /// `-lfoo` or `-l:libfoo.a`.
1254 Optional<std::string> searchLibrary(StringRef Input,
1255                                     ArrayRef<StringRef> SearchPaths) {
1256   if (!Input.startswith("-l"))
1257     return None;
1258   StringRef Name = Input.drop_front(2);
1259   if (Name.startswith(":"))
1260     return findFromSearchPaths(Name.drop_front(), SearchPaths);
1261   return searchLibraryBaseName(Name, SearchPaths);
1262 }
1263 
1264 } // namespace
1265 
1266 int main(int argc, const char **argv) {
1267   InitLLVM X(argc, argv);
1268   InitializeAllTargetInfos();
1269   InitializeAllTargets();
1270   InitializeAllTargetMCs();
1271   InitializeAllAsmParsers();
1272   InitializeAllAsmPrinters();
1273 
1274   LinkerExecutable = argv[0];
1275   sys::PrintStackTraceOnErrorSignal(argv[0]);
1276   cl::SetVersionPrinter(PrintVersion);
1277   cl::HideUnrelatedOptions(ClangLinkerWrapperCategory);
1278   cl::ParseCommandLineOptions(
1279       argc, argv,
1280       "A wrapper utility over the host linker. It scans the input files for\n"
1281       "sections that require additional processing prior to linking. The tool\n"
1282       "will then transparently pass all arguments and input to the specified\n"
1283       "host linker to create the final binary.\n");
1284 
1285   if (Help) {
1286     cl::PrintHelpMessage();
1287     return EXIT_SUCCESS;
1288   }
1289 
1290   auto reportError = [argv](Error E) {
1291     logAllUnhandledErrors(std::move(E), WithColor::error(errs(), argv[0]));
1292     return EXIT_FAILURE;
1293   };
1294 
1295   if (!CudaPath.empty())
1296     CudaBinaryPath = CudaPath + "/bin";
1297 
1298   auto RootIt = llvm::find_if(HostLinkerArgs, [](StringRef Arg) {
1299     return Arg.startswith("--sysroot=");
1300   });
1301   if (RootIt != HostLinkerArgs.end())
1302     Sysroot = StringRef(*RootIt).split('=').second;
1303 
1304   ExecutableName = *std::next(llvm::find(HostLinkerArgs, "-o"));
1305   SmallVector<std::string, 16> LinkerArgs;
1306   for (const std::string &Arg : HostLinkerArgs)
1307     LinkerArgs.push_back(Arg);
1308 
1309   SmallVector<StringRef, 16> LibraryPaths;
1310   for (StringRef Arg : LinkerArgs) {
1311     if (Arg.startswith("-L"))
1312       LibraryPaths.push_back(Arg.drop_front(2));
1313   }
1314 
1315   // Try to extract device code from the linker input and replace the linker
1316   // input with a new file that has the device section stripped.
1317   SmallVector<DeviceFile, 4> DeviceFiles;
1318   for (std::string &Arg : LinkerArgs) {
1319     if (Arg == ExecutableName)
1320       continue;
1321 
1322     // Search for static libraries in the library link path.
1323     std::string Filename = Arg;
1324     if (Optional<std::string> Library = searchLibrary(Arg, LibraryPaths))
1325       Filename = *Library;
1326 
1327     if (sys::fs::exists(Filename) && !sys::fs::is_directory(Filename)) {
1328       ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
1329           MemoryBuffer::getFileOrSTDIN(Filename);
1330       if (std::error_code EC = BufferOrErr.getError())
1331         return reportError(createFileError(Filename, EC));
1332 
1333       auto NewFileOrErr =
1334           extractFromBuffer(std::move(*BufferOrErr), DeviceFiles);
1335 
1336       if (!NewFileOrErr)
1337         return reportError(NewFileOrErr.takeError());
1338 
1339       if (NewFileOrErr->hasValue())
1340         Arg = **NewFileOrErr;
1341     }
1342   }
1343 
1344   // Add the device bitcode libraries to the device files if any were passed in.
1345   for (StringRef LibraryStr : BitcodeLibraries)
1346     DeviceFiles.push_back(getBitcodeLibrary(LibraryStr));
1347 
1348   // Link the device images extracted from the linker input.
1349   SmallVector<std::string, 16> LinkedImages;
1350   if (Error Err = linkDeviceFiles(DeviceFiles, LinkedImages))
1351     return reportError(std::move(Err));
1352 
1353   // Wrap each linked device image into a linkable host binary and add it to the
1354   // link job's inputs.
1355   auto FileOrErr = wrapDeviceImages(LinkedImages);
1356   if (!FileOrErr)
1357     return reportError(FileOrErr.takeError());
1358   LinkerArgs.push_back(*FileOrErr);
1359 
1360   // Run the host linking job.
1361   if (Error Err = runLinker(LinkerUserPath, LinkerArgs))
1362     return reportError(std::move(Err));
1363 
1364   // Remove the temporary files created.
1365   for (const auto &TempFile : TempFiles)
1366     if (std::error_code EC = sys::fs::remove(TempFile))
1367       reportError(createFileError(TempFile, EC));
1368 
1369   return EXIT_SUCCESS;
1370 }
1371