1 //===--- CommonArgs.cpp - Args handling for multiple toolchains -*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "CommonArgs.h"
11 #include "InputInfo.h"
12 #include "Hexagon.h"
13 #include "Arch/AArch64.h"
14 #include "Arch/ARM.h"
15 #include "Arch/Mips.h"
16 #include "Arch/PPC.h"
17 #include "Arch/SystemZ.h"
18 #include "Arch/X86.h"
19 #include "clang/Basic/CharInfo.h"
20 #include "clang/Basic/LangOptions.h"
21 #include "clang/Basic/ObjCRuntime.h"
22 #include "clang/Basic/Version.h"
23 #include "clang/Basic/VirtualFileSystem.h"
24 #include "clang/Config/config.h"
25 #include "clang/Driver/Action.h"
26 #include "clang/Driver/Compilation.h"
27 #include "clang/Driver/Driver.h"
28 #include "clang/Driver/DriverDiagnostic.h"
29 #include "clang/Driver/Job.h"
30 #include "clang/Driver/Options.h"
31 #include "clang/Driver/SanitizerArgs.h"
32 #include "clang/Driver/ToolChain.h"
33 #include "clang/Driver/Util.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/ADT/SmallString.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/ADT/StringSwitch.h"
38 #include "llvm/ADT/Twine.h"
39 #include "llvm/Option/Arg.h"
40 #include "llvm/Option/ArgList.h"
41 #include "llvm/Option/Option.h"
42 #include "llvm/Support/CodeGen.h"
43 #include "llvm/Support/Compression.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/FileSystem.h"
46 #include "llvm/Support/Host.h"
47 #include "llvm/Support/Path.h"
48 #include "llvm/Support/Process.h"
49 #include "llvm/Support/Program.h"
50 #include "llvm/Support/ScopedPrinter.h"
51 #include "llvm/Support/TargetParser.h"
52 #include "llvm/Support/YAMLParser.h"
53 
54 using namespace clang::driver;
55 using namespace clang::driver::tools;
56 using namespace clang;
57 using namespace llvm::opt;
58 
59 void tools::addPathIfExists(const Driver &D, const Twine &Path,
60                             ToolChain::path_list &Paths) {
61   if (D.getVFS().exists(Path))
62     Paths.push_back(Path.str());
63 }
64 
65 void tools::handleTargetFeaturesGroup(const ArgList &Args,
66                                       std::vector<StringRef> &Features,
67                                       OptSpecifier Group) {
68   for (const Arg *A : Args.filtered(Group)) {
69     StringRef Name = A->getOption().getName();
70     A->claim();
71 
72     // Skip over "-m".
73     assert(Name.startswith("m") && "Invalid feature name.");
74     Name = Name.substr(1);
75 
76     bool IsNegative = Name.startswith("no-");
77     if (IsNegative)
78       Name = Name.substr(3);
79     Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
80   }
81 }
82 
83 void tools::addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
84                              const char *ArgName, const char *EnvVar) {
85   const char *DirList = ::getenv(EnvVar);
86   bool CombinedArg = false;
87 
88   if (!DirList)
89     return; // Nothing to do.
90 
91   StringRef Name(ArgName);
92   if (Name.equals("-I") || Name.equals("-L"))
93     CombinedArg = true;
94 
95   StringRef Dirs(DirList);
96   if (Dirs.empty()) // Empty string should not add '.'.
97     return;
98 
99   StringRef::size_type Delim;
100   while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
101     if (Delim == 0) { // Leading colon.
102       if (CombinedArg) {
103         CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
104       } else {
105         CmdArgs.push_back(ArgName);
106         CmdArgs.push_back(".");
107       }
108     } else {
109       if (CombinedArg) {
110         CmdArgs.push_back(
111             Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
112       } else {
113         CmdArgs.push_back(ArgName);
114         CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
115       }
116     }
117     Dirs = Dirs.substr(Delim + 1);
118   }
119 
120   if (Dirs.empty()) { // Trailing colon.
121     if (CombinedArg) {
122       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
123     } else {
124       CmdArgs.push_back(ArgName);
125       CmdArgs.push_back(".");
126     }
127   } else { // Add the last path.
128     if (CombinedArg) {
129       CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
130     } else {
131       CmdArgs.push_back(ArgName);
132       CmdArgs.push_back(Args.MakeArgString(Dirs));
133     }
134   }
135 }
136 
137 void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
138                             const ArgList &Args, ArgStringList &CmdArgs,
139                             const JobAction &JA) {
140   const Driver &D = TC.getDriver();
141 
142   // Add extra linker input arguments which are not treated as inputs
143   // (constructed via -Xarch_).
144   Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
145 
146   for (const auto &II : Inputs) {
147     // If the current tool chain refers to an OpenMP offloading host, we should
148     // ignore inputs that refer to OpenMP offloading devices - they will be
149     // embedded according to a proper linker script.
150     if (auto *IA = II.getAction())
151       if (JA.isHostOffloading(Action::OFK_OpenMP) &&
152           IA->isDeviceOffloading(Action::OFK_OpenMP))
153         continue;
154 
155     if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
156       // Don't try to pass LLVM inputs unless we have native support.
157       D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
158 
159     // Add filenames immediately.
160     if (II.isFilename()) {
161       CmdArgs.push_back(II.getFilename());
162       continue;
163     }
164 
165     // Otherwise, this is a linker input argument.
166     const Arg &A = II.getInputArg();
167 
168     // Handle reserved library options.
169     if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
170       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
171     else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
172       TC.AddCCKextLibArgs(Args, CmdArgs);
173     else if (A.getOption().matches(options::OPT_z)) {
174       // Pass -z prefix for gcc linker compatibility.
175       A.claim();
176       A.render(Args, CmdArgs);
177     } else {
178       A.renderAsInput(Args, CmdArgs);
179     }
180   }
181 
182   // LIBRARY_PATH - included following the user specified library paths.
183   //                and only supported on native toolchains.
184   if (!TC.isCrossCompiling()) {
185     addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
186   }
187 }
188 
189 void tools::AddTargetFeature(const ArgList &Args,
190                              std::vector<StringRef> &Features,
191                              OptSpecifier OnOpt, OptSpecifier OffOpt,
192                              StringRef FeatureName) {
193   if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
194     if (A->getOption().matches(OnOpt))
195       Features.push_back(Args.MakeArgString("+" + FeatureName));
196     else
197       Features.push_back(Args.MakeArgString("-" + FeatureName));
198   }
199 }
200 
201 /// Get the (LLVM) name of the R600 gpu we are targeting.
202 static std::string getR600TargetGPU(const ArgList &Args) {
203   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
204     const char *GPUName = A->getValue();
205     return llvm::StringSwitch<const char *>(GPUName)
206         .Cases("rv630", "rv635", "r600")
207         .Cases("rv610", "rv620", "rs780", "rs880")
208         .Case("rv740", "rv770")
209         .Case("palm", "cedar")
210         .Cases("sumo", "sumo2", "sumo")
211         .Case("hemlock", "cypress")
212         .Case("aruba", "cayman")
213         .Default(GPUName);
214   }
215   return "";
216 }
217 
218 static std::string getNios2TargetCPU(const ArgList &Args) {
219   Arg *A = Args.getLastArg(options::OPT_mcpu_EQ);
220   if (!A)
221     A = Args.getLastArg(options::OPT_march_EQ);
222 
223   if (!A)
224     return "";
225 
226   const char *name = A->getValue();
227   return llvm::StringSwitch<const char *>(name)
228       .Case("r1", "nios2r1")
229       .Case("r2", "nios2r2")
230       .Default(name);
231 }
232 
233 static std::string getLanaiTargetCPU(const ArgList &Args) {
234   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
235     return A->getValue();
236   }
237   return "";
238 }
239 
240 /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
241 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
242   // If we have -mcpu=, use that.
243   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
244     StringRef CPU = A->getValue();
245 
246 #ifdef __wasm__
247     // Handle "native" by examining the host. "native" isn't meaningful when
248     // cross compiling, so only support this when the host is also WebAssembly.
249     if (CPU == "native")
250       return llvm::sys::getHostCPUName();
251 #endif
252 
253     return CPU;
254   }
255 
256   return "generic";
257 }
258 
259 std::string tools::getCPUName(const ArgList &Args, const llvm::Triple &T,
260                               bool FromAs) {
261   Arg *A;
262 
263   switch (T.getArch()) {
264   default:
265     return "";
266 
267   case llvm::Triple::aarch64:
268   case llvm::Triple::aarch64_be:
269     return aarch64::getAArch64TargetCPU(Args, A);
270 
271   case llvm::Triple::arm:
272   case llvm::Triple::armeb:
273   case llvm::Triple::thumb:
274   case llvm::Triple::thumbeb: {
275     StringRef MArch, MCPU;
276     arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
277     return arm::getARMTargetCPU(MCPU, MArch, T);
278   }
279 
280   case llvm::Triple::avr:
281     if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ))
282       return A->getValue();
283     return "";
284 
285   case llvm::Triple::nios2: {
286     return getNios2TargetCPU(Args);
287   }
288 
289   case llvm::Triple::mips:
290   case llvm::Triple::mipsel:
291   case llvm::Triple::mips64:
292   case llvm::Triple::mips64el: {
293     StringRef CPUName;
294     StringRef ABIName;
295     mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
296     return CPUName;
297   }
298 
299   case llvm::Triple::nvptx:
300   case llvm::Triple::nvptx64:
301     if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
302       return A->getValue();
303     return "";
304 
305   case llvm::Triple::ppc:
306   case llvm::Triple::ppc64:
307   case llvm::Triple::ppc64le: {
308     std::string TargetCPUName = ppc::getPPCTargetCPU(Args);
309     // LLVM may default to generating code for the native CPU,
310     // but, like gcc, we default to a more generic option for
311     // each architecture. (except on Darwin)
312     if (TargetCPUName.empty() && !T.isOSDarwin()) {
313       if (T.getArch() == llvm::Triple::ppc64)
314         TargetCPUName = "ppc64";
315       else if (T.getArch() == llvm::Triple::ppc64le)
316         TargetCPUName = "ppc64le";
317       else
318         TargetCPUName = "ppc";
319     }
320     return TargetCPUName;
321   }
322 
323   case llvm::Triple::bpfel:
324   case llvm::Triple::bpfeb:
325   case llvm::Triple::sparc:
326   case llvm::Triple::sparcel:
327   case llvm::Triple::sparcv9:
328     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
329       return A->getValue();
330     return "";
331 
332   case llvm::Triple::x86:
333   case llvm::Triple::x86_64:
334     return x86::getX86TargetCPU(Args, T);
335 
336   case llvm::Triple::hexagon:
337     return "hexagon" +
338            toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
339 
340   case llvm::Triple::lanai:
341     return getLanaiTargetCPU(Args);
342 
343   case llvm::Triple::systemz:
344     return systemz::getSystemZTargetCPU(Args);
345 
346   case llvm::Triple::r600:
347   case llvm::Triple::amdgcn:
348     return getR600TargetGPU(Args);
349 
350   case llvm::Triple::wasm32:
351   case llvm::Triple::wasm64:
352     return getWebAssemblyTargetCPU(Args);
353   }
354 }
355 
356 unsigned tools::getLTOParallelism(const ArgList &Args, const Driver &D) {
357   unsigned Parallelism = 0;
358   Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
359   if (LtoJobsArg &&
360       StringRef(LtoJobsArg->getValue()).getAsInteger(10, Parallelism))
361     D.Diag(diag::err_drv_invalid_int_value) << LtoJobsArg->getAsString(Args)
362                                             << LtoJobsArg->getValue();
363   return Parallelism;
364 }
365 
366 // CloudABI uses -ffunction-sections and -fdata-sections by default.
367 bool tools::isUseSeparateSections(const llvm::Triple &Triple) {
368   return Triple.getOS() == llvm::Triple::CloudABI;
369 }
370 
371 void tools::AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
372                           ArgStringList &CmdArgs, bool IsThinLTO,
373                           const Driver &D) {
374   // Tell the linker to load the plugin. This has to come before AddLinkerInputs
375   // as gold requires -plugin to come before any -plugin-opt that -Wl might
376   // forward.
377   CmdArgs.push_back("-plugin");
378 
379 #if defined(LLVM_ON_WIN32)
380   const char *Suffix = ".dll";
381 #elif defined(__APPLE__)
382   const char *Suffix = ".dylib";
383 #else
384   const char *Suffix = ".so";
385 #endif
386 
387   SmallString<1024> Plugin;
388   llvm::sys::path::native(Twine(ToolChain.getDriver().Dir) +
389                               "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold" +
390                               Suffix,
391                           Plugin);
392   CmdArgs.push_back(Args.MakeArgString(Plugin));
393 
394   // Try to pass driver level flags relevant to LTO code generation down to
395   // the plugin.
396 
397   // Handle flags for selecting CPU variants.
398   std::string CPU = getCPUName(Args, ToolChain.getTriple());
399   if (!CPU.empty())
400     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
401 
402   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
403     StringRef OOpt;
404     if (A->getOption().matches(options::OPT_O4) ||
405         A->getOption().matches(options::OPT_Ofast))
406       OOpt = "3";
407     else if (A->getOption().matches(options::OPT_O))
408       OOpt = A->getValue();
409     else if (A->getOption().matches(options::OPT_O0))
410       OOpt = "0";
411     if (!OOpt.empty())
412       CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
413   }
414 
415   if (IsThinLTO)
416     CmdArgs.push_back("-plugin-opt=thinlto");
417 
418   if (unsigned Parallelism = getLTOParallelism(Args, D))
419     CmdArgs.push_back(
420         Args.MakeArgString("-plugin-opt=jobs=" + Twine(Parallelism)));
421 
422   // If an explicit debugger tuning argument appeared, pass it along.
423   if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
424                                options::OPT_ggdbN_Group)) {
425     if (A->getOption().matches(options::OPT_glldb))
426       CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
427     else if (A->getOption().matches(options::OPT_gsce))
428       CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
429     else
430       CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
431   }
432 
433   bool UseSeparateSections =
434       isUseSeparateSections(ToolChain.getEffectiveTriple());
435 
436   if (Args.hasFlag(options::OPT_ffunction_sections,
437                    options::OPT_fno_function_sections, UseSeparateSections)) {
438     CmdArgs.push_back("-plugin-opt=-function-sections");
439   }
440 
441   if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
442                    UseSeparateSections)) {
443     CmdArgs.push_back("-plugin-opt=-data-sections");
444   }
445 
446   if (Arg *A = getLastProfileSampleUseArg(Args)) {
447     StringRef FName = A->getValue();
448     if (!llvm::sys::fs::exists(FName))
449       D.Diag(diag::err_drv_no_such_file) << FName;
450     else
451       CmdArgs.push_back(
452           Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName));
453   }
454 
455   // Need this flag to turn on new pass manager via Gold plugin.
456   if (Args.hasFlag(options::OPT_fexperimental_new_pass_manager,
457                    options::OPT_fno_experimental_new_pass_manager,
458                    /* Default */ false)) {
459     CmdArgs.push_back("-plugin-opt=new-pass-manager");
460   }
461 
462 }
463 
464 void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args,
465                                  ArgStringList &CmdArgs) {
466   std::string CandidateRPath = TC.getArchSpecificLibPath();
467   if (TC.getVFS().exists(CandidateRPath)) {
468     CmdArgs.push_back("-rpath");
469     CmdArgs.push_back(Args.MakeArgString(CandidateRPath.c_str()));
470   }
471 }
472 
473 bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
474                              const ArgList &Args, bool IsOffloadingHost,
475                              bool GompNeedsRT) {
476   if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
477                     options::OPT_fno_openmp, false))
478     return false;
479 
480   switch (TC.getDriver().getOpenMPRuntime(Args)) {
481   case Driver::OMPRT_OMP:
482     CmdArgs.push_back("-lomp");
483     break;
484   case Driver::OMPRT_GOMP:
485     CmdArgs.push_back("-lgomp");
486 
487     if (GompNeedsRT)
488       CmdArgs.push_back("-lrt");
489     break;
490   case Driver::OMPRT_IOMP5:
491     CmdArgs.push_back("-liomp5");
492     break;
493   case Driver::OMPRT_Unknown:
494     // Already diagnosed.
495     return false;
496   }
497 
498   if (IsOffloadingHost)
499     CmdArgs.push_back("-lomptarget");
500 
501   addArchSpecificRPath(TC, Args, CmdArgs);
502 
503   return true;
504 }
505 
506 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
507                                 ArgStringList &CmdArgs, StringRef Sanitizer,
508                                 bool IsShared, bool IsWhole) {
509   // Wrap any static runtimes that must be forced into executable in
510   // whole-archive.
511   if (IsWhole) CmdArgs.push_back("--whole-archive");
512   CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
513   if (IsWhole) CmdArgs.push_back("--no-whole-archive");
514 
515   if (IsShared) {
516     addArchSpecificRPath(TC, Args, CmdArgs);
517   }
518 }
519 
520 // Tries to use a file with the list of dynamic symbols that need to be exported
521 // from the runtime library. Returns true if the file was found.
522 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
523                                     ArgStringList &CmdArgs,
524                                     StringRef Sanitizer) {
525   // Solaris ld defaults to --export-dynamic behaviour but doesn't support
526   // the option, so don't try to pass it.
527   if (TC.getTriple().getOS() == llvm::Triple::Solaris)
528     return true;
529   SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
530   if (llvm::sys::fs::exists(SanRT + ".syms")) {
531     CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
532     return true;
533   }
534   return false;
535 }
536 
537 void tools::linkSanitizerRuntimeDeps(const ToolChain &TC,
538                                      ArgStringList &CmdArgs) {
539   // Force linking against the system libraries sanitizers depends on
540   // (see PR15823 why this is necessary).
541   CmdArgs.push_back("--no-as-needed");
542   // There's no libpthread or librt on RTEMS.
543   if (TC.getTriple().getOS() != llvm::Triple::RTEMS) {
544     CmdArgs.push_back("-lpthread");
545     if (TC.getTriple().getOS() != llvm::Triple::OpenBSD)
546       CmdArgs.push_back("-lrt");
547   }
548   CmdArgs.push_back("-lm");
549   // There's no libdl on all OSes.
550   if (TC.getTriple().getOS() != llvm::Triple::FreeBSD &&
551       TC.getTriple().getOS() != llvm::Triple::NetBSD &&
552       TC.getTriple().getOS() != llvm::Triple::OpenBSD &&
553       TC.getTriple().getOS() != llvm::Triple::RTEMS)
554     CmdArgs.push_back("-ldl");
555   // Required for backtrace on some OSes
556   if (TC.getTriple().getOS() == llvm::Triple::NetBSD ||
557       TC.getTriple().getOS() == llvm::Triple::FreeBSD)
558     CmdArgs.push_back("-lexecinfo");
559 }
560 
561 static void
562 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
563                          SmallVectorImpl<StringRef> &SharedRuntimes,
564                          SmallVectorImpl<StringRef> &StaticRuntimes,
565                          SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
566                          SmallVectorImpl<StringRef> &HelperStaticRuntimes,
567                          SmallVectorImpl<StringRef> &RequiredSymbols) {
568   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
569   // Collect shared runtimes.
570   if (SanArgs.needsSharedRt()) {
571     if (SanArgs.needsAsanRt()) {
572       SharedRuntimes.push_back("asan");
573       if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
574         HelperStaticRuntimes.push_back("asan-preinit");
575     }
576     if (SanArgs.needsUbsanRt()) {
577       if (SanArgs.requiresMinimalRuntime()) {
578         SharedRuntimes.push_back("ubsan_minimal");
579       } else {
580         SharedRuntimes.push_back("ubsan_standalone");
581       }
582     }
583     if (SanArgs.needsScudoRt())
584       SharedRuntimes.push_back("scudo");
585     if (SanArgs.needsHwasanRt())
586       SharedRuntimes.push_back("hwasan");
587   }
588 
589   // The stats_client library is also statically linked into DSOs.
590   if (SanArgs.needsStatsRt())
591     StaticRuntimes.push_back("stats_client");
592 
593   // Collect static runtimes.
594   if (Args.hasArg(options::OPT_shared) || SanArgs.needsSharedRt()) {
595     // Don't link static runtimes into DSOs or if -shared-libasan.
596     return;
597   }
598   if (SanArgs.needsAsanRt()) {
599     StaticRuntimes.push_back("asan");
600     if (SanArgs.linkCXXRuntimes())
601       StaticRuntimes.push_back("asan_cxx");
602   }
603 
604   if (SanArgs.needsHwasanRt()) {
605     StaticRuntimes.push_back("hwasan");
606     if (SanArgs.linkCXXRuntimes())
607       StaticRuntimes.push_back("hwasan_cxx");
608   }
609   if (SanArgs.needsDfsanRt())
610     StaticRuntimes.push_back("dfsan");
611   if (SanArgs.needsLsanRt())
612     StaticRuntimes.push_back("lsan");
613   if (SanArgs.needsMsanRt()) {
614     StaticRuntimes.push_back("msan");
615     if (SanArgs.linkCXXRuntimes())
616       StaticRuntimes.push_back("msan_cxx");
617   }
618   if (SanArgs.needsTsanRt()) {
619     StaticRuntimes.push_back("tsan");
620     if (SanArgs.linkCXXRuntimes())
621       StaticRuntimes.push_back("tsan_cxx");
622   }
623   if (SanArgs.needsUbsanRt()) {
624     if (SanArgs.requiresMinimalRuntime()) {
625       StaticRuntimes.push_back("ubsan_minimal");
626     } else {
627       StaticRuntimes.push_back("ubsan_standalone");
628       if (SanArgs.linkCXXRuntimes())
629         StaticRuntimes.push_back("ubsan_standalone_cxx");
630     }
631   }
632   if (SanArgs.needsSafeStackRt()) {
633     NonWholeStaticRuntimes.push_back("safestack");
634     RequiredSymbols.push_back("__safestack_init");
635   }
636   if (SanArgs.needsCfiRt())
637     StaticRuntimes.push_back("cfi");
638   if (SanArgs.needsCfiDiagRt()) {
639     StaticRuntimes.push_back("cfi_diag");
640     if (SanArgs.linkCXXRuntimes())
641       StaticRuntimes.push_back("ubsan_standalone_cxx");
642   }
643   if (SanArgs.needsStatsRt()) {
644     NonWholeStaticRuntimes.push_back("stats");
645     RequiredSymbols.push_back("__sanitizer_stats_register");
646   }
647   if (SanArgs.needsEsanRt())
648     StaticRuntimes.push_back("esan");
649   if (SanArgs.needsScudoRt()) {
650     StaticRuntimes.push_back("scudo");
651     if (SanArgs.linkCXXRuntimes())
652       StaticRuntimes.push_back("scudo_cxx");
653   }
654 }
655 
656 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
657 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
658 bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
659                                  ArgStringList &CmdArgs) {
660   SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
661       NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
662   collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
663                            NonWholeStaticRuntimes, HelperStaticRuntimes,
664                            RequiredSymbols);
665 
666   // Inject libfuzzer dependencies.
667   if (TC.getSanitizerArgs().needsFuzzer()
668       && !Args.hasArg(options::OPT_shared)) {
669 
670     addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true);
671     if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx))
672       TC.AddCXXStdlibLibArgs(Args, CmdArgs);
673   }
674 
675   for (auto RT : SharedRuntimes)
676     addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
677   for (auto RT : HelperStaticRuntimes)
678     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
679   bool AddExportDynamic = false;
680   for (auto RT : StaticRuntimes) {
681     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
682     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
683   }
684   for (auto RT : NonWholeStaticRuntimes) {
685     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
686     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
687   }
688   for (auto S : RequiredSymbols) {
689     CmdArgs.push_back("-u");
690     CmdArgs.push_back(Args.MakeArgString(S));
691   }
692   // If there is a static runtime with no dynamic list, force all the symbols
693   // to be dynamic to be sure we export sanitizer interface functions.
694   if (AddExportDynamic)
695     CmdArgs.push_back("--export-dynamic");
696 
697   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
698   if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
699     CmdArgs.push_back("-export-dynamic-symbol=__cfi_check");
700 
701   return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
702 }
703 
704 bool tools::areOptimizationsEnabled(const ArgList &Args) {
705   // Find the last -O arg and see if it is non-zero.
706   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
707     return !A->getOption().matches(options::OPT_O0);
708   // Defaults to -O0.
709   return false;
710 }
711 
712 const char *tools::SplitDebugName(const ArgList &Args, const InputInfo &Input) {
713   Arg *FinalOutput = Args.getLastArg(options::OPT_o);
714   if (FinalOutput && Args.hasArg(options::OPT_c)) {
715     SmallString<128> T(FinalOutput->getValue());
716     llvm::sys::path::replace_extension(T, "dwo");
717     return Args.MakeArgString(T);
718   } else {
719     // Use the compilation dir.
720     SmallString<128> T(
721         Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
722     SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
723     llvm::sys::path::replace_extension(F, "dwo");
724     T += F;
725     return Args.MakeArgString(F);
726   }
727 }
728 
729 void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
730                            const JobAction &JA, const ArgList &Args,
731                            const InputInfo &Output, const char *OutFile) {
732   ArgStringList ExtractArgs;
733   ExtractArgs.push_back("--extract-dwo");
734 
735   ArgStringList StripArgs;
736   StripArgs.push_back("--strip-dwo");
737 
738   // Grabbing the output of the earlier compile step.
739   StripArgs.push_back(Output.getFilename());
740   ExtractArgs.push_back(Output.getFilename());
741   ExtractArgs.push_back(OutFile);
742 
743   const char *Exec =
744       Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY));
745   InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
746 
747   // First extract the dwo sections.
748   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
749 
750   // Then remove them from the original .o file.
751   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
752 }
753 
754 // Claim options we don't want to warn if they are unused. We do this for
755 // options that build systems might add but are unused when assembling or only
756 // running the preprocessor for example.
757 void tools::claimNoWarnArgs(const ArgList &Args) {
758   // Don't warn about unused -f(no-)?lto.  This can happen when we're
759   // preprocessing, precompiling or assembling.
760   Args.ClaimAllArgs(options::OPT_flto_EQ);
761   Args.ClaimAllArgs(options::OPT_flto);
762   Args.ClaimAllArgs(options::OPT_fno_lto);
763 }
764 
765 Arg *tools::getLastProfileUseArg(const ArgList &Args) {
766   auto *ProfileUseArg = Args.getLastArg(
767       options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
768       options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
769       options::OPT_fno_profile_instr_use);
770 
771   if (ProfileUseArg &&
772       ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
773     ProfileUseArg = nullptr;
774 
775   return ProfileUseArg;
776 }
777 
778 Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
779   auto *ProfileSampleUseArg = Args.getLastArg(
780       options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ,
781       options::OPT_fauto_profile, options::OPT_fauto_profile_EQ,
782       options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile);
783 
784   if (ProfileSampleUseArg &&
785       (ProfileSampleUseArg->getOption().matches(
786            options::OPT_fno_profile_sample_use) ||
787        ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile)))
788     return nullptr;
789 
790   return Args.getLastArg(options::OPT_fprofile_sample_use_EQ,
791                          options::OPT_fauto_profile_EQ);
792 }
793 
794 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments.  Then,
795 /// smooshes them together with platform defaults, to decide whether
796 /// this compile should be using PIC mode or not. Returns a tuple of
797 /// (RelocationModel, PICLevel, IsPIE).
798 std::tuple<llvm::Reloc::Model, unsigned, bool>
799 tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
800   const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
801   const llvm::Triple &Triple = ToolChain.getTriple();
802 
803   bool PIE = ToolChain.isPIEDefault();
804   bool PIC = PIE || ToolChain.isPICDefault();
805   // The Darwin/MachO default to use PIC does not apply when using -static.
806   if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
807     PIE = PIC = false;
808   bool IsPICLevelTwo = PIC;
809 
810   bool KernelOrKext =
811       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
812 
813   // Android-specific defaults for PIC/PIE
814   if (Triple.isAndroid()) {
815     switch (Triple.getArch()) {
816     case llvm::Triple::arm:
817     case llvm::Triple::armeb:
818     case llvm::Triple::thumb:
819     case llvm::Triple::thumbeb:
820     case llvm::Triple::aarch64:
821     case llvm::Triple::mips:
822     case llvm::Triple::mipsel:
823     case llvm::Triple::mips64:
824     case llvm::Triple::mips64el:
825       PIC = true; // "-fpic"
826       break;
827 
828     case llvm::Triple::x86:
829     case llvm::Triple::x86_64:
830       PIC = true; // "-fPIC"
831       IsPICLevelTwo = true;
832       break;
833 
834     default:
835       break;
836     }
837   }
838 
839   // OpenBSD-specific defaults for PIE
840   if (Triple.getOS() == llvm::Triple::OpenBSD) {
841     switch (ToolChain.getArch()) {
842     case llvm::Triple::arm:
843     case llvm::Triple::aarch64:
844     case llvm::Triple::mips64:
845     case llvm::Triple::mips64el:
846     case llvm::Triple::x86:
847     case llvm::Triple::x86_64:
848       IsPICLevelTwo = false; // "-fpie"
849       break;
850 
851     case llvm::Triple::ppc:
852     case llvm::Triple::sparc:
853     case llvm::Triple::sparcel:
854     case llvm::Triple::sparcv9:
855       IsPICLevelTwo = true; // "-fPIE"
856       break;
857 
858     default:
859       break;
860     }
861   }
862 
863   // AMDGPU-specific defaults for PIC.
864   if (Triple.getArch() == llvm::Triple::amdgcn)
865     PIC = true;
866 
867   // The last argument relating to either PIC or PIE wins, and no
868   // other argument is used. If the last argument is any flavor of the
869   // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
870   // option implicitly enables PIC at the same level.
871   Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
872                                     options::OPT_fpic, options::OPT_fno_pic,
873                                     options::OPT_fPIE, options::OPT_fno_PIE,
874                                     options::OPT_fpie, options::OPT_fno_pie);
875   if (Triple.isOSWindows() && LastPICArg &&
876       LastPICArg ==
877           Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
878                           options::OPT_fPIE, options::OPT_fpie)) {
879     ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
880         << LastPICArg->getSpelling() << Triple.str();
881     if (Triple.getArch() == llvm::Triple::x86_64)
882       return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
883     return std::make_tuple(llvm::Reloc::Static, 0U, false);
884   }
885 
886   // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
887   // is forced, then neither PIC nor PIE flags will have no effect.
888   if (!ToolChain.isPICDefaultForced()) {
889     if (LastPICArg) {
890       Option O = LastPICArg->getOption();
891       if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
892           O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
893         PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
894         PIC =
895             PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
896         IsPICLevelTwo =
897             O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
898       } else {
899         PIE = PIC = false;
900         if (EffectiveTriple.isPS4CPU()) {
901           Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
902           StringRef Model = ModelArg ? ModelArg->getValue() : "";
903           if (Model != "kernel") {
904             PIC = true;
905             ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
906                 << LastPICArg->getSpelling();
907           }
908         }
909       }
910     }
911   }
912 
913   // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
914   // PIC level would've been set to level 1, force it back to level 2 PIC
915   // instead.
916   if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS4CPU()))
917     IsPICLevelTwo |= ToolChain.isPICDefault();
918 
919   // This kernel flags are a trump-card: they will disable PIC/PIE
920   // generation, independent of the argument order.
921   if (KernelOrKext &&
922       ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
923        !EffectiveTriple.isWatchOS()))
924     PIC = PIE = false;
925 
926   if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
927     // This is a very special mode. It trumps the other modes, almost no one
928     // uses it, and it isn't even valid on any OS but Darwin.
929     if (!Triple.isOSDarwin())
930       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
931           << A->getSpelling() << Triple.str();
932 
933     // FIXME: Warn when this flag trumps some other PIC or PIE flag.
934 
935     // Only a forced PIC mode can cause the actual compile to have PIC defines
936     // etc., no flags are sufficient. This behavior was selected to closely
937     // match that of llvm-gcc and Apple GCC before that.
938     PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
939 
940     return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
941   }
942 
943   bool EmbeddedPISupported;
944   switch (Triple.getArch()) {
945     case llvm::Triple::arm:
946     case llvm::Triple::armeb:
947     case llvm::Triple::thumb:
948     case llvm::Triple::thumbeb:
949       EmbeddedPISupported = true;
950       break;
951     default:
952       EmbeddedPISupported = false;
953       break;
954   }
955 
956   bool ROPI = false, RWPI = false;
957   Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
958   if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
959     if (!EmbeddedPISupported)
960       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
961           << LastROPIArg->getSpelling() << Triple.str();
962     ROPI = true;
963   }
964   Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
965   if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
966     if (!EmbeddedPISupported)
967       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
968           << LastRWPIArg->getSpelling() << Triple.str();
969     RWPI = true;
970   }
971 
972   // ROPI and RWPI are not comaptible with PIC or PIE.
973   if ((ROPI || RWPI) && (PIC || PIE))
974     ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
975 
976   // When targettng MIPS64 with N64, the default is PIC, unless -mno-abicalls is
977   // used.
978   if ((Triple.getArch() == llvm::Triple::mips64 ||
979        Triple.getArch() == llvm::Triple::mips64el) &&
980       Args.hasArg(options::OPT_mno_abicalls))
981     return std::make_tuple(llvm::Reloc::Static, 0U, false);
982 
983   if (PIC)
984     return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
985 
986   llvm::Reloc::Model RelocM = llvm::Reloc::Static;
987   if (ROPI && RWPI)
988     RelocM = llvm::Reloc::ROPI_RWPI;
989   else if (ROPI)
990     RelocM = llvm::Reloc::ROPI;
991   else if (RWPI)
992     RelocM = llvm::Reloc::RWPI;
993 
994   return std::make_tuple(RelocM, 0U, false);
995 }
996 
997 void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
998                              ArgStringList &CmdArgs) {
999   llvm::Reloc::Model RelocationModel;
1000   unsigned PICLevel;
1001   bool IsPIE;
1002   std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
1003 
1004   if (RelocationModel != llvm::Reloc::Static)
1005     CmdArgs.push_back("-KPIC");
1006 }
1007 
1008 /// \brief Determine whether Objective-C automated reference counting is
1009 /// enabled.
1010 bool tools::isObjCAutoRefCount(const ArgList &Args) {
1011   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
1012 }
1013 
1014 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
1015                       ArgStringList &CmdArgs, const ArgList &Args) {
1016   bool isAndroid = Triple.isAndroid();
1017   bool isCygMing = Triple.isOSCygMing();
1018   bool IsIAMCU = Triple.isOSIAMCU();
1019   bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
1020                       Args.hasArg(options::OPT_static);
1021   if (!D.CCCIsCXX())
1022     CmdArgs.push_back("-lgcc");
1023 
1024   if (StaticLibgcc || isAndroid) {
1025     if (D.CCCIsCXX())
1026       CmdArgs.push_back("-lgcc");
1027   } else {
1028     if (!D.CCCIsCXX() && !isCygMing)
1029       CmdArgs.push_back("--as-needed");
1030     CmdArgs.push_back("-lgcc_s");
1031     if (!D.CCCIsCXX() && !isCygMing)
1032       CmdArgs.push_back("--no-as-needed");
1033   }
1034 
1035   if (StaticLibgcc && !isAndroid && !IsIAMCU)
1036     CmdArgs.push_back("-lgcc_eh");
1037   else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
1038     CmdArgs.push_back("-lgcc");
1039 
1040   // According to Android ABI, we have to link with libdl if we are
1041   // linking with non-static libgcc.
1042   //
1043   // NOTE: This fixes a link error on Android MIPS as well.  The non-static
1044   // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
1045   if (isAndroid && !StaticLibgcc)
1046     CmdArgs.push_back("-ldl");
1047 }
1048 
1049 void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
1050                            ArgStringList &CmdArgs, const ArgList &Args) {
1051   // Make use of compiler-rt if --rtlib option is used
1052   ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
1053 
1054   switch (RLT) {
1055   case ToolChain::RLT_CompilerRT:
1056     CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
1057     break;
1058   case ToolChain::RLT_Libgcc:
1059     // Make sure libgcc is not used under MSVC environment by default
1060     if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
1061       // Issue error diagnostic if libgcc is explicitly specified
1062       // through command line as --rtlib option argument.
1063       if (Args.hasArg(options::OPT_rtlib_EQ)) {
1064         TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
1065             << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
1066       }
1067     } else
1068       AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
1069     break;
1070   }
1071 }
1072 
1073 /// Add OpenMP linker script arguments at the end of the argument list so that
1074 /// the fat binary is built by embedding each of the device images into the
1075 /// host. The linker script also defines a few symbols required by the code
1076 /// generation so that the images can be easily retrieved at runtime by the
1077 /// offloading library. This should be used only in tool chains that support
1078 /// linker scripts.
1079 void tools::AddOpenMPLinkerScript(const ToolChain &TC, Compilation &C,
1080                                   const InputInfo &Output,
1081                                   const InputInfoList &Inputs,
1082                                   const ArgList &Args, ArgStringList &CmdArgs,
1083                                   const JobAction &JA) {
1084 
1085   // If this is not an OpenMP host toolchain, we don't need to do anything.
1086   if (!JA.isHostOffloading(Action::OFK_OpenMP))
1087     return;
1088 
1089   // Create temporary linker script. Keep it if save-temps is enabled.
1090   const char *LKS;
1091   SmallString<256> Name = llvm::sys::path::filename(Output.getFilename());
1092   if (C.getDriver().isSaveTempsEnabled()) {
1093     llvm::sys::path::replace_extension(Name, "lk");
1094     LKS = C.getArgs().MakeArgString(Name.c_str());
1095   } else {
1096     llvm::sys::path::replace_extension(Name, "");
1097     Name = C.getDriver().GetTemporaryPath(Name, "lk");
1098     LKS = C.addTempFile(C.getArgs().MakeArgString(Name.c_str()));
1099   }
1100 
1101   // Add linker script option to the command.
1102   CmdArgs.push_back("-T");
1103   CmdArgs.push_back(LKS);
1104 
1105   // Create a buffer to write the contents of the linker script.
1106   std::string LksBuffer;
1107   llvm::raw_string_ostream LksStream(LksBuffer);
1108 
1109   // Get the OpenMP offload tool chains so that we can extract the triple
1110   // associated with each device input.
1111   auto OpenMPToolChains = C.getOffloadToolChains<Action::OFK_OpenMP>();
1112   assert(OpenMPToolChains.first != OpenMPToolChains.second &&
1113          "No OpenMP toolchains??");
1114 
1115   // Track the input file name and device triple in order to build the script,
1116   // inserting binaries in the designated sections.
1117   SmallVector<std::pair<std::string, const char *>, 8> InputBinaryInfo;
1118 
1119   // Add commands to embed target binaries. We ensure that each section and
1120   // image is 16-byte aligned. This is not mandatory, but increases the
1121   // likelihood of data to be aligned with a cache block in several main host
1122   // machines.
1123   LksStream << "/*\n";
1124   LksStream << "       OpenMP Offload Linker Script\n";
1125   LksStream << " *** Automatically generated by Clang ***\n";
1126   LksStream << "*/\n";
1127   LksStream << "TARGET(binary)\n";
1128   auto DTC = OpenMPToolChains.first;
1129   for (auto &II : Inputs) {
1130     const Action *A = II.getAction();
1131     // Is this a device linking action?
1132     if (A && isa<LinkJobAction>(A) &&
1133         A->isDeviceOffloading(Action::OFK_OpenMP)) {
1134       assert(DTC != OpenMPToolChains.second &&
1135              "More device inputs than device toolchains??");
1136       InputBinaryInfo.push_back(std::make_pair(
1137           DTC->second->getTriple().normalize(), II.getFilename()));
1138       ++DTC;
1139       LksStream << "INPUT(" << II.getFilename() << ")\n";
1140     }
1141   }
1142 
1143   assert(DTC == OpenMPToolChains.second &&
1144          "Less device inputs than device toolchains??");
1145 
1146   LksStream << "SECTIONS\n";
1147   LksStream << "{\n";
1148 
1149   // Put each target binary into a separate section.
1150   for (const auto &BI : InputBinaryInfo) {
1151     LksStream << "  .omp_offloading." << BI.first << " :\n";
1152     LksStream << "  ALIGN(0x10)\n";
1153     LksStream << "  {\n";
1154     LksStream << "    PROVIDE_HIDDEN(.omp_offloading.img_start." << BI.first
1155               << " = .);\n";
1156     LksStream << "    " << BI.second << "\n";
1157     LksStream << "    PROVIDE_HIDDEN(.omp_offloading.img_end." << BI.first
1158               << " = .);\n";
1159     LksStream << "  }\n";
1160   }
1161 
1162   // Add commands to define host entries begin and end. We use 1-byte subalign
1163   // so that the linker does not add any padding and the elements in this
1164   // section form an array.
1165   LksStream << "  .omp_offloading.entries :\n";
1166   LksStream << "  ALIGN(0x10)\n";
1167   LksStream << "  SUBALIGN(0x01)\n";
1168   LksStream << "  {\n";
1169   LksStream << "    PROVIDE_HIDDEN(.omp_offloading.entries_begin = .);\n";
1170   LksStream << "    *(.omp_offloading.entries)\n";
1171   LksStream << "    PROVIDE_HIDDEN(.omp_offloading.entries_end = .);\n";
1172   LksStream << "  }\n";
1173   LksStream << "}\n";
1174   LksStream << "INSERT BEFORE .data\n";
1175   LksStream.flush();
1176 
1177   // Dump the contents of the linker script if the user requested that. We
1178   // support this option to enable testing of behavior with -###.
1179   if (C.getArgs().hasArg(options::OPT_fopenmp_dump_offload_linker_script))
1180     llvm::errs() << LksBuffer;
1181 
1182   // If this is a dry run, do not create the linker script file.
1183   if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1184     return;
1185 
1186   // Open script file and write the contents.
1187   std::error_code EC;
1188   llvm::raw_fd_ostream Lksf(LKS, EC, llvm::sys::fs::F_None);
1189 
1190   if (EC) {
1191     C.getDriver().Diag(clang::diag::err_unable_to_make_temp) << EC.message();
1192     return;
1193   }
1194 
1195   Lksf << LksBuffer;
1196 }
1197