]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Driver/ToolChains/CommonArgs.cpp
Merge ^/head r318560 through r318657.
[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 "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 getLanaiTargetCPU(const ArgList &Args) {
219   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
220     return A->getValue();
221   }
222   return "";
223 }
224
225 /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
226 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
227   // If we have -mcpu=, use that.
228   if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
229     StringRef CPU = A->getValue();
230
231 #ifdef __wasm__
232     // Handle "native" by examining the host. "native" isn't meaningful when
233     // cross compiling, so only support this when the host is also WebAssembly.
234     if (CPU == "native")
235       return llvm::sys::getHostCPUName();
236 #endif
237
238     return CPU;
239   }
240
241   return "generic";
242 }
243
244 std::string tools::getCPUName(const ArgList &Args, const llvm::Triple &T,
245                               bool FromAs) {
246   Arg *A;
247
248   switch (T.getArch()) {
249   default:
250     return "";
251
252   case llvm::Triple::aarch64:
253   case llvm::Triple::aarch64_be:
254     return aarch64::getAArch64TargetCPU(Args, A);
255
256   case llvm::Triple::arm:
257   case llvm::Triple::armeb:
258   case llvm::Triple::thumb:
259   case llvm::Triple::thumbeb: {
260     StringRef MArch, MCPU;
261     arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
262     return arm::getARMTargetCPU(MCPU, MArch, T);
263   }
264
265   case llvm::Triple::avr:
266     if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ))
267       return A->getValue();
268     return "";
269
270   case llvm::Triple::mips:
271   case llvm::Triple::mipsel:
272   case llvm::Triple::mips64:
273   case llvm::Triple::mips64el: {
274     StringRef CPUName;
275     StringRef ABIName;
276     mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
277     return CPUName;
278   }
279
280   case llvm::Triple::nvptx:
281   case llvm::Triple::nvptx64:
282     if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
283       return A->getValue();
284     return "";
285
286   case llvm::Triple::ppc:
287   case llvm::Triple::ppc64:
288   case llvm::Triple::ppc64le: {
289     std::string TargetCPUName = ppc::getPPCTargetCPU(Args);
290     // LLVM may default to generating code for the native CPU,
291     // but, like gcc, we default to a more generic option for
292     // each architecture. (except on Darwin)
293     if (TargetCPUName.empty() && !T.isOSDarwin()) {
294       if (T.getArch() == llvm::Triple::ppc64)
295         TargetCPUName = "ppc64";
296       else if (T.getArch() == llvm::Triple::ppc64le)
297         TargetCPUName = "ppc64le";
298       else
299         TargetCPUName = "ppc";
300     }
301     return TargetCPUName;
302   }
303
304   case llvm::Triple::sparc:
305   case llvm::Triple::sparcel:
306   case llvm::Triple::sparcv9:
307     if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
308       return A->getValue();
309     return "";
310
311   case llvm::Triple::x86:
312   case llvm::Triple::x86_64:
313     return x86::getX86TargetCPU(Args, T);
314
315   case llvm::Triple::hexagon:
316     return "hexagon" +
317            toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
318
319   case llvm::Triple::lanai:
320     return getLanaiTargetCPU(Args);
321
322   case llvm::Triple::systemz:
323     return systemz::getSystemZTargetCPU(Args);
324
325   case llvm::Triple::r600:
326   case llvm::Triple::amdgcn:
327     return getR600TargetGPU(Args);
328
329   case llvm::Triple::wasm32:
330   case llvm::Triple::wasm64:
331     return getWebAssemblyTargetCPU(Args);
332   }
333 }
334
335 unsigned tools::getLTOParallelism(const ArgList &Args, const Driver &D) {
336   unsigned Parallelism = 0;
337   Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
338   if (LtoJobsArg &&
339       StringRef(LtoJobsArg->getValue()).getAsInteger(10, Parallelism))
340     D.Diag(diag::err_drv_invalid_int_value) << LtoJobsArg->getAsString(Args)
341                                             << LtoJobsArg->getValue();
342   return Parallelism;
343 }
344
345 // CloudABI and WebAssembly use -ffunction-sections and -fdata-sections by
346 // default.
347 bool tools::isUseSeparateSections(const llvm::Triple &Triple) {
348   return Triple.getOS() == llvm::Triple::CloudABI ||
349          Triple.getArch() == llvm::Triple::wasm32 ||
350          Triple.getArch() == llvm::Triple::wasm64;
351 }
352
353 void tools::AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
354                           ArgStringList &CmdArgs, bool IsThinLTO,
355                           const Driver &D) {
356   // Tell the linker to load the plugin. This has to come before AddLinkerInputs
357   // as gold requires -plugin to come before any -plugin-opt that -Wl might
358   // forward.
359   CmdArgs.push_back("-plugin");
360   std::string Plugin =
361       ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
362   CmdArgs.push_back(Args.MakeArgString(Plugin));
363
364   // Try to pass driver level flags relevant to LTO code generation down to
365   // the plugin.
366
367   // Handle flags for selecting CPU variants.
368   std::string CPU = getCPUName(Args, ToolChain.getTriple());
369   if (!CPU.empty())
370     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
371
372   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
373     StringRef OOpt;
374     if (A->getOption().matches(options::OPT_O4) ||
375         A->getOption().matches(options::OPT_Ofast))
376       OOpt = "3";
377     else if (A->getOption().matches(options::OPT_O))
378       OOpt = A->getValue();
379     else if (A->getOption().matches(options::OPT_O0))
380       OOpt = "0";
381     if (!OOpt.empty())
382       CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
383   }
384
385   if (IsThinLTO)
386     CmdArgs.push_back("-plugin-opt=thinlto");
387
388   if (unsigned Parallelism = getLTOParallelism(Args, D))
389     CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=jobs=") +
390                                          llvm::to_string(Parallelism)));
391
392   // If an explicit debugger tuning argument appeared, pass it along.
393   if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
394                                options::OPT_ggdbN_Group)) {
395     if (A->getOption().matches(options::OPT_glldb))
396       CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
397     else if (A->getOption().matches(options::OPT_gsce))
398       CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
399     else
400       CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
401   }
402
403   bool UseSeparateSections =
404       isUseSeparateSections(ToolChain.getEffectiveTriple());
405
406   if (Args.hasFlag(options::OPT_ffunction_sections,
407                    options::OPT_fno_function_sections, UseSeparateSections)) {
408     CmdArgs.push_back("-plugin-opt=-function-sections");
409   }
410
411   if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
412                    UseSeparateSections)) {
413     CmdArgs.push_back("-plugin-opt=-data-sections");
414   }
415
416   if (Arg *A = getLastProfileSampleUseArg(Args)) {
417     StringRef FName = A->getValue();
418     if (!llvm::sys::fs::exists(FName))
419       D.Diag(diag::err_drv_no_such_file) << FName;
420     else
421       CmdArgs.push_back(
422           Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName));
423   }
424 }
425
426 void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args,
427                                  ArgStringList &CmdArgs) {
428   std::string CandidateRPath = TC.getArchSpecificLibPath();
429   if (TC.getVFS().exists(CandidateRPath)) {
430     CmdArgs.push_back("-rpath");
431     CmdArgs.push_back(Args.MakeArgString(CandidateRPath.c_str()));
432   }
433 }
434
435 bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
436                              const ArgList &Args, bool IsOffloadingHost,
437                              bool GompNeedsRT) {
438   if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
439                     options::OPT_fno_openmp, false))
440     return false;
441
442   switch (TC.getDriver().getOpenMPRuntime(Args)) {
443   case Driver::OMPRT_OMP:
444     CmdArgs.push_back("-lomp");
445     break;
446   case Driver::OMPRT_GOMP:
447     CmdArgs.push_back("-lgomp");
448
449     if (GompNeedsRT)
450       CmdArgs.push_back("-lrt");
451     break;
452   case Driver::OMPRT_IOMP5:
453     CmdArgs.push_back("-liomp5");
454     break;
455   case Driver::OMPRT_Unknown:
456     // Already diagnosed.
457     return false;
458   }
459
460   if (IsOffloadingHost)
461     CmdArgs.push_back("-lomptarget");
462
463   addArchSpecificRPath(TC, Args, CmdArgs);
464
465   return true;
466 }
467
468 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
469                                 ArgStringList &CmdArgs, StringRef Sanitizer,
470                                 bool IsShared, bool IsWhole) {
471   // Wrap any static runtimes that must be forced into executable in
472   // whole-archive.
473   if (IsWhole) CmdArgs.push_back("-whole-archive");
474   CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
475   if (IsWhole) CmdArgs.push_back("-no-whole-archive");
476
477   if (IsShared) {
478     addArchSpecificRPath(TC, Args, CmdArgs);
479   }
480 }
481
482 // Tries to use a file with the list of dynamic symbols that need to be exported
483 // from the runtime library. Returns true if the file was found.
484 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
485                                     ArgStringList &CmdArgs,
486                                     StringRef Sanitizer) {
487   SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
488   if (llvm::sys::fs::exists(SanRT + ".syms")) {
489     CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
490     return true;
491   }
492   return false;
493 }
494
495 void tools::linkSanitizerRuntimeDeps(const ToolChain &TC,
496                                      ArgStringList &CmdArgs) {
497   // Force linking against the system libraries sanitizers depends on
498   // (see PR15823 why this is necessary).
499   CmdArgs.push_back("--no-as-needed");
500   // There's no libpthread or librt on RTEMS.
501   if (TC.getTriple().getOS() != llvm::Triple::RTEMS) {
502     CmdArgs.push_back("-lpthread");
503     CmdArgs.push_back("-lrt");
504   }
505   CmdArgs.push_back("-lm");
506   // There's no libdl on FreeBSD or RTEMS.
507   if (TC.getTriple().getOS() != llvm::Triple::FreeBSD &&
508       TC.getTriple().getOS() != llvm::Triple::RTEMS)
509     CmdArgs.push_back("-ldl");
510 }
511
512 static void
513 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
514                          SmallVectorImpl<StringRef> &SharedRuntimes,
515                          SmallVectorImpl<StringRef> &StaticRuntimes,
516                          SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
517                          SmallVectorImpl<StringRef> &HelperStaticRuntimes,
518                          SmallVectorImpl<StringRef> &RequiredSymbols) {
519   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
520   // Collect shared runtimes.
521   if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
522     SharedRuntimes.push_back("asan");
523   }
524   // The stats_client library is also statically linked into DSOs.
525   if (SanArgs.needsStatsRt())
526     StaticRuntimes.push_back("stats_client");
527
528   // Collect static runtimes.
529   if (Args.hasArg(options::OPT_shared) || TC.getTriple().isAndroid()) {
530     // Don't link static runtimes into DSOs or if compiling for Android.
531     return;
532   }
533   if (SanArgs.needsAsanRt()) {
534     if (SanArgs.needsSharedAsanRt()) {
535       HelperStaticRuntimes.push_back("asan-preinit");
536     } else {
537       StaticRuntimes.push_back("asan");
538       if (SanArgs.linkCXXRuntimes())
539         StaticRuntimes.push_back("asan_cxx");
540     }
541   }
542   if (SanArgs.needsDfsanRt())
543     StaticRuntimes.push_back("dfsan");
544   if (SanArgs.needsLsanRt())
545     StaticRuntimes.push_back("lsan");
546   if (SanArgs.needsMsanRt()) {
547     StaticRuntimes.push_back("msan");
548     if (SanArgs.linkCXXRuntimes())
549       StaticRuntimes.push_back("msan_cxx");
550   }
551   if (SanArgs.needsTsanRt()) {
552     StaticRuntimes.push_back("tsan");
553     if (SanArgs.linkCXXRuntimes())
554       StaticRuntimes.push_back("tsan_cxx");
555   }
556   if (SanArgs.needsUbsanRt()) {
557     StaticRuntimes.push_back("ubsan_standalone");
558     if (SanArgs.linkCXXRuntimes())
559       StaticRuntimes.push_back("ubsan_standalone_cxx");
560   }
561   if (SanArgs.needsSafeStackRt()) {
562     NonWholeStaticRuntimes.push_back("safestack");
563     RequiredSymbols.push_back("__safestack_init");
564   }
565   if (SanArgs.needsCfiRt())
566     StaticRuntimes.push_back("cfi");
567   if (SanArgs.needsCfiDiagRt()) {
568     StaticRuntimes.push_back("cfi_diag");
569     if (SanArgs.linkCXXRuntimes())
570       StaticRuntimes.push_back("ubsan_standalone_cxx");
571   }
572   if (SanArgs.needsStatsRt()) {
573     NonWholeStaticRuntimes.push_back("stats");
574     RequiredSymbols.push_back("__sanitizer_stats_register");
575   }
576   if (SanArgs.needsEsanRt())
577     StaticRuntimes.push_back("esan");
578 }
579
580 static void addLibFuzzerRuntime(const ToolChain &TC,
581                                 const ArgList &Args,
582                                 ArgStringList &CmdArgs) {
583     StringRef ParentDir = llvm::sys::path::parent_path(TC.getDriver().InstalledDir);
584     SmallString<128> P(ParentDir);
585     llvm::sys::path::append(P, "lib", "libLLVMFuzzer.a");
586     CmdArgs.push_back(Args.MakeArgString(P));
587     TC.AddCXXStdlibLibArgs(Args, CmdArgs);
588 }
589
590
591 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
592 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
593 bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
594                                  ArgStringList &CmdArgs) {
595   SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
596       NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
597   collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
598                            NonWholeStaticRuntimes, HelperStaticRuntimes,
599                            RequiredSymbols);
600   // Inject libfuzzer dependencies.
601   if (TC.getSanitizerArgs().needsFuzzer()) {
602     addLibFuzzerRuntime(TC, Args, CmdArgs);
603   }
604
605   for (auto RT : SharedRuntimes)
606     addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
607   for (auto RT : HelperStaticRuntimes)
608     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
609   bool AddExportDynamic = false;
610   for (auto RT : StaticRuntimes) {
611     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
612     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
613   }
614   for (auto RT : NonWholeStaticRuntimes) {
615     addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
616     AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
617   }
618   for (auto S : RequiredSymbols) {
619     CmdArgs.push_back("-u");
620     CmdArgs.push_back(Args.MakeArgString(S));
621   }
622   // If there is a static runtime with no dynamic list, force all the symbols
623   // to be dynamic to be sure we export sanitizer interface functions.
624   if (AddExportDynamic)
625     CmdArgs.push_back("-export-dynamic");
626
627   const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
628   if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
629     CmdArgs.push_back("-export-dynamic-symbol=__cfi_check");
630
631   return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
632 }
633
634 bool tools::areOptimizationsEnabled(const ArgList &Args) {
635   // Find the last -O arg and see if it is non-zero.
636   if (Arg *A = Args.getLastArg(options::OPT_O_Group))
637     return !A->getOption().matches(options::OPT_O0);
638   // Defaults to -O0.
639   return false;
640 }
641
642 const char *tools::SplitDebugName(const ArgList &Args, const InputInfo &Input) {
643   Arg *FinalOutput = Args.getLastArg(options::OPT_o);
644   if (FinalOutput && Args.hasArg(options::OPT_c)) {
645     SmallString<128> T(FinalOutput->getValue());
646     llvm::sys::path::replace_extension(T, "dwo");
647     return Args.MakeArgString(T);
648   } else {
649     // Use the compilation dir.
650     SmallString<128> T(
651         Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
652     SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
653     llvm::sys::path::replace_extension(F, "dwo");
654     T += F;
655     return Args.MakeArgString(F);
656   }
657 }
658
659 void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
660                            const JobAction &JA, const ArgList &Args,
661                            const InputInfo &Output, const char *OutFile) {
662   ArgStringList ExtractArgs;
663   ExtractArgs.push_back("--extract-dwo");
664
665   ArgStringList StripArgs;
666   StripArgs.push_back("--strip-dwo");
667
668   // Grabbing the output of the earlier compile step.
669   StripArgs.push_back(Output.getFilename());
670   ExtractArgs.push_back(Output.getFilename());
671   ExtractArgs.push_back(OutFile);
672
673   const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
674   InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
675
676   // First extract the dwo sections.
677   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
678
679   // Then remove them from the original .o file.
680   C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
681 }
682
683 // Claim options we don't want to warn if they are unused. We do this for
684 // options that build systems might add but are unused when assembling or only
685 // running the preprocessor for example.
686 void tools::claimNoWarnArgs(const ArgList &Args) {
687   // Don't warn about unused -f(no-)?lto.  This can happen when we're
688   // preprocessing, precompiling or assembling.
689   Args.ClaimAllArgs(options::OPT_flto_EQ);
690   Args.ClaimAllArgs(options::OPT_flto);
691   Args.ClaimAllArgs(options::OPT_fno_lto);
692 }
693
694 Arg *tools::getLastProfileUseArg(const ArgList &Args) {
695   auto *ProfileUseArg = Args.getLastArg(
696       options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
697       options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
698       options::OPT_fno_profile_instr_use);
699
700   if (ProfileUseArg &&
701       ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
702     ProfileUseArg = nullptr;
703
704   return ProfileUseArg;
705 }
706
707 Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
708   auto *ProfileSampleUseArg = Args.getLastArg(
709       options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ,
710       options::OPT_fauto_profile, options::OPT_fauto_profile_EQ,
711       options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile);
712
713   if (ProfileSampleUseArg &&
714       (ProfileSampleUseArg->getOption().matches(
715            options::OPT_fno_profile_sample_use) ||
716        ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile)))
717     return nullptr;
718
719   return Args.getLastArg(options::OPT_fprofile_sample_use_EQ,
720                          options::OPT_fauto_profile_EQ);
721 }
722
723 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments.  Then,
724 /// smooshes them together with platform defaults, to decide whether
725 /// this compile should be using PIC mode or not. Returns a tuple of
726 /// (RelocationModel, PICLevel, IsPIE).
727 std::tuple<llvm::Reloc::Model, unsigned, bool>
728 tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
729   const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
730   const llvm::Triple &Triple = ToolChain.getTriple();
731
732   bool PIE = ToolChain.isPIEDefault();
733   bool PIC = PIE || ToolChain.isPICDefault();
734   // The Darwin/MachO default to use PIC does not apply when using -static.
735   if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
736     PIE = PIC = false;
737   bool IsPICLevelTwo = PIC;
738
739   bool KernelOrKext =
740       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
741
742   // Android-specific defaults for PIC/PIE
743   if (Triple.isAndroid()) {
744     switch (Triple.getArch()) {
745     case llvm::Triple::arm:
746     case llvm::Triple::armeb:
747     case llvm::Triple::thumb:
748     case llvm::Triple::thumbeb:
749     case llvm::Triple::aarch64:
750     case llvm::Triple::mips:
751     case llvm::Triple::mipsel:
752     case llvm::Triple::mips64:
753     case llvm::Triple::mips64el:
754       PIC = true; // "-fpic"
755       break;
756
757     case llvm::Triple::x86:
758     case llvm::Triple::x86_64:
759       PIC = true; // "-fPIC"
760       IsPICLevelTwo = true;
761       break;
762
763     default:
764       break;
765     }
766   }
767
768   // OpenBSD-specific defaults for PIE
769   if (Triple.getOS() == llvm::Triple::OpenBSD) {
770     switch (ToolChain.getArch()) {
771     case llvm::Triple::arm:
772     case llvm::Triple::aarch64:
773     case llvm::Triple::mips64:
774     case llvm::Triple::mips64el:
775     case llvm::Triple::x86:
776     case llvm::Triple::x86_64:
777       IsPICLevelTwo = false; // "-fpie"
778       break;
779
780     case llvm::Triple::ppc:
781     case llvm::Triple::sparc:
782     case llvm::Triple::sparcel:
783     case llvm::Triple::sparcv9:
784       IsPICLevelTwo = true; // "-fPIE"
785       break;
786
787     default:
788       break;
789     }
790   }
791
792   // The last argument relating to either PIC or PIE wins, and no
793   // other argument is used. If the last argument is any flavor of the
794   // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
795   // option implicitly enables PIC at the same level.
796   Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
797                                     options::OPT_fpic, options::OPT_fno_pic,
798                                     options::OPT_fPIE, options::OPT_fno_PIE,
799                                     options::OPT_fpie, options::OPT_fno_pie);
800   if (Triple.isOSWindows() && LastPICArg &&
801       LastPICArg ==
802           Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
803                           options::OPT_fPIE, options::OPT_fpie)) {
804     ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
805         << LastPICArg->getSpelling() << Triple.str();
806     if (Triple.getArch() == llvm::Triple::x86_64)
807       return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
808     return std::make_tuple(llvm::Reloc::Static, 0U, false);
809   }
810
811   // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
812   // is forced, then neither PIC nor PIE flags will have no effect.
813   if (!ToolChain.isPICDefaultForced()) {
814     if (LastPICArg) {
815       Option O = LastPICArg->getOption();
816       if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
817           O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
818         PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
819         PIC =
820             PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
821         IsPICLevelTwo =
822             O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
823       } else {
824         PIE = PIC = false;
825         if (EffectiveTriple.isPS4CPU()) {
826           Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
827           StringRef Model = ModelArg ? ModelArg->getValue() : "";
828           if (Model != "kernel") {
829             PIC = true;
830             ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
831                 << LastPICArg->getSpelling();
832           }
833         }
834       }
835     }
836   }
837
838   // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
839   // PIC level would've been set to level 1, force it back to level 2 PIC
840   // instead.
841   if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS4CPU()))
842     IsPICLevelTwo |= ToolChain.isPICDefault();
843
844   // This kernel flags are a trump-card: they will disable PIC/PIE
845   // generation, independent of the argument order.
846   if (KernelOrKext &&
847       ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
848        !EffectiveTriple.isWatchOS()))
849     PIC = PIE = false;
850
851   if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
852     // This is a very special mode. It trumps the other modes, almost no one
853     // uses it, and it isn't even valid on any OS but Darwin.
854     if (!Triple.isOSDarwin())
855       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
856           << A->getSpelling() << Triple.str();
857
858     // FIXME: Warn when this flag trumps some other PIC or PIE flag.
859
860     // Only a forced PIC mode can cause the actual compile to have PIC defines
861     // etc., no flags are sufficient. This behavior was selected to closely
862     // match that of llvm-gcc and Apple GCC before that.
863     PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
864
865     return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
866   }
867
868   bool EmbeddedPISupported;
869   switch (Triple.getArch()) {
870     case llvm::Triple::arm:
871     case llvm::Triple::armeb:
872     case llvm::Triple::thumb:
873     case llvm::Triple::thumbeb:
874       EmbeddedPISupported = true;
875       break;
876     default:
877       EmbeddedPISupported = false;
878       break;
879   }
880
881   bool ROPI = false, RWPI = false;
882   Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
883   if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
884     if (!EmbeddedPISupported)
885       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
886           << LastROPIArg->getSpelling() << Triple.str();
887     ROPI = true;
888   }
889   Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
890   if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
891     if (!EmbeddedPISupported)
892       ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
893           << LastRWPIArg->getSpelling() << Triple.str();
894     RWPI = true;
895   }
896
897   // ROPI and RWPI are not comaptible with PIC or PIE.
898   if ((ROPI || RWPI) && (PIC || PIE))
899     ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
900
901   // When targettng MIPS64 with N64, the default is PIC, unless -mno-abicalls is
902   // used.
903   if ((Triple.getArch() == llvm::Triple::mips64 ||
904        Triple.getArch() == llvm::Triple::mips64el) &&
905       Args.hasArg(options::OPT_mno_abicalls))
906     return std::make_tuple(llvm::Reloc::Static, 0U, false);
907
908   if (PIC)
909     return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
910
911   llvm::Reloc::Model RelocM = llvm::Reloc::Static;
912   if (ROPI && RWPI)
913     RelocM = llvm::Reloc::ROPI_RWPI;
914   else if (ROPI)
915     RelocM = llvm::Reloc::ROPI;
916   else if (RWPI)
917     RelocM = llvm::Reloc::RWPI;
918
919   return std::make_tuple(RelocM, 0U, false);
920 }
921
922 void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
923                              ArgStringList &CmdArgs) {
924   llvm::Reloc::Model RelocationModel;
925   unsigned PICLevel;
926   bool IsPIE;
927   std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
928
929   if (RelocationModel != llvm::Reloc::Static)
930     CmdArgs.push_back("-KPIC");
931 }
932
933 /// \brief Determine whether Objective-C automated reference counting is
934 /// enabled.
935 bool tools::isObjCAutoRefCount(const ArgList &Args) {
936   return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
937 }
938
939 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
940                       ArgStringList &CmdArgs, const ArgList &Args) {
941   bool isAndroid = Triple.isAndroid();
942   bool isCygMing = Triple.isOSCygMing();
943   bool IsIAMCU = Triple.isOSIAMCU();
944   bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
945                       Args.hasArg(options::OPT_static);
946   if (!D.CCCIsCXX())
947     CmdArgs.push_back("-lgcc");
948
949   if (StaticLibgcc || isAndroid) {
950     if (D.CCCIsCXX())
951       CmdArgs.push_back("-lgcc");
952   } else {
953     if (!D.CCCIsCXX() && !isCygMing)
954       CmdArgs.push_back("--as-needed");
955     CmdArgs.push_back("-lgcc_s");
956     if (!D.CCCIsCXX() && !isCygMing)
957       CmdArgs.push_back("--no-as-needed");
958   }
959
960   if (StaticLibgcc && !isAndroid && !IsIAMCU)
961     CmdArgs.push_back("-lgcc_eh");
962   else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
963     CmdArgs.push_back("-lgcc");
964
965   // According to Android ABI, we have to link with libdl if we are
966   // linking with non-static libgcc.
967   //
968   // NOTE: This fixes a link error on Android MIPS as well.  The non-static
969   // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
970   if (isAndroid && !StaticLibgcc)
971     CmdArgs.push_back("-ldl");
972 }
973
974 void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
975                            ArgStringList &CmdArgs, const ArgList &Args) {
976   // Make use of compiler-rt if --rtlib option is used
977   ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
978
979   switch (RLT) {
980   case ToolChain::RLT_CompilerRT:
981     switch (TC.getTriple().getOS()) {
982     default:
983       llvm_unreachable("unsupported OS");
984     case llvm::Triple::Win32:
985     case llvm::Triple::Linux:
986     case llvm::Triple::Fuchsia:
987       CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
988       break;
989     }
990     break;
991   case ToolChain::RLT_Libgcc:
992     // Make sure libgcc is not used under MSVC environment by default
993     if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
994       // Issue error diagnostic if libgcc is explicitly specified
995       // through command line as --rtlib option argument.
996       if (Args.hasArg(options::OPT_rtlib_EQ)) {
997         TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
998             << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
999       }
1000     } else
1001       AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
1002     break;
1003   }
1004 }