blob: 6a7f8179b6a84fde9e800b51eb9dc8084c6ad63d [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));
716 CmdArgs.push_back("-no-whole-archive");
717 return true;
718 }
719
720 return false;
721}
722
723void tools::linkXRayRuntimeDeps(const ToolChain &TC, ArgStringList &CmdArgs) {
724 CmdArgs.push_back("--no-as-needed");
725 CmdArgs.push_back("-lpthread");
726 if (TC.getTriple().getOS() != llvm::Triple::OpenBSD)
727 CmdArgs.push_back("-lrt");
728 CmdArgs.push_back("-lm");
729
730 if (TC.getTriple().getOS() != llvm::Triple::FreeBSD &&
731 TC.getTriple().getOS() != llvm::Triple::NetBSD &&
732 TC.getTriple().getOS() != llvm::Triple::OpenBSD)
733 CmdArgs.push_back("-ldl");
734}
735
David L. Jonesf561aba2017-03-08 01:02:16 +0000736bool tools::areOptimizationsEnabled(const ArgList &Args) {
737 // Find the last -O arg and see if it is non-zero.
738 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
739 return !A->getOption().matches(options::OPT_O0);
740 // Defaults to -O0.
741 return false;
742}
743
744const char *tools::SplitDebugName(const ArgList &Args, const InputInfo &Input) {
745 Arg *FinalOutput = Args.getLastArg(options::OPT_o);
746 if (FinalOutput && Args.hasArg(options::OPT_c)) {
747 SmallString<128> T(FinalOutput->getValue());
748 llvm::sys::path::replace_extension(T, "dwo");
749 return Args.MakeArgString(T);
750 } else {
751 // Use the compilation dir.
752 SmallString<128> T(
753 Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
754 SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
755 llvm::sys::path::replace_extension(F, "dwo");
756 T += F;
757 return Args.MakeArgString(F);
758 }
759}
760
761void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
762 const JobAction &JA, const ArgList &Args,
763 const InputInfo &Output, const char *OutFile) {
764 ArgStringList ExtractArgs;
765 ExtractArgs.push_back("--extract-dwo");
766
767 ArgStringList StripArgs;
768 StripArgs.push_back("--strip-dwo");
769
770 // Grabbing the output of the earlier compile step.
771 StripArgs.push_back(Output.getFilename());
772 ExtractArgs.push_back(Output.getFilename());
773 ExtractArgs.push_back(OutFile);
774
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000775 const char *Exec =
776 Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY));
David L. Jonesf561aba2017-03-08 01:02:16 +0000777 InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
778
779 // First extract the dwo sections.
780 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
781
782 // Then remove them from the original .o file.
783 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
784}
785
786// Claim options we don't want to warn if they are unused. We do this for
787// options that build systems might add but are unused when assembling or only
788// running the preprocessor for example.
789void tools::claimNoWarnArgs(const ArgList &Args) {
790 // Don't warn about unused -f(no-)?lto. This can happen when we're
791 // preprocessing, precompiling or assembling.
792 Args.ClaimAllArgs(options::OPT_flto_EQ);
793 Args.ClaimAllArgs(options::OPT_flto);
794 Args.ClaimAllArgs(options::OPT_fno_lto);
795}
796
797Arg *tools::getLastProfileUseArg(const ArgList &Args) {
798 auto *ProfileUseArg = Args.getLastArg(
799 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
800 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
801 options::OPT_fno_profile_instr_use);
802
803 if (ProfileUseArg &&
804 ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
805 ProfileUseArg = nullptr;
806
807 return ProfileUseArg;
808}
809
Dehao Chenea4b78f2017-03-21 21:40:53 +0000810Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
811 auto *ProfileSampleUseArg = Args.getLastArg(
812 options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ,
813 options::OPT_fauto_profile, options::OPT_fauto_profile_EQ,
814 options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile);
815
816 if (ProfileSampleUseArg &&
817 (ProfileSampleUseArg->getOption().matches(
818 options::OPT_fno_profile_sample_use) ||
819 ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile)))
820 return nullptr;
821
822 return Args.getLastArg(options::OPT_fprofile_sample_use_EQ,
823 options::OPT_fauto_profile_EQ);
824}
825
David L. Jonesf561aba2017-03-08 01:02:16 +0000826/// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
827/// smooshes them together with platform defaults, to decide whether
828/// this compile should be using PIC mode or not. Returns a tuple of
829/// (RelocationModel, PICLevel, IsPIE).
830std::tuple<llvm::Reloc::Model, unsigned, bool>
831tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
832 const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
833 const llvm::Triple &Triple = ToolChain.getTriple();
834
835 bool PIE = ToolChain.isPIEDefault();
836 bool PIC = PIE || ToolChain.isPICDefault();
837 // The Darwin/MachO default to use PIC does not apply when using -static.
838 if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
839 PIE = PIC = false;
840 bool IsPICLevelTwo = PIC;
841
842 bool KernelOrKext =
843 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
844
845 // Android-specific defaults for PIC/PIE
846 if (Triple.isAndroid()) {
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 case llvm::Triple::aarch64:
853 case llvm::Triple::mips:
854 case llvm::Triple::mipsel:
855 case llvm::Triple::mips64:
856 case llvm::Triple::mips64el:
857 PIC = true; // "-fpic"
858 break;
859
860 case llvm::Triple::x86:
861 case llvm::Triple::x86_64:
862 PIC = true; // "-fPIC"
863 IsPICLevelTwo = true;
864 break;
865
866 default:
867 break;
868 }
869 }
870
871 // OpenBSD-specific defaults for PIE
872 if (Triple.getOS() == llvm::Triple::OpenBSD) {
873 switch (ToolChain.getArch()) {
Brad Smith3f2b1d72017-03-31 22:13:17 +0000874 case llvm::Triple::arm:
875 case llvm::Triple::aarch64:
David L. Jonesf561aba2017-03-08 01:02:16 +0000876 case llvm::Triple::mips64:
877 case llvm::Triple::mips64el:
David L. Jonesf561aba2017-03-08 01:02:16 +0000878 case llvm::Triple::x86:
879 case llvm::Triple::x86_64:
880 IsPICLevelTwo = false; // "-fpie"
881 break;
882
883 case llvm::Triple::ppc:
884 case llvm::Triple::sparc:
Brad Smith3f2b1d72017-03-31 22:13:17 +0000885 case llvm::Triple::sparcel:
David L. Jonesf561aba2017-03-08 01:02:16 +0000886 case llvm::Triple::sparcv9:
887 IsPICLevelTwo = true; // "-fPIE"
888 break;
889
890 default:
891 break;
892 }
893 }
894
Konstantin Zhuravlyovb4c83a02018-02-15 01:01:53 +0000895 // AMDGPU-specific defaults for PIC.
896 if (Triple.getArch() == llvm::Triple::amdgcn)
897 PIC = true;
898
David L. Jonesf561aba2017-03-08 01:02:16 +0000899 // The last argument relating to either PIC or PIE wins, and no
900 // other argument is used. If the last argument is any flavor of the
901 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
902 // option implicitly enables PIC at the same level.
903 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
904 options::OPT_fpic, options::OPT_fno_pic,
905 options::OPT_fPIE, options::OPT_fno_PIE,
906 options::OPT_fpie, options::OPT_fno_pie);
907 if (Triple.isOSWindows() && LastPICArg &&
908 LastPICArg ==
909 Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
910 options::OPT_fPIE, options::OPT_fpie)) {
911 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
912 << LastPICArg->getSpelling() << Triple.str();
913 if (Triple.getArch() == llvm::Triple::x86_64)
914 return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
915 return std::make_tuple(llvm::Reloc::Static, 0U, false);
916 }
917
918 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
919 // is forced, then neither PIC nor PIE flags will have no effect.
920 if (!ToolChain.isPICDefaultForced()) {
921 if (LastPICArg) {
922 Option O = LastPICArg->getOption();
923 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
924 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
925 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
926 PIC =
927 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
928 IsPICLevelTwo =
929 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
930 } else {
931 PIE = PIC = false;
932 if (EffectiveTriple.isPS4CPU()) {
933 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
934 StringRef Model = ModelArg ? ModelArg->getValue() : "";
935 if (Model != "kernel") {
936 PIC = true;
937 ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
938 << LastPICArg->getSpelling();
939 }
940 }
941 }
942 }
943 }
944
945 // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
946 // PIC level would've been set to level 1, force it back to level 2 PIC
947 // instead.
948 if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS4CPU()))
949 IsPICLevelTwo |= ToolChain.isPICDefault();
950
951 // This kernel flags are a trump-card: they will disable PIC/PIE
952 // generation, independent of the argument order.
953 if (KernelOrKext &&
954 ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
955 !EffectiveTriple.isWatchOS()))
956 PIC = PIE = false;
957
958 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
959 // This is a very special mode. It trumps the other modes, almost no one
960 // uses it, and it isn't even valid on any OS but Darwin.
961 if (!Triple.isOSDarwin())
962 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
963 << A->getSpelling() << Triple.str();
964
965 // FIXME: Warn when this flag trumps some other PIC or PIE flag.
966
967 // Only a forced PIC mode can cause the actual compile to have PIC defines
968 // etc., no flags are sufficient. This behavior was selected to closely
969 // match that of llvm-gcc and Apple GCC before that.
970 PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
971
972 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
973 }
974
975 bool EmbeddedPISupported;
976 switch (Triple.getArch()) {
977 case llvm::Triple::arm:
978 case llvm::Triple::armeb:
979 case llvm::Triple::thumb:
980 case llvm::Triple::thumbeb:
981 EmbeddedPISupported = true;
982 break;
983 default:
984 EmbeddedPISupported = false;
985 break;
986 }
987
988 bool ROPI = false, RWPI = false;
989 Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
990 if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
991 if (!EmbeddedPISupported)
992 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
993 << LastROPIArg->getSpelling() << Triple.str();
994 ROPI = true;
995 }
996 Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
997 if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
998 if (!EmbeddedPISupported)
999 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1000 << LastRWPIArg->getSpelling() << Triple.str();
1001 RWPI = true;
1002 }
1003
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001004 // ROPI and RWPI are not compatible with PIC or PIE.
David L. Jonesf561aba2017-03-08 01:02:16 +00001005 if ((ROPI || RWPI) && (PIC || PIE))
1006 ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
1007
1008 // When targettng MIPS64 with N64, the default is PIC, unless -mno-abicalls is
1009 // used.
1010 if ((Triple.getArch() == llvm::Triple::mips64 ||
1011 Triple.getArch() == llvm::Triple::mips64el) &&
1012 Args.hasArg(options::OPT_mno_abicalls))
1013 return std::make_tuple(llvm::Reloc::Static, 0U, false);
1014
1015 if (PIC)
1016 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
1017
1018 llvm::Reloc::Model RelocM = llvm::Reloc::Static;
1019 if (ROPI && RWPI)
1020 RelocM = llvm::Reloc::ROPI_RWPI;
1021 else if (ROPI)
1022 RelocM = llvm::Reloc::ROPI;
1023 else if (RWPI)
1024 RelocM = llvm::Reloc::RWPI;
1025
1026 return std::make_tuple(RelocM, 0U, false);
1027}
1028
1029void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
1030 ArgStringList &CmdArgs) {
1031 llvm::Reloc::Model RelocationModel;
1032 unsigned PICLevel;
1033 bool IsPIE;
1034 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
1035
1036 if (RelocationModel != llvm::Reloc::Static)
1037 CmdArgs.push_back("-KPIC");
1038}
1039
1040/// \brief Determine whether Objective-C automated reference counting is
1041/// enabled.
1042bool tools::isObjCAutoRefCount(const ArgList &Args) {
1043 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
1044}
1045
1046static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
1047 ArgStringList &CmdArgs, const ArgList &Args) {
1048 bool isAndroid = Triple.isAndroid();
1049 bool isCygMing = Triple.isOSCygMing();
1050 bool IsIAMCU = Triple.isOSIAMCU();
1051 bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
1052 Args.hasArg(options::OPT_static);
1053 if (!D.CCCIsCXX())
1054 CmdArgs.push_back("-lgcc");
1055
1056 if (StaticLibgcc || isAndroid) {
1057 if (D.CCCIsCXX())
1058 CmdArgs.push_back("-lgcc");
1059 } else {
1060 if (!D.CCCIsCXX() && !isCygMing)
1061 CmdArgs.push_back("--as-needed");
1062 CmdArgs.push_back("-lgcc_s");
1063 if (!D.CCCIsCXX() && !isCygMing)
1064 CmdArgs.push_back("--no-as-needed");
1065 }
1066
1067 if (StaticLibgcc && !isAndroid && !IsIAMCU)
1068 CmdArgs.push_back("-lgcc_eh");
1069 else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
1070 CmdArgs.push_back("-lgcc");
1071
1072 // According to Android ABI, we have to link with libdl if we are
1073 // linking with non-static libgcc.
1074 //
1075 // NOTE: This fixes a link error on Android MIPS as well. The non-static
1076 // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
1077 if (isAndroid && !StaticLibgcc)
1078 CmdArgs.push_back("-ldl");
1079}
1080
1081void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
1082 ArgStringList &CmdArgs, const ArgList &Args) {
1083 // Make use of compiler-rt if --rtlib option is used
1084 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
1085
1086 switch (RLT) {
1087 case ToolChain::RLT_CompilerRT:
Sam Clegga08631e2017-10-27 00:26:07 +00001088 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
David L. Jonesf561aba2017-03-08 01:02:16 +00001089 break;
1090 case ToolChain::RLT_Libgcc:
1091 // Make sure libgcc is not used under MSVC environment by default
1092 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
1093 // Issue error diagnostic if libgcc is explicitly specified
1094 // through command line as --rtlib option argument.
1095 if (Args.hasArg(options::OPT_rtlib_EQ)) {
1096 TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
1097 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
1098 }
1099 } else
1100 AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
1101 break;
1102 }
1103}
Gheorghe-Teodor Bercea2c926932017-08-08 14:33:05 +00001104
1105/// Add OpenMP linker script arguments at the end of the argument list so that
1106/// the fat binary is built by embedding each of the device images into the
1107/// host. The linker script also defines a few symbols required by the code
1108/// generation so that the images can be easily retrieved at runtime by the
1109/// offloading library. This should be used only in tool chains that support
1110/// linker scripts.
1111void tools::AddOpenMPLinkerScript(const ToolChain &TC, Compilation &C,
1112 const InputInfo &Output,
1113 const InputInfoList &Inputs,
1114 const ArgList &Args, ArgStringList &CmdArgs,
1115 const JobAction &JA) {
1116
1117 // If this is not an OpenMP host toolchain, we don't need to do anything.
1118 if (!JA.isHostOffloading(Action::OFK_OpenMP))
1119 return;
1120
1121 // Create temporary linker script. Keep it if save-temps is enabled.
1122 const char *LKS;
1123 SmallString<256> Name = llvm::sys::path::filename(Output.getFilename());
1124 if (C.getDriver().isSaveTempsEnabled()) {
1125 llvm::sys::path::replace_extension(Name, "lk");
1126 LKS = C.getArgs().MakeArgString(Name.c_str());
1127 } else {
1128 llvm::sys::path::replace_extension(Name, "");
1129 Name = C.getDriver().GetTemporaryPath(Name, "lk");
1130 LKS = C.addTempFile(C.getArgs().MakeArgString(Name.c_str()));
1131 }
1132
1133 // Add linker script option to the command.
1134 CmdArgs.push_back("-T");
1135 CmdArgs.push_back(LKS);
1136
1137 // Create a buffer to write the contents of the linker script.
1138 std::string LksBuffer;
1139 llvm::raw_string_ostream LksStream(LksBuffer);
1140
1141 // Get the OpenMP offload tool chains so that we can extract the triple
1142 // associated with each device input.
1143 auto OpenMPToolChains = C.getOffloadToolChains<Action::OFK_OpenMP>();
1144 assert(OpenMPToolChains.first != OpenMPToolChains.second &&
1145 "No OpenMP toolchains??");
1146
1147 // Track the input file name and device triple in order to build the script,
1148 // inserting binaries in the designated sections.
1149 SmallVector<std::pair<std::string, const char *>, 8> InputBinaryInfo;
1150
1151 // Add commands to embed target binaries. We ensure that each section and
1152 // image is 16-byte aligned. This is not mandatory, but increases the
1153 // likelihood of data to be aligned with a cache block in several main host
1154 // machines.
1155 LksStream << "/*\n";
1156 LksStream << " OpenMP Offload Linker Script\n";
1157 LksStream << " *** Automatically generated by Clang ***\n";
1158 LksStream << "*/\n";
1159 LksStream << "TARGET(binary)\n";
1160 auto DTC = OpenMPToolChains.first;
1161 for (auto &II : Inputs) {
1162 const Action *A = II.getAction();
1163 // Is this a device linking action?
1164 if (A && isa<LinkJobAction>(A) &&
1165 A->isDeviceOffloading(Action::OFK_OpenMP)) {
1166 assert(DTC != OpenMPToolChains.second &&
1167 "More device inputs than device toolchains??");
1168 InputBinaryInfo.push_back(std::make_pair(
1169 DTC->second->getTriple().normalize(), II.getFilename()));
1170 ++DTC;
1171 LksStream << "INPUT(" << II.getFilename() << ")\n";
1172 }
1173 }
1174
1175 assert(DTC == OpenMPToolChains.second &&
1176 "Less device inputs than device toolchains??");
1177
1178 LksStream << "SECTIONS\n";
1179 LksStream << "{\n";
1180
1181 // Put each target binary into a separate section.
1182 for (const auto &BI : InputBinaryInfo) {
1183 LksStream << " .omp_offloading." << BI.first << " :\n";
1184 LksStream << " ALIGN(0x10)\n";
1185 LksStream << " {\n";
1186 LksStream << " PROVIDE_HIDDEN(.omp_offloading.img_start." << BI.first
1187 << " = .);\n";
1188 LksStream << " " << BI.second << "\n";
1189 LksStream << " PROVIDE_HIDDEN(.omp_offloading.img_end." << BI.first
1190 << " = .);\n";
1191 LksStream << " }\n";
1192 }
1193
1194 // Add commands to define host entries begin and end. We use 1-byte subalign
1195 // so that the linker does not add any padding and the elements in this
1196 // section form an array.
1197 LksStream << " .omp_offloading.entries :\n";
1198 LksStream << " ALIGN(0x10)\n";
1199 LksStream << " SUBALIGN(0x01)\n";
1200 LksStream << " {\n";
1201 LksStream << " PROVIDE_HIDDEN(.omp_offloading.entries_begin = .);\n";
1202 LksStream << " *(.omp_offloading.entries)\n";
1203 LksStream << " PROVIDE_HIDDEN(.omp_offloading.entries_end = .);\n";
1204 LksStream << " }\n";
1205 LksStream << "}\n";
1206 LksStream << "INSERT BEFORE .data\n";
1207 LksStream.flush();
1208
1209 // Dump the contents of the linker script if the user requested that. We
1210 // support this option to enable testing of behavior with -###.
1211 if (C.getArgs().hasArg(options::OPT_fopenmp_dump_offload_linker_script))
1212 llvm::errs() << LksBuffer;
1213
1214 // If this is a dry run, do not create the linker script file.
1215 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1216 return;
1217
1218 // Open script file and write the contents.
1219 std::error_code EC;
1220 llvm::raw_fd_ostream Lksf(LKS, EC, llvm::sys::fs::F_None);
1221
1222 if (EC) {
1223 C.getDriver().Diag(clang::diag::err_unable_to_make_temp) << EC.message();
1224 return;
1225 }
1226
1227 Lksf << LksBuffer;
1228}