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