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