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