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