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