1 //===--- CommonArgs.cpp - Args handling for multiple toolchains -*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "CommonArgs.h"
10 #include "Arch/AArch64.h"
11 #include "Arch/ARM.h"
12 #include "Arch/M68k.h"
13 #include "Arch/Mips.h"
14 #include "Arch/PPC.h"
15 #include "Arch/SystemZ.h"
16 #include "Arch/VE.h"
17 #include "Arch/X86.h"
18 #include "HIP.h"
19 #include "Hexagon.h"
20 #include "clang/Basic/CharInfo.h"
21 #include "clang/Basic/LangOptions.h"
22 #include "clang/Basic/ObjCRuntime.h"
23 #include "clang/Basic/Version.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/InputInfo.h"
30 #include "clang/Driver/Job.h"
31 #include "clang/Driver/Options.h"
32 #include "clang/Driver/SanitizerArgs.h"
33 #include "clang/Driver/ToolChain.h"
34 #include "clang/Driver/Util.h"
35 #include "clang/Driver/XRayArgs.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/SmallString.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/ADT/StringSwitch.h"
40 #include "llvm/ADT/Twine.h"
41 #include "llvm/Config/llvm-config.h"
42 #include "llvm/Option/Arg.h"
43 #include "llvm/Option/ArgList.h"
44 #include "llvm/Option/Option.h"
45 #include "llvm/Support/CodeGen.h"
46 #include "llvm/Support/Compression.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/FileSystem.h"
50 #include "llvm/Support/Host.h"
51 #include "llvm/Support/Path.h"
52 #include "llvm/Support/Process.h"
53 #include "llvm/Support/Program.h"
54 #include "llvm/Support/ScopedPrinter.h"
55 #include "llvm/Support/TargetParser.h"
56 #include "llvm/Support/Threading.h"
57 #include "llvm/Support/VirtualFileSystem.h"
58 #include "llvm/Support/YAMLParser.h"
59
60 using namespace clang::driver;
61 using namespace clang::driver::tools;
62 using namespace clang;
63 using namespace llvm::opt;
64
renderRpassOptions(const ArgList & Args,ArgStringList & CmdArgs)65 static void renderRpassOptions(const ArgList &Args, ArgStringList &CmdArgs) {
66 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ))
67 CmdArgs.push_back(Args.MakeArgString(Twine("--plugin-opt=-pass-remarks=") +
68 A->getValue()));
69
70 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ))
71 CmdArgs.push_back(Args.MakeArgString(
72 Twine("--plugin-opt=-pass-remarks-missed=") + A->getValue()));
73
74 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ))
75 CmdArgs.push_back(Args.MakeArgString(
76 Twine("--plugin-opt=-pass-remarks-analysis=") + A->getValue()));
77 }
78
renderRemarksOptions(const ArgList & Args,ArgStringList & CmdArgs,const llvm::Triple & Triple,const InputInfo & Input,const InputInfo & Output)79 static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
80 const llvm::Triple &Triple,
81 const InputInfo &Input,
82 const InputInfo &Output) {
83 StringRef Format = "yaml";
84 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
85 Format = A->getValue();
86
87 SmallString<128> F;
88 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
89 if (A)
90 F = A->getValue();
91 else if (Output.isFilename())
92 F = Output.getFilename();
93
94 assert(!F.empty() && "Cannot determine remarks output name.");
95 // Append "opt.ld.<format>" to the end of the file name.
96 CmdArgs.push_back(
97 Args.MakeArgString(Twine("--plugin-opt=opt-remarks-filename=") + F +
98 Twine(".opt.ld.") + Format));
99
100 if (const Arg *A =
101 Args.getLastArg(options::OPT_foptimization_record_passes_EQ))
102 CmdArgs.push_back(Args.MakeArgString(
103 Twine("--plugin-opt=opt-remarks-passes=") + A->getValue()));
104
105 CmdArgs.push_back(Args.MakeArgString(
106 Twine("--plugin-opt=opt-remarks-format=") + Format.data()));
107 }
108
renderRemarksHotnessOptions(const ArgList & Args,ArgStringList & CmdArgs)109 static void renderRemarksHotnessOptions(const ArgList &Args,
110 ArgStringList &CmdArgs) {
111 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
112 options::OPT_fno_diagnostics_show_hotness, false))
113 CmdArgs.push_back("--plugin-opt=opt-remarks-with-hotness");
114
115 if (const Arg *A =
116 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ))
117 CmdArgs.push_back(Args.MakeArgString(
118 Twine("--plugin-opt=opt-remarks-hotness-threshold=") + A->getValue()));
119 }
120
addPathIfExists(const Driver & D,const Twine & Path,ToolChain::path_list & Paths)121 void tools::addPathIfExists(const Driver &D, const Twine &Path,
122 ToolChain::path_list &Paths) {
123 if (D.getVFS().exists(Path))
124 Paths.push_back(Path.str());
125 }
126
handleTargetFeaturesGroup(const ArgList & Args,std::vector<StringRef> & Features,OptSpecifier Group)127 void tools::handleTargetFeaturesGroup(const ArgList &Args,
128 std::vector<StringRef> &Features,
129 OptSpecifier Group) {
130 for (const Arg *A : Args.filtered(Group)) {
131 StringRef Name = A->getOption().getName();
132 A->claim();
133
134 // Skip over "-m".
135 assert(Name.startswith("m") && "Invalid feature name.");
136 Name = Name.substr(1);
137
138 bool IsNegative = Name.startswith("no-");
139 if (IsNegative)
140 Name = Name.substr(3);
141 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
142 }
143 }
144
145 std::vector<StringRef>
unifyTargetFeatures(const std::vector<StringRef> & Features)146 tools::unifyTargetFeatures(const std::vector<StringRef> &Features) {
147 std::vector<StringRef> UnifiedFeatures;
148 // Find the last of each feature.
149 llvm::StringMap<unsigned> LastOpt;
150 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
151 StringRef Name = Features[I];
152 assert(Name[0] == '-' || Name[0] == '+');
153 LastOpt[Name.drop_front(1)] = I;
154 }
155
156 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
157 // If this feature was overridden, ignore it.
158 StringRef Name = Features[I];
159 llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name.drop_front(1));
160 assert(LastI != LastOpt.end());
161 unsigned Last = LastI->second;
162 if (Last != I)
163 continue;
164
165 UnifiedFeatures.push_back(Name);
166 }
167 return UnifiedFeatures;
168 }
169
addDirectoryList(const ArgList & Args,ArgStringList & CmdArgs,const char * ArgName,const char * EnvVar)170 void tools::addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
171 const char *ArgName, const char *EnvVar) {
172 const char *DirList = ::getenv(EnvVar);
173 bool CombinedArg = false;
174
175 if (!DirList)
176 return; // Nothing to do.
177
178 StringRef Name(ArgName);
179 if (Name.equals("-I") || Name.equals("-L") || Name.empty())
180 CombinedArg = true;
181
182 StringRef Dirs(DirList);
183 if (Dirs.empty()) // Empty string should not add '.'.
184 return;
185
186 StringRef::size_type Delim;
187 while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
188 if (Delim == 0) { // Leading colon.
189 if (CombinedArg) {
190 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
191 } else {
192 CmdArgs.push_back(ArgName);
193 CmdArgs.push_back(".");
194 }
195 } else {
196 if (CombinedArg) {
197 CmdArgs.push_back(
198 Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
199 } else {
200 CmdArgs.push_back(ArgName);
201 CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
202 }
203 }
204 Dirs = Dirs.substr(Delim + 1);
205 }
206
207 if (Dirs.empty()) { // Trailing colon.
208 if (CombinedArg) {
209 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
210 } else {
211 CmdArgs.push_back(ArgName);
212 CmdArgs.push_back(".");
213 }
214 } else { // Add the last path.
215 if (CombinedArg) {
216 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
217 } else {
218 CmdArgs.push_back(ArgName);
219 CmdArgs.push_back(Args.MakeArgString(Dirs));
220 }
221 }
222 }
223
AddLinkerInputs(const ToolChain & TC,const InputInfoList & Inputs,const ArgList & Args,ArgStringList & CmdArgs,const JobAction & JA)224 void tools::AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
225 const ArgList &Args, ArgStringList &CmdArgs,
226 const JobAction &JA) {
227 const Driver &D = TC.getDriver();
228
229 // Add extra linker input arguments which are not treated as inputs
230 // (constructed via -Xarch_).
231 Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
232
233 // LIBRARY_PATH are included before user inputs and only supported on native
234 // toolchains.
235 if (!TC.isCrossCompiling())
236 addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
237
238 for (const auto &II : Inputs) {
239 // If the current tool chain refers to an OpenMP offloading host, we
240 // should ignore inputs that refer to OpenMP offloading devices -
241 // they will be embedded according to a proper linker script.
242 if (auto *IA = II.getAction())
243 if ((JA.isHostOffloading(Action::OFK_OpenMP) &&
244 IA->isDeviceOffloading(Action::OFK_OpenMP)))
245 continue;
246
247 if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
248 // Don't try to pass LLVM inputs unless we have native support.
249 D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
250
251 // Add filenames immediately.
252 if (II.isFilename()) {
253 CmdArgs.push_back(II.getFilename());
254 continue;
255 }
256
257 // Otherwise, this is a linker input argument.
258 const Arg &A = II.getInputArg();
259
260 // Handle reserved library options.
261 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
262 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
263 else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
264 TC.AddCCKextLibArgs(Args, CmdArgs);
265 else if (A.getOption().matches(options::OPT_z)) {
266 // Pass -z prefix for gcc linker compatibility.
267 A.claim();
268 A.render(Args, CmdArgs);
269 } else {
270 A.renderAsInput(Args, CmdArgs);
271 }
272 }
273 }
274
addLinkerCompressDebugSectionsOption(const ToolChain & TC,const llvm::opt::ArgList & Args,llvm::opt::ArgStringList & CmdArgs)275 void tools::addLinkerCompressDebugSectionsOption(
276 const ToolChain &TC, const llvm::opt::ArgList &Args,
277 llvm::opt::ArgStringList &CmdArgs) {
278 // GNU ld supports --compress-debug-sections=none|zlib|zlib-gnu|zlib-gabi
279 // whereas zlib is an alias to zlib-gabi. Therefore -gz=none|zlib|zlib-gnu
280 // are translated to --compress-debug-sections=none|zlib|zlib-gnu.
281 // -gz is not translated since ld --compress-debug-sections option requires an
282 // argument.
283 if (const Arg *A = Args.getLastArg(options::OPT_gz_EQ)) {
284 StringRef V = A->getValue();
285 if (V == "none" || V == "zlib" || V == "zlib-gnu")
286 CmdArgs.push_back(Args.MakeArgString("--compress-debug-sections=" + V));
287 else
288 TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
289 << A->getOption().getName() << V;
290 }
291 }
292
AddTargetFeature(const ArgList & Args,std::vector<StringRef> & Features,OptSpecifier OnOpt,OptSpecifier OffOpt,StringRef FeatureName)293 void tools::AddTargetFeature(const ArgList &Args,
294 std::vector<StringRef> &Features,
295 OptSpecifier OnOpt, OptSpecifier OffOpt,
296 StringRef FeatureName) {
297 if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
298 if (A->getOption().matches(OnOpt))
299 Features.push_back(Args.MakeArgString("+" + FeatureName));
300 else
301 Features.push_back(Args.MakeArgString("-" + FeatureName));
302 }
303 }
304
305 /// Get the (LLVM) name of the AMDGPU gpu we are targeting.
getAMDGPUTargetGPU(const llvm::Triple & T,const ArgList & Args)306 static std::string getAMDGPUTargetGPU(const llvm::Triple &T,
307 const ArgList &Args) {
308 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
309 auto GPUName = getProcessorFromTargetID(T, A->getValue());
310 return llvm::StringSwitch<std::string>(GPUName)
311 .Cases("rv630", "rv635", "r600")
312 .Cases("rv610", "rv620", "rs780", "rs880")
313 .Case("rv740", "rv770")
314 .Case("palm", "cedar")
315 .Cases("sumo", "sumo2", "sumo")
316 .Case("hemlock", "cypress")
317 .Case("aruba", "cayman")
318 .Default(GPUName.str());
319 }
320 return "";
321 }
322
getLanaiTargetCPU(const ArgList & Args)323 static std::string getLanaiTargetCPU(const ArgList &Args) {
324 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
325 return A->getValue();
326 }
327 return "";
328 }
329
330 /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
getWebAssemblyTargetCPU(const ArgList & Args)331 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
332 // If we have -mcpu=, use that.
333 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
334 StringRef CPU = A->getValue();
335
336 #ifdef __wasm__
337 // Handle "native" by examining the host. "native" isn't meaningful when
338 // cross compiling, so only support this when the host is also WebAssembly.
339 if (CPU == "native")
340 return llvm::sys::getHostCPUName();
341 #endif
342
343 return CPU;
344 }
345
346 return "generic";
347 }
348
getCPUName(const ArgList & Args,const llvm::Triple & T,bool FromAs)349 std::string tools::getCPUName(const ArgList &Args, const llvm::Triple &T,
350 bool FromAs) {
351 Arg *A;
352
353 switch (T.getArch()) {
354 default:
355 return "";
356
357 case llvm::Triple::aarch64:
358 case llvm::Triple::aarch64_32:
359 case llvm::Triple::aarch64_be:
360 return aarch64::getAArch64TargetCPU(Args, T, A);
361
362 case llvm::Triple::arm:
363 case llvm::Triple::armeb:
364 case llvm::Triple::thumb:
365 case llvm::Triple::thumbeb: {
366 StringRef MArch, MCPU;
367 arm::getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
368 return arm::getARMTargetCPU(MCPU, MArch, T);
369 }
370
371 case llvm::Triple::avr:
372 if (const Arg *A = Args.getLastArg(options::OPT_mmcu_EQ))
373 return A->getValue();
374 return "";
375
376 case llvm::Triple::m68k:
377 return m68k::getM68kTargetCPU(Args);
378
379 case llvm::Triple::mips:
380 case llvm::Triple::mipsel:
381 case llvm::Triple::mips64:
382 case llvm::Triple::mips64el: {
383 StringRef CPUName;
384 StringRef ABIName;
385 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
386 return std::string(CPUName);
387 }
388
389 case llvm::Triple::nvptx:
390 case llvm::Triple::nvptx64:
391 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
392 return A->getValue();
393 return "";
394
395 case llvm::Triple::ppc:
396 case llvm::Triple::ppcle:
397 case llvm::Triple::ppc64:
398 case llvm::Triple::ppc64le: {
399 std::string TargetCPUName = ppc::getPPCTargetCPU(Args);
400 // LLVM may default to generating code for the native CPU,
401 // but, like gcc, we default to a more generic option for
402 // each architecture. (except on AIX)
403 if (!TargetCPUName.empty())
404 return TargetCPUName;
405
406 if (T.isOSAIX()) {
407 unsigned major, minor, unused_micro;
408 T.getOSVersion(major, minor, unused_micro);
409 // The minimal arch level moved from pwr4 for AIX7.1 to
410 // pwr7 for AIX7.2.
411 TargetCPUName =
412 (major < 7 || (major == 7 && minor < 2)) ? "pwr4" : "pwr7";
413 } else if (T.getArch() == llvm::Triple::ppc64le)
414 TargetCPUName = "ppc64le";
415 else if (T.getArch() == llvm::Triple::ppc64)
416 TargetCPUName = "ppc64";
417 else
418 TargetCPUName = "ppc";
419
420 return TargetCPUName;
421 }
422 case llvm::Triple::riscv32:
423 case llvm::Triple::riscv64:
424 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
425 return A->getValue();
426 return "";
427
428 case llvm::Triple::bpfel:
429 case llvm::Triple::bpfeb:
430 case llvm::Triple::sparc:
431 case llvm::Triple::sparcel:
432 case llvm::Triple::sparcv9:
433 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
434 return A->getValue();
435 if (T.getArch() == llvm::Triple::sparc && T.isOSSolaris())
436 return "v9";
437 return "";
438
439 case llvm::Triple::x86:
440 case llvm::Triple::x86_64:
441 return x86::getX86TargetCPU(Args, T);
442
443 case llvm::Triple::hexagon:
444 return "hexagon" +
445 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
446
447 case llvm::Triple::lanai:
448 return getLanaiTargetCPU(Args);
449
450 case llvm::Triple::systemz:
451 return systemz::getSystemZTargetCPU(Args);
452
453 case llvm::Triple::r600:
454 case llvm::Triple::amdgcn:
455 return getAMDGPUTargetGPU(T, Args);
456
457 case llvm::Triple::wasm32:
458 case llvm::Triple::wasm64:
459 return std::string(getWebAssemblyTargetCPU(Args));
460 }
461 }
462
getLTOParallelism(const ArgList & Args,const Driver & D)463 llvm::StringRef tools::getLTOParallelism(const ArgList &Args, const Driver &D) {
464 Arg *LtoJobsArg = Args.getLastArg(options::OPT_flto_jobs_EQ);
465 if (!LtoJobsArg)
466 return {};
467 if (!llvm::get_threadpool_strategy(LtoJobsArg->getValue()))
468 D.Diag(diag::err_drv_invalid_int_value)
469 << LtoJobsArg->getAsString(Args) << LtoJobsArg->getValue();
470 return LtoJobsArg->getValue();
471 }
472
473 // CloudABI uses -ffunction-sections and -fdata-sections by default.
isUseSeparateSections(const llvm::Triple & Triple)474 bool tools::isUseSeparateSections(const llvm::Triple &Triple) {
475 return Triple.getOS() == llvm::Triple::CloudABI;
476 }
477
addLTOOptions(const ToolChain & ToolChain,const ArgList & Args,ArgStringList & CmdArgs,const InputInfo & Output,const InputInfo & Input,bool IsThinLTO)478 void tools::addLTOOptions(const ToolChain &ToolChain, const ArgList &Args,
479 ArgStringList &CmdArgs, const InputInfo &Output,
480 const InputInfo &Input, bool IsThinLTO) {
481 const char *Linker = Args.MakeArgString(ToolChain.GetLinkerPath());
482 const Driver &D = ToolChain.getDriver();
483 if (llvm::sys::path::filename(Linker) != "ld.lld" &&
484 llvm::sys::path::stem(Linker) != "ld.lld") {
485 // Tell the linker to load the plugin. This has to come before
486 // AddLinkerInputs as gold requires -plugin to come before any -plugin-opt
487 // that -Wl might forward.
488 CmdArgs.push_back("-plugin");
489
490 #if defined(_WIN32)
491 const char *Suffix = ".dll";
492 #elif defined(__APPLE__)
493 const char *Suffix = ".dylib";
494 #else
495 const char *Suffix = ".so";
496 #endif
497
498 SmallString<1024> Plugin;
499 llvm::sys::path::native(
500 Twine(D.Dir) + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold" + Suffix,
501 Plugin);
502 CmdArgs.push_back(Args.MakeArgString(Plugin));
503 }
504
505 // Try to pass driver level flags relevant to LTO code generation down to
506 // the plugin.
507
508 // Handle flags for selecting CPU variants.
509 std::string CPU = getCPUName(Args, ToolChain.getTriple());
510 if (!CPU.empty())
511 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
512
513 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
514 // The optimization level matches
515 // CompilerInvocation.cpp:getOptimizationLevel().
516 StringRef OOpt;
517 if (A->getOption().matches(options::OPT_O4) ||
518 A->getOption().matches(options::OPT_Ofast))
519 OOpt = "3";
520 else if (A->getOption().matches(options::OPT_O)) {
521 OOpt = A->getValue();
522 if (OOpt == "g")
523 OOpt = "1";
524 else if (OOpt == "s" || OOpt == "z")
525 OOpt = "2";
526 } else if (A->getOption().matches(options::OPT_O0))
527 OOpt = "0";
528 if (!OOpt.empty())
529 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
530 }
531
532 if (Args.hasArg(options::OPT_gsplit_dwarf)) {
533 CmdArgs.push_back(
534 Args.MakeArgString(Twine("-plugin-opt=dwo_dir=") +
535 Output.getFilename() + "_dwo"));
536 }
537
538 if (IsThinLTO)
539 CmdArgs.push_back("-plugin-opt=thinlto");
540
541 StringRef Parallelism = getLTOParallelism(Args, D);
542 if (!Parallelism.empty())
543 CmdArgs.push_back(
544 Args.MakeArgString("-plugin-opt=jobs=" + Twine(Parallelism)));
545
546 // If an explicit debugger tuning argument appeared, pass it along.
547 if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
548 options::OPT_ggdbN_Group)) {
549 if (A->getOption().matches(options::OPT_glldb))
550 CmdArgs.push_back("-plugin-opt=-debugger-tune=lldb");
551 else if (A->getOption().matches(options::OPT_gsce))
552 CmdArgs.push_back("-plugin-opt=-debugger-tune=sce");
553 else if (A->getOption().matches(options::OPT_gdbx))
554 CmdArgs.push_back("-plugin-opt=-debugger-tune=dbx");
555 else
556 CmdArgs.push_back("-plugin-opt=-debugger-tune=gdb");
557 }
558
559 bool UseSeparateSections =
560 isUseSeparateSections(ToolChain.getEffectiveTriple());
561
562 if (Args.hasFlag(options::OPT_ffunction_sections,
563 options::OPT_fno_function_sections, UseSeparateSections)) {
564 CmdArgs.push_back("-plugin-opt=-function-sections");
565 }
566
567 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
568 UseSeparateSections)) {
569 CmdArgs.push_back("-plugin-opt=-data-sections");
570 }
571
572 if (Arg *A = getLastProfileSampleUseArg(Args)) {
573 StringRef FName = A->getValue();
574 if (!llvm::sys::fs::exists(FName))
575 D.Diag(diag::err_drv_no_such_file) << FName;
576 else
577 CmdArgs.push_back(
578 Args.MakeArgString(Twine("-plugin-opt=sample-profile=") + FName));
579 }
580
581 auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
582 options::OPT_fcs_profile_generate_EQ,
583 options::OPT_fno_profile_generate);
584 if (CSPGOGenerateArg &&
585 CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
586 CSPGOGenerateArg = nullptr;
587
588 auto *ProfileUseArg = getLastProfileUseArg(Args);
589
590 if (CSPGOGenerateArg) {
591 CmdArgs.push_back(Args.MakeArgString("-plugin-opt=cs-profile-generate"));
592 if (CSPGOGenerateArg->getOption().matches(
593 options::OPT_fcs_profile_generate_EQ)) {
594 SmallString<128> Path(CSPGOGenerateArg->getValue());
595 llvm::sys::path::append(Path, "default_%m.profraw");
596 CmdArgs.push_back(
597 Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") + Path));
598 } else
599 CmdArgs.push_back(
600 Args.MakeArgString("-plugin-opt=cs-profile-path=default_%m.profraw"));
601 } else if (ProfileUseArg) {
602 SmallString<128> Path(
603 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
604 if (Path.empty() || llvm::sys::fs::is_directory(Path))
605 llvm::sys::path::append(Path, "default.profdata");
606 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=cs-profile-path=") +
607 Path));
608 }
609
610 // Pass an option to enable/disable the new pass manager.
611 if (auto *A = Args.getLastArg(options::OPT_flegacy_pass_manager,
612 options::OPT_fno_legacy_pass_manager)) {
613 if (A->getOption().matches(options::OPT_flegacy_pass_manager))
614 CmdArgs.push_back("-plugin-opt=legacy-pass-manager");
615 else
616 CmdArgs.push_back("-plugin-opt=new-pass-manager");
617 }
618
619 // Pass an option to enable pseudo probe emission.
620 if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling,
621 options::OPT_fno_pseudo_probe_for_profiling, false))
622 CmdArgs.push_back("-plugin-opt=pseudo-probe-for-profiling");
623
624 // Setup statistics file output.
625 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
626 if (!StatsFile.empty())
627 CmdArgs.push_back(
628 Args.MakeArgString(Twine("-plugin-opt=stats-file=") + StatsFile));
629
630 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/true);
631
632 // Handle remark diagnostics on screen options: '-Rpass-*'.
633 renderRpassOptions(Args, CmdArgs);
634
635 // Handle serialized remarks options: '-fsave-optimization-record'
636 // and '-foptimization-record-*'.
637 if (willEmitRemarks(Args))
638 renderRemarksOptions(Args, CmdArgs, ToolChain.getEffectiveTriple(), Input,
639 Output);
640
641 // Handle remarks hotness/threshold related options.
642 renderRemarksHotnessOptions(Args, CmdArgs);
643
644 addMachineOutlinerArgs(D, Args, CmdArgs, ToolChain.getEffectiveTriple(),
645 /*IsLTO=*/true);
646 }
647
addArchSpecificRPath(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)648 void tools::addArchSpecificRPath(const ToolChain &TC, const ArgList &Args,
649 ArgStringList &CmdArgs) {
650 // Enable -frtlib-add-rpath by default for the case of VE.
651 const bool IsVE = TC.getTriple().isVE();
652 bool DefaultValue = IsVE;
653 if (!Args.hasFlag(options::OPT_frtlib_add_rpath,
654 options::OPT_fno_rtlib_add_rpath, DefaultValue))
655 return;
656
657 std::string CandidateRPath = TC.getArchSpecificLibPath();
658 if (TC.getVFS().exists(CandidateRPath)) {
659 CmdArgs.push_back("-rpath");
660 CmdArgs.push_back(Args.MakeArgString(CandidateRPath.c_str()));
661 }
662 }
663
addOpenMPRuntime(ArgStringList & CmdArgs,const ToolChain & TC,const ArgList & Args,bool ForceStaticHostRuntime,bool IsOffloadingHost,bool GompNeedsRT)664 bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
665 const ArgList &Args, bool ForceStaticHostRuntime,
666 bool IsOffloadingHost, bool GompNeedsRT) {
667 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
668 options::OPT_fno_openmp, false))
669 return false;
670
671 Driver::OpenMPRuntimeKind RTKind = TC.getDriver().getOpenMPRuntime(Args);
672
673 if (RTKind == Driver::OMPRT_Unknown)
674 // Already diagnosed.
675 return false;
676
677 if (ForceStaticHostRuntime)
678 CmdArgs.push_back("-Bstatic");
679
680 switch (RTKind) {
681 case Driver::OMPRT_OMP:
682 CmdArgs.push_back("-lomp");
683 break;
684 case Driver::OMPRT_GOMP:
685 CmdArgs.push_back("-lgomp");
686 break;
687 case Driver::OMPRT_IOMP5:
688 CmdArgs.push_back("-liomp5");
689 break;
690 case Driver::OMPRT_Unknown:
691 break;
692 }
693
694 if (ForceStaticHostRuntime)
695 CmdArgs.push_back("-Bdynamic");
696
697 if (RTKind == Driver::OMPRT_GOMP && GompNeedsRT)
698 CmdArgs.push_back("-lrt");
699
700 if (IsOffloadingHost)
701 CmdArgs.push_back("-lomptarget");
702
703 addArchSpecificRPath(TC, Args, CmdArgs);
704
705 return true;
706 }
707
addSanitizerRuntime(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs,StringRef Sanitizer,bool IsShared,bool IsWhole)708 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
709 ArgStringList &CmdArgs, StringRef Sanitizer,
710 bool IsShared, bool IsWhole) {
711 // Wrap any static runtimes that must be forced into executable in
712 // whole-archive.
713 if (IsWhole) CmdArgs.push_back("--whole-archive");
714 CmdArgs.push_back(TC.getCompilerRTArgString(
715 Args, Sanitizer, IsShared ? ToolChain::FT_Shared : ToolChain::FT_Static));
716 if (IsWhole) CmdArgs.push_back("--no-whole-archive");
717
718 if (IsShared) {
719 addArchSpecificRPath(TC, Args, CmdArgs);
720 }
721 }
722
723 // Tries to use a file with the list of dynamic symbols that need to be exported
724 // from the runtime library. Returns true if the file was found.
addSanitizerDynamicList(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs,StringRef Sanitizer)725 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
726 ArgStringList &CmdArgs,
727 StringRef Sanitizer) {
728 // Solaris ld defaults to --export-dynamic behaviour but doesn't support
729 // the option, so don't try to pass it.
730 if (TC.getTriple().getOS() == llvm::Triple::Solaris)
731 return true;
732 SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
733 if (llvm::sys::fs::exists(SanRT + ".syms")) {
734 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
735 return true;
736 }
737 return false;
738 }
739
getAsNeededOption(const ToolChain & TC,bool as_needed)740 static const char *getAsNeededOption(const ToolChain &TC, bool as_needed) {
741 assert(!TC.getTriple().isOSAIX() &&
742 "AIX linker does not support any form of --as-needed option yet.");
743
744 // While the Solaris 11.2 ld added --as-needed/--no-as-needed as aliases
745 // for the native forms -z ignore/-z record, they are missing in Illumos,
746 // so always use the native form.
747 if (TC.getTriple().isOSSolaris())
748 return as_needed ? "-zignore" : "-zrecord";
749 else
750 return as_needed ? "--as-needed" : "--no-as-needed";
751 }
752
linkSanitizerRuntimeDeps(const ToolChain & TC,ArgStringList & CmdArgs)753 void tools::linkSanitizerRuntimeDeps(const ToolChain &TC,
754 ArgStringList &CmdArgs) {
755 // Fuchsia never needs these. Any sanitizer runtimes with system
756 // dependencies use the `.deplibs` feature instead.
757 if (TC.getTriple().isOSFuchsia())
758 return;
759
760 // Force linking against the system libraries sanitizers depends on
761 // (see PR15823 why this is necessary).
762 CmdArgs.push_back(getAsNeededOption(TC, false));
763 // There's no libpthread or librt on RTEMS & Android.
764 if (TC.getTriple().getOS() != llvm::Triple::RTEMS &&
765 !TC.getTriple().isAndroid()) {
766 CmdArgs.push_back("-lpthread");
767 if (!TC.getTriple().isOSOpenBSD())
768 CmdArgs.push_back("-lrt");
769 }
770 CmdArgs.push_back("-lm");
771 // There's no libdl on all OSes.
772 if (!TC.getTriple().isOSFreeBSD() && !TC.getTriple().isOSNetBSD() &&
773 !TC.getTriple().isOSOpenBSD() &&
774 TC.getTriple().getOS() != llvm::Triple::RTEMS)
775 CmdArgs.push_back("-ldl");
776 // Required for backtrace on some OSes
777 if (TC.getTriple().isOSFreeBSD() ||
778 TC.getTriple().isOSNetBSD() ||
779 TC.getTriple().isOSOpenBSD())
780 CmdArgs.push_back("-lexecinfo");
781 }
782
783 static void
collectSanitizerRuntimes(const ToolChain & TC,const ArgList & Args,SmallVectorImpl<StringRef> & SharedRuntimes,SmallVectorImpl<StringRef> & StaticRuntimes,SmallVectorImpl<StringRef> & NonWholeStaticRuntimes,SmallVectorImpl<StringRef> & HelperStaticRuntimes,SmallVectorImpl<StringRef> & RequiredSymbols)784 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
785 SmallVectorImpl<StringRef> &SharedRuntimes,
786 SmallVectorImpl<StringRef> &StaticRuntimes,
787 SmallVectorImpl<StringRef> &NonWholeStaticRuntimes,
788 SmallVectorImpl<StringRef> &HelperStaticRuntimes,
789 SmallVectorImpl<StringRef> &RequiredSymbols) {
790 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
791 // Collect shared runtimes.
792 if (SanArgs.needsSharedRt()) {
793 if (SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) {
794 SharedRuntimes.push_back("asan");
795 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
796 HelperStaticRuntimes.push_back("asan-preinit");
797 }
798 if (SanArgs.needsMemProfRt() && SanArgs.linkRuntimes()) {
799 SharedRuntimes.push_back("memprof");
800 if (!Args.hasArg(options::OPT_shared) && !TC.getTriple().isAndroid())
801 HelperStaticRuntimes.push_back("memprof-preinit");
802 }
803 if (SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) {
804 if (SanArgs.requiresMinimalRuntime())
805 SharedRuntimes.push_back("ubsan_minimal");
806 else
807 SharedRuntimes.push_back("ubsan_standalone");
808 }
809 if (SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) {
810 if (SanArgs.requiresMinimalRuntime())
811 SharedRuntimes.push_back("scudo_minimal");
812 else
813 SharedRuntimes.push_back("scudo");
814 }
815 if (SanArgs.needsTsanRt() && SanArgs.linkRuntimes())
816 SharedRuntimes.push_back("tsan");
817 if (SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) {
818 if (SanArgs.needsHwasanAliasesRt())
819 SharedRuntimes.push_back("hwasan_aliases");
820 else
821 SharedRuntimes.push_back("hwasan");
822 }
823 }
824
825 // The stats_client library is also statically linked into DSOs.
826 if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes())
827 StaticRuntimes.push_back("stats_client");
828
829 // Collect static runtimes.
830 if (Args.hasArg(options::OPT_shared)) {
831 // Don't link static runtimes into DSOs.
832 return;
833 }
834
835 // Each static runtime that has a DSO counterpart above is excluded below,
836 // but runtimes that exist only as static are not affected by needsSharedRt.
837
838 if (!SanArgs.needsSharedRt() && SanArgs.needsAsanRt() && SanArgs.linkRuntimes()) {
839 StaticRuntimes.push_back("asan");
840 if (SanArgs.linkCXXRuntimes())
841 StaticRuntimes.push_back("asan_cxx");
842 }
843
844 if (!SanArgs.needsSharedRt() && SanArgs.needsMemProfRt() &&
845 SanArgs.linkRuntimes()) {
846 StaticRuntimes.push_back("memprof");
847 if (SanArgs.linkCXXRuntimes())
848 StaticRuntimes.push_back("memprof_cxx");
849 }
850
851 if (!SanArgs.needsSharedRt() && SanArgs.needsHwasanRt() && SanArgs.linkRuntimes()) {
852 if (SanArgs.needsHwasanAliasesRt()) {
853 StaticRuntimes.push_back("hwasan_aliases");
854 if (SanArgs.linkCXXRuntimes())
855 StaticRuntimes.push_back("hwasan_aliases_cxx");
856 } else {
857 StaticRuntimes.push_back("hwasan");
858 if (SanArgs.linkCXXRuntimes())
859 StaticRuntimes.push_back("hwasan_cxx");
860 }
861 }
862 if (SanArgs.needsDfsanRt() && SanArgs.linkRuntimes())
863 StaticRuntimes.push_back("dfsan");
864 if (SanArgs.needsLsanRt() && SanArgs.linkRuntimes())
865 StaticRuntimes.push_back("lsan");
866 if (SanArgs.needsMsanRt() && SanArgs.linkRuntimes()) {
867 StaticRuntimes.push_back("msan");
868 if (SanArgs.linkCXXRuntimes())
869 StaticRuntimes.push_back("msan_cxx");
870 }
871 if (!SanArgs.needsSharedRt() && SanArgs.needsTsanRt() &&
872 SanArgs.linkRuntimes()) {
873 StaticRuntimes.push_back("tsan");
874 if (SanArgs.linkCXXRuntimes())
875 StaticRuntimes.push_back("tsan_cxx");
876 }
877 if (!SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes()) {
878 if (SanArgs.requiresMinimalRuntime()) {
879 StaticRuntimes.push_back("ubsan_minimal");
880 } else {
881 StaticRuntimes.push_back("ubsan_standalone");
882 if (SanArgs.linkCXXRuntimes())
883 StaticRuntimes.push_back("ubsan_standalone_cxx");
884 }
885 }
886 if (SanArgs.needsSafeStackRt() && SanArgs.linkRuntimes()) {
887 NonWholeStaticRuntimes.push_back("safestack");
888 RequiredSymbols.push_back("__safestack_init");
889 }
890 if (!(SanArgs.needsSharedRt() && SanArgs.needsUbsanRt() && SanArgs.linkRuntimes())) {
891 if (SanArgs.needsCfiRt() && SanArgs.linkRuntimes())
892 StaticRuntimes.push_back("cfi");
893 if (SanArgs.needsCfiDiagRt() && SanArgs.linkRuntimes()) {
894 StaticRuntimes.push_back("cfi_diag");
895 if (SanArgs.linkCXXRuntimes())
896 StaticRuntimes.push_back("ubsan_standalone_cxx");
897 }
898 }
899 if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes()) {
900 NonWholeStaticRuntimes.push_back("stats");
901 RequiredSymbols.push_back("__sanitizer_stats_register");
902 }
903 if (!SanArgs.needsSharedRt() && SanArgs.needsScudoRt() && SanArgs.linkRuntimes()) {
904 if (SanArgs.requiresMinimalRuntime()) {
905 StaticRuntimes.push_back("scudo_minimal");
906 if (SanArgs.linkCXXRuntimes())
907 StaticRuntimes.push_back("scudo_cxx_minimal");
908 } else {
909 StaticRuntimes.push_back("scudo");
910 if (SanArgs.linkCXXRuntimes())
911 StaticRuntimes.push_back("scudo_cxx");
912 }
913 }
914 }
915
916 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
917 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
addSanitizerRuntimes(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)918 bool tools::addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
919 ArgStringList &CmdArgs) {
920 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
921 NonWholeStaticRuntimes, HelperStaticRuntimes, RequiredSymbols;
922 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
923 NonWholeStaticRuntimes, HelperStaticRuntimes,
924 RequiredSymbols);
925
926 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
927 // Inject libfuzzer dependencies.
928 if (SanArgs.needsFuzzer() && SanArgs.linkRuntimes() &&
929 !Args.hasArg(options::OPT_shared)) {
930
931 addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer", false, true);
932 if (SanArgs.needsFuzzerInterceptors())
933 addSanitizerRuntime(TC, Args, CmdArgs, "fuzzer_interceptors", false,
934 true);
935 if (!Args.hasArg(clang::driver::options::OPT_nostdlibxx)) {
936 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
937 !Args.hasArg(options::OPT_static);
938 if (OnlyLibstdcxxStatic)
939 CmdArgs.push_back("-Bstatic");
940 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
941 if (OnlyLibstdcxxStatic)
942 CmdArgs.push_back("-Bdynamic");
943 }
944 }
945
946 for (auto RT : SharedRuntimes)
947 addSanitizerRuntime(TC, Args, CmdArgs, RT, true, false);
948 for (auto RT : HelperStaticRuntimes)
949 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
950 bool AddExportDynamic = false;
951 for (auto RT : StaticRuntimes) {
952 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, true);
953 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
954 }
955 for (auto RT : NonWholeStaticRuntimes) {
956 addSanitizerRuntime(TC, Args, CmdArgs, RT, false, false);
957 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
958 }
959 for (auto S : RequiredSymbols) {
960 CmdArgs.push_back("-u");
961 CmdArgs.push_back(Args.MakeArgString(S));
962 }
963 // If there is a static runtime with no dynamic list, force all the symbols
964 // to be dynamic to be sure we export sanitizer interface functions.
965 if (AddExportDynamic)
966 CmdArgs.push_back("--export-dynamic");
967
968 if (SanArgs.hasCrossDsoCfi() && !AddExportDynamic)
969 CmdArgs.push_back("--export-dynamic-symbol=__cfi_check");
970
971 return !StaticRuntimes.empty() || !NonWholeStaticRuntimes.empty();
972 }
973
addXRayRuntime(const ToolChain & TC,const ArgList & Args,ArgStringList & CmdArgs)974 bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, ArgStringList &CmdArgs) {
975 if (Args.hasArg(options::OPT_shared))
976 return false;
977
978 if (TC.getXRayArgs().needsXRayRt()) {
979 CmdArgs.push_back("-whole-archive");
980 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray"));
981 for (const auto &Mode : TC.getXRayArgs().modeList())
982 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Mode));
983 CmdArgs.push_back("-no-whole-archive");
984 return true;
985 }
986
987 return false;
988 }
989
linkXRayRuntimeDeps(const ToolChain & TC,ArgStringList & CmdArgs)990 void tools::linkXRayRuntimeDeps(const ToolChain &TC, ArgStringList &CmdArgs) {
991 CmdArgs.push_back(getAsNeededOption(TC, false));
992 CmdArgs.push_back("-lpthread");
993 if (!TC.getTriple().isOSOpenBSD())
994 CmdArgs.push_back("-lrt");
995 CmdArgs.push_back("-lm");
996
997 if (!TC.getTriple().isOSFreeBSD() &&
998 !TC.getTriple().isOSNetBSD() &&
999 !TC.getTriple().isOSOpenBSD())
1000 CmdArgs.push_back("-ldl");
1001 }
1002
areOptimizationsEnabled(const ArgList & Args)1003 bool tools::areOptimizationsEnabled(const ArgList &Args) {
1004 // Find the last -O arg and see if it is non-zero.
1005 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
1006 return !A->getOption().matches(options::OPT_O0);
1007 // Defaults to -O0.
1008 return false;
1009 }
1010
SplitDebugName(const JobAction & JA,const ArgList & Args,const InputInfo & Input,const InputInfo & Output)1011 const char *tools::SplitDebugName(const JobAction &JA, const ArgList &Args,
1012 const InputInfo &Input,
1013 const InputInfo &Output) {
1014 auto AddPostfix = [JA](auto &F) {
1015 if (JA.getOffloadingDeviceKind() == Action::OFK_HIP)
1016 F += (Twine("_") + JA.getOffloadingArch()).str();
1017 F += ".dwo";
1018 };
1019 if (Arg *A = Args.getLastArg(options::OPT_gsplit_dwarf_EQ))
1020 if (StringRef(A->getValue()) == "single")
1021 return Args.MakeArgString(Output.getFilename());
1022
1023 Arg *FinalOutput = Args.getLastArg(options::OPT_o);
1024 if (FinalOutput && Args.hasArg(options::OPT_c)) {
1025 SmallString<128> T(FinalOutput->getValue());
1026 llvm::sys::path::remove_filename(T);
1027 llvm::sys::path::append(T, llvm::sys::path::stem(FinalOutput->getValue()));
1028 AddPostfix(T);
1029 return Args.MakeArgString(T);
1030 } else {
1031 // Use the compilation dir.
1032 Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
1033 options::OPT_fdebug_compilation_dir_EQ);
1034 SmallString<128> T(A ? A->getValue() : "");
1035 SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
1036 AddPostfix(F);
1037 T += F;
1038 return Args.MakeArgString(T);
1039 }
1040 }
1041
SplitDebugInfo(const ToolChain & TC,Compilation & C,const Tool & T,const JobAction & JA,const ArgList & Args,const InputInfo & Output,const char * OutFile)1042 void tools::SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
1043 const JobAction &JA, const ArgList &Args,
1044 const InputInfo &Output, const char *OutFile) {
1045 ArgStringList ExtractArgs;
1046 ExtractArgs.push_back("--extract-dwo");
1047
1048 ArgStringList StripArgs;
1049 StripArgs.push_back("--strip-dwo");
1050
1051 // Grabbing the output of the earlier compile step.
1052 StripArgs.push_back(Output.getFilename());
1053 ExtractArgs.push_back(Output.getFilename());
1054 ExtractArgs.push_back(OutFile);
1055
1056 const char *Exec =
1057 Args.MakeArgString(TC.GetProgramPath(CLANG_DEFAULT_OBJCOPY));
1058 InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
1059
1060 // First extract the dwo sections.
1061 C.addCommand(std::make_unique<Command>(JA, T,
1062 ResponseFileSupport::AtFileCurCP(),
1063 Exec, ExtractArgs, II, Output));
1064
1065 // Then remove them from the original .o file.
1066 C.addCommand(std::make_unique<Command>(
1067 JA, T, ResponseFileSupport::AtFileCurCP(), Exec, StripArgs, II, Output));
1068 }
1069
1070 // Claim options we don't want to warn if they are unused. We do this for
1071 // options that build systems might add but are unused when assembling or only
1072 // running the preprocessor for example.
claimNoWarnArgs(const ArgList & Args)1073 void tools::claimNoWarnArgs(const ArgList &Args) {
1074 // Don't warn about unused -f(no-)?lto. This can happen when we're
1075 // preprocessing, precompiling or assembling.
1076 Args.ClaimAllArgs(options::OPT_flto_EQ);
1077 Args.ClaimAllArgs(options::OPT_flto);
1078 Args.ClaimAllArgs(options::OPT_fno_lto);
1079 }
1080
getLastProfileUseArg(const ArgList & Args)1081 Arg *tools::getLastProfileUseArg(const ArgList &Args) {
1082 auto *ProfileUseArg = Args.getLastArg(
1083 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
1084 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
1085 options::OPT_fno_profile_instr_use);
1086
1087 if (ProfileUseArg &&
1088 ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
1089 ProfileUseArg = nullptr;
1090
1091 return ProfileUseArg;
1092 }
1093
getLastProfileSampleUseArg(const ArgList & Args)1094 Arg *tools::getLastProfileSampleUseArg(const ArgList &Args) {
1095 auto *ProfileSampleUseArg = Args.getLastArg(
1096 options::OPT_fprofile_sample_use, options::OPT_fprofile_sample_use_EQ,
1097 options::OPT_fauto_profile, options::OPT_fauto_profile_EQ,
1098 options::OPT_fno_profile_sample_use, options::OPT_fno_auto_profile);
1099
1100 if (ProfileSampleUseArg &&
1101 (ProfileSampleUseArg->getOption().matches(
1102 options::OPT_fno_profile_sample_use) ||
1103 ProfileSampleUseArg->getOption().matches(options::OPT_fno_auto_profile)))
1104 return nullptr;
1105
1106 return Args.getLastArg(options::OPT_fprofile_sample_use_EQ,
1107 options::OPT_fauto_profile_EQ);
1108 }
1109
1110 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
1111 /// smooshes them together with platform defaults, to decide whether
1112 /// this compile should be using PIC mode or not. Returns a tuple of
1113 /// (RelocationModel, PICLevel, IsPIE).
1114 std::tuple<llvm::Reloc::Model, unsigned, bool>
ParsePICArgs(const ToolChain & ToolChain,const ArgList & Args)1115 tools::ParsePICArgs(const ToolChain &ToolChain, const ArgList &Args) {
1116 const llvm::Triple &EffectiveTriple = ToolChain.getEffectiveTriple();
1117 const llvm::Triple &Triple = ToolChain.getTriple();
1118
1119 bool PIE = ToolChain.isPIEDefault();
1120 bool PIC = PIE || ToolChain.isPICDefault();
1121 // The Darwin/MachO default to use PIC does not apply when using -static.
1122 if (Triple.isOSBinFormatMachO() && Args.hasArg(options::OPT_static))
1123 PIE = PIC = false;
1124 bool IsPICLevelTwo = PIC;
1125
1126 bool KernelOrKext =
1127 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
1128
1129 // Android-specific defaults for PIC/PIE
1130 if (Triple.isAndroid()) {
1131 switch (Triple.getArch()) {
1132 case llvm::Triple::arm:
1133 case llvm::Triple::armeb:
1134 case llvm::Triple::thumb:
1135 case llvm::Triple::thumbeb:
1136 case llvm::Triple::aarch64:
1137 case llvm::Triple::mips:
1138 case llvm::Triple::mipsel:
1139 case llvm::Triple::mips64:
1140 case llvm::Triple::mips64el:
1141 PIC = true; // "-fpic"
1142 break;
1143
1144 case llvm::Triple::x86:
1145 case llvm::Triple::x86_64:
1146 PIC = true; // "-fPIC"
1147 IsPICLevelTwo = true;
1148 break;
1149
1150 default:
1151 break;
1152 }
1153 }
1154
1155 // OpenBSD-specific defaults for PIE
1156 if (Triple.isOSOpenBSD()) {
1157 switch (ToolChain.getArch()) {
1158 case llvm::Triple::arm:
1159 case llvm::Triple::aarch64:
1160 case llvm::Triple::mips64:
1161 case llvm::Triple::mips64el:
1162 case llvm::Triple::x86:
1163 case llvm::Triple::x86_64:
1164 IsPICLevelTwo = false; // "-fpie"
1165 break;
1166
1167 case llvm::Triple::ppc:
1168 case llvm::Triple::sparcv9:
1169 IsPICLevelTwo = true; // "-fPIE"
1170 break;
1171
1172 default:
1173 break;
1174 }
1175 }
1176
1177 // AMDGPU-specific defaults for PIC.
1178 if (Triple.getArch() == llvm::Triple::amdgcn)
1179 PIC = true;
1180
1181 // The last argument relating to either PIC or PIE wins, and no
1182 // other argument is used. If the last argument is any flavor of the
1183 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
1184 // option implicitly enables PIC at the same level.
1185 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
1186 options::OPT_fpic, options::OPT_fno_pic,
1187 options::OPT_fPIE, options::OPT_fno_PIE,
1188 options::OPT_fpie, options::OPT_fno_pie);
1189 if (Triple.isOSWindows() && LastPICArg &&
1190 LastPICArg ==
1191 Args.getLastArg(options::OPT_fPIC, options::OPT_fpic,
1192 options::OPT_fPIE, options::OPT_fpie)) {
1193 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1194 << LastPICArg->getSpelling() << Triple.str();
1195 if (Triple.getArch() == llvm::Triple::x86_64)
1196 return std::make_tuple(llvm::Reloc::PIC_, 2U, false);
1197 return std::make_tuple(llvm::Reloc::Static, 0U, false);
1198 }
1199
1200 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
1201 // is forced, then neither PIC nor PIE flags will have no effect.
1202 if (!ToolChain.isPICDefaultForced()) {
1203 if (LastPICArg) {
1204 Option O = LastPICArg->getOption();
1205 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
1206 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
1207 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
1208 PIC =
1209 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
1210 IsPICLevelTwo =
1211 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
1212 } else {
1213 PIE = PIC = false;
1214 if (EffectiveTriple.isPS4CPU()) {
1215 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
1216 StringRef Model = ModelArg ? ModelArg->getValue() : "";
1217 if (Model != "kernel") {
1218 PIC = true;
1219 ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
1220 << LastPICArg->getSpelling();
1221 }
1222 }
1223 }
1224 }
1225 }
1226
1227 // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
1228 // PIC level would've been set to level 1, force it back to level 2 PIC
1229 // instead.
1230 if (PIC && (Triple.isOSDarwin() || EffectiveTriple.isPS4CPU()))
1231 IsPICLevelTwo |= ToolChain.isPICDefault();
1232
1233 // This kernel flags are a trump-card: they will disable PIC/PIE
1234 // generation, independent of the argument order.
1235 if (KernelOrKext &&
1236 ((!EffectiveTriple.isiOS() || EffectiveTriple.isOSVersionLT(6)) &&
1237 !EffectiveTriple.isWatchOS()))
1238 PIC = PIE = false;
1239
1240 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
1241 // This is a very special mode. It trumps the other modes, almost no one
1242 // uses it, and it isn't even valid on any OS but Darwin.
1243 if (!Triple.isOSDarwin())
1244 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1245 << A->getSpelling() << Triple.str();
1246
1247 // FIXME: Warn when this flag trumps some other PIC or PIE flag.
1248
1249 // Only a forced PIC mode can cause the actual compile to have PIC defines
1250 // etc., no flags are sufficient. This behavior was selected to closely
1251 // match that of llvm-gcc and Apple GCC before that.
1252 PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
1253
1254 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2U : 0U, false);
1255 }
1256
1257 bool EmbeddedPISupported;
1258 switch (Triple.getArch()) {
1259 case llvm::Triple::arm:
1260 case llvm::Triple::armeb:
1261 case llvm::Triple::thumb:
1262 case llvm::Triple::thumbeb:
1263 EmbeddedPISupported = true;
1264 break;
1265 default:
1266 EmbeddedPISupported = false;
1267 break;
1268 }
1269
1270 bool ROPI = false, RWPI = false;
1271 Arg* LastROPIArg = Args.getLastArg(options::OPT_fropi, options::OPT_fno_ropi);
1272 if (LastROPIArg && LastROPIArg->getOption().matches(options::OPT_fropi)) {
1273 if (!EmbeddedPISupported)
1274 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1275 << LastROPIArg->getSpelling() << Triple.str();
1276 ROPI = true;
1277 }
1278 Arg *LastRWPIArg = Args.getLastArg(options::OPT_frwpi, options::OPT_fno_rwpi);
1279 if (LastRWPIArg && LastRWPIArg->getOption().matches(options::OPT_frwpi)) {
1280 if (!EmbeddedPISupported)
1281 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
1282 << LastRWPIArg->getSpelling() << Triple.str();
1283 RWPI = true;
1284 }
1285
1286 // ROPI and RWPI are not compatible with PIC or PIE.
1287 if ((ROPI || RWPI) && (PIC || PIE))
1288 ToolChain.getDriver().Diag(diag::err_drv_ropi_rwpi_incompatible_with_pic);
1289
1290 if (Triple.isMIPS()) {
1291 StringRef CPUName;
1292 StringRef ABIName;
1293 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1294 // When targeting the N64 ABI, PIC is the default, except in the case
1295 // when the -mno-abicalls option is used. In that case we exit
1296 // at next check regardless of PIC being set below.
1297 if (ABIName == "n64")
1298 PIC = true;
1299 // When targettng MIPS with -mno-abicalls, it's always static.
1300 if(Args.hasArg(options::OPT_mno_abicalls))
1301 return std::make_tuple(llvm::Reloc::Static, 0U, false);
1302 // Unlike other architectures, MIPS, even with -fPIC/-mxgot/multigot,
1303 // does not use PIC level 2 for historical reasons.
1304 IsPICLevelTwo = false;
1305 }
1306
1307 if (PIC)
1308 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2U : 1U, PIE);
1309
1310 llvm::Reloc::Model RelocM = llvm::Reloc::Static;
1311 if (ROPI && RWPI)
1312 RelocM = llvm::Reloc::ROPI_RWPI;
1313 else if (ROPI)
1314 RelocM = llvm::Reloc::ROPI;
1315 else if (RWPI)
1316 RelocM = llvm::Reloc::RWPI;
1317
1318 return std::make_tuple(RelocM, 0U, false);
1319 }
1320
1321 // `-falign-functions` indicates that the functions should be aligned to a
1322 // 16-byte boundary.
1323 //
1324 // `-falign-functions=1` is the same as `-fno-align-functions`.
1325 //
1326 // The scalar `n` in `-falign-functions=n` must be an integral value between
1327 // [0, 65536]. If the value is not a power-of-two, it will be rounded up to
1328 // the nearest power-of-two.
1329 //
1330 // If we return `0`, the frontend will default to the backend's preferred
1331 // alignment.
1332 //
1333 // NOTE: icc only allows values between [0, 4096]. icc uses `-falign-functions`
1334 // to mean `-falign-functions=16`. GCC defaults to the backend's preferred
1335 // alignment. For unaligned functions, we default to the backend's preferred
1336 // alignment.
ParseFunctionAlignment(const ToolChain & TC,const ArgList & Args)1337 unsigned tools::ParseFunctionAlignment(const ToolChain &TC,
1338 const ArgList &Args) {
1339 const Arg *A = Args.getLastArg(options::OPT_falign_functions,
1340 options::OPT_falign_functions_EQ,
1341 options::OPT_fno_align_functions);
1342 if (!A || A->getOption().matches(options::OPT_fno_align_functions))
1343 return 0;
1344
1345 if (A->getOption().matches(options::OPT_falign_functions))
1346 return 0;
1347
1348 unsigned Value = 0;
1349 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
1350 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
1351 << A->getAsString(Args) << A->getValue();
1352 return Value ? llvm::Log2_32_Ceil(std::min(Value, 65536u)) : Value;
1353 }
1354
ParseDebugDefaultVersion(const ToolChain & TC,const ArgList & Args)1355 unsigned tools::ParseDebugDefaultVersion(const ToolChain &TC,
1356 const ArgList &Args) {
1357 const Arg *A = Args.getLastArg(options::OPT_fdebug_default_version);
1358
1359 if (!A)
1360 return 0;
1361
1362 unsigned Value = 0;
1363 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 5 ||
1364 Value < 2)
1365 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
1366 << A->getAsString(Args) << A->getValue();
1367 return Value;
1368 }
1369
AddAssemblerKPIC(const ToolChain & ToolChain,const ArgList & Args,ArgStringList & CmdArgs)1370 void tools::AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
1371 ArgStringList &CmdArgs) {
1372 llvm::Reloc::Model RelocationModel;
1373 unsigned PICLevel;
1374 bool IsPIE;
1375 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(ToolChain, Args);
1376
1377 if (RelocationModel != llvm::Reloc::Static)
1378 CmdArgs.push_back("-KPIC");
1379 }
1380
1381 /// Determine whether Objective-C automated reference counting is
1382 /// enabled.
isObjCAutoRefCount(const ArgList & Args)1383 bool tools::isObjCAutoRefCount(const ArgList &Args) {
1384 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
1385 }
1386
1387 enum class LibGccType { UnspecifiedLibGcc, StaticLibGcc, SharedLibGcc };
1388
getLibGccType(const ToolChain & TC,const Driver & D,const ArgList & Args)1389 static LibGccType getLibGccType(const ToolChain &TC, const Driver &D,
1390 const ArgList &Args) {
1391 if (Args.hasArg(options::OPT_static_libgcc) ||
1392 Args.hasArg(options::OPT_static) || Args.hasArg(options::OPT_static_pie))
1393 return LibGccType::StaticLibGcc;
1394 if (Args.hasArg(options::OPT_shared_libgcc))
1395 return LibGccType::SharedLibGcc;
1396 // The Android NDK only provides libunwind.a, not libunwind.so.
1397 if (TC.getTriple().isAndroid())
1398 return LibGccType::StaticLibGcc;
1399 // For MinGW, don't imply a shared libgcc here, we only want to return
1400 // SharedLibGcc if that was explicitly requested.
1401 if (D.CCCIsCXX() && !TC.getTriple().isOSCygMing())
1402 return LibGccType::SharedLibGcc;
1403 return LibGccType::UnspecifiedLibGcc;
1404 }
1405
1406 // Gcc adds libgcc arguments in various ways:
1407 //
1408 // gcc <none>: -lgcc --as-needed -lgcc_s --no-as-needed
1409 // g++ <none>: -lgcc_s -lgcc
1410 // gcc shared: -lgcc_s -lgcc
1411 // g++ shared: -lgcc_s -lgcc
1412 // gcc static: -lgcc -lgcc_eh
1413 // g++ static: -lgcc -lgcc_eh
1414 // gcc static-pie: -lgcc -lgcc_eh
1415 // g++ static-pie: -lgcc -lgcc_eh
1416 //
1417 // Also, certain targets need additional adjustments.
1418
AddUnwindLibrary(const ToolChain & TC,const Driver & D,ArgStringList & CmdArgs,const ArgList & Args)1419 static void AddUnwindLibrary(const ToolChain &TC, const Driver &D,
1420 ArgStringList &CmdArgs, const ArgList &Args) {
1421 ToolChain::UnwindLibType UNW = TC.GetUnwindLibType(Args);
1422 // Targets that don't use unwind libraries.
1423 if ((TC.getTriple().isAndroid() && UNW == ToolChain::UNW_Libgcc) ||
1424 TC.getTriple().isOSIAMCU() || TC.getTriple().isOSBinFormatWasm() ||
1425 UNW == ToolChain::UNW_None)
1426 return;
1427
1428 LibGccType LGT = getLibGccType(TC, D, Args);
1429 bool AsNeeded = LGT == LibGccType::UnspecifiedLibGcc &&
1430 !TC.getTriple().isAndroid() &&
1431 !TC.getTriple().isOSCygMing() && !TC.getTriple().isOSAIX();
1432 if (AsNeeded)
1433 CmdArgs.push_back(getAsNeededOption(TC, true));
1434
1435 switch (UNW) {
1436 case ToolChain::UNW_None:
1437 return;
1438 case ToolChain::UNW_Libgcc: {
1439 if (LGT == LibGccType::StaticLibGcc)
1440 CmdArgs.push_back("-lgcc_eh");
1441 else
1442 CmdArgs.push_back("-lgcc_s");
1443 break;
1444 }
1445 case ToolChain::UNW_CompilerRT:
1446 if (TC.getTriple().isOSAIX()) {
1447 // AIX only has libunwind as a shared library. So do not pass
1448 // anything in if -static is specified.
1449 if (LGT != LibGccType::StaticLibGcc)
1450 CmdArgs.push_back("-lunwind");
1451 } else if (LGT == LibGccType::StaticLibGcc) {
1452 CmdArgs.push_back("-l:libunwind.a");
1453 } else if (TC.getTriple().isOSCygMing()) {
1454 if (LGT == LibGccType::SharedLibGcc)
1455 CmdArgs.push_back("-l:libunwind.dll.a");
1456 else
1457 // Let the linker choose between libunwind.dll.a and libunwind.a
1458 // depending on what's available, and depending on the -static flag
1459 CmdArgs.push_back("-lunwind");
1460 } else {
1461 CmdArgs.push_back("-l:libunwind.so");
1462 }
1463 break;
1464 }
1465
1466 if (AsNeeded)
1467 CmdArgs.push_back(getAsNeededOption(TC, false));
1468 }
1469
AddLibgcc(const ToolChain & TC,const Driver & D,ArgStringList & CmdArgs,const ArgList & Args)1470 static void AddLibgcc(const ToolChain &TC, const Driver &D,
1471 ArgStringList &CmdArgs, const ArgList &Args) {
1472 LibGccType LGT = getLibGccType(TC, D, Args);
1473 if (LGT != LibGccType::SharedLibGcc)
1474 CmdArgs.push_back("-lgcc");
1475 AddUnwindLibrary(TC, D, CmdArgs, Args);
1476 if (LGT == LibGccType::SharedLibGcc)
1477 CmdArgs.push_back("-lgcc");
1478 }
1479
AddRunTimeLibs(const ToolChain & TC,const Driver & D,ArgStringList & CmdArgs,const ArgList & Args)1480 void tools::AddRunTimeLibs(const ToolChain &TC, const Driver &D,
1481 ArgStringList &CmdArgs, const ArgList &Args) {
1482 // Make use of compiler-rt if --rtlib option is used
1483 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
1484
1485 switch (RLT) {
1486 case ToolChain::RLT_CompilerRT:
1487 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
1488 AddUnwindLibrary(TC, D, CmdArgs, Args);
1489 break;
1490 case ToolChain::RLT_Libgcc:
1491 // Make sure libgcc is not used under MSVC environment by default
1492 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
1493 // Issue error diagnostic if libgcc is explicitly specified
1494 // through command line as --rtlib option argument.
1495 if (Args.hasArg(options::OPT_rtlib_EQ)) {
1496 TC.getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform)
1497 << Args.getLastArg(options::OPT_rtlib_EQ)->getValue() << "MSVC";
1498 }
1499 } else
1500 AddLibgcc(TC, D, CmdArgs, Args);
1501 break;
1502 }
1503
1504 // On Android, the unwinder uses dl_iterate_phdr (or one of
1505 // dl_unwind_find_exidx/__gnu_Unwind_Find_exidx on arm32) from libdl.so. For
1506 // statically-linked executables, these functions come from libc.a instead.
1507 if (TC.getTriple().isAndroid() && !Args.hasArg(options::OPT_static) &&
1508 !Args.hasArg(options::OPT_static_pie))
1509 CmdArgs.push_back("-ldl");
1510 }
1511
getStatsFileName(const llvm::opt::ArgList & Args,const InputInfo & Output,const InputInfo & Input,const Driver & D)1512 SmallString<128> tools::getStatsFileName(const llvm::opt::ArgList &Args,
1513 const InputInfo &Output,
1514 const InputInfo &Input,
1515 const Driver &D) {
1516 const Arg *A = Args.getLastArg(options::OPT_save_stats_EQ);
1517 if (!A)
1518 return {};
1519
1520 StringRef SaveStats = A->getValue();
1521 SmallString<128> StatsFile;
1522 if (SaveStats == "obj" && Output.isFilename()) {
1523 StatsFile.assign(Output.getFilename());
1524 llvm::sys::path::remove_filename(StatsFile);
1525 } else if (SaveStats != "cwd") {
1526 D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << SaveStats;
1527 return {};
1528 }
1529
1530 StringRef BaseName = llvm::sys::path::filename(Input.getBaseInput());
1531 llvm::sys::path::append(StatsFile, BaseName);
1532 llvm::sys::path::replace_extension(StatsFile, "stats");
1533 return StatsFile;
1534 }
1535
addMultilibFlag(bool Enabled,const char * const Flag,Multilib::flags_list & Flags)1536 void tools::addMultilibFlag(bool Enabled, const char *const Flag,
1537 Multilib::flags_list &Flags) {
1538 Flags.push_back(std::string(Enabled ? "+" : "-") + Flag);
1539 }
1540
addX86AlignBranchArgs(const Driver & D,const ArgList & Args,ArgStringList & CmdArgs,bool IsLTO)1541 void tools::addX86AlignBranchArgs(const Driver &D, const ArgList &Args,
1542 ArgStringList &CmdArgs, bool IsLTO) {
1543 auto addArg = [&, IsLTO](const Twine &Arg) {
1544 if (IsLTO) {
1545 CmdArgs.push_back(Args.MakeArgString("-plugin-opt=" + Arg));
1546 } else {
1547 CmdArgs.push_back("-mllvm");
1548 CmdArgs.push_back(Args.MakeArgString(Arg));
1549 }
1550 };
1551
1552 if (Args.hasArg(options::OPT_mbranches_within_32B_boundaries)) {
1553 addArg(Twine("-x86-branches-within-32B-boundaries"));
1554 }
1555 if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_boundary_EQ)) {
1556 StringRef Value = A->getValue();
1557 unsigned Boundary;
1558 if (Value.getAsInteger(10, Boundary) || Boundary < 16 ||
1559 !llvm::isPowerOf2_64(Boundary)) {
1560 D.Diag(diag::err_drv_invalid_argument_to_option)
1561 << Value << A->getOption().getName();
1562 } else {
1563 addArg("-x86-align-branch-boundary=" + Twine(Boundary));
1564 }
1565 }
1566 if (const Arg *A = Args.getLastArg(options::OPT_malign_branch_EQ)) {
1567 std::string AlignBranch;
1568 for (StringRef T : A->getValues()) {
1569 if (T != "fused" && T != "jcc" && T != "jmp" && T != "call" &&
1570 T != "ret" && T != "indirect")
1571 D.Diag(diag::err_drv_invalid_malign_branch_EQ)
1572 << T << "fused, jcc, jmp, call, ret, indirect";
1573 if (!AlignBranch.empty())
1574 AlignBranch += '+';
1575 AlignBranch += T;
1576 }
1577 addArg("-x86-align-branch=" + Twine(AlignBranch));
1578 }
1579 if (const Arg *A = Args.getLastArg(options::OPT_mpad_max_prefix_size_EQ)) {
1580 StringRef Value = A->getValue();
1581 unsigned PrefixSize;
1582 if (Value.getAsInteger(10, PrefixSize)) {
1583 D.Diag(diag::err_drv_invalid_argument_to_option)
1584 << Value << A->getOption().getName();
1585 } else {
1586 addArg("-x86-pad-max-prefix-size=" + Twine(PrefixSize));
1587 }
1588 }
1589 }
1590
1591 static llvm::opt::Arg *
getAMDGPUCodeObjectArgument(const Driver & D,const llvm::opt::ArgList & Args)1592 getAMDGPUCodeObjectArgument(const Driver &D, const llvm::opt::ArgList &Args) {
1593 // The last of -mcode-object-v3, -mno-code-object-v3 and
1594 // -mcode-object-version=<version> wins.
1595 return Args.getLastArg(options::OPT_mcode_object_v3_legacy,
1596 options::OPT_mno_code_object_v3_legacy,
1597 options::OPT_mcode_object_version_EQ);
1598 }
1599
checkAMDGPUCodeObjectVersion(const Driver & D,const llvm::opt::ArgList & Args)1600 void tools::checkAMDGPUCodeObjectVersion(const Driver &D,
1601 const llvm::opt::ArgList &Args) {
1602 const unsigned MinCodeObjVer = 2;
1603 const unsigned MaxCodeObjVer = 4;
1604
1605 // Emit warnings for legacy options even if they are overridden.
1606 if (Args.hasArg(options::OPT_mno_code_object_v3_legacy))
1607 D.Diag(diag::warn_drv_deprecated_arg) << "-mno-code-object-v3"
1608 << "-mcode-object-version=2";
1609
1610 if (Args.hasArg(options::OPT_mcode_object_v3_legacy))
1611 D.Diag(diag::warn_drv_deprecated_arg) << "-mcode-object-v3"
1612 << "-mcode-object-version=3";
1613
1614 if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) {
1615 if (CodeObjArg->getOption().getID() ==
1616 options::OPT_mcode_object_version_EQ) {
1617 unsigned CodeObjVer = MaxCodeObjVer;
1618 auto Remnant =
1619 StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer);
1620 if (Remnant || CodeObjVer < MinCodeObjVer || CodeObjVer > MaxCodeObjVer)
1621 D.Diag(diag::err_drv_invalid_int_value)
1622 << CodeObjArg->getAsString(Args) << CodeObjArg->getValue();
1623 }
1624 }
1625 }
1626
getAMDGPUCodeObjectVersion(const Driver & D,const llvm::opt::ArgList & Args)1627 unsigned tools::getAMDGPUCodeObjectVersion(const Driver &D,
1628 const llvm::opt::ArgList &Args) {
1629 unsigned CodeObjVer = 4; // default
1630 if (auto *CodeObjArg = getAMDGPUCodeObjectArgument(D, Args)) {
1631 if (CodeObjArg->getOption().getID() ==
1632 options::OPT_mno_code_object_v3_legacy) {
1633 CodeObjVer = 2;
1634 } else if (CodeObjArg->getOption().getID() ==
1635 options::OPT_mcode_object_v3_legacy) {
1636 CodeObjVer = 3;
1637 } else {
1638 StringRef(CodeObjArg->getValue()).getAsInteger(0, CodeObjVer);
1639 }
1640 }
1641 return CodeObjVer;
1642 }
1643
haveAMDGPUCodeObjectVersionArgument(const Driver & D,const llvm::opt::ArgList & Args)1644 bool tools::haveAMDGPUCodeObjectVersionArgument(
1645 const Driver &D, const llvm::opt::ArgList &Args) {
1646 return getAMDGPUCodeObjectArgument(D, Args) != nullptr;
1647 }
1648
addMachineOutlinerArgs(const Driver & D,const llvm::opt::ArgList & Args,llvm::opt::ArgStringList & CmdArgs,const llvm::Triple & Triple,bool IsLTO)1649 void tools::addMachineOutlinerArgs(const Driver &D,
1650 const llvm::opt::ArgList &Args,
1651 llvm::opt::ArgStringList &CmdArgs,
1652 const llvm::Triple &Triple, bool IsLTO) {
1653 auto addArg = [&, IsLTO](const Twine &Arg) {
1654 if (IsLTO) {
1655 CmdArgs.push_back(Args.MakeArgString("-plugin-opt=" + Arg));
1656 } else {
1657 CmdArgs.push_back("-mllvm");
1658 CmdArgs.push_back(Args.MakeArgString(Arg));
1659 }
1660 };
1661
1662 if (Arg *A = Args.getLastArg(options::OPT_moutline,
1663 options::OPT_mno_outline)) {
1664 if (A->getOption().matches(options::OPT_moutline)) {
1665 // We only support -moutline in AArch64 and ARM targets right now. If
1666 // we're not compiling for these, emit a warning and ignore the flag.
1667 // Otherwise, add the proper mllvm flags.
1668 if (!(Triple.isARM() || Triple.isThumb() ||
1669 Triple.getArch() == llvm::Triple::aarch64 ||
1670 Triple.getArch() == llvm::Triple::aarch64_32)) {
1671 D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
1672 } else {
1673 addArg(Twine("-enable-machine-outliner"));
1674 }
1675 } else {
1676 // Disable all outlining behaviour.
1677 addArg(Twine("-enable-machine-outliner=never"));
1678 }
1679 }
1680 }
1681
addOpenMPDeviceRTL(const Driver & D,const llvm::opt::ArgList & DriverArgs,llvm::opt::ArgStringList & CC1Args,StringRef BitcodeSuffix,const llvm::Triple & Triple)1682 void tools::addOpenMPDeviceRTL(const Driver &D,
1683 const llvm::opt::ArgList &DriverArgs,
1684 llvm::opt::ArgStringList &CC1Args,
1685 StringRef BitcodeSuffix,
1686 const llvm::Triple &Triple) {
1687 SmallVector<StringRef, 8> LibraryPaths;
1688 // Add user defined library paths from LIBRARY_PATH.
1689 llvm::Optional<std::string> LibPath =
1690 llvm::sys::Process::GetEnv("LIBRARY_PATH");
1691 if (LibPath) {
1692 SmallVector<StringRef, 8> Frags;
1693 const char EnvPathSeparatorStr[] = {llvm::sys::EnvPathSeparator, '\0'};
1694 llvm::SplitString(*LibPath, Frags, EnvPathSeparatorStr);
1695 for (StringRef Path : Frags)
1696 LibraryPaths.emplace_back(Path.trim());
1697 }
1698
1699 // Add path to lib / lib64 folder.
1700 SmallString<256> DefaultLibPath = llvm::sys::path::parent_path(D.Dir);
1701 llvm::sys::path::append(DefaultLibPath, Twine("lib") + CLANG_LIBDIR_SUFFIX);
1702 LibraryPaths.emplace_back(DefaultLibPath.c_str());
1703
1704 OptSpecifier LibomptargetBCPathOpt =
1705 Triple.isAMDGCN() ? options::OPT_libomptarget_amdgcn_bc_path_EQ
1706 : options::OPT_libomptarget_nvptx_bc_path_EQ;
1707
1708 StringRef ArchPrefix = Triple.isAMDGCN() ? "amdgcn" : "nvptx";
1709 // First check whether user specifies bc library
1710 if (const Arg *A = DriverArgs.getLastArg(LibomptargetBCPathOpt)) {
1711 std::string LibOmpTargetName(A->getValue());
1712 if (llvm::sys::fs::exists(LibOmpTargetName)) {
1713 CC1Args.push_back("-mlink-builtin-bitcode");
1714 CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetName));
1715 } else {
1716 D.Diag(diag::err_drv_omp_offload_target_bcruntime_not_found)
1717 << LibOmpTargetName;
1718 }
1719 } else {
1720 bool FoundBCLibrary = false;
1721
1722 std::string LibOmpTargetName =
1723 "libomptarget-" + BitcodeSuffix.str() + ".bc";
1724
1725 for (StringRef LibraryPath : LibraryPaths) {
1726 SmallString<128> LibOmpTargetFile(LibraryPath);
1727 llvm::sys::path::append(LibOmpTargetFile, LibOmpTargetName);
1728 if (llvm::sys::fs::exists(LibOmpTargetFile)) {
1729 CC1Args.push_back("-mlink-builtin-bitcode");
1730 CC1Args.push_back(DriverArgs.MakeArgString(LibOmpTargetFile));
1731 FoundBCLibrary = true;
1732 break;
1733 }
1734 }
1735
1736 if (!FoundBCLibrary)
1737 D.Diag(diag::err_drv_omp_offload_target_missingbcruntime)
1738 << LibOmpTargetName << ArchPrefix;
1739 }
1740 }
1741