1 //===--- Tools.cpp - Tools Implementations ----------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 #include "InputInfo.h"
12 #include "ToolChains.h"
13 #include "clang/Basic/CharInfo.h"
14 #include "clang/Basic/LangOptions.h"
15 #include "clang/Basic/ObjCRuntime.h"
16 #include "clang/Basic/Version.h"
17 #include "clang/Config/config.h"
18 #include "clang/Driver/Action.h"
19 #include "clang/Driver/Compilation.h"
20 #include "clang/Driver/Driver.h"
21 #include "clang/Driver/DriverDiagnostic.h"
22 #include "clang/Driver/Job.h"
23 #include "clang/Driver/Options.h"
24 #include "clang/Driver/SanitizerArgs.h"
25 #include "clang/Driver/ToolChain.h"
26 #include "clang/Driver/Util.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/StringSwitch.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/Option/Arg.h"
33 #include "llvm/Option/ArgList.h"
34 #include "llvm/Option/Option.h"
35 #include "llvm/Support/CodeGen.h"
36 #include "llvm/Support/Compression.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/FileSystem.h"
39 #include "llvm/Support/Host.h"
40 #include "llvm/Support/Path.h"
41 #include "llvm/Support/Process.h"
42 #include "llvm/Support/Program.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Support/TargetParser.h"
47 #include <unistd.h> // For getuid().
50 using namespace clang::driver;
51 using namespace clang::driver::tools;
52 using namespace clang;
53 using namespace llvm::opt;
55 static void handleTargetFeaturesGroup(const ArgList &Args,
56 std::vector<const char *> &Features,
58 for (const Arg *A : Args.filtered(Group)) {
59 StringRef Name = A->getOption().getName();
63 assert(Name.startswith("m") && "Invalid feature name.");
64 Name = Name.substr(1);
66 bool IsNegative = Name.startswith("no-");
68 Name = Name.substr(3);
69 Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
73 static const char *getSparcAsmModeForCPU(StringRef Name,
74 const llvm::Triple &Triple) {
75 if (Triple.getArch() == llvm::Triple::sparcv9) {
76 return llvm::StringSwitch<const char *>(Name)
77 .Case("niagara", "-Av9b")
78 .Case("niagara2", "-Av9b")
79 .Case("niagara3", "-Av9d")
80 .Case("niagara4", "-Av9d")
83 return llvm::StringSwitch<const char *>(Name)
85 .Case("supersparc", "-Av8")
86 .Case("sparclite", "-Asparclite")
87 .Case("f934", "-Asparclite")
88 .Case("hypersparc", "-Av8")
89 .Case("sparclite86x", "-Asparclite")
90 .Case("sparclet", "-Asparclet")
91 .Case("tsc701", "-Asparclet")
92 .Case("v9", "-Av8plus")
93 .Case("ultrasparc", "-Av8plus")
94 .Case("ultrasparc3", "-Av8plus")
95 .Case("niagara", "-Av8plusb")
96 .Case("niagara2", "-Av8plusb")
97 .Case("niagara3", "-Av8plusd")
98 .Case("niagara4", "-Av8plusd")
103 /// CheckPreprocessingOptions - Perform some validation of preprocessing
104 /// arguments that is shared with gcc.
105 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
106 if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC)) {
107 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
108 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
109 D.Diag(diag::err_drv_argument_only_allowed_with)
110 << A->getBaseArg().getAsString(Args)
111 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
116 /// CheckCodeGenerationOptions - Perform some validation of code generation
117 /// arguments that is shared with gcc.
118 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
119 // In gcc, only ARM checks this, but it seems reasonable to check universally.
120 if (Args.hasArg(options::OPT_static))
122 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
123 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
127 // Add backslashes to escape spaces and other backslashes.
128 // This is used for the space-separated argument list specified with
129 // the -dwarf-debug-flags option.
130 static void EscapeSpacesAndBackslashes(const char *Arg,
131 SmallVectorImpl<char> &Res) {
132 for (; *Arg; ++Arg) {
145 // Quote target names for inclusion in GNU Make dependency files.
146 // Only the characters '$', '#', ' ', '\t' are quoted.
147 static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
148 for (unsigned i = 0, e = Target.size(); i != e; ++i) {
152 // Escape the preceding backslashes
153 for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
156 // Escape the space/tab
169 Res.push_back(Target[i]);
173 static void addDirectoryList(const ArgList &Args, ArgStringList &CmdArgs,
174 const char *ArgName, const char *EnvVar) {
175 const char *DirList = ::getenv(EnvVar);
176 bool CombinedArg = false;
179 return; // Nothing to do.
181 StringRef Name(ArgName);
182 if (Name.equals("-I") || Name.equals("-L"))
185 StringRef Dirs(DirList);
186 if (Dirs.empty()) // Empty string should not add '.'.
189 StringRef::size_type Delim;
190 while ((Delim = Dirs.find(llvm::sys::EnvPathSeparator)) != StringRef::npos) {
191 if (Delim == 0) { // Leading colon.
193 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
195 CmdArgs.push_back(ArgName);
196 CmdArgs.push_back(".");
201 Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim)));
203 CmdArgs.push_back(ArgName);
204 CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim)));
207 Dirs = Dirs.substr(Delim + 1);
210 if (Dirs.empty()) { // Trailing colon.
212 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + "."));
214 CmdArgs.push_back(ArgName);
215 CmdArgs.push_back(".");
217 } else { // Add the last path.
219 CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs));
221 CmdArgs.push_back(ArgName);
222 CmdArgs.push_back(Args.MakeArgString(Dirs));
227 static void AddLinkerInputs(const ToolChain &TC, const InputInfoList &Inputs,
228 const ArgList &Args, ArgStringList &CmdArgs) {
229 const Driver &D = TC.getDriver();
231 // Add extra linker input arguments which are not treated as inputs
232 // (constructed via -Xarch_).
233 Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input);
235 for (const auto &II : Inputs) {
236 if (!TC.HasNativeLLVMSupport() && types::isLLVMIR(II.getType()))
237 // Don't try to pass LLVM inputs unless we have native support.
238 D.Diag(diag::err_drv_no_linker_llvm_support) << TC.getTripleString();
240 // Add filenames immediately.
241 if (II.isFilename()) {
242 CmdArgs.push_back(II.getFilename());
246 // Otherwise, this is a linker input argument.
247 const Arg &A = II.getInputArg();
249 // Handle reserved library options.
250 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx))
251 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
252 else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext))
253 TC.AddCCKextLibArgs(Args, CmdArgs);
254 else if (A.getOption().matches(options::OPT_z)) {
255 // Pass -z prefix for gcc linker compatibility.
257 A.render(Args, CmdArgs);
259 A.renderAsInput(Args, CmdArgs);
263 // LIBRARY_PATH - included following the user specified library paths.
264 // and only supported on native toolchains.
265 if (!TC.isCrossCompiling())
266 addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
269 /// \brief Determine whether Objective-C automated reference counting is
271 static bool isObjCAutoRefCount(const ArgList &Args) {
272 return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false);
275 /// \brief Determine whether we are linking the ObjC runtime.
276 static bool isObjCRuntimeLinked(const ArgList &Args) {
277 if (isObjCAutoRefCount(Args)) {
278 Args.ClaimAllArgs(options::OPT_fobjc_link_runtime);
281 return Args.hasArg(options::OPT_fobjc_link_runtime);
284 static bool forwardToGCC(const Option &O) {
285 // Don't forward inputs from the original command line. They are added from
287 return O.getKind() != Option::InputClass &&
288 !O.hasFlag(options::DriverOption) && !O.hasFlag(options::LinkerInput);
291 void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
292 const Driver &D, const ArgList &Args,
293 ArgStringList &CmdArgs,
294 const InputInfo &Output,
295 const InputInfoList &Inputs,
296 const ToolChain *AuxToolChain) const {
299 CheckPreprocessingOptions(D, Args);
301 Args.AddLastArg(CmdArgs, options::OPT_C);
302 Args.AddLastArg(CmdArgs, options::OPT_CC);
304 // Handle dependency file generation.
305 if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
306 (A = Args.getLastArg(options::OPT_MD)) ||
307 (A = Args.getLastArg(options::OPT_MMD))) {
308 // Determine the output location.
310 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
311 DepFile = MF->getValue();
312 C.addFailureResultFile(DepFile, &JA);
313 } else if (Output.getType() == types::TY_Dependencies) {
314 DepFile = Output.getFilename();
315 } else if (A->getOption().matches(options::OPT_M) ||
316 A->getOption().matches(options::OPT_MM)) {
319 DepFile = getDependencyFileName(Args, Inputs);
320 C.addFailureResultFile(DepFile, &JA);
322 CmdArgs.push_back("-dependency-file");
323 CmdArgs.push_back(DepFile);
325 // Add a default target if one wasn't specified.
326 if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
327 const char *DepTarget;
329 // If user provided -o, that is the dependency target, except
330 // when we are only generating a dependency file.
331 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
332 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
333 DepTarget = OutputOpt->getValue();
335 // Otherwise derive from the base input.
337 // FIXME: This should use the computed output file location.
338 SmallString<128> P(Inputs[0].getBaseInput());
339 llvm::sys::path::replace_extension(P, "o");
340 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
343 CmdArgs.push_back("-MT");
344 SmallString<128> Quoted;
345 QuoteTarget(DepTarget, Quoted);
346 CmdArgs.push_back(Args.MakeArgString(Quoted));
349 if (A->getOption().matches(options::OPT_M) ||
350 A->getOption().matches(options::OPT_MD))
351 CmdArgs.push_back("-sys-header-deps");
352 if ((isa<PrecompileJobAction>(JA) &&
353 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
354 Args.hasArg(options::OPT_fmodule_file_deps))
355 CmdArgs.push_back("-module-file-deps");
358 if (Args.hasArg(options::OPT_MG)) {
359 if (!A || A->getOption().matches(options::OPT_MD) ||
360 A->getOption().matches(options::OPT_MMD))
361 D.Diag(diag::err_drv_mg_requires_m_or_mm);
362 CmdArgs.push_back("-MG");
365 Args.AddLastArg(CmdArgs, options::OPT_MP);
366 Args.AddLastArg(CmdArgs, options::OPT_MV);
368 // Convert all -MQ <target> args to -MT <quoted target>
369 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
372 if (A->getOption().matches(options::OPT_MQ)) {
373 CmdArgs.push_back("-MT");
374 SmallString<128> Quoted;
375 QuoteTarget(A->getValue(), Quoted);
376 CmdArgs.push_back(Args.MakeArgString(Quoted));
378 // -MT flag - no change
380 A->render(Args, CmdArgs);
384 // Add -i* options, and automatically translate to
385 // -include-pch/-include-pth for transparent PCH support. It's
386 // wonky, but we include looking for .gch so we can support seamless
387 // replacement into a build system already set up to be generating
389 bool RenderedImplicitInclude = false;
390 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
391 if (A->getOption().matches(options::OPT_include)) {
392 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
393 RenderedImplicitInclude = true;
395 // Use PCH if the user requested it.
396 bool UsePCH = D.CCCUsePCH;
398 bool FoundPTH = false;
399 bool FoundPCH = false;
400 SmallString<128> P(A->getValue());
401 // We want the files to have a name like foo.h.pch. Add a dummy extension
402 // so that replace_extension does the right thing.
405 llvm::sys::path::replace_extension(P, "pch");
406 if (llvm::sys::fs::exists(P))
411 llvm::sys::path::replace_extension(P, "pth");
412 if (llvm::sys::fs::exists(P))
416 if (!FoundPCH && !FoundPTH) {
417 llvm::sys::path::replace_extension(P, "gch");
418 if (llvm::sys::fs::exists(P)) {
424 if (FoundPCH || FoundPTH) {
425 if (IsFirstImplicitInclude) {
428 CmdArgs.push_back("-include-pch");
430 CmdArgs.push_back("-include-pth");
431 CmdArgs.push_back(Args.MakeArgString(P));
434 // Ignore the PCH if not first on command line and emit warning.
435 D.Diag(diag::warn_drv_pch_not_first_include) << P
436 << A->getAsString(Args);
441 // Not translated, render as usual.
443 A->render(Args, CmdArgs);
446 Args.AddAllArgs(CmdArgs,
447 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
448 options::OPT_F, options::OPT_index_header_map});
450 // Add -Wp, and -Xpreprocessor if using the preprocessor.
452 // FIXME: There is a very unfortunate problem here, some troubled
453 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
454 // really support that we would have to parse and then translate
456 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
457 options::OPT_Xpreprocessor);
459 // -I- is a deprecated GCC feature, reject it.
460 if (Arg *A = Args.getLastArg(options::OPT_I_))
461 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
463 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
464 // -isysroot to the CC1 invocation.
465 StringRef sysroot = C.getSysRoot();
467 if (!Args.hasArg(options::OPT_isysroot)) {
468 CmdArgs.push_back("-isysroot");
469 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
473 // Parse additional include paths from environment variables.
474 // FIXME: We should probably sink the logic for handling these from the
475 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
476 // CPATH - included following the user specified includes (but prior to
477 // builtin and standard includes).
478 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
479 // C_INCLUDE_PATH - system includes enabled when compiling C.
480 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
481 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
482 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
483 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
484 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
485 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
486 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
488 // Optional AuxToolChain indicates that we need to include headers
489 // for more than one target. If that's the case, add include paths
490 // from AuxToolChain right after include paths of the same kind for
491 // the current target.
493 // Add C++ include arguments, if needed.
494 if (types::isCXX(Inputs[0].getType())) {
495 getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
497 AuxToolChain->AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
500 // Add system include arguments.
501 getToolChain().AddClangSystemIncludeArgs(Args, CmdArgs);
503 AuxToolChain->AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
505 // Add CUDA include arguments, if needed.
506 if (types::isCuda(Inputs[0].getType()))
507 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
510 // FIXME: Move to target hook.
511 static bool isSignedCharDefault(const llvm::Triple &Triple) {
512 switch (Triple.getArch()) {
516 case llvm::Triple::aarch64:
517 case llvm::Triple::aarch64_be:
518 case llvm::Triple::arm:
519 case llvm::Triple::armeb:
520 case llvm::Triple::thumb:
521 case llvm::Triple::thumbeb:
522 if (Triple.isOSDarwin() || Triple.isOSWindows())
526 case llvm::Triple::ppc:
527 case llvm::Triple::ppc64:
528 if (Triple.isOSDarwin())
532 case llvm::Triple::hexagon:
533 case llvm::Triple::ppc64le:
534 case llvm::Triple::systemz:
535 case llvm::Triple::xcore:
540 static bool isNoCommonDefault(const llvm::Triple &Triple) {
541 switch (Triple.getArch()) {
545 case llvm::Triple::xcore:
546 case llvm::Triple::wasm32:
547 case llvm::Triple::wasm64:
555 static int getARMSubArchVersionNumber(const llvm::Triple &Triple) {
556 llvm::StringRef Arch = Triple.getArchName();
557 return llvm::ARM::parseArchVersion(Arch);
560 // True if M-profile.
561 static bool isARMMProfile(const llvm::Triple &Triple) {
562 llvm::StringRef Arch = Triple.getArchName();
563 unsigned Profile = llvm::ARM::parseArchProfile(Arch);
564 return Profile == llvm::ARM::PK_M;
567 // Get Arch/CPU from args.
568 static void getARMArchCPUFromArgs(const ArgList &Args, llvm::StringRef &Arch,
569 llvm::StringRef &CPU, bool FromAs = false) {
570 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
572 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
573 Arch = A->getValue();
578 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
579 StringRef Value = A->getValue();
580 if (Value.startswith("-mcpu="))
581 CPU = Value.substr(6);
582 if (Value.startswith("-march="))
583 Arch = Value.substr(7);
588 // FIXME: Use ARMTargetParser.
589 static void getARMHWDivFeatures(const Driver &D, const Arg *A,
590 const ArgList &Args, StringRef HWDiv,
591 std::vector<const char *> &Features) {
592 unsigned HWDivID = llvm::ARM::parseHWDiv(HWDiv);
593 if (!llvm::ARM::getHWDivFeatures(HWDivID, Features))
594 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
598 static void getARMFPUFeatures(const Driver &D, const Arg *A,
599 const ArgList &Args, StringRef FPU,
600 std::vector<const char *> &Features) {
601 unsigned FPUID = llvm::ARM::parseFPU(FPU);
602 if (!llvm::ARM::getFPUFeatures(FPUID, Features))
603 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
606 // Decode ARM features from string like +[no]featureA+[no]featureB+...
607 static bool DecodeARMFeatures(const Driver &D, StringRef text,
608 std::vector<const char *> &Features) {
609 SmallVector<StringRef, 8> Split;
610 text.split(Split, StringRef("+"), -1, false);
612 for (StringRef Feature : Split) {
613 const char *FeatureName = llvm::ARM::getArchExtFeature(Feature);
615 Features.push_back(FeatureName);
622 // Check if -march is valid by checking if it can be canonicalised and parsed.
623 // getARMArch is used here instead of just checking the -march value in order
624 // to handle -march=native correctly.
625 static void checkARMArchName(const Driver &D, const Arg *A, const ArgList &Args,
626 llvm::StringRef ArchName,
627 std::vector<const char *> &Features,
628 const llvm::Triple &Triple) {
629 std::pair<StringRef, StringRef> Split = ArchName.split("+");
631 std::string MArch = arm::getARMArch(ArchName, Triple);
632 if (llvm::ARM::parseArch(MArch) == llvm::ARM::AK_INVALID ||
633 (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
634 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
637 // Check -mcpu=. Needs ArchName to handle -mcpu=generic.
638 static void checkARMCPUName(const Driver &D, const Arg *A, const ArgList &Args,
639 llvm::StringRef CPUName, llvm::StringRef ArchName,
640 std::vector<const char *> &Features,
641 const llvm::Triple &Triple) {
642 std::pair<StringRef, StringRef> Split = CPUName.split("+");
644 std::string CPU = arm::getARMTargetCPU(CPUName, ArchName, Triple);
645 if (arm::getLLVMArchSuffixForARM(CPU, ArchName, Triple).empty() ||
646 (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
647 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
650 static bool useAAPCSForMachO(const llvm::Triple &T) {
651 // The backend is hardwired to assume AAPCS for M-class processors, ensure
652 // the frontend matches that.
653 return T.getEnvironment() == llvm::Triple::EABI ||
654 T.getOS() == llvm::Triple::UnknownOS || isARMMProfile(T);
657 // Select the float ABI as determined by -msoft-float, -mhard-float, and
659 arm::FloatABI arm::getARMFloatABI(const ToolChain &TC, const ArgList &Args) {
660 const Driver &D = TC.getDriver();
661 const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(Args));
662 auto SubArch = getARMSubArchVersionNumber(Triple);
663 arm::FloatABI ABI = FloatABI::Invalid;
665 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
666 options::OPT_mfloat_abi_EQ)) {
667 if (A->getOption().matches(options::OPT_msoft_float)) {
668 ABI = FloatABI::Soft;
669 } else if (A->getOption().matches(options::OPT_mhard_float)) {
670 ABI = FloatABI::Hard;
672 ABI = llvm::StringSwitch<arm::FloatABI>(A->getValue())
673 .Case("soft", FloatABI::Soft)
674 .Case("softfp", FloatABI::SoftFP)
675 .Case("hard", FloatABI::Hard)
676 .Default(FloatABI::Invalid);
677 if (ABI == FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
678 D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
679 ABI = FloatABI::Soft;
683 // It is incorrect to select hard float ABI on MachO platforms if the ABI is
685 if (Triple.isOSBinFormatMachO() && !useAAPCSForMachO(Triple) &&
686 ABI == FloatABI::Hard) {
687 D.Diag(diag::err_drv_unsupported_opt_for_target) << A->getAsString(Args)
688 << Triple.getArchName();
692 // If unspecified, choose the default based on the platform.
693 if (ABI == FloatABI::Invalid) {
694 switch (Triple.getOS()) {
695 case llvm::Triple::Darwin:
696 case llvm::Triple::MacOSX:
697 case llvm::Triple::IOS:
698 case llvm::Triple::TvOS: {
699 // Darwin defaults to "softfp" for v6 and v7.
700 ABI = (SubArch == 6 || SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
703 case llvm::Triple::WatchOS:
704 ABI = FloatABI::Hard;
707 // FIXME: this is invalid for WindowsCE
708 case llvm::Triple::Win32:
709 ABI = FloatABI::Hard;
712 case llvm::Triple::FreeBSD:
713 switch (Triple.getEnvironment()) {
714 case llvm::Triple::GNUEABIHF:
715 ABI = FloatABI::Hard;
718 // FreeBSD defaults to soft float
719 ABI = FloatABI::Soft;
725 switch (Triple.getEnvironment()) {
726 case llvm::Triple::GNUEABIHF:
727 case llvm::Triple::EABIHF:
728 ABI = FloatABI::Hard;
730 case llvm::Triple::GNUEABI:
731 case llvm::Triple::EABI:
732 // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
733 ABI = FloatABI::SoftFP;
735 case llvm::Triple::Android:
736 ABI = (SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
739 // Assume "soft", but warn the user we are guessing.
740 ABI = FloatABI::Soft;
741 if (Triple.getOS() != llvm::Triple::UnknownOS ||
742 !Triple.isOSBinFormatMachO())
743 D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
749 assert(ABI != FloatABI::Invalid && "must select an ABI");
753 static void getARMTargetFeatures(const ToolChain &TC,
754 const llvm::Triple &Triple,
756 std::vector<const char *> &Features,
758 const Driver &D = TC.getDriver();
761 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
762 arm::FloatABI ABI = arm::getARMFloatABI(TC, Args);
763 const Arg *WaCPU = nullptr, *WaFPU = nullptr;
764 const Arg *WaHDiv = nullptr, *WaArch = nullptr;
767 // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
768 // yet (it uses the -mfloat-abi and -msoft-float options), and it is
769 // stripped out by the ARM target. We should probably pass this a new
770 // -target-option, which is handled by the -cc1/-cc1as invocation.
772 // FIXME2: For consistency, it would be ideal if we set up the target
773 // machine state the same when using the frontend or the assembler. We don't
774 // currently do that for the assembler, we pass the options directly to the
775 // backend and never even instantiate the frontend TargetInfo. If we did,
776 // and used its handleTargetFeatures hook, then we could ensure the
777 // assembler and the frontend behave the same.
779 // Use software floating point operations?
780 if (ABI == arm::FloatABI::Soft)
781 Features.push_back("+soft-float");
783 // Use software floating point argument passing?
784 if (ABI != arm::FloatABI::Hard)
785 Features.push_back("+soft-float-abi");
787 // Here, we make sure that -Wa,-mfpu/cpu/arch/hwdiv will be passed down
788 // to the assembler correctly.
790 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
791 StringRef Value = A->getValue();
792 if (Value.startswith("-mfpu=")) {
794 } else if (Value.startswith("-mcpu=")) {
796 } else if (Value.startswith("-mhwdiv=")) {
798 } else if (Value.startswith("-march=")) {
804 // Check -march. ClangAs gives preference to -Wa,-march=.
805 const Arg *ArchArg = Args.getLastArg(options::OPT_march_EQ);
809 D.Diag(clang::diag::warn_drv_unused_argument)
810 << ArchArg->getAsString(Args);
811 ArchName = StringRef(WaArch->getValue()).substr(7);
812 checkARMArchName(D, WaArch, Args, ArchName, Features, Triple);
814 D.Diag(clang::diag::warn_drv_unused_argument) << WaArch->getAsString(Args);
815 } else if (ArchArg) {
816 ArchName = ArchArg->getValue();
817 checkARMArchName(D, ArchArg, Args, ArchName, Features, Triple);
820 // Check -mcpu. ClangAs gives preference to -Wa,-mcpu=.
821 const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
825 D.Diag(clang::diag::warn_drv_unused_argument)
826 << CPUArg->getAsString(Args);
827 CPUName = StringRef(WaCPU->getValue()).substr(6);
828 checkARMCPUName(D, WaCPU, Args, CPUName, ArchName, Features, Triple);
830 CPUName = CPUArg->getValue();
831 checkARMCPUName(D, CPUArg, Args, CPUName, ArchName, Features, Triple);
834 // Add CPU features for generic CPUs
835 if (CPUName == "native") {
836 llvm::StringMap<bool> HostFeatures;
837 if (llvm::sys::getHostCPUFeatures(HostFeatures))
838 for (auto &F : HostFeatures)
840 Args.MakeArgString((F.second ? "+" : "-") + F.first()));
843 // Honor -mfpu=. ClangAs gives preference to -Wa,-mfpu=.
844 const Arg *FPUArg = Args.getLastArg(options::OPT_mfpu_EQ);
847 D.Diag(clang::diag::warn_drv_unused_argument)
848 << FPUArg->getAsString(Args);
849 getARMFPUFeatures(D, WaFPU, Args, StringRef(WaFPU->getValue()).substr(6),
852 getARMFPUFeatures(D, FPUArg, Args, FPUArg->getValue(), Features);
855 // Honor -mhwdiv=. ClangAs gives preference to -Wa,-mhwdiv=.
856 const Arg *HDivArg = Args.getLastArg(options::OPT_mhwdiv_EQ);
859 D.Diag(clang::diag::warn_drv_unused_argument)
860 << HDivArg->getAsString(Args);
861 getARMHWDivFeatures(D, WaHDiv, Args,
862 StringRef(WaHDiv->getValue()).substr(8), Features);
864 getARMHWDivFeatures(D, HDivArg, Args, HDivArg->getValue(), Features);
866 // Setting -msoft-float effectively disables NEON because of the GCC
867 // implementation, although the same isn't true of VFP or VFP3.
868 if (ABI == arm::FloatABI::Soft) {
869 Features.push_back("-neon");
870 // Also need to explicitly disable features which imply NEON.
871 Features.push_back("-crypto");
874 // En/disable crc code generation.
875 if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
876 if (A->getOption().matches(options::OPT_mcrc))
877 Features.push_back("+crc");
879 Features.push_back("-crc");
882 if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8_1a) {
883 Features.insert(Features.begin(), "+v8.1a");
886 // Look for the last occurrence of -mlong-calls or -mno-long-calls. If
887 // neither options are specified, see if we are compiling for kernel/kext and
888 // decide whether to pass "+long-calls" based on the OS and its version.
889 if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
890 options::OPT_mno_long_calls)) {
891 if (A->getOption().matches(options::OPT_mlong_calls))
892 Features.push_back("+long-calls");
893 } else if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
894 !Triple.isWatchOS()) {
895 Features.push_back("+long-calls");
898 // Kernel code has more strict alignment requirements.
900 Features.push_back("+strict-align");
901 else if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
902 options::OPT_munaligned_access)) {
903 if (A->getOption().matches(options::OPT_munaligned_access)) {
904 // No v6M core supports unaligned memory access (v6M ARM ARM A3.2).
905 if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
906 D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
908 Features.push_back("+strict-align");
910 // Assume pre-ARMv6 doesn't support unaligned accesses.
912 // ARMv6 may or may not support unaligned accesses depending on the
913 // SCTLR.U bit, which is architecture-specific. We assume ARMv6
914 // Darwin and NetBSD targets support unaligned accesses, and others don't.
916 // ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit
917 // which raises an alignment fault on unaligned accesses. Linux
918 // defaults this bit to 0 and handles it as a system-wide (not
919 // per-process) setting. It is therefore safe to assume that ARMv7+
920 // Linux targets support unaligned accesses. The same goes for NaCl.
922 // The above behavior is consistent with GCC.
923 int VersionNum = getARMSubArchVersionNumber(Triple);
924 if (Triple.isOSDarwin() || Triple.isOSNetBSD()) {
925 if (VersionNum < 6 ||
926 Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
927 Features.push_back("+strict-align");
928 } else if (Triple.isOSLinux() || Triple.isOSNaCl()) {
930 Features.push_back("+strict-align");
932 Features.push_back("+strict-align");
935 // llvm does not support reserving registers in general. There is support
936 // for reserving r9 on ARM though (defined as a platform-specific register
938 if (Args.hasArg(options::OPT_ffixed_r9))
939 Features.push_back("+reserve-r9");
941 // The kext linker doesn't know how to deal with movw/movt.
942 if (KernelOrKext || Args.hasArg(options::OPT_mno_movt))
943 Features.push_back("+no-movt");
946 void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
947 ArgStringList &CmdArgs, bool KernelOrKext) const {
948 // Select the ABI to use.
949 // FIXME: Support -meabi.
950 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
951 const char *ABIName = nullptr;
952 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
953 ABIName = A->getValue();
954 } else if (Triple.isOSBinFormatMachO()) {
955 if (useAAPCSForMachO(Triple)) {
957 } else if (Triple.isWatchOS()) {
960 ABIName = "apcs-gnu";
962 } else if (Triple.isOSWindows()) {
963 // FIXME: this is invalid for WindowsCE
966 // Select the default based on the platform.
967 switch (Triple.getEnvironment()) {
968 case llvm::Triple::Android:
969 case llvm::Triple::GNUEABI:
970 case llvm::Triple::GNUEABIHF:
971 ABIName = "aapcs-linux";
973 case llvm::Triple::EABIHF:
974 case llvm::Triple::EABI:
978 if (Triple.getOS() == llvm::Triple::NetBSD)
979 ABIName = "apcs-gnu";
985 CmdArgs.push_back("-target-abi");
986 CmdArgs.push_back(ABIName);
988 // Determine floating point ABI from the options & target defaults.
989 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
990 if (ABI == arm::FloatABI::Soft) {
991 // Floating point operations and argument passing are soft.
992 // FIXME: This changes CPP defines, we need -target-soft-float.
993 CmdArgs.push_back("-msoft-float");
994 CmdArgs.push_back("-mfloat-abi");
995 CmdArgs.push_back("soft");
996 } else if (ABI == arm::FloatABI::SoftFP) {
997 // Floating point operations are hard, but argument passing is soft.
998 CmdArgs.push_back("-mfloat-abi");
999 CmdArgs.push_back("soft");
1001 // Floating point operations and argument passing are hard.
1002 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1003 CmdArgs.push_back("-mfloat-abi");
1004 CmdArgs.push_back("hard");
1007 // Forward the -mglobal-merge option for explicit control over the pass.
1008 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1009 options::OPT_mno_global_merge)) {
1010 CmdArgs.push_back("-backend-option");
1011 if (A->getOption().matches(options::OPT_mno_global_merge))
1012 CmdArgs.push_back("-arm-global-merge=false");
1014 CmdArgs.push_back("-arm-global-merge=true");
1017 if (!Args.hasFlag(options::OPT_mimplicit_float,
1018 options::OPT_mno_implicit_float, true))
1019 CmdArgs.push_back("-no-implicit-float");
1023 /// getAArch64TargetCPU - Get the (LLVM) name of the AArch64 cpu we are
1025 static std::string getAArch64TargetCPU(const ArgList &Args) {
1028 // If we have -mtune or -mcpu, use that.
1029 if ((A = Args.getLastArg(options::OPT_mtune_EQ))) {
1030 CPU = StringRef(A->getValue()).lower();
1031 } else if ((A = Args.getLastArg(options::OPT_mcpu_EQ))) {
1032 StringRef Mcpu = A->getValue();
1033 CPU = Mcpu.split("+").first.lower();
1036 // Handle CPU name is 'native'.
1037 if (CPU == "native")
1038 return llvm::sys::getHostCPUName();
1039 else if (CPU.size())
1042 // Make sure we pick "cyclone" if -arch is used.
1043 // FIXME: Should this be picked by checking the target triple instead?
1044 if (Args.getLastArg(options::OPT_arch))
1050 void Clang::AddAArch64TargetArgs(const ArgList &Args,
1051 ArgStringList &CmdArgs) const {
1052 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
1053 llvm::Triple Triple(TripleStr);
1055 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1056 Args.hasArg(options::OPT_mkernel) ||
1057 Args.hasArg(options::OPT_fapple_kext))
1058 CmdArgs.push_back("-disable-red-zone");
1060 if (!Args.hasFlag(options::OPT_mimplicit_float,
1061 options::OPT_mno_implicit_float, true))
1062 CmdArgs.push_back("-no-implicit-float");
1064 const char *ABIName = nullptr;
1065 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1066 ABIName = A->getValue();
1067 else if (Triple.isOSDarwin())
1068 ABIName = "darwinpcs";
1072 CmdArgs.push_back("-target-abi");
1073 CmdArgs.push_back(ABIName);
1075 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1076 options::OPT_mno_fix_cortex_a53_835769)) {
1077 CmdArgs.push_back("-backend-option");
1078 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1079 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1081 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1082 } else if (Triple.isAndroid()) {
1083 // Enabled A53 errata (835769) workaround by default on android
1084 CmdArgs.push_back("-backend-option");
1085 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1088 // Forward the -mglobal-merge option for explicit control over the pass.
1089 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1090 options::OPT_mno_global_merge)) {
1091 CmdArgs.push_back("-backend-option");
1092 if (A->getOption().matches(options::OPT_mno_global_merge))
1093 CmdArgs.push_back("-aarch64-global-merge=false");
1095 CmdArgs.push_back("-aarch64-global-merge=true");
1099 // Get CPU and ABI names. They are not independent
1100 // so we have to calculate them together.
1101 void mips::getMipsCPUAndABI(const ArgList &Args, const llvm::Triple &Triple,
1102 StringRef &CPUName, StringRef &ABIName) {
1103 const char *DefMips32CPU = "mips32r2";
1104 const char *DefMips64CPU = "mips64r2";
1106 // MIPS32r6 is the default for mips(el)?-img-linux-gnu and MIPS64r6 is the
1107 // default for mips64(el)?-img-linux-gnu.
1108 if (Triple.getVendor() == llvm::Triple::ImaginationTechnologies &&
1109 Triple.getEnvironment() == llvm::Triple::GNU) {
1110 DefMips32CPU = "mips32r6";
1111 DefMips64CPU = "mips64r6";
1114 // MIPS64r6 is the default for Android MIPS64 (mips64el-linux-android).
1115 if (Triple.isAndroid())
1116 DefMips64CPU = "mips64r6";
1118 // MIPS3 is the default for mips64*-unknown-openbsd.
1119 if (Triple.getOS() == llvm::Triple::OpenBSD)
1120 DefMips64CPU = "mips3";
1122 if (Arg *A = Args.getLastArg(options::OPT_march_EQ, options::OPT_mcpu_EQ))
1123 CPUName = A->getValue();
1125 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1126 ABIName = A->getValue();
1127 // Convert a GNU style Mips ABI name to the name
1128 // accepted by LLVM Mips backend.
1129 ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
1135 // Setup default CPU and ABI names.
1136 if (CPUName.empty() && ABIName.empty()) {
1137 switch (Triple.getArch()) {
1139 llvm_unreachable("Unexpected triple arch name");
1140 case llvm::Triple::mips:
1141 case llvm::Triple::mipsel:
1142 CPUName = DefMips32CPU;
1144 case llvm::Triple::mips64:
1145 case llvm::Triple::mips64el:
1146 CPUName = DefMips64CPU;
1151 if (ABIName.empty()) {
1152 // Deduce ABI name from the target triple.
1153 if (Triple.getArch() == llvm::Triple::mips ||
1154 Triple.getArch() == llvm::Triple::mipsel)
1160 if (CPUName.empty()) {
1161 // Deduce CPU name from ABI name.
1162 CPUName = llvm::StringSwitch<const char *>(ABIName)
1163 .Cases("o32", "eabi", DefMips32CPU)
1164 .Cases("n32", "n64", DefMips64CPU)
1168 // FIXME: Warn on inconsistent use of -march and -mabi.
1171 std::string mips::getMipsABILibSuffix(const ArgList &Args,
1172 const llvm::Triple &Triple) {
1173 StringRef CPUName, ABIName;
1174 tools::mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1175 return llvm::StringSwitch<std::string>(ABIName)
1181 // Convert ABI name to the GNU tools acceptable variant.
1182 static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
1183 return llvm::StringSwitch<llvm::StringRef>(ABI)
1189 // Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
1190 // and -mfloat-abi=.
1191 static mips::FloatABI getMipsFloatABI(const Driver &D, const ArgList &Args) {
1192 mips::FloatABI ABI = mips::FloatABI::Invalid;
1194 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1195 options::OPT_mfloat_abi_EQ)) {
1196 if (A->getOption().matches(options::OPT_msoft_float))
1197 ABI = mips::FloatABI::Soft;
1198 else if (A->getOption().matches(options::OPT_mhard_float))
1199 ABI = mips::FloatABI::Hard;
1201 ABI = llvm::StringSwitch<mips::FloatABI>(A->getValue())
1202 .Case("soft", mips::FloatABI::Soft)
1203 .Case("hard", mips::FloatABI::Hard)
1204 .Default(mips::FloatABI::Invalid);
1205 if (ABI == mips::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
1206 D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1207 ABI = mips::FloatABI::Hard;
1212 // If unspecified, choose the default based on the platform.
1213 if (ABI == mips::FloatABI::Invalid) {
1214 // Assume "hard", because it's a default value used by gcc.
1215 // When we start to recognize specific target MIPS processors,
1216 // we will be able to select the default more correctly.
1217 ABI = mips::FloatABI::Hard;
1220 assert(ABI != mips::FloatABI::Invalid && "must select an ABI");
1224 static void AddTargetFeature(const ArgList &Args,
1225 std::vector<const char *> &Features,
1226 OptSpecifier OnOpt, OptSpecifier OffOpt,
1227 StringRef FeatureName) {
1228 if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) {
1229 if (A->getOption().matches(OnOpt))
1230 Features.push_back(Args.MakeArgString("+" + FeatureName));
1232 Features.push_back(Args.MakeArgString("-" + FeatureName));
1236 static void getMIPSTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1237 const ArgList &Args,
1238 std::vector<const char *> &Features) {
1241 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1242 ABIName = getGnuCompatibleMipsABIName(ABIName);
1244 AddTargetFeature(Args, Features, options::OPT_mno_abicalls,
1245 options::OPT_mabicalls, "noabicalls");
1247 mips::FloatABI FloatABI = getMipsFloatABI(D, Args);
1248 if (FloatABI == mips::FloatABI::Soft) {
1249 // FIXME: Note, this is a hack. We need to pass the selected float
1250 // mode to the MipsTargetInfoBase to define appropriate macros there.
1251 // Now it is the only method.
1252 Features.push_back("+soft-float");
1255 if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
1256 StringRef Val = StringRef(A->getValue());
1257 if (Val == "2008") {
1258 if (mips::getSupportedNanEncoding(CPUName) & mips::Nan2008)
1259 Features.push_back("+nan2008");
1261 Features.push_back("-nan2008");
1262 D.Diag(diag::warn_target_unsupported_nan2008) << CPUName;
1264 } else if (Val == "legacy") {
1265 if (mips::getSupportedNanEncoding(CPUName) & mips::NanLegacy)
1266 Features.push_back("-nan2008");
1268 Features.push_back("+nan2008");
1269 D.Diag(diag::warn_target_unsupported_nanlegacy) << CPUName;
1272 D.Diag(diag::err_drv_unsupported_option_argument)
1273 << A->getOption().getName() << Val;
1276 AddTargetFeature(Args, Features, options::OPT_msingle_float,
1277 options::OPT_mdouble_float, "single-float");
1278 AddTargetFeature(Args, Features, options::OPT_mips16, options::OPT_mno_mips16,
1280 AddTargetFeature(Args, Features, options::OPT_mmicromips,
1281 options::OPT_mno_micromips, "micromips");
1282 AddTargetFeature(Args, Features, options::OPT_mdsp, options::OPT_mno_dsp,
1284 AddTargetFeature(Args, Features, options::OPT_mdspr2, options::OPT_mno_dspr2,
1286 AddTargetFeature(Args, Features, options::OPT_mmsa, options::OPT_mno_msa,
1289 // Add the last -mfp32/-mfpxx/-mfp64 or if none are given and the ABI is O32
1291 if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
1292 options::OPT_mfp64)) {
1293 if (A->getOption().matches(options::OPT_mfp32))
1294 Features.push_back(Args.MakeArgString("-fp64"));
1295 else if (A->getOption().matches(options::OPT_mfpxx)) {
1296 Features.push_back(Args.MakeArgString("+fpxx"));
1297 Features.push_back(Args.MakeArgString("+nooddspreg"));
1299 Features.push_back(Args.MakeArgString("+fp64"));
1300 } else if (mips::shouldUseFPXX(Args, Triple, CPUName, ABIName, FloatABI)) {
1301 Features.push_back(Args.MakeArgString("+fpxx"));
1302 Features.push_back(Args.MakeArgString("+nooddspreg"));
1305 AddTargetFeature(Args, Features, options::OPT_mno_odd_spreg,
1306 options::OPT_modd_spreg, "nooddspreg");
1309 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1310 ArgStringList &CmdArgs) const {
1311 const Driver &D = getToolChain().getDriver();
1314 const llvm::Triple &Triple = getToolChain().getTriple();
1315 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1317 CmdArgs.push_back("-target-abi");
1318 CmdArgs.push_back(ABIName.data());
1320 mips::FloatABI ABI = getMipsFloatABI(D, Args);
1321 if (ABI == mips::FloatABI::Soft) {
1322 // Floating point operations and argument passing are soft.
1323 CmdArgs.push_back("-msoft-float");
1324 CmdArgs.push_back("-mfloat-abi");
1325 CmdArgs.push_back("soft");
1327 // Floating point operations and argument passing are hard.
1328 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1329 CmdArgs.push_back("-mfloat-abi");
1330 CmdArgs.push_back("hard");
1333 if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1334 if (A->getOption().matches(options::OPT_mxgot)) {
1335 CmdArgs.push_back("-mllvm");
1336 CmdArgs.push_back("-mxgot");
1340 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1341 options::OPT_mno_ldc1_sdc1)) {
1342 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1343 CmdArgs.push_back("-mllvm");
1344 CmdArgs.push_back("-mno-ldc1-sdc1");
1348 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1349 options::OPT_mno_check_zero_division)) {
1350 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1351 CmdArgs.push_back("-mllvm");
1352 CmdArgs.push_back("-mno-check-zero-division");
1356 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1357 StringRef v = A->getValue();
1358 CmdArgs.push_back("-mllvm");
1359 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1364 /// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting.
1365 static std::string getPPCTargetCPU(const ArgList &Args) {
1366 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1367 StringRef CPUName = A->getValue();
1369 if (CPUName == "native") {
1370 std::string CPU = llvm::sys::getHostCPUName();
1371 if (!CPU.empty() && CPU != "generic")
1377 return llvm::StringSwitch<const char *>(CPUName)
1378 .Case("common", "generic")
1380 .Case("440fp", "440")
1385 .Case("603e", "603e")
1386 .Case("603ev", "603ev")
1388 .Case("604e", "604e")
1390 .Case("630", "pwr3")
1392 .Case("7400", "7400")
1394 .Case("7450", "7450")
1401 .Case("e500mc", "e500mc")
1402 .Case("e5500", "e5500")
1403 .Case("power3", "pwr3")
1404 .Case("power4", "pwr4")
1405 .Case("power5", "pwr5")
1406 .Case("power5x", "pwr5x")
1407 .Case("power6", "pwr6")
1408 .Case("power6x", "pwr6x")
1409 .Case("power7", "pwr7")
1410 .Case("power8", "pwr8")
1411 .Case("pwr3", "pwr3")
1412 .Case("pwr4", "pwr4")
1413 .Case("pwr5", "pwr5")
1414 .Case("pwr5x", "pwr5x")
1415 .Case("pwr6", "pwr6")
1416 .Case("pwr6x", "pwr6x")
1417 .Case("pwr7", "pwr7")
1418 .Case("pwr8", "pwr8")
1419 .Case("powerpc", "ppc")
1420 .Case("powerpc64", "ppc64")
1421 .Case("powerpc64le", "ppc64le")
1428 static void getPPCTargetFeatures(const Driver &D, const llvm::Triple &Triple,
1429 const ArgList &Args,
1430 std::vector<const char *> &Features) {
1431 handleTargetFeaturesGroup(Args, Features, options::OPT_m_ppc_Features_Group);
1433 ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
1434 if (FloatABI == ppc::FloatABI::Soft &&
1435 !(Triple.getArch() == llvm::Triple::ppc64 ||
1436 Triple.getArch() == llvm::Triple::ppc64le))
1437 Features.push_back("+soft-float");
1438 else if (FloatABI == ppc::FloatABI::Soft &&
1439 (Triple.getArch() == llvm::Triple::ppc64 ||
1440 Triple.getArch() == llvm::Triple::ppc64le))
1441 D.Diag(diag::err_drv_invalid_mfloat_abi)
1442 << "soft float is not supported for ppc64";
1444 // Altivec is a bit weird, allow overriding of the Altivec feature here.
1445 AddTargetFeature(Args, Features, options::OPT_faltivec,
1446 options::OPT_fno_altivec, "altivec");
1449 ppc::FloatABI ppc::getPPCFloatABI(const Driver &D, const ArgList &Args) {
1450 ppc::FloatABI ABI = ppc::FloatABI::Invalid;
1452 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
1453 options::OPT_mfloat_abi_EQ)) {
1454 if (A->getOption().matches(options::OPT_msoft_float))
1455 ABI = ppc::FloatABI::Soft;
1456 else if (A->getOption().matches(options::OPT_mhard_float))
1457 ABI = ppc::FloatABI::Hard;
1459 ABI = llvm::StringSwitch<ppc::FloatABI>(A->getValue())
1460 .Case("soft", ppc::FloatABI::Soft)
1461 .Case("hard", ppc::FloatABI::Hard)
1462 .Default(ppc::FloatABI::Invalid);
1463 if (ABI == ppc::FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
1464 D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
1465 ABI = ppc::FloatABI::Hard;
1470 // If unspecified, choose the default based on the platform.
1471 if (ABI == ppc::FloatABI::Invalid) {
1472 ABI = ppc::FloatABI::Hard;
1478 void Clang::AddPPCTargetArgs(const ArgList &Args,
1479 ArgStringList &CmdArgs) const {
1480 // Select the ABI to use.
1481 const char *ABIName = nullptr;
1482 if (getToolChain().getTriple().isOSLinux())
1483 switch (getToolChain().getArch()) {
1484 case llvm::Triple::ppc64: {
1485 // When targeting a processor that supports QPX, or if QPX is
1486 // specifically enabled, default to using the ABI that supports QPX (so
1487 // long as it is not specifically disabled).
1488 bool HasQPX = false;
1489 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1490 HasQPX = A->getValue() == StringRef("a2q");
1491 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1493 ABIName = "elfv1-qpx";
1500 case llvm::Triple::ppc64le:
1507 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1508 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1509 // the option if given as we don't have backend support for any targets
1510 // that don't use the altivec abi.
1511 if (StringRef(A->getValue()) != "altivec")
1512 ABIName = A->getValue();
1514 ppc::FloatABI FloatABI =
1515 ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1517 if (FloatABI == ppc::FloatABI::Soft) {
1518 // Floating point operations and argument passing are soft.
1519 CmdArgs.push_back("-msoft-float");
1520 CmdArgs.push_back("-mfloat-abi");
1521 CmdArgs.push_back("soft");
1523 // Floating point operations and argument passing are hard.
1524 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1525 CmdArgs.push_back("-mfloat-abi");
1526 CmdArgs.push_back("hard");
1530 CmdArgs.push_back("-target-abi");
1531 CmdArgs.push_back(ABIName);
1535 bool ppc::hasPPCAbiArg(const ArgList &Args, const char *Value) {
1536 Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
1537 return A && (A->getValue() == StringRef(Value));
1540 /// Get the (LLVM) name of the R600 gpu we are targeting.
1541 static std::string getR600TargetGPU(const ArgList &Args) {
1542 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1543 const char *GPUName = A->getValue();
1544 return llvm::StringSwitch<const char *>(GPUName)
1545 .Cases("rv630", "rv635", "r600")
1546 .Cases("rv610", "rv620", "rs780", "rs880")
1547 .Case("rv740", "rv770")
1548 .Case("palm", "cedar")
1549 .Cases("sumo", "sumo2", "sumo")
1550 .Case("hemlock", "cypress")
1551 .Case("aruba", "cayman")
1557 void Clang::AddSparcTargetArgs(const ArgList &Args,
1558 ArgStringList &CmdArgs) const {
1559 const Driver &D = getToolChain().getDriver();
1560 std::string Triple = getToolChain().ComputeEffectiveClangTriple(Args);
1562 bool SoftFloatABI = false;
1564 Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float)) {
1565 if (A->getOption().matches(options::OPT_msoft_float))
1566 SoftFloatABI = true;
1569 // Only the hard-float ABI on Sparc is standardized, and it is the
1570 // default. GCC also supports a nonstandard soft-float ABI mode, and
1571 // perhaps LLVM should implement that, too. However, since llvm
1572 // currently does not support Sparc soft-float, at all, display an
1573 // error if it's requested.
1575 D.Diag(diag::err_drv_unsupported_opt_for_target) << "-msoft-float"
1580 static const char *getSystemZTargetCPU(const ArgList &Args) {
1581 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1582 return A->getValue();
1586 static void getSystemZTargetFeatures(const ArgList &Args,
1587 std::vector<const char *> &Features) {
1588 // -m(no-)htm overrides use of the transactional-execution facility.
1589 if (Arg *A = Args.getLastArg(options::OPT_mhtm, options::OPT_mno_htm)) {
1590 if (A->getOption().matches(options::OPT_mhtm))
1591 Features.push_back("+transactional-execution");
1593 Features.push_back("-transactional-execution");
1595 // -m(no-)vx overrides use of the vector facility.
1596 if (Arg *A = Args.getLastArg(options::OPT_mvx, options::OPT_mno_vx)) {
1597 if (A->getOption().matches(options::OPT_mvx))
1598 Features.push_back("+vector");
1600 Features.push_back("-vector");
1604 static const char *getX86TargetCPU(const ArgList &Args,
1605 const llvm::Triple &Triple) {
1606 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1607 if (StringRef(A->getValue()) != "native") {
1608 if (Triple.isOSDarwin() && Triple.getArchName() == "x86_64h")
1611 return A->getValue();
1614 // FIXME: Reject attempts to use -march=native unless the target matches
1617 // FIXME: We should also incorporate the detected target features for use
1619 std::string CPU = llvm::sys::getHostCPUName();
1620 if (!CPU.empty() && CPU != "generic")
1621 return Args.MakeArgString(CPU);
1624 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
1625 // Mapping built by referring to X86TargetInfo::getDefaultFeatures().
1626 StringRef Arch = A->getValue();
1628 if (Triple.getArch() == llvm::Triple::x86) {
1629 CPU = llvm::StringSwitch<const char *>(Arch)
1630 .Case("IA32", "i386")
1631 .Case("SSE", "pentium3")
1632 .Case("SSE2", "pentium4")
1633 .Case("AVX", "sandybridge")
1634 .Case("AVX2", "haswell")
1637 CPU = llvm::StringSwitch<const char *>(Arch)
1638 .Case("AVX", "sandybridge")
1639 .Case("AVX2", "haswell")
1646 // Select the default CPU if none was given (or detection failed).
1648 if (Triple.getArch() != llvm::Triple::x86_64 &&
1649 Triple.getArch() != llvm::Triple::x86)
1650 return nullptr; // This routine is only handling x86 targets.
1652 bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
1654 // FIXME: Need target hooks.
1655 if (Triple.isOSDarwin()) {
1656 if (Triple.getArchName() == "x86_64h")
1658 return Is64Bit ? "core2" : "yonah";
1661 // Set up default CPU name for PS4 compilers.
1662 if (Triple.isPS4CPU())
1665 // On Android use targets compatible with gcc
1666 if (Triple.isAndroid())
1667 return Is64Bit ? "x86-64" : "i686";
1669 // Everything else goes to x86-64 in 64-bit mode.
1673 switch (Triple.getOS()) {
1674 case llvm::Triple::FreeBSD:
1675 case llvm::Triple::NetBSD:
1676 case llvm::Triple::OpenBSD:
1678 case llvm::Triple::Haiku:
1680 case llvm::Triple::Bitrig:
1688 /// Get the (LLVM) name of the WebAssembly cpu we are targeting.
1689 static StringRef getWebAssemblyTargetCPU(const ArgList &Args) {
1690 // If we have -mcpu=, use that.
1691 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1692 StringRef CPU = A->getValue();
1695 // Handle "native" by examining the host. "native" isn't meaningful when
1696 // cross compiling, so only support this when the host is also WebAssembly.
1697 if (CPU == "native")
1698 return llvm::sys::getHostCPUName();
1707 static std::string getCPUName(const ArgList &Args, const llvm::Triple &T,
1708 bool FromAs = false) {
1709 switch (T.getArch()) {
1713 case llvm::Triple::aarch64:
1714 case llvm::Triple::aarch64_be:
1715 return getAArch64TargetCPU(Args);
1717 case llvm::Triple::arm:
1718 case llvm::Triple::armeb:
1719 case llvm::Triple::thumb:
1720 case llvm::Triple::thumbeb: {
1721 StringRef MArch, MCPU;
1722 getARMArchCPUFromArgs(Args, MArch, MCPU, FromAs);
1723 return arm::getARMTargetCPU(MCPU, MArch, T);
1725 case llvm::Triple::mips:
1726 case llvm::Triple::mipsel:
1727 case llvm::Triple::mips64:
1728 case llvm::Triple::mips64el: {
1731 mips::getMipsCPUAndABI(Args, T, CPUName, ABIName);
1735 case llvm::Triple::nvptx:
1736 case llvm::Triple::nvptx64:
1737 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
1738 return A->getValue();
1741 case llvm::Triple::ppc:
1742 case llvm::Triple::ppc64:
1743 case llvm::Triple::ppc64le: {
1744 std::string TargetCPUName = getPPCTargetCPU(Args);
1745 // LLVM may default to generating code for the native CPU,
1746 // but, like gcc, we default to a more generic option for
1747 // each architecture. (except on Darwin)
1748 if (TargetCPUName.empty() && !T.isOSDarwin()) {
1749 if (T.getArch() == llvm::Triple::ppc64)
1750 TargetCPUName = "ppc64";
1751 else if (T.getArch() == llvm::Triple::ppc64le)
1752 TargetCPUName = "ppc64le";
1754 TargetCPUName = "ppc";
1756 return TargetCPUName;
1759 case llvm::Triple::sparc:
1760 case llvm::Triple::sparcel:
1761 case llvm::Triple::sparcv9:
1762 if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1763 return A->getValue();
1766 case llvm::Triple::x86:
1767 case llvm::Triple::x86_64:
1768 return getX86TargetCPU(Args, T);
1770 case llvm::Triple::hexagon:
1772 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
1774 case llvm::Triple::systemz:
1775 return getSystemZTargetCPU(Args);
1777 case llvm::Triple::r600:
1778 case llvm::Triple::amdgcn:
1779 return getR600TargetGPU(Args);
1781 case llvm::Triple::wasm32:
1782 case llvm::Triple::wasm64:
1783 return getWebAssemblyTargetCPU(Args);
1787 static void AddGoldPlugin(const ToolChain &ToolChain, const ArgList &Args,
1788 ArgStringList &CmdArgs, bool IsThinLTO) {
1789 // Tell the linker to load the plugin. This has to come before AddLinkerInputs
1790 // as gold requires -plugin to come before any -plugin-opt that -Wl might
1792 CmdArgs.push_back("-plugin");
1793 std::string Plugin =
1794 ToolChain.getDriver().Dir + "/../lib" CLANG_LIBDIR_SUFFIX "/LLVMgold.so";
1795 CmdArgs.push_back(Args.MakeArgString(Plugin));
1797 // Try to pass driver level flags relevant to LTO code generation down to
1800 // Handle flags for selecting CPU variants.
1801 std::string CPU = getCPUName(Args, ToolChain.getTriple());
1803 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=mcpu=") + CPU));
1805 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
1807 if (A->getOption().matches(options::OPT_O4) ||
1808 A->getOption().matches(options::OPT_Ofast))
1810 else if (A->getOption().matches(options::OPT_O))
1811 OOpt = A->getValue();
1812 else if (A->getOption().matches(options::OPT_O0))
1815 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-opt=O") + OOpt));
1819 CmdArgs.push_back("-plugin-opt=thinlto");
1822 /// This is a helper function for validating the optional refinement step
1823 /// parameter in reciprocal argument strings. Return false if there is an error
1824 /// parsing the refinement step. Otherwise, return true and set the Position
1825 /// of the refinement step in the input string.
1826 static bool getRefinementStep(StringRef In, const Driver &D,
1827 const Arg &A, size_t &Position) {
1828 const char RefinementStepToken = ':';
1829 Position = In.find(RefinementStepToken);
1830 if (Position != StringRef::npos) {
1831 StringRef Option = A.getOption().getName();
1832 StringRef RefStep = In.substr(Position + 1);
1833 // Allow exactly one numeric character for the additional refinement
1834 // step parameter. This is reasonable for all currently-supported
1835 // operations and architectures because we would expect that a larger value
1836 // of refinement steps would cause the estimate "optimization" to
1837 // under-perform the native operation. Also, if the estimate does not
1838 // converge quickly, it probably will not ever converge, so further
1839 // refinement steps will not produce a better answer.
1840 if (RefStep.size() != 1) {
1841 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
1844 char RefStepChar = RefStep[0];
1845 if (RefStepChar < '0' || RefStepChar > '9') {
1846 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
1853 /// The -mrecip flag requires processing of many optional parameters.
1854 static void ParseMRecip(const Driver &D, const ArgList &Args,
1855 ArgStringList &OutStrings) {
1856 StringRef DisabledPrefixIn = "!";
1857 StringRef DisabledPrefixOut = "!";
1858 StringRef EnabledPrefixOut = "";
1859 StringRef Out = "-mrecip=";
1861 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
1865 unsigned NumOptions = A->getNumValues();
1866 if (NumOptions == 0) {
1867 // No option is the same as "all".
1868 OutStrings.push_back(Args.MakeArgString(Out + "all"));
1872 // Pass through "all", "none", or "default" with an optional refinement step.
1873 if (NumOptions == 1) {
1874 StringRef Val = A->getValue(0);
1876 if (!getRefinementStep(Val, D, *A, RefStepLoc))
1878 StringRef ValBase = Val.slice(0, RefStepLoc);
1879 if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
1880 OutStrings.push_back(Args.MakeArgString(Out + Val));
1885 // Each reciprocal type may be enabled or disabled individually.
1886 // Check each input value for validity, concatenate them all back together,
1887 // and pass through.
1889 llvm::StringMap<bool> OptionStrings;
1890 OptionStrings.insert(std::make_pair("divd", false));
1891 OptionStrings.insert(std::make_pair("divf", false));
1892 OptionStrings.insert(std::make_pair("vec-divd", false));
1893 OptionStrings.insert(std::make_pair("vec-divf", false));
1894 OptionStrings.insert(std::make_pair("sqrtd", false));
1895 OptionStrings.insert(std::make_pair("sqrtf", false));
1896 OptionStrings.insert(std::make_pair("vec-sqrtd", false));
1897 OptionStrings.insert(std::make_pair("vec-sqrtf", false));
1899 for (unsigned i = 0; i != NumOptions; ++i) {
1900 StringRef Val = A->getValue(i);
1902 bool IsDisabled = Val.startswith(DisabledPrefixIn);
1903 // Ignore the disablement token for string matching.
1905 Val = Val.substr(1);
1908 if (!getRefinementStep(Val, D, *A, RefStep))
1911 StringRef ValBase = Val.slice(0, RefStep);
1912 llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
1913 if (OptionIter == OptionStrings.end()) {
1914 // Try again specifying float suffix.
1915 OptionIter = OptionStrings.find(ValBase.str() + 'f');
1916 if (OptionIter == OptionStrings.end()) {
1917 // The input name did not match any known option string.
1918 D.Diag(diag::err_drv_unknown_argument) << Val;
1921 // The option was specified without a float or double suffix.
1922 // Make sure that the double entry was not already specified.
1923 // The float entry will be checked below.
1924 if (OptionStrings[ValBase.str() + 'd']) {
1925 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
1930 if (OptionIter->second == true) {
1931 // Duplicate option specified.
1932 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
1936 // Mark the matched option as found. Do not allow duplicate specifiers.
1937 OptionIter->second = true;
1939 // If the precision was not specified, also mark the double entry as found.
1940 if (ValBase.back() != 'f' && ValBase.back() != 'd')
1941 OptionStrings[ValBase.str() + 'd'] = true;
1943 // Build the output string.
1944 StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
1945 Out = Args.MakeArgString(Out + Prefix + Val);
1946 if (i != NumOptions - 1)
1947 Out = Args.MakeArgString(Out + ",");
1950 OutStrings.push_back(Args.MakeArgString(Out));
1953 static void getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
1954 const ArgList &Args,
1955 std::vector<const char *> &Features) {
1956 // If -march=native, autodetect the feature list.
1957 if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1958 if (StringRef(A->getValue()) == "native") {
1959 llvm::StringMap<bool> HostFeatures;
1960 if (llvm::sys::getHostCPUFeatures(HostFeatures))
1961 for (auto &F : HostFeatures)
1963 Args.MakeArgString((F.second ? "+" : "-") + F.first()));
1967 if (Triple.getArchName() == "x86_64h") {
1968 // x86_64h implies quite a few of the more modern subtarget features
1969 // for Haswell class CPUs, but not all of them. Opt-out of a few.
1970 Features.push_back("-rdrnd");
1971 Features.push_back("-aes");
1972 Features.push_back("-pclmul");
1973 Features.push_back("-rtm");
1974 Features.push_back("-hle");
1975 Features.push_back("-fsgsbase");
1978 const llvm::Triple::ArchType ArchType = Triple.getArch();
1979 // Add features to be compatible with gcc for Android.
1980 if (Triple.isAndroid()) {
1981 if (ArchType == llvm::Triple::x86_64) {
1982 Features.push_back("+sse4.2");
1983 Features.push_back("+popcnt");
1985 Features.push_back("+ssse3");
1988 // Set features according to the -arch flag on MSVC.
1989 if (Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
1990 StringRef Arch = A->getValue();
1991 bool ArchUsed = false;
1992 // First, look for flags that are shared in x86 and x86-64.
1993 if (ArchType == llvm::Triple::x86_64 || ArchType == llvm::Triple::x86) {
1994 if (Arch == "AVX" || Arch == "AVX2") {
1996 Features.push_back(Args.MakeArgString("+" + Arch.lower()));
1999 // Then, look for x86-specific flags.
2000 if (ArchType == llvm::Triple::x86) {
2001 if (Arch == "IA32") {
2003 } else if (Arch == "SSE" || Arch == "SSE2") {
2005 Features.push_back(Args.MakeArgString("+" + Arch.lower()));
2009 D.Diag(clang::diag::warn_drv_unused_argument) << A->getAsString(Args);
2012 // Now add any that the user explicitly requested on the command line,
2013 // which may override the defaults.
2014 handleTargetFeaturesGroup(Args, Features, options::OPT_m_x86_Features_Group);
2017 void Clang::AddX86TargetArgs(const ArgList &Args,
2018 ArgStringList &CmdArgs) const {
2019 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2020 Args.hasArg(options::OPT_mkernel) ||
2021 Args.hasArg(options::OPT_fapple_kext))
2022 CmdArgs.push_back("-disable-red-zone");
2024 // Default to avoid implicit floating-point for kernel/kext code, but allow
2025 // that to be overridden with -mno-soft-float.
2026 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2027 Args.hasArg(options::OPT_fapple_kext));
2028 if (Arg *A = Args.getLastArg(
2029 options::OPT_msoft_float, options::OPT_mno_soft_float,
2030 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2031 const Option &O = A->getOption();
2032 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2033 O.matches(options::OPT_msoft_float));
2035 if (NoImplicitFloat)
2036 CmdArgs.push_back("-no-implicit-float");
2038 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2039 StringRef Value = A->getValue();
2040 if (Value == "intel" || Value == "att") {
2041 CmdArgs.push_back("-mllvm");
2042 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2044 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
2045 << A->getOption().getName() << Value;
2050 void Clang::AddHexagonTargetArgs(const ArgList &Args,
2051 ArgStringList &CmdArgs) const {
2052 CmdArgs.push_back("-mqdsp6-compat");
2053 CmdArgs.push_back("-Wreturn-type");
2055 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
2056 std::string N = llvm::utostr(G.getValue());
2057 std::string Opt = std::string("-hexagon-small-data-threshold=") + N;
2058 CmdArgs.push_back("-mllvm");
2059 CmdArgs.push_back(Args.MakeArgString(Opt));
2062 if (!Args.hasArg(options::OPT_fno_short_enums))
2063 CmdArgs.push_back("-fshort-enums");
2064 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2065 CmdArgs.push_back("-mllvm");
2066 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2068 CmdArgs.push_back("-mllvm");
2069 CmdArgs.push_back("-machine-sink-split=0");
2072 void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2073 ArgStringList &CmdArgs) const {
2074 // Default to "hidden" visibility.
2075 if (!Args.hasArg(options::OPT_fvisibility_EQ,
2076 options::OPT_fvisibility_ms_compat)) {
2077 CmdArgs.push_back("-fvisibility");
2078 CmdArgs.push_back("hidden");
2082 // Decode AArch64 features from string like +[no]featureA+[no]featureB+...
2083 static bool DecodeAArch64Features(const Driver &D, StringRef text,
2084 std::vector<const char *> &Features) {
2085 SmallVector<StringRef, 8> Split;
2086 text.split(Split, StringRef("+"), -1, false);
2088 for (StringRef Feature : Split) {
2089 const char *result = llvm::StringSwitch<const char *>(Feature)
2090 .Case("fp", "+fp-armv8")
2091 .Case("simd", "+neon")
2092 .Case("crc", "+crc")
2093 .Case("crypto", "+crypto")
2094 .Case("fp16", "+fullfp16")
2095 .Case("profile", "+spe")
2096 .Case("nofp", "-fp-armv8")
2097 .Case("nosimd", "-neon")
2098 .Case("nocrc", "-crc")
2099 .Case("nocrypto", "-crypto")
2100 .Case("nofp16", "-fullfp16")
2101 .Case("noprofile", "-spe")
2104 Features.push_back(result);
2105 else if (Feature == "neon" || Feature == "noneon")
2106 D.Diag(diag::err_drv_no_neon_modifier);
2113 // Check if the CPU name and feature modifiers in -mcpu are legal. If yes,
2114 // decode CPU and feature.
2115 static bool DecodeAArch64Mcpu(const Driver &D, StringRef Mcpu, StringRef &CPU,
2116 std::vector<const char *> &Features) {
2117 std::pair<StringRef, StringRef> Split = Mcpu.split("+");
2119 if (CPU == "cyclone" || CPU == "cortex-a53" || CPU == "cortex-a57" ||
2120 CPU == "cortex-a72" || CPU == "cortex-a35" || CPU == "exynos-m1") {
2121 Features.push_back("+neon");
2122 Features.push_back("+crc");
2123 Features.push_back("+crypto");
2124 } else if (CPU == "generic") {
2125 Features.push_back("+neon");
2130 if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
2137 getAArch64ArchFeaturesFromMarch(const Driver &D, StringRef March,
2138 const ArgList &Args,
2139 std::vector<const char *> &Features) {
2140 std::string MarchLowerCase = March.lower();
2141 std::pair<StringRef, StringRef> Split = StringRef(MarchLowerCase).split("+");
2143 if (Split.first == "armv8-a" || Split.first == "armv8a") {
2144 // ok, no additional features.
2145 } else if (Split.first == "armv8.1-a" || Split.first == "armv8.1a") {
2146 Features.push_back("+v8.1a");
2147 } else if (Split.first == "armv8.2-a" || Split.first == "armv8.2a" ) {
2148 Features.push_back("+v8.2a");
2153 if (Split.second.size() && !DecodeAArch64Features(D, Split.second, Features))
2160 getAArch64ArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
2161 const ArgList &Args,
2162 std::vector<const char *> &Features) {
2164 std::string McpuLowerCase = Mcpu.lower();
2165 if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, Features))
2172 getAArch64MicroArchFeaturesFromMtune(const Driver &D, StringRef Mtune,
2173 const ArgList &Args,
2174 std::vector<const char *> &Features) {
2175 std::string MtuneLowerCase = Mtune.lower();
2176 // Handle CPU name is 'native'.
2177 if (MtuneLowerCase == "native")
2178 MtuneLowerCase = llvm::sys::getHostCPUName();
2179 if (MtuneLowerCase == "cyclone") {
2180 Features.push_back("+zcm");
2181 Features.push_back("+zcz");
2187 getAArch64MicroArchFeaturesFromMcpu(const Driver &D, StringRef Mcpu,
2188 const ArgList &Args,
2189 std::vector<const char *> &Features) {
2191 std::vector<const char *> DecodedFeature;
2192 std::string McpuLowerCase = Mcpu.lower();
2193 if (!DecodeAArch64Mcpu(D, McpuLowerCase, CPU, DecodedFeature))
2196 return getAArch64MicroArchFeaturesFromMtune(D, CPU, Args, Features);
2199 static void getAArch64TargetFeatures(const Driver &D, const ArgList &Args,
2200 std::vector<const char *> &Features) {
2202 bool success = true;
2203 // Enable NEON by default.
2204 Features.push_back("+neon");
2205 if ((A = Args.getLastArg(options::OPT_march_EQ)))
2206 success = getAArch64ArchFeaturesFromMarch(D, A->getValue(), Args, Features);
2207 else if ((A = Args.getLastArg(options::OPT_mcpu_EQ)))
2208 success = getAArch64ArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2209 else if (Args.hasArg(options::OPT_arch))
2210 success = getAArch64ArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args), Args,
2213 if (success && (A = Args.getLastArg(options::OPT_mtune_EQ)))
2215 getAArch64MicroArchFeaturesFromMtune(D, A->getValue(), Args, Features);
2216 else if (success && (A = Args.getLastArg(options::OPT_mcpu_EQ)))
2218 getAArch64MicroArchFeaturesFromMcpu(D, A->getValue(), Args, Features);
2219 else if (Args.hasArg(options::OPT_arch))
2220 success = getAArch64MicroArchFeaturesFromMcpu(D, getAArch64TargetCPU(Args),
2224 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
2226 if (Args.getLastArg(options::OPT_mgeneral_regs_only)) {
2227 Features.push_back("-fp-armv8");
2228 Features.push_back("-crypto");
2229 Features.push_back("-neon");
2233 if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
2234 if (A->getOption().matches(options::OPT_mcrc))
2235 Features.push_back("+crc");
2237 Features.push_back("-crc");
2240 if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
2241 options::OPT_munaligned_access))
2242 if (A->getOption().matches(options::OPT_mno_unaligned_access))
2243 Features.push_back("+strict-align");
2245 if (Args.hasArg(options::OPT_ffixed_x18))
2246 Features.push_back("+reserve-x18");
2249 static void getHexagonTargetFeatures(const ArgList &Args,
2250 std::vector<const char *> &Features) {
2251 bool HasHVX = false, HasHVXD = false;
2253 // FIXME: This should be able to use handleTargetFeaturesGroup except it is
2254 // doing dependent option handling here rather than in initFeatureMap or a
2256 for (auto &A : Args) {
2257 auto &Opt = A->getOption();
2258 if (Opt.matches(options::OPT_mhexagon_hvx))
2260 else if (Opt.matches(options::OPT_mno_hexagon_hvx))
2261 HasHVXD = HasHVX = false;
2262 else if (Opt.matches(options::OPT_mhexagon_hvx_double))
2263 HasHVXD = HasHVX = true;
2264 else if (Opt.matches(options::OPT_mno_hexagon_hvx_double))
2271 Features.push_back(HasHVX ? "+hvx" : "-hvx");
2272 Features.push_back(HasHVXD ? "+hvx-double" : "-hvx-double");
2275 static void getWebAssemblyTargetFeatures(const ArgList &Args,
2276 std::vector<const char *> &Features) {
2277 handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
2280 static void getTargetFeatures(const ToolChain &TC, const llvm::Triple &Triple,
2281 const ArgList &Args, ArgStringList &CmdArgs,
2283 const Driver &D = TC.getDriver();
2284 std::vector<const char *> Features;
2285 switch (Triple.getArch()) {
2288 case llvm::Triple::mips:
2289 case llvm::Triple::mipsel:
2290 case llvm::Triple::mips64:
2291 case llvm::Triple::mips64el:
2292 getMIPSTargetFeatures(D, Triple, Args, Features);
2295 case llvm::Triple::arm:
2296 case llvm::Triple::armeb:
2297 case llvm::Triple::thumb:
2298 case llvm::Triple::thumbeb:
2299 getARMTargetFeatures(TC, Triple, Args, Features, ForAS);
2302 case llvm::Triple::ppc:
2303 case llvm::Triple::ppc64:
2304 case llvm::Triple::ppc64le:
2305 getPPCTargetFeatures(D, Triple, Args, Features);
2307 case llvm::Triple::systemz:
2308 getSystemZTargetFeatures(Args, Features);
2310 case llvm::Triple::aarch64:
2311 case llvm::Triple::aarch64_be:
2312 getAArch64TargetFeatures(D, Args, Features);
2314 case llvm::Triple::x86:
2315 case llvm::Triple::x86_64:
2316 getX86TargetFeatures(D, Triple, Args, Features);
2318 case llvm::Triple::hexagon:
2319 getHexagonTargetFeatures(Args, Features);
2321 case llvm::Triple::wasm32:
2322 case llvm::Triple::wasm64:
2323 getWebAssemblyTargetFeatures(Args, Features);
2327 // Find the last of each feature.
2328 llvm::StringMap<unsigned> LastOpt;
2329 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2330 const char *Name = Features[I];
2331 assert(Name[0] == '-' || Name[0] == '+');
2332 LastOpt[Name + 1] = I;
2335 for (unsigned I = 0, N = Features.size(); I < N; ++I) {
2336 // If this feature was overridden, ignore it.
2337 const char *Name = Features[I];
2338 llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name + 1);
2339 assert(LastI != LastOpt.end());
2340 unsigned Last = LastI->second;
2344 CmdArgs.push_back("-target-feature");
2345 CmdArgs.push_back(Name);
2350 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
2351 const llvm::Triple &Triple) {
2352 // We use the zero-cost exception tables for Objective-C if the non-fragile
2353 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
2355 if (runtime.isNonFragile())
2358 if (!Triple.isMacOSX())
2361 return (!Triple.isMacOSXVersionLT(10, 5) &&
2362 (Triple.getArch() == llvm::Triple::x86_64 ||
2363 Triple.getArch() == llvm::Triple::arm));
2366 /// Adds exception related arguments to the driver command arguments. There's a
2367 /// master flag, -fexceptions and also language specific flags to enable/disable
2368 /// C++ and Objective-C exceptions. This makes it possible to for example
2369 /// disable C++ exceptions but enable Objective-C exceptions.
2370 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
2371 const ToolChain &TC, bool KernelOrKext,
2372 const ObjCRuntime &objcRuntime,
2373 ArgStringList &CmdArgs) {
2374 const Driver &D = TC.getDriver();
2375 const llvm::Triple &Triple = TC.getTriple();
2378 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
2379 // arguments now to avoid warnings about unused arguments.
2380 Args.ClaimAllArgs(options::OPT_fexceptions);
2381 Args.ClaimAllArgs(options::OPT_fno_exceptions);
2382 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
2383 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
2384 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
2385 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
2389 // See if the user explicitly enabled exceptions.
2390 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
2393 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
2394 // is not necessarily sensible, but follows GCC.
2395 if (types::isObjC(InputType) &&
2396 Args.hasFlag(options::OPT_fobjc_exceptions,
2397 options::OPT_fno_objc_exceptions, true)) {
2398 CmdArgs.push_back("-fobjc-exceptions");
2400 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
2403 if (types::isCXX(InputType)) {
2404 // Disable C++ EH by default on XCore, PS4, and MSVC.
2405 // FIXME: Remove MSVC from this list once things work.
2406 bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
2407 !Triple.isPS4CPU() &&
2408 !Triple.isWindowsMSVCEnvironment();
2409 Arg *ExceptionArg = Args.getLastArg(
2410 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
2411 options::OPT_fexceptions, options::OPT_fno_exceptions);
2413 CXXExceptionsEnabled =
2414 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
2415 ExceptionArg->getOption().matches(options::OPT_fexceptions);
2417 if (CXXExceptionsEnabled) {
2418 if (Triple.isPS4CPU()) {
2419 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
2420 assert(ExceptionArg &&
2421 "On the PS4 exceptions should only be enabled if passing "
2423 if (RTTIMode == ToolChain::RM_DisabledExplicitly) {
2424 const Arg *RTTIArg = TC.getRTTIArg();
2425 assert(RTTIArg && "RTTI disabled explicitly but no RTTIArg!");
2426 D.Diag(diag::err_drv_argument_not_allowed_with)
2427 << RTTIArg->getAsString(Args) << ExceptionArg->getAsString(Args);
2428 } else if (RTTIMode == ToolChain::RM_EnabledImplicitly)
2429 D.Diag(diag::warn_drv_enabling_rtti_with_exceptions);
2431 assert(TC.getRTTIMode() != ToolChain::RM_DisabledImplicitly);
2433 CmdArgs.push_back("-fcxx-exceptions");
2440 CmdArgs.push_back("-fexceptions");
2443 static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
2444 bool Default = true;
2445 if (TC.getTriple().isOSDarwin()) {
2446 // The native darwin assembler doesn't support the linker_option directives,
2447 // so we disable them if we think the .s file will be passed to it.
2448 Default = TC.useIntegratedAs();
2450 return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
2454 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
2455 const ToolChain &TC) {
2456 bool UseDwarfDirectory =
2457 Args.hasFlag(options::OPT_fdwarf_directory_asm,
2458 options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
2459 return !UseDwarfDirectory;
2462 /// \brief Check whether the given input tree contains any compilation actions.
2463 static bool ContainsCompileAction(const Action *A) {
2464 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
2467 for (const auto &Act : *A)
2468 if (ContainsCompileAction(Act))
2474 /// \brief Check if -relax-all should be passed to the internal assembler.
2475 /// This is done by default when compiling non-assembler source with -O0.
2476 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
2477 bool RelaxDefault = true;
2479 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2480 RelaxDefault = A->getOption().matches(options::OPT_O0);
2483 RelaxDefault = false;
2484 for (const auto &Act : C.getActions()) {
2485 if (ContainsCompileAction(Act)) {
2486 RelaxDefault = true;
2492 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
2496 // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
2497 // to the corresponding DebugInfoKind.
2498 static CodeGenOptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
2499 assert(A.getOption().matches(options::OPT_gN_Group) &&
2500 "Not a -g option that specifies a debug-info level");
2501 if (A.getOption().matches(options::OPT_g0) ||
2502 A.getOption().matches(options::OPT_ggdb0))
2503 return CodeGenOptions::NoDebugInfo;
2504 if (A.getOption().matches(options::OPT_gline_tables_only) ||
2505 A.getOption().matches(options::OPT_ggdb1))
2506 return CodeGenOptions::DebugLineTablesOnly;
2507 return CodeGenOptions::LimitedDebugInfo;
2510 // Extract the integer N from a string spelled "-dwarf-N", returning 0
2511 // on mismatch. The StringRef input (rather than an Arg) allows
2512 // for use by the "-Xassembler" option parser.
2513 static unsigned DwarfVersionNum(StringRef ArgValue) {
2514 return llvm::StringSwitch<unsigned>(ArgValue)
2515 .Case("-gdwarf-2", 2)
2516 .Case("-gdwarf-3", 3)
2517 .Case("-gdwarf-4", 4)
2518 .Case("-gdwarf-5", 5)
2522 static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
2523 CodeGenOptions::DebugInfoKind DebugInfoKind,
2524 unsigned DwarfVersion,
2525 llvm::DebuggerKind DebuggerTuning) {
2526 switch (DebugInfoKind) {
2527 case CodeGenOptions::DebugLineTablesOnly:
2528 CmdArgs.push_back("-debug-info-kind=line-tables-only");
2530 case CodeGenOptions::LimitedDebugInfo:
2531 CmdArgs.push_back("-debug-info-kind=limited");
2533 case CodeGenOptions::FullDebugInfo:
2534 CmdArgs.push_back("-debug-info-kind=standalone");
2539 if (DwarfVersion > 0)
2541 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
2542 switch (DebuggerTuning) {
2543 case llvm::DebuggerKind::GDB:
2544 CmdArgs.push_back("-debugger-tuning=gdb");
2546 case llvm::DebuggerKind::LLDB:
2547 CmdArgs.push_back("-debugger-tuning=lldb");
2549 case llvm::DebuggerKind::SCE:
2550 CmdArgs.push_back("-debugger-tuning=sce");
2557 static void CollectArgsForIntegratedAssembler(Compilation &C,
2558 const ArgList &Args,
2559 ArgStringList &CmdArgs,
2561 if (UseRelaxAll(C, Args))
2562 CmdArgs.push_back("-mrelax-all");
2564 // Only default to -mincremental-linker-compatible if we think we are
2565 // targeting the MSVC linker.
2566 bool DefaultIncrementalLinkerCompatible =
2567 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2568 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2569 options::OPT_mno_incremental_linker_compatible,
2570 DefaultIncrementalLinkerCompatible))
2571 CmdArgs.push_back("-mincremental-linker-compatible");
2573 // When passing -I arguments to the assembler we sometimes need to
2574 // unconditionally take the next argument. For example, when parsing
2575 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2576 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2577 // arg after parsing the '-I' arg.
2578 bool TakeNextArg = false;
2580 // When using an integrated assembler, translate -Wa, and -Xassembler
2582 bool CompressDebugSections = false;
2584 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2587 for (StringRef Value : A->getValues()) {
2589 CmdArgs.push_back(Value.data());
2590 TakeNextArg = false;
2594 switch (C.getDefaultToolChain().getArch()) {
2597 case llvm::Triple::mips:
2598 case llvm::Triple::mipsel:
2599 case llvm::Triple::mips64:
2600 case llvm::Triple::mips64el:
2601 if (Value == "--trap") {
2602 CmdArgs.push_back("-target-feature");
2603 CmdArgs.push_back("+use-tcc-in-div");
2606 if (Value == "--break") {
2607 CmdArgs.push_back("-target-feature");
2608 CmdArgs.push_back("-use-tcc-in-div");
2611 if (Value.startswith("-msoft-float")) {
2612 CmdArgs.push_back("-target-feature");
2613 CmdArgs.push_back("+soft-float");
2616 if (Value.startswith("-mhard-float")) {
2617 CmdArgs.push_back("-target-feature");
2618 CmdArgs.push_back("-soft-float");
2624 if (Value == "-force_cpusubtype_ALL") {
2625 // Do nothing, this is the default and we don't support anything else.
2626 } else if (Value == "-L") {
2627 CmdArgs.push_back("-msave-temp-labels");
2628 } else if (Value == "--fatal-warnings") {
2629 CmdArgs.push_back("-massembler-fatal-warnings");
2630 } else if (Value == "--noexecstack") {
2631 CmdArgs.push_back("-mnoexecstack");
2632 } else if (Value == "-compress-debug-sections" ||
2633 Value == "--compress-debug-sections") {
2634 CompressDebugSections = true;
2635 } else if (Value == "-nocompress-debug-sections" ||
2636 Value == "--nocompress-debug-sections") {
2637 CompressDebugSections = false;
2638 } else if (Value.startswith("-I")) {
2639 CmdArgs.push_back(Value.data());
2640 // We need to consume the next argument if the current arg is a plain
2641 // -I. The next arg will be the include directory.
2644 } else if (Value.startswith("-gdwarf-")) {
2645 // "-gdwarf-N" options are not cc1as options.
2646 unsigned DwarfVersion = DwarfVersionNum(Value);
2647 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2648 CmdArgs.push_back(Value.data());
2650 RenderDebugEnablingArgs(
2651 Args, CmdArgs, CodeGenOptions::LimitedDebugInfo, DwarfVersion,
2652 llvm::DebuggerKind::Default);
2654 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2655 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2656 // Do nothing, we'll validate it later.
2658 D.Diag(diag::err_drv_unsupported_option_argument)
2659 << A->getOption().getName() << Value;
2663 if (CompressDebugSections) {
2664 if (llvm::zlib::isAvailable())
2665 CmdArgs.push_back("-compress-debug-sections");
2667 D.Diag(diag::warn_debug_compression_unavailable);
2671 // This adds the static libclang_rt.builtins-arch.a directly to the command line
2672 // FIXME: Make sure we can also emit shared objects if they're requested
2673 // and available, check for possible errors, etc.
2674 static void addClangRT(const ToolChain &TC, const ArgList &Args,
2675 ArgStringList &CmdArgs) {
2676 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "builtins"));
2680 enum OpenMPRuntimeKind {
2681 /// An unknown OpenMP runtime. We can't generate effective OpenMP code
2682 /// without knowing what runtime to target.
2685 /// The LLVM OpenMP runtime. When completed and integrated, this will become
2686 /// the default for Clang.
2689 /// The GNU OpenMP runtime. Clang doesn't support generating OpenMP code for
2690 /// this runtime but can swallow the pragmas, and find and link against the
2691 /// runtime library itself.
2694 /// The legacy name for the LLVM OpenMP runtime from when it was the Intel
2695 /// OpenMP runtime. We support this mode for users with existing dependencies
2696 /// on this runtime library name.
2701 /// Compute the desired OpenMP runtime from the flag provided.
2702 static OpenMPRuntimeKind getOpenMPRuntime(const ToolChain &TC,
2703 const ArgList &Args) {
2704 StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
2706 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
2708 RuntimeName = A->getValue();
2710 auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
2711 .Case("libomp", OMPRT_OMP)
2712 .Case("libgomp", OMPRT_GOMP)
2713 .Case("libiomp5", OMPRT_IOMP5)
2714 .Default(OMPRT_Unknown);
2716 if (RT == OMPRT_Unknown) {
2718 TC.getDriver().Diag(diag::err_drv_unsupported_option_argument)
2719 << A->getOption().getName() << A->getValue();
2721 // FIXME: We could use a nicer diagnostic here.
2722 TC.getDriver().Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
2728 static void addOpenMPRuntime(ArgStringList &CmdArgs, const ToolChain &TC,
2729 const ArgList &Args) {
2730 if (!Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
2731 options::OPT_fno_openmp, false))
2734 switch (getOpenMPRuntime(TC, Args)) {
2736 CmdArgs.push_back("-lomp");
2739 CmdArgs.push_back("-lgomp");
2742 CmdArgs.push_back("-liomp5");
2745 // Already diagnosed.
2750 static void addSanitizerRuntime(const ToolChain &TC, const ArgList &Args,
2751 ArgStringList &CmdArgs, StringRef Sanitizer,
2753 // Static runtimes must be forced into executable, so we wrap them in
2755 if (!IsShared) CmdArgs.push_back("-whole-archive");
2756 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Sanitizer, IsShared));
2757 if (!IsShared) CmdArgs.push_back("-no-whole-archive");
2760 // Tries to use a file with the list of dynamic symbols that need to be exported
2761 // from the runtime library. Returns true if the file was found.
2762 static bool addSanitizerDynamicList(const ToolChain &TC, const ArgList &Args,
2763 ArgStringList &CmdArgs,
2764 StringRef Sanitizer) {
2765 SmallString<128> SanRT(TC.getCompilerRT(Args, Sanitizer));
2766 if (llvm::sys::fs::exists(SanRT + ".syms")) {
2767 CmdArgs.push_back(Args.MakeArgString("--dynamic-list=" + SanRT + ".syms"));
2773 static void linkSanitizerRuntimeDeps(const ToolChain &TC,
2774 ArgStringList &CmdArgs) {
2775 // Force linking against the system libraries sanitizers depends on
2776 // (see PR15823 why this is necessary).
2777 CmdArgs.push_back("--no-as-needed");
2778 CmdArgs.push_back("-lpthread");
2779 CmdArgs.push_back("-lrt");
2780 CmdArgs.push_back("-lm");
2781 // There's no libdl on FreeBSD.
2782 if (TC.getTriple().getOS() != llvm::Triple::FreeBSD)
2783 CmdArgs.push_back("-ldl");
2787 collectSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
2788 SmallVectorImpl<StringRef> &SharedRuntimes,
2789 SmallVectorImpl<StringRef> &StaticRuntimes,
2790 SmallVectorImpl<StringRef> &HelperStaticRuntimes) {
2791 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
2792 // Collect shared runtimes.
2793 if (SanArgs.needsAsanRt() && SanArgs.needsSharedAsanRt()) {
2794 SharedRuntimes.push_back("asan");
2797 // Collect static runtimes.
2798 if (Args.hasArg(options::OPT_shared) || TC.getTriple().isAndroid()) {
2799 // Don't link static runtimes into DSOs or if compiling for Android.
2802 if (SanArgs.needsAsanRt()) {
2803 if (SanArgs.needsSharedAsanRt()) {
2804 HelperStaticRuntimes.push_back("asan-preinit");
2806 StaticRuntimes.push_back("asan");
2807 if (SanArgs.linkCXXRuntimes())
2808 StaticRuntimes.push_back("asan_cxx");
2811 if (SanArgs.needsDfsanRt())
2812 StaticRuntimes.push_back("dfsan");
2813 if (SanArgs.needsLsanRt())
2814 StaticRuntimes.push_back("lsan");
2815 if (SanArgs.needsMsanRt()) {
2816 StaticRuntimes.push_back("msan");
2817 if (SanArgs.linkCXXRuntimes())
2818 StaticRuntimes.push_back("msan_cxx");
2820 if (SanArgs.needsTsanRt()) {
2821 StaticRuntimes.push_back("tsan");
2822 if (SanArgs.linkCXXRuntimes())
2823 StaticRuntimes.push_back("tsan_cxx");
2825 if (SanArgs.needsUbsanRt()) {
2826 StaticRuntimes.push_back("ubsan_standalone");
2827 if (SanArgs.linkCXXRuntimes())
2828 StaticRuntimes.push_back("ubsan_standalone_cxx");
2830 if (SanArgs.needsSafeStackRt())
2831 StaticRuntimes.push_back("safestack");
2832 if (SanArgs.needsCfiRt())
2833 StaticRuntimes.push_back("cfi");
2834 if (SanArgs.needsCfiDiagRt())
2835 StaticRuntimes.push_back("cfi_diag");
2838 // Should be called before we add system libraries (C++ ABI, libstdc++/libc++,
2839 // C runtime, etc). Returns true if sanitizer system deps need to be linked in.
2840 static bool addSanitizerRuntimes(const ToolChain &TC, const ArgList &Args,
2841 ArgStringList &CmdArgs) {
2842 SmallVector<StringRef, 4> SharedRuntimes, StaticRuntimes,
2843 HelperStaticRuntimes;
2844 collectSanitizerRuntimes(TC, Args, SharedRuntimes, StaticRuntimes,
2845 HelperStaticRuntimes);
2846 for (auto RT : SharedRuntimes)
2847 addSanitizerRuntime(TC, Args, CmdArgs, RT, true);
2848 for (auto RT : HelperStaticRuntimes)
2849 addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
2850 bool AddExportDynamic = false;
2851 for (auto RT : StaticRuntimes) {
2852 addSanitizerRuntime(TC, Args, CmdArgs, RT, false);
2853 AddExportDynamic |= !addSanitizerDynamicList(TC, Args, CmdArgs, RT);
2855 // If there is a static runtime with no dynamic list, force all the symbols
2856 // to be dynamic to be sure we export sanitizer interface functions.
2857 if (AddExportDynamic)
2858 CmdArgs.push_back("-export-dynamic");
2859 return !StaticRuntimes.empty();
2862 static bool areOptimizationsEnabled(const ArgList &Args) {
2863 // Find the last -O arg and see if it is non-zero.
2864 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
2865 return !A->getOption().matches(options::OPT_O0);
2870 static bool shouldUseFramePointerForTarget(const ArgList &Args,
2871 const llvm::Triple &Triple) {
2872 switch (Triple.getArch()) {
2873 case llvm::Triple::xcore:
2874 case llvm::Triple::wasm32:
2875 case llvm::Triple::wasm64:
2876 // XCore never wants frame pointers, regardless of OS.
2877 // WebAssembly never wants frame pointers.
2883 if (Triple.isOSLinux()) {
2884 switch (Triple.getArch()) {
2885 // Don't use a frame pointer on linux if optimizing for certain targets.
2886 case llvm::Triple::mips64:
2887 case llvm::Triple::mips64el:
2888 case llvm::Triple::mips:
2889 case llvm::Triple::mipsel:
2890 case llvm::Triple::systemz:
2891 case llvm::Triple::x86:
2892 case llvm::Triple::x86_64:
2893 return !areOptimizationsEnabled(Args);
2899 if (Triple.isOSWindows()) {
2900 switch (Triple.getArch()) {
2901 case llvm::Triple::x86:
2902 return !areOptimizationsEnabled(Args);
2903 case llvm::Triple::arm:
2904 case llvm::Triple::thumb:
2905 // Windows on ARM builds with FPO disabled to aid fast stack walking
2908 // All other supported Windows ISAs use xdata unwind information, so frame
2909 // pointers are not generally useful.
2917 static bool shouldUseFramePointer(const ArgList &Args,
2918 const llvm::Triple &Triple) {
2919 if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
2920 options::OPT_fomit_frame_pointer))
2921 return A->getOption().matches(options::OPT_fno_omit_frame_pointer);
2922 if (Args.hasArg(options::OPT_pg))
2925 return shouldUseFramePointerForTarget(Args, Triple);
2928 static bool shouldUseLeafFramePointer(const ArgList &Args,
2929 const llvm::Triple &Triple) {
2930 if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
2931 options::OPT_momit_leaf_frame_pointer))
2932 return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
2933 if (Args.hasArg(options::OPT_pg))
2936 if (Triple.isPS4CPU())
2939 return shouldUseFramePointerForTarget(Args, Triple);
2942 /// Add a CC1 option to specify the debug compilation directory.
2943 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
2944 SmallString<128> cwd;
2945 if (!llvm::sys::fs::current_path(cwd)) {
2946 CmdArgs.push_back("-fdebug-compilation-dir");
2947 CmdArgs.push_back(Args.MakeArgString(cwd));
2951 static const char *SplitDebugName(const ArgList &Args, const InputInfo &Input) {
2952 Arg *FinalOutput = Args.getLastArg(options::OPT_o);
2953 if (FinalOutput && Args.hasArg(options::OPT_c)) {
2954 SmallString<128> T(FinalOutput->getValue());
2955 llvm::sys::path::replace_extension(T, "dwo");
2956 return Args.MakeArgString(T);
2958 // Use the compilation dir.
2960 Args.getLastArgValue(options::OPT_fdebug_compilation_dir));
2961 SmallString<128> F(llvm::sys::path::stem(Input.getBaseInput()));
2962 llvm::sys::path::replace_extension(F, "dwo");
2964 return Args.MakeArgString(F);
2968 static void SplitDebugInfo(const ToolChain &TC, Compilation &C, const Tool &T,
2969 const JobAction &JA, const ArgList &Args,
2970 const InputInfo &Output, const char *OutFile) {
2971 ArgStringList ExtractArgs;
2972 ExtractArgs.push_back("--extract-dwo");
2974 ArgStringList StripArgs;
2975 StripArgs.push_back("--strip-dwo");
2977 // Grabbing the output of the earlier compile step.
2978 StripArgs.push_back(Output.getFilename());
2979 ExtractArgs.push_back(Output.getFilename());
2980 ExtractArgs.push_back(OutFile);
2982 const char *Exec = Args.MakeArgString(TC.GetProgramPath("objcopy"));
2983 InputInfo II(types::TY_Object, Output.getFilename(), Output.getFilename());
2985 // First extract the dwo sections.
2986 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, ExtractArgs, II));
2988 // Then remove them from the original .o file.
2989 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, StripArgs, II));
2992 /// \brief Vectorize at all optimization levels greater than 1 except for -Oz.
2993 /// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
2994 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
2995 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
2996 if (A->getOption().matches(options::OPT_O4) ||
2997 A->getOption().matches(options::OPT_Ofast))
3000 if (A->getOption().matches(options::OPT_O0))
3003 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
3006 StringRef S(A->getValue());
3010 // Don't vectorize -Oz, unless it's the slp vectorizer.
3014 unsigned OptLevel = 0;
3015 if (S.getAsInteger(10, OptLevel))
3018 return OptLevel > 1;
3024 /// Add -x lang to \p CmdArgs for \p Input.
3025 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
3026 ArgStringList &CmdArgs) {
3027 // When using -verify-pch, we don't want to provide the type
3028 // 'precompiled-header' if it was inferred from the file extension
3029 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
3032 CmdArgs.push_back("-x");
3033 if (Args.hasArg(options::OPT_rewrite_objc))
3034 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
3036 CmdArgs.push_back(types::getTypeName(Input.getType()));
3039 static VersionTuple getMSCompatibilityVersion(unsigned Version) {
3041 return VersionTuple(Version);
3043 if (Version < 10000)
3044 return VersionTuple(Version / 100, Version % 100);
3046 unsigned Build = 0, Factor = 1;
3047 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
3048 Build = Build + (Version % 10) * Factor;
3049 return VersionTuple(Version / 100, Version % 100, Build);
3052 // Claim options we don't want to warn if they are unused. We do this for
3053 // options that build systems might add but are unused when assembling or only
3054 // running the preprocessor for example.
3055 static void claimNoWarnArgs(const ArgList &Args) {
3056 // Don't warn about unused -f(no-)?lto. This can happen when we're
3057 // preprocessing, precompiling or assembling.
3058 Args.ClaimAllArgs(options::OPT_flto_EQ);
3059 Args.ClaimAllArgs(options::OPT_flto);
3060 Args.ClaimAllArgs(options::OPT_fno_lto);
3063 static void appendUserToPath(SmallVectorImpl<char> &Result) {
3065 const char *Username = getenv("LOGNAME");
3067 const char *Username = getenv("USERNAME");
3070 // Validate that LoginName can be used in a path, and get its length.
3072 for (const char *P = Username; *P; ++P, ++Len) {
3073 if (!isAlphanumeric(*P) && *P != '_') {
3079 if (Username && Len > 0) {
3080 Result.append(Username, Username + Len);
3085 // Fallback to user id.
3087 std::string UID = llvm::utostr(getuid());
3089 // FIXME: Windows seems to have an 'SID' that might work.
3090 std::string UID = "9999";
3092 Result.append(UID.begin(), UID.end());
3095 VersionTuple visualstudio::getMSVCVersion(const Driver *D,
3096 const llvm::Triple &Triple,
3097 const llvm::opt::ArgList &Args,
3098 bool IsWindowsMSVC) {
3099 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
3101 Args.hasArg(options::OPT_fmsc_version) ||
3102 Args.hasArg(options::OPT_fms_compatibility_version)) {
3103 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
3104 const Arg *MSCompatibilityVersion =
3105 Args.getLastArg(options::OPT_fms_compatibility_version);
3107 if (MSCVersion && MSCompatibilityVersion) {
3109 D->Diag(diag::err_drv_argument_not_allowed_with)
3110 << MSCVersion->getAsString(Args)
3111 << MSCompatibilityVersion->getAsString(Args);
3112 return VersionTuple();
3115 if (MSCompatibilityVersion) {
3117 if (MSVT.tryParse(MSCompatibilityVersion->getValue()) && D)
3118 D->Diag(diag::err_drv_invalid_value)
3119 << MSCompatibilityVersion->getAsString(Args)
3120 << MSCompatibilityVersion->getValue();
3125 unsigned Version = 0;
3126 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version) && D)
3127 D->Diag(diag::err_drv_invalid_value) << MSCVersion->getAsString(Args)
3128 << MSCVersion->getValue();
3129 return getMSCompatibilityVersion(Version);
3132 unsigned Major, Minor, Micro;
3133 Triple.getEnvironmentVersion(Major, Minor, Micro);
3134 if (Major || Minor || Micro)
3135 return VersionTuple(Major, Minor, Micro);
3137 return VersionTuple(18);
3139 return VersionTuple();
3142 static void addPGOAndCoverageFlags(Compilation &C, const Driver &D,
3143 const InputInfo &Output, const ArgList &Args,
3144 ArgStringList &CmdArgs) {
3145 auto *ProfileGenerateArg = Args.getLastArg(
3146 options::OPT_fprofile_instr_generate,
3147 options::OPT_fprofile_instr_generate_EQ, options::OPT_fprofile_generate,
3148 options::OPT_fprofile_generate_EQ,
3149 options::OPT_fno_profile_instr_generate);
3150 if (ProfileGenerateArg &&
3151 ProfileGenerateArg->getOption().matches(
3152 options::OPT_fno_profile_instr_generate))
3153 ProfileGenerateArg = nullptr;
3155 auto *ProfileUseArg = Args.getLastArg(
3156 options::OPT_fprofile_instr_use, options::OPT_fprofile_instr_use_EQ,
3157 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ,
3158 options::OPT_fno_profile_instr_use);
3159 if (ProfileUseArg &&
3160 ProfileUseArg->getOption().matches(options::OPT_fno_profile_instr_use))
3161 ProfileUseArg = nullptr;
3163 if (ProfileGenerateArg && ProfileUseArg)
3164 D.Diag(diag::err_drv_argument_not_allowed_with)
3165 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
3167 if (ProfileGenerateArg) {
3168 if (ProfileGenerateArg->getOption().matches(
3169 options::OPT_fprofile_instr_generate_EQ))
3170 ProfileGenerateArg->render(Args, CmdArgs);
3171 else if (ProfileGenerateArg->getOption().matches(
3172 options::OPT_fprofile_generate_EQ)) {
3173 SmallString<128> Path(ProfileGenerateArg->getValue());
3174 llvm::sys::path::append(Path, "default.profraw");
3176 Args.MakeArgString(Twine("-fprofile-instr-generate=") + Path));
3178 Args.AddAllArgs(CmdArgs, options::OPT_fprofile_instr_generate);
3181 if (ProfileUseArg) {
3182 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
3183 ProfileUseArg->render(Args, CmdArgs);
3184 else if ((ProfileUseArg->getOption().matches(
3185 options::OPT_fprofile_use_EQ) ||
3186 ProfileUseArg->getOption().matches(
3187 options::OPT_fprofile_instr_use))) {
3188 SmallString<128> Path(
3189 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
3190 if (Path.empty() || llvm::sys::fs::is_directory(Path))
3191 llvm::sys::path::append(Path, "default.profdata");
3193 Args.MakeArgString(Twine("-fprofile-instr-use=") + Path));
3197 if (Args.hasArg(options::OPT_ftest_coverage) ||
3198 Args.hasArg(options::OPT_coverage))
3199 CmdArgs.push_back("-femit-coverage-notes");
3200 if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
3202 Args.hasArg(options::OPT_coverage))
3203 CmdArgs.push_back("-femit-coverage-data");
3205 if (Args.hasFlag(options::OPT_fcoverage_mapping,
3206 options::OPT_fno_coverage_mapping, false) &&
3207 !ProfileGenerateArg)
3208 D.Diag(diag::err_drv_argument_only_allowed_with)
3209 << "-fcoverage-mapping"
3210 << "-fprofile-instr-generate";
3212 if (Args.hasFlag(options::OPT_fcoverage_mapping,
3213 options::OPT_fno_coverage_mapping, false))
3214 CmdArgs.push_back("-fcoverage-mapping");
3216 if (C.getArgs().hasArg(options::OPT_c) ||
3217 C.getArgs().hasArg(options::OPT_S)) {
3218 if (Output.isFilename()) {
3219 CmdArgs.push_back("-coverage-file");
3220 SmallString<128> CoverageFilename;
3221 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
3222 CoverageFilename = FinalOutput->getValue();
3224 CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
3226 if (llvm::sys::path::is_relative(CoverageFilename)) {
3227 SmallString<128> Pwd;
3228 if (!llvm::sys::fs::current_path(Pwd)) {
3229 llvm::sys::path::append(Pwd, CoverageFilename);
3230 CoverageFilename.swap(Pwd);
3233 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
3238 static void addPS4ProfileRTArgs(const ToolChain &TC, const ArgList &Args,
3239 ArgStringList &CmdArgs) {
3240 if ((Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
3242 Args.hasFlag(options::OPT_fprofile_generate,
3243 options::OPT_fno_profile_instr_generate, false) ||
3244 Args.hasFlag(options::OPT_fprofile_generate_EQ,
3245 options::OPT_fno_profile_instr_generate, false) ||
3246 Args.hasFlag(options::OPT_fprofile_instr_generate,
3247 options::OPT_fno_profile_instr_generate, false) ||
3248 Args.hasFlag(options::OPT_fprofile_instr_generate_EQ,
3249 options::OPT_fno_profile_instr_generate, false) ||
3250 Args.hasArg(options::OPT_fcreate_profile) ||
3251 Args.hasArg(options::OPT_coverage)))
3252 CmdArgs.push_back("--dependent-lib=libclang_rt.profile-x86_64.a");
3255 /// Parses the various -fpic/-fPIC/-fpie/-fPIE arguments. Then,
3256 /// smooshes them together with platform defaults, to decide whether
3257 /// this compile should be using PIC mode or not. Returns a tuple of
3258 /// (RelocationModel, PICLevel, IsPIE).
3259 static std::tuple<llvm::Reloc::Model, unsigned, bool>
3260 ParsePICArgs(const ToolChain &ToolChain, const llvm::Triple &Triple,
3261 const ArgList &Args) {
3262 // FIXME: why does this code...and so much everywhere else, use both
3263 // ToolChain.getTriple() and Triple?
3264 bool PIE = ToolChain.isPIEDefault();
3265 bool PIC = PIE || ToolChain.isPICDefault();
3266 // The Darwin/MachO default to use PIC does not apply when using -static.
3267 if (ToolChain.getTriple().isOSBinFormatMachO() &&
3268 Args.hasArg(options::OPT_static))
3270 bool IsPICLevelTwo = PIC;
3273 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3275 // Android-specific defaults for PIC/PIE
3276 if (ToolChain.getTriple().isAndroid()) {
3277 switch (ToolChain.getArch()) {
3278 case llvm::Triple::arm:
3279 case llvm::Triple::armeb:
3280 case llvm::Triple::thumb:
3281 case llvm::Triple::thumbeb:
3282 case llvm::Triple::aarch64:
3283 case llvm::Triple::mips:
3284 case llvm::Triple::mipsel:
3285 case llvm::Triple::mips64:
3286 case llvm::Triple::mips64el:
3287 PIC = true; // "-fpic"
3290 case llvm::Triple::x86:
3291 case llvm::Triple::x86_64:
3292 PIC = true; // "-fPIC"
3293 IsPICLevelTwo = true;
3301 // OpenBSD-specific defaults for PIE
3302 if (ToolChain.getTriple().getOS() == llvm::Triple::OpenBSD) {
3303 switch (ToolChain.getArch()) {
3304 case llvm::Triple::mips64:
3305 case llvm::Triple::mips64el:
3306 case llvm::Triple::sparcel:
3307 case llvm::Triple::x86:
3308 case llvm::Triple::x86_64:
3309 IsPICLevelTwo = false; // "-fpie"
3312 case llvm::Triple::ppc:
3313 case llvm::Triple::sparc:
3314 case llvm::Triple::sparcv9:
3315 IsPICLevelTwo = true; // "-fPIE"
3323 // The last argument relating to either PIC or PIE wins, and no
3324 // other argument is used. If the last argument is any flavor of the
3325 // '-fno-...' arguments, both PIC and PIE are disabled. Any PIE
3326 // option implicitly enables PIC at the same level.
3327 Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
3328 options::OPT_fpic, options::OPT_fno_pic,
3329 options::OPT_fPIE, options::OPT_fno_PIE,
3330 options::OPT_fpie, options::OPT_fno_pie);
3331 // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
3332 // is forced, then neither PIC nor PIE flags will have no effect.
3333 if (!ToolChain.isPICDefaultForced()) {
3335 Option O = LastPICArg->getOption();
3336 if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
3337 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
3338 PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
3340 PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
3342 O.matches(options::OPT_fPIE) || O.matches(options::OPT_fPIC);
3345 if (Triple.isPS4CPU()) {
3346 Arg *ModelArg = Args.getLastArg(options::OPT_mcmodel_EQ);
3347 StringRef Model = ModelArg ? ModelArg->getValue() : "";
3348 if (Model != "kernel") {
3350 ToolChain.getDriver().Diag(diag::warn_drv_ps4_force_pic)
3351 << LastPICArg->getSpelling();
3358 // Introduce a Darwin and PS4-specific hack. If the default is PIC, but the
3359 // PIC level would've been set to level 1, force it back to level 2 PIC
3361 if (PIC && (ToolChain.getTriple().isOSDarwin() || Triple.isPS4CPU()))
3362 IsPICLevelTwo |= ToolChain.isPICDefault();
3364 // This kernel flags are a trump-card: they will disable PIC/PIE
3365 // generation, independent of the argument order.
3366 if (KernelOrKext && ((!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
3367 !Triple.isWatchOS()))
3370 if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) {
3371 // This is a very special mode. It trumps the other modes, almost no one
3372 // uses it, and it isn't even valid on any OS but Darwin.
3373 if (!ToolChain.getTriple().isOSDarwin())
3374 ToolChain.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
3375 << A->getSpelling() << ToolChain.getTriple().str();
3377 // FIXME: Warn when this flag trumps some other PIC or PIE flag.
3379 // Only a forced PIC mode can cause the actual compile to have PIC defines
3380 // etc., no flags are sufficient. This behavior was selected to closely
3381 // match that of llvm-gcc and Apple GCC before that.
3382 PIC = ToolChain.isPICDefault() && ToolChain.isPICDefaultForced();
3384 return std::make_tuple(llvm::Reloc::DynamicNoPIC, PIC ? 2 : 0, false);
3388 return std::make_tuple(llvm::Reloc::PIC_, IsPICLevelTwo ? 2 : 1, PIE);
3390 return std::make_tuple(llvm::Reloc::Static, 0, false);
3393 static const char *RelocationModelName(llvm::Reloc::Model Model) {
3395 case llvm::Reloc::Default:
3397 case llvm::Reloc::Static:
3399 case llvm::Reloc::PIC_:
3401 case llvm::Reloc::DynamicNoPIC:
3402 return "dynamic-no-pic";
3404 llvm_unreachable("Unknown Reloc::Model kind");
3407 static void AddAssemblerKPIC(const ToolChain &ToolChain, const ArgList &Args,
3408 ArgStringList &CmdArgs) {
3409 llvm::Reloc::Model RelocationModel;
3412 std::tie(RelocationModel, PICLevel, IsPIE) =
3413 ParsePICArgs(ToolChain, ToolChain.getTriple(), Args);
3415 if (RelocationModel != llvm::Reloc::Static)
3416 CmdArgs.push_back("-KPIC");
3419 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3420 const InputInfo &Output, const InputInfoList &Inputs,
3421 const ArgList &Args, const char *LinkingOutput) const {
3422 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
3423 const llvm::Triple Triple(TripleStr);
3426 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3427 const Driver &D = getToolChain().getDriver();
3428 ArgStringList CmdArgs;
3430 bool IsWindowsGNU = getToolChain().getTriple().isWindowsGNUEnvironment();
3431 bool IsWindowsCygnus =
3432 getToolChain().getTriple().isWindowsCygwinEnvironment();
3433 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
3434 bool IsPS4CPU = getToolChain().getTriple().isPS4CPU();
3436 // Check number of inputs for sanity. We need at least one input.
3437 assert(Inputs.size() >= 1 && "Must have at least one input.");
3438 const InputInfo &Input = Inputs[0];
3439 // CUDA compilation may have multiple inputs (source file + results of
3440 // device-side compilations). All other jobs are expected to have exactly one
3442 bool IsCuda = types::isCuda(Input.getType());
3443 assert((IsCuda || Inputs.size() == 1) && "Unable to handle multiple inputs.");
3445 // Invoke ourselves in -cc1 mode.
3447 // FIXME: Implement custom jobs for internal actions.
3448 CmdArgs.push_back("-cc1");
3450 // Add the "effective" target triple.
3451 CmdArgs.push_back("-triple");
3452 CmdArgs.push_back(Args.MakeArgString(TripleStr));
3454 const ToolChain *AuxToolChain = nullptr;
3456 // FIXME: We need a (better) way to pass information about
3457 // particular compilation pass we're constructing here. For now we
3458 // can check which toolchain we're using and pick the other one to
3459 // extract the triple.
3460 if (&getToolChain() == C.getCudaDeviceToolChain())
3461 AuxToolChain = C.getCudaHostToolChain();
3462 else if (&getToolChain() == C.getCudaHostToolChain())
3463 AuxToolChain = C.getCudaDeviceToolChain();
3465 llvm_unreachable("Can't figure out CUDA compilation mode.");
3466 assert(AuxToolChain != nullptr && "No aux toolchain.");
3467 CmdArgs.push_back("-aux-triple");
3468 CmdArgs.push_back(Args.MakeArgString(AuxToolChain->getTriple().str()));
3469 CmdArgs.push_back("-fcuda-target-overloads");
3470 CmdArgs.push_back("-fcuda-disable-target-call-checks");
3473 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3474 Triple.getArch() == llvm::Triple::thumb)) {
3475 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3477 Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3479 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3483 // Push all default warning arguments that are specific to
3484 // the given target. These come before user provided warning options
3486 getToolChain().addClangWarningOptions(CmdArgs);
3488 // Select the appropriate action.
3489 RewriteKind rewriteKind = RK_None;
3491 if (isa<AnalyzeJobAction>(JA)) {
3492 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3493 CmdArgs.push_back("-analyze");
3494 } else if (isa<MigrateJobAction>(JA)) {
3495 CmdArgs.push_back("-migrate");
3496 } else if (isa<PreprocessJobAction>(JA)) {
3497 if (Output.getType() == types::TY_Dependencies)
3498 CmdArgs.push_back("-Eonly");
3500 CmdArgs.push_back("-E");
3501 if (Args.hasArg(options::OPT_rewrite_objc) &&
3502 !Args.hasArg(options::OPT_g_Group))
3503 CmdArgs.push_back("-P");
3505 } else if (isa<AssembleJobAction>(JA)) {
3506 CmdArgs.push_back("-emit-obj");
3508 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3510 // Also ignore explicit -force_cpusubtype_ALL option.
3511 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3512 } else if (isa<PrecompileJobAction>(JA)) {
3513 // Use PCH if the user requested it.
3514 bool UsePCH = D.CCCUsePCH;
3516 if (JA.getType() == types::TY_Nothing)
3517 CmdArgs.push_back("-fsyntax-only");
3519 CmdArgs.push_back("-emit-pch");
3521 CmdArgs.push_back("-emit-pth");
3522 } else if (isa<VerifyPCHJobAction>(JA)) {
3523 CmdArgs.push_back("-verify-pch");
3525 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3526 "Invalid action for clang tool.");
3527 if (JA.getType() == types::TY_Nothing) {
3528 CmdArgs.push_back("-fsyntax-only");
3529 } else if (JA.getType() == types::TY_LLVM_IR ||
3530 JA.getType() == types::TY_LTO_IR) {
3531 CmdArgs.push_back("-emit-llvm");
3532 } else if (JA.getType() == types::TY_LLVM_BC ||
3533 JA.getType() == types::TY_LTO_BC) {
3534 CmdArgs.push_back("-emit-llvm-bc");
3535 } else if (JA.getType() == types::TY_PP_Asm) {
3536 CmdArgs.push_back("-S");
3537 } else if (JA.getType() == types::TY_AST) {
3538 CmdArgs.push_back("-emit-pch");
3539 } else if (JA.getType() == types::TY_ModuleFile) {
3540 CmdArgs.push_back("-module-file-info");
3541 } else if (JA.getType() == types::TY_RewrittenObjC) {
3542 CmdArgs.push_back("-rewrite-objc");
3543 rewriteKind = RK_NonFragile;
3544 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3545 CmdArgs.push_back("-rewrite-objc");
3546 rewriteKind = RK_Fragile;
3548 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3551 // Preserve use-list order by default when emitting bitcode, so that
3552 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3553 // same result as running passes here. For LTO, we don't need to preserve
3554 // the use-list order, since serialization to bitcode is part of the flow.
3555 if (JA.getType() == types::TY_LLVM_BC)
3556 CmdArgs.push_back("-emit-llvm-uselists");
3559 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3562 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3563 if (!types::isLLVMIR(Input.getType()))
3564 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3566 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3569 // We normally speed up the clang process a bit by skipping destructors at
3570 // exit, but when we're generating diagnostics we can rely on some of the
3572 if (!C.isForDiagnostics())
3573 CmdArgs.push_back("-disable-free");
3575 // Disable the verification pass in -asserts builds.
3577 CmdArgs.push_back("-disable-llvm-verifier");
3580 // Set the main file name, so that debug info works even with
3582 CmdArgs.push_back("-main-file-name");
3583 CmdArgs.push_back(getBaseInputName(Args, Input));
3585 // Some flags which affect the language (via preprocessor
3587 if (Args.hasArg(options::OPT_static))
3588 CmdArgs.push_back("-static-define");
3590 if (isa<AnalyzeJobAction>(JA)) {
3591 // Enable region store model by default.
3592 CmdArgs.push_back("-analyzer-store=region");
3594 // Treat blocks as analysis entry points.
3595 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
3597 CmdArgs.push_back("-analyzer-eagerly-assume");
3599 // Add default argument set.
3600 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3601 CmdArgs.push_back("-analyzer-checker=core");
3604 CmdArgs.push_back("-analyzer-checker=unix");
3606 // Disable some unix checkers for PS4.
3608 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
3609 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
3612 if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple)
3613 CmdArgs.push_back("-analyzer-checker=osx");
3615 CmdArgs.push_back("-analyzer-checker=deadcode");
3617 if (types::isCXX(Input.getType()))
3618 CmdArgs.push_back("-analyzer-checker=cplusplus");
3622 "-analyzer-checker=security.insecureAPI.UncheckedReturn");
3623 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3624 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3625 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3626 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3627 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3630 // Default nullability checks.
3631 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
3633 "-analyzer-checker=nullability.NullReturnedFromNonnull");
3636 // Set the output format. The default is plist, for (lame) historical
3638 CmdArgs.push_back("-analyzer-output");
3639 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3640 CmdArgs.push_back(A->getValue());
3642 CmdArgs.push_back("plist");
3644 // Disable the presentation of standard compiler warnings when
3645 // using --analyze. We only want to show static analyzer diagnostics
3646 // or frontend errors.
3647 CmdArgs.push_back("-w");
3649 // Add -Xanalyzer arguments when running as analyzer.
3650 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3653 CheckCodeGenerationOptions(D, Args);
3655 llvm::Reloc::Model RelocationModel;
3658 std::tie(RelocationModel, PICLevel, IsPIE) =
3659 ParsePICArgs(getToolChain(), Triple, Args);
3661 const char *RMName = RelocationModelName(RelocationModel);
3663 CmdArgs.push_back("-mrelocation-model");
3664 CmdArgs.push_back(RMName);
3667 CmdArgs.push_back("-pic-level");
3668 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3670 CmdArgs.push_back("-pie-level");
3671 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3675 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3676 CmdArgs.push_back("-meabi");
3677 CmdArgs.push_back(A->getValue());
3680 CmdArgs.push_back("-mthread-model");
3681 if (Arg *A = Args.getLastArg(options::OPT_mthread_model))
3682 CmdArgs.push_back(A->getValue());
3684 CmdArgs.push_back(Args.MakeArgString(getToolChain().getThreadModel()));
3686 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3688 if (!Args.hasFlag(options::OPT_fmerge_all_constants,
3689 options::OPT_fno_merge_all_constants))
3690 CmdArgs.push_back("-fno-merge-all-constants");
3692 // LLVM Code Generator Options.
3694 if (Args.hasArg(options::OPT_frewrite_map_file) ||
3695 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3696 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3697 options::OPT_frewrite_map_file_EQ)) {
3698 CmdArgs.push_back("-frewrite-map-file");
3699 CmdArgs.push_back(A->getValue());
3704 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3705 StringRef v = A->getValue();
3706 CmdArgs.push_back("-mllvm");
3707 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3711 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3712 CmdArgs.push_back("-mregparm");
3713 CmdArgs.push_back(A->getValue());
3716 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3717 options::OPT_freg_struct_return)) {
3718 if (getToolChain().getArch() != llvm::Triple::x86) {
3719 D.Diag(diag::err_drv_unsupported_opt_for_target)
3720 << A->getSpelling() << getToolChain().getTriple().str();
3721 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3722 CmdArgs.push_back("-fpcc-struct-return");
3724 assert(A->getOption().matches(options::OPT_freg_struct_return));
3725 CmdArgs.push_back("-freg-struct-return");
3729 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3730 CmdArgs.push_back("-mrtd");
3732 if (shouldUseFramePointer(Args, getToolChain().getTriple()))
3733 CmdArgs.push_back("-mdisable-fp-elim");
3734 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3735 options::OPT_fno_zero_initialized_in_bss))
3736 CmdArgs.push_back("-mno-zero-initialized-in-bss");
3738 bool OFastEnabled = isOptimizationLevelFast(Args);
3739 // If -Ofast is the optimization level, then -fstrict-aliasing should be
3740 // enabled. This alias option is being used to simplify the hasFlag logic.
3741 OptSpecifier StrictAliasingAliasOption =
3742 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3743 // We turn strict aliasing off by default if we're in CL mode, since MSVC
3744 // doesn't do any TBAA.
3745 bool TBAAOnByDefault = !getToolChain().getDriver().IsCLMode();
3746 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3747 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3748 CmdArgs.push_back("-relaxed-aliasing");
3749 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3750 options::OPT_fno_struct_path_tbaa))
3751 CmdArgs.push_back("-no-struct-path-tbaa");
3752 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3754 CmdArgs.push_back("-fstrict-enums");
3755 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
3756 options::OPT_fno_strict_vtable_pointers,
3758 CmdArgs.push_back("-fstrict-vtable-pointers");
3759 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3760 options::OPT_fno_optimize_sibling_calls))
3761 CmdArgs.push_back("-mdisable-tail-calls");
3763 // Handle segmented stacks.
3764 if (Args.hasArg(options::OPT_fsplit_stack))
3765 CmdArgs.push_back("-split-stacks");
3767 // If -Ofast is the optimization level, then -ffast-math should be enabled.
3768 // This alias option is being used to simplify the getLastArg logic.
3769 OptSpecifier FastMathAliasOption =
3770 OFastEnabled ? options::OPT_Ofast : options::OPT_ffast_math;
3772 // Handle various floating point optimization flags, mapping them to the
3773 // appropriate LLVM code generation flags. The pattern for all of these is to
3774 // default off the codegen optimizations, and if any flag enables them and no
3775 // flag disables them after the flag enabling them, enable the codegen
3776 // optimization. This is complicated by several "umbrella" flags.
3777 if (Arg *A = Args.getLastArg(
3778 options::OPT_ffast_math, FastMathAliasOption,
3779 options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
3780 options::OPT_fno_finite_math_only, options::OPT_fhonor_infinities,
3781 options::OPT_fno_honor_infinities))
3782 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3783 A->getOption().getID() != options::OPT_fno_finite_math_only &&
3784 A->getOption().getID() != options::OPT_fhonor_infinities)
3785 CmdArgs.push_back("-menable-no-infs");
3786 if (Arg *A = Args.getLastArg(
3787 options::OPT_ffast_math, FastMathAliasOption,
3788 options::OPT_fno_fast_math, options::OPT_ffinite_math_only,
3789 options::OPT_fno_finite_math_only, options::OPT_fhonor_nans,
3790 options::OPT_fno_honor_nans))
3791 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3792 A->getOption().getID() != options::OPT_fno_finite_math_only &&
3793 A->getOption().getID() != options::OPT_fhonor_nans)
3794 CmdArgs.push_back("-menable-no-nans");
3796 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
3797 bool MathErrno = getToolChain().IsMathErrnoDefault();
3799 Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3800 options::OPT_fno_fast_math, options::OPT_fmath_errno,
3801 options::OPT_fno_math_errno)) {
3802 // Turning on -ffast_math (with either flag) removes the need for MathErrno.
3803 // However, turning *off* -ffast_math merely restores the toolchain default
3804 // (which may be false).
3805 if (A->getOption().getID() == options::OPT_fno_math_errno ||
3806 A->getOption().getID() == options::OPT_ffast_math ||
3807 A->getOption().getID() == options::OPT_Ofast)
3809 else if (A->getOption().getID() == options::OPT_fmath_errno)
3813 CmdArgs.push_back("-fmath-errno");
3815 // There are several flags which require disabling very specific
3816 // optimizations. Any of these being disabled forces us to turn off the
3817 // entire set of LLVM optimizations, so collect them through all the flag
3819 bool AssociativeMath = false;
3820 if (Arg *A = Args.getLastArg(
3821 options::OPT_ffast_math, FastMathAliasOption,
3822 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3823 options::OPT_fno_unsafe_math_optimizations,
3824 options::OPT_fassociative_math, options::OPT_fno_associative_math))
3825 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3826 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3827 A->getOption().getID() != options::OPT_fno_associative_math)
3828 AssociativeMath = true;
3829 bool ReciprocalMath = false;
3830 if (Arg *A = Args.getLastArg(
3831 options::OPT_ffast_math, FastMathAliasOption,
3832 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3833 options::OPT_fno_unsafe_math_optimizations,
3834 options::OPT_freciprocal_math, options::OPT_fno_reciprocal_math))
3835 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3836 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3837 A->getOption().getID() != options::OPT_fno_reciprocal_math)
3838 ReciprocalMath = true;
3839 bool SignedZeros = true;
3840 if (Arg *A = Args.getLastArg(
3841 options::OPT_ffast_math, FastMathAliasOption,
3842 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3843 options::OPT_fno_unsafe_math_optimizations,
3844 options::OPT_fsigned_zeros, options::OPT_fno_signed_zeros))
3845 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3846 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3847 A->getOption().getID() != options::OPT_fsigned_zeros)
3848 SignedZeros = false;
3849 bool TrappingMath = true;
3850 if (Arg *A = Args.getLastArg(
3851 options::OPT_ffast_math, FastMathAliasOption,
3852 options::OPT_fno_fast_math, options::OPT_funsafe_math_optimizations,
3853 options::OPT_fno_unsafe_math_optimizations,
3854 options::OPT_ftrapping_math, options::OPT_fno_trapping_math))
3855 if (A->getOption().getID() != options::OPT_fno_fast_math &&
3856 A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations &&
3857 A->getOption().getID() != options::OPT_ftrapping_math)
3858 TrappingMath = false;
3859 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
3861 CmdArgs.push_back("-menable-unsafe-fp-math");
3864 CmdArgs.push_back("-fno-signed-zeros");
3867 CmdArgs.push_back("-freciprocal-math");
3869 // Validate and pass through -fp-contract option.
3870 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3871 options::OPT_fno_fast_math,
3872 options::OPT_ffp_contract)) {
3873 if (A->getOption().getID() == options::OPT_ffp_contract) {
3874 StringRef Val = A->getValue();
3875 if (Val == "fast" || Val == "on" || Val == "off") {
3876 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val));
3878 D.Diag(diag::err_drv_unsupported_option_argument)
3879 << A->getOption().getName() << Val;
3881 } else if (A->getOption().matches(options::OPT_ffast_math) ||
3882 (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
3883 // If fast-math is set then set the fp-contract mode to fast.
3884 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
3888 ParseMRecip(getToolChain().getDriver(), Args, CmdArgs);
3890 // We separately look for the '-ffast-math' and '-ffinite-math-only' flags,
3891 // and if we find them, tell the frontend to provide the appropriate
3892 // preprocessor macros. This is distinct from enabling any optimizations as
3893 // these options induce language changes which must survive serialization
3894 // and deserialization, etc.
3895 if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
3896 options::OPT_fno_fast_math))
3897 if (!A->getOption().matches(options::OPT_fno_fast_math))
3898 CmdArgs.push_back("-ffast-math");
3899 if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only,
3900 options::OPT_fno_fast_math))
3901 if (A->getOption().matches(options::OPT_ffinite_math_only))
3902 CmdArgs.push_back("-ffinite-math-only");
3904 // Decide whether to use verbose asm. Verbose assembly is the default on
3905 // toolchains which have the integrated assembler on by default.
3906 bool IsIntegratedAssemblerDefault =
3907 getToolChain().IsIntegratedAssemblerDefault();
3908 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
3909 IsIntegratedAssemblerDefault) ||
3910 Args.hasArg(options::OPT_dA))
3911 CmdArgs.push_back("-masm-verbose");
3913 if (!Args.hasFlag(options::OPT_fintegrated_as, options::OPT_fno_integrated_as,
3914 IsIntegratedAssemblerDefault))
3915 CmdArgs.push_back("-no-integrated-as");
3917 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
3918 CmdArgs.push_back("-mdebug-pass");
3919 CmdArgs.push_back("Structure");
3921 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
3922 CmdArgs.push_back("-mdebug-pass");
3923 CmdArgs.push_back("Arguments");
3926 // Enable -mconstructor-aliases except on darwin, where we have to
3927 // work around a linker bug; see <rdar://problem/7651567>.
3928 if (!getToolChain().getTriple().isOSDarwin())
3929 CmdArgs.push_back("-mconstructor-aliases");
3931 // Darwin's kernel doesn't support guard variables; just die if we
3933 if (KernelOrKext && getToolChain().getTriple().isOSDarwin())
3934 CmdArgs.push_back("-fforbid-guard-variables");
3936 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
3938 CmdArgs.push_back("-mms-bitfields");
3941 // This is a coarse approximation of what llvm-gcc actually does, both
3942 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
3943 // complicated ways.
3944 bool AsynchronousUnwindTables =
3945 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
3946 options::OPT_fno_asynchronous_unwind_tables,
3947 (getToolChain().IsUnwindTablesDefault() ||
3948 getToolChain().getSanitizerArgs().needsUnwindTables()) &&
3950 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
3951 AsynchronousUnwindTables))
3952 CmdArgs.push_back("-munwind-tables");
3954 getToolChain().addClangTargetOptions(Args, CmdArgs);
3956 if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3957 CmdArgs.push_back("-mlimit-float-precision");
3958 CmdArgs.push_back(A->getValue());
3961 // FIXME: Handle -mtune=.
3962 (void)Args.hasArg(options::OPT_mtune_EQ);
3964 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
3965 CmdArgs.push_back("-mcode-model");
3966 CmdArgs.push_back(A->getValue());
3969 // Add the target cpu
3970 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
3972 CmdArgs.push_back("-target-cpu");
3973 CmdArgs.push_back(Args.MakeArgString(CPU));
3976 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3977 CmdArgs.push_back("-mfpmath");
3978 CmdArgs.push_back(A->getValue());
3981 // Add the target features
3982 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, false);
3984 // Add target specific flags.
3985 switch (getToolChain().getArch()) {
3989 case llvm::Triple::arm:
3990 case llvm::Triple::armeb:
3991 case llvm::Triple::thumb:
3992 case llvm::Triple::thumbeb:
3993 // Use the effective triple, which takes into account the deployment target.
3994 AddARMTargetArgs(Triple, Args, CmdArgs, KernelOrKext);
3997 case llvm::Triple::aarch64:
3998 case llvm::Triple::aarch64_be:
3999 AddAArch64TargetArgs(Args, CmdArgs);
4002 case llvm::Triple::mips:
4003 case llvm::Triple::mipsel:
4004 case llvm::Triple::mips64:
4005 case llvm::Triple::mips64el:
4006 AddMIPSTargetArgs(Args, CmdArgs);
4009 case llvm::Triple::ppc:
4010 case llvm::Triple::ppc64:
4011 case llvm::Triple::ppc64le:
4012 AddPPCTargetArgs(Args, CmdArgs);
4015 case llvm::Triple::sparc:
4016 case llvm::Triple::sparcel:
4017 case llvm::Triple::sparcv9:
4018 AddSparcTargetArgs(Args, CmdArgs);
4021 case llvm::Triple::x86:
4022 case llvm::Triple::x86_64:
4023 AddX86TargetArgs(Args, CmdArgs);
4026 case llvm::Triple::hexagon:
4027 AddHexagonTargetArgs(Args, CmdArgs);
4030 case llvm::Triple::wasm32:
4031 case llvm::Triple::wasm64:
4032 AddWebAssemblyTargetArgs(Args, CmdArgs);
4036 // The 'g' groups options involve a somewhat intricate sequence of decisions
4037 // about what to pass from the driver to the frontend, but by the time they
4038 // reach cc1 they've been factored into three well-defined orthogonal choices:
4039 // * what level of debug info to generate
4040 // * what dwarf version to write
4041 // * what debugger tuning to use
4042 // This avoids having to monkey around further in cc1 other than to disable
4043 // codeview if not running in a Windows environment. Perhaps even that
4044 // decision should be made in the driver as well though.
4045 unsigned DwarfVersion = 0;
4046 llvm::DebuggerKind DebuggerTuning = getToolChain().getDefaultDebuggerTuning();
4047 // These two are potentially updated by AddClangCLArgs.
4048 enum CodeGenOptions::DebugInfoKind DebugInfoKind =
4049 CodeGenOptions::NoDebugInfo;
4050 bool EmitCodeView = false;
4052 // Add clang-cl arguments.
4053 if (getToolChain().getDriver().IsCLMode())
4054 AddClangCLArgs(Args, CmdArgs, &DebugInfoKind, &EmitCodeView);
4056 // Pass the linker version in use.
4057 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4058 CmdArgs.push_back("-target-linker-version");
4059 CmdArgs.push_back(A->getValue());
4062 if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple()))
4063 CmdArgs.push_back("-momit-leaf-frame-pointer");
4065 // Explicitly error on some things we know we don't support and can't just
4067 types::ID InputType = Input.getType();
4068 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
4070 if (types::isCXX(InputType) && getToolChain().getTriple().isOSDarwin() &&
4071 getToolChain().getArch() == llvm::Triple::x86) {
4072 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
4073 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
4074 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
4075 << Unsupported->getOption().getName();
4079 Args.AddAllArgs(CmdArgs, options::OPT_v);
4080 Args.AddLastArg(CmdArgs, options::OPT_H);
4081 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
4082 CmdArgs.push_back("-header-include-file");
4083 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
4086 Args.AddLastArg(CmdArgs, options::OPT_P);
4087 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
4089 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
4090 CmdArgs.push_back("-diagnostic-log-file");
4091 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
4095 Args.ClaimAllArgs(options::OPT_g_Group);
4096 Arg *SplitDwarfArg = Args.getLastArg(options::OPT_gsplit_dwarf);
4097 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4098 // If the last option explicitly specified a debug-info level, use it.
4099 if (A->getOption().matches(options::OPT_gN_Group)) {
4100 DebugInfoKind = DebugLevelToInfoKind(*A);
4101 // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
4102 // But -gsplit-dwarf is not a g_group option, hence we have to check the
4103 // order explicitly. (If -gsplit-dwarf wins, we fix DebugInfoKind later.)
4104 if (SplitDwarfArg && DebugInfoKind < CodeGenOptions::LimitedDebugInfo &&
4105 A->getIndex() > SplitDwarfArg->getIndex())
4106 SplitDwarfArg = nullptr;
4108 // For any other 'g' option, use Limited.
4109 DebugInfoKind = CodeGenOptions::LimitedDebugInfo;
4112 // If a debugger tuning argument appeared, remember it.
4113 if (Arg *A = Args.getLastArg(options::OPT_gTune_Group,
4114 options::OPT_ggdbN_Group)) {
4115 if (A->getOption().matches(options::OPT_glldb))
4116 DebuggerTuning = llvm::DebuggerKind::LLDB;
4117 else if (A->getOption().matches(options::OPT_gsce))
4118 DebuggerTuning = llvm::DebuggerKind::SCE;
4120 DebuggerTuning = llvm::DebuggerKind::GDB;
4123 // If a -gdwarf argument appeared, remember it.
4124 if (Arg *A = Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
4125 options::OPT_gdwarf_4, options::OPT_gdwarf_5))
4126 DwarfVersion = DwarfVersionNum(A->getSpelling());
4128 // Forward -gcodeview.
4129 // 'EmitCodeView might have been set by CL-compatibility argument parsing.
4130 if (Args.hasArg(options::OPT_gcodeview) || EmitCodeView) {
4131 // DwarfVersion remains at 0 if no explicit choice was made.
4132 CmdArgs.push_back("-gcodeview");
4133 } else if (DwarfVersion == 0 &&
4134 DebugInfoKind != CodeGenOptions::NoDebugInfo) {
4135 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
4138 // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now.
4139 Args.ClaimAllArgs(options::OPT_g_flags_Group);
4141 // PS4 defaults to no column info
4142 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4143 /*Default=*/ !IsPS4CPU))
4144 CmdArgs.push_back("-dwarf-column-info");
4146 // FIXME: Move backend command line options to the module.
4147 if (Args.hasArg(options::OPT_gmodules)) {
4148 DebugInfoKind = CodeGenOptions::LimitedDebugInfo;
4149 CmdArgs.push_back("-dwarf-ext-refs");
4150 CmdArgs.push_back("-fmodule-format=obj");
4153 // -gsplit-dwarf should turn on -g and enable the backend dwarf
4154 // splitting and extraction.
4155 // FIXME: Currently only works on Linux.
4156 if (getToolChain().getTriple().isOSLinux() && SplitDwarfArg) {
4157 DebugInfoKind = CodeGenOptions::LimitedDebugInfo;
4158 CmdArgs.push_back("-backend-option");
4159 CmdArgs.push_back("-split-dwarf=Enable");
4162 // After we've dealt with all combinations of things that could
4163 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4164 // figure out if we need to "upgrade" it to standalone debug info.
4165 // We parse these two '-f' options whether or not they will be used,
4166 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4167 bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
4168 options::OPT_fno_standalone_debug,
4169 getToolChain().GetDefaultStandaloneDebug());
4170 if (DebugInfoKind == CodeGenOptions::LimitedDebugInfo && NeedFullDebug)
4171 DebugInfoKind = CodeGenOptions::FullDebugInfo;
4172 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
4175 // -ggnu-pubnames turns on gnu style pubnames in the backend.
4176 if (Args.hasArg(options::OPT_ggnu_pubnames)) {
4177 CmdArgs.push_back("-backend-option");
4178 CmdArgs.push_back("-generate-gnu-dwarf-pub-sections");
4181 // -gdwarf-aranges turns on the emission of the aranges section in the
4183 // Always enabled on the PS4.
4184 if (Args.hasArg(options::OPT_gdwarf_aranges) || IsPS4CPU) {
4185 CmdArgs.push_back("-backend-option");
4186 CmdArgs.push_back("-generate-arange-section");
4189 if (Args.hasFlag(options::OPT_fdebug_types_section,
4190 options::OPT_fno_debug_types_section, false)) {
4191 CmdArgs.push_back("-backend-option");
4192 CmdArgs.push_back("-generate-type-units");
4195 // CloudABI and WebAssembly use -ffunction-sections and -fdata-sections by
4197 bool UseSeparateSections = Triple.getOS() == llvm::Triple::CloudABI ||
4198 Triple.getArch() == llvm::Triple::wasm32 ||
4199 Triple.getArch() == llvm::Triple::wasm64;
4201 if (Args.hasFlag(options::OPT_ffunction_sections,
4202 options::OPT_fno_function_sections, UseSeparateSections)) {
4203 CmdArgs.push_back("-ffunction-sections");
4206 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
4207 UseSeparateSections)) {
4208 CmdArgs.push_back("-fdata-sections");
4211 if (!Args.hasFlag(options::OPT_funique_section_names,
4212 options::OPT_fno_unique_section_names, true))
4213 CmdArgs.push_back("-fno-unique-section-names");
4215 Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions);
4217 addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
4219 // Add runtime flag for PS4 when PGO or Coverage are enabled.
4220 if (getToolChain().getTriple().isPS4CPU())
4221 addPS4ProfileRTArgs(getToolChain(), Args, CmdArgs);
4223 // Pass options for controlling the default header search paths.
4224 if (Args.hasArg(options::OPT_nostdinc)) {
4225 CmdArgs.push_back("-nostdsysteminc");
4226 CmdArgs.push_back("-nobuiltininc");
4228 if (Args.hasArg(options::OPT_nostdlibinc))
4229 CmdArgs.push_back("-nostdsysteminc");
4230 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
4231 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
4234 // Pass the path to compiler resource files.
4235 CmdArgs.push_back("-resource-dir");
4236 CmdArgs.push_back(D.ResourceDir.c_str());
4238 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
4240 bool ARCMTEnabled = false;
4241 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
4242 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
4243 options::OPT_ccc_arcmt_modify,
4244 options::OPT_ccc_arcmt_migrate)) {
4245 ARCMTEnabled = true;
4246 switch (A->getOption().getID()) {
4248 llvm_unreachable("missed a case");
4249 case options::OPT_ccc_arcmt_check:
4250 CmdArgs.push_back("-arcmt-check");
4252 case options::OPT_ccc_arcmt_modify:
4253 CmdArgs.push_back("-arcmt-modify");
4255 case options::OPT_ccc_arcmt_migrate:
4256 CmdArgs.push_back("-arcmt-migrate");
4257 CmdArgs.push_back("-mt-migrate-directory");
4258 CmdArgs.push_back(A->getValue());
4260 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
4261 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
4266 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
4267 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
4268 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
4271 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
4273 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
4274 << "-ccc-arcmt-migrate";
4276 CmdArgs.push_back("-mt-migrate-directory");
4277 CmdArgs.push_back(A->getValue());
4279 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
4280 options::OPT_objcmt_migrate_subscripting,
4281 options::OPT_objcmt_migrate_property)) {
4282 // None specified, means enable them all.
4283 CmdArgs.push_back("-objcmt-migrate-literals");
4284 CmdArgs.push_back("-objcmt-migrate-subscripting");
4285 CmdArgs.push_back("-objcmt-migrate-property");
4287 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
4288 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
4289 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
4292 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
4293 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
4294 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
4295 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
4296 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
4297 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
4298 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
4299 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
4300 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
4301 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
4302 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
4303 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
4304 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
4305 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
4306 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
4307 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
4310 // Add preprocessing options like -I, -D, etc. if we are using the
4313 // FIXME: Support -fpreprocessed
4314 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
4315 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs,
4318 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
4319 // that "The compiler can only warn and ignore the option if not recognized".
4320 // When building with ccache, it will pass -D options to clang even on
4321 // preprocessed inputs and configure concludes that -fPIC is not supported.
4322 Args.ClaimAllArgs(options::OPT_D);
4324 // Manually translate -O4 to -O3; let clang reject others.
4325 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4326 if (A->getOption().matches(options::OPT_O4)) {
4327 CmdArgs.push_back("-O3");
4328 D.Diag(diag::warn_O4_is_O3);
4330 A->render(Args, CmdArgs);
4334 // Warn about ignored options to clang.
4336 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
4337 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
4341 claimNoWarnArgs(Args);
4343 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
4344 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
4345 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
4346 CmdArgs.push_back("-pedantic");
4347 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
4348 Args.AddLastArg(CmdArgs, options::OPT_w);
4350 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
4351 // (-ansi is equivalent to -std=c89 or -std=c++98).
4353 // If a std is supplied, only add -trigraphs if it follows the
4355 bool ImplyVCPPCXXVer = false;
4356 if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
4357 if (Std->getOption().matches(options::OPT_ansi))
4358 if (types::isCXX(InputType))
4359 CmdArgs.push_back("-std=c++98");
4361 CmdArgs.push_back("-std=c89");
4363 Std->render(Args, CmdArgs);
4365 // If -f(no-)trigraphs appears after the language standard flag, honor it.
4366 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
4367 options::OPT_ftrigraphs,
4368 options::OPT_fno_trigraphs))
4370 A->render(Args, CmdArgs);
4372 // Honor -std-default.
4374 // FIXME: Clang doesn't correctly handle -std= when the input language
4375 // doesn't match. For the time being just ignore this for C++ inputs;
4376 // eventually we want to do all the standard defaulting here instead of
4377 // splitting it between the driver and clang -cc1.
4378 if (!types::isCXX(InputType))
4379 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
4381 else if (IsWindowsMSVC)
4382 ImplyVCPPCXXVer = true;
4384 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
4385 options::OPT_fno_trigraphs);
4388 // GCC's behavior for -Wwrite-strings is a bit strange:
4389 // * In C, this "warning flag" changes the types of string literals from
4390 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
4391 // for the discarded qualifier.
4392 // * In C++, this is just a normal warning flag.
4394 // Implementing this warning correctly in C is hard, so we follow GCC's
4395 // behavior for now. FIXME: Directly diagnose uses of a string literal as
4396 // a non-const char* in C, rather than using this crude hack.
4397 if (!types::isCXX(InputType)) {
4398 // FIXME: This should behave just like a warning flag, and thus should also
4399 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
4401 Args.getLastArg(options::OPT_Wwrite_strings,
4402 options::OPT_Wno_write_strings, options::OPT_w);
4404 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
4405 CmdArgs.push_back("-fconst-strings");
4408 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
4409 // during C++ compilation, which it is by default. GCC keeps this define even
4410 // in the presence of '-w', match this behavior bug-for-bug.
4411 if (types::isCXX(InputType) &&
4412 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
4414 CmdArgs.push_back("-fdeprecated-macro");
4417 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
4418 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
4419 if (Asm->getOption().matches(options::OPT_fasm))
4420 CmdArgs.push_back("-fgnu-keywords");
4422 CmdArgs.push_back("-fno-gnu-keywords");
4425 if (ShouldDisableDwarfDirectory(Args, getToolChain()))
4426 CmdArgs.push_back("-fno-dwarf-directory-asm");
4428 if (ShouldDisableAutolink(Args, getToolChain()))
4429 CmdArgs.push_back("-fno-autolink");
4431 // Add in -fdebug-compilation-dir if necessary.
4432 addDebugCompDirArg(Args, CmdArgs);
4434 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
4435 StringRef Map = A->getValue();
4436 if (Map.find('=') == StringRef::npos)
4437 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
4439 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
4443 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
4444 options::OPT_ftemplate_depth_EQ)) {
4445 CmdArgs.push_back("-ftemplate-depth");
4446 CmdArgs.push_back(A->getValue());
4449 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
4450 CmdArgs.push_back("-foperator-arrow-depth");
4451 CmdArgs.push_back(A->getValue());
4454 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
4455 CmdArgs.push_back("-fconstexpr-depth");
4456 CmdArgs.push_back(A->getValue());
4459 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
4460 CmdArgs.push_back("-fconstexpr-steps");
4461 CmdArgs.push_back(A->getValue());
4464 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
4465 CmdArgs.push_back("-fbracket-depth");
4466 CmdArgs.push_back(A->getValue());
4469 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
4470 options::OPT_Wlarge_by_value_copy_def)) {
4471 if (A->getNumValues()) {
4472 StringRef bytes = A->getValue();
4473 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
4475 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
4478 if (Args.hasArg(options::OPT_relocatable_pch))
4479 CmdArgs.push_back("-relocatable-pch");
4481 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
4482 CmdArgs.push_back("-fconstant-string-class");
4483 CmdArgs.push_back(A->getValue());
4486 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
4487 CmdArgs.push_back("-ftabstop");
4488 CmdArgs.push_back(A->getValue());
4491 CmdArgs.push_back("-ferror-limit");
4492 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
4493 CmdArgs.push_back(A->getValue());
4495 CmdArgs.push_back("19");
4497 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
4498 CmdArgs.push_back("-fmacro-backtrace-limit");
4499 CmdArgs.push_back(A->getValue());
4502 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
4503 CmdArgs.push_back("-ftemplate-backtrace-limit");
4504 CmdArgs.push_back(A->getValue());
4507 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
4508 CmdArgs.push_back("-fconstexpr-backtrace-limit");
4509 CmdArgs.push_back(A->getValue());
4512 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
4513 CmdArgs.push_back("-fspell-checking-limit");
4514 CmdArgs.push_back(A->getValue());
4517 // Pass -fmessage-length=.
4518 CmdArgs.push_back("-fmessage-length");
4519 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
4520 CmdArgs.push_back(A->getValue());
4522 // If -fmessage-length=N was not specified, determine whether this is a
4523 // terminal and, if so, implicitly define -fmessage-length appropriately.
4524 unsigned N = llvm::sys::Process::StandardErrColumns();
4525 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
4528 // -fvisibility= and -fvisibility-ms-compat are of a piece.
4529 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
4530 options::OPT_fvisibility_ms_compat)) {
4531 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
4532 CmdArgs.push_back("-fvisibility");
4533 CmdArgs.push_back(A->getValue());
4535 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
4536 CmdArgs.push_back("-fvisibility");
4537 CmdArgs.push_back("hidden");
4538 CmdArgs.push_back("-ftype-visibility");
4539 CmdArgs.push_back("default");
4543 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
4545 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
4547 // -fhosted is default.
4548 if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
4550 CmdArgs.push_back("-ffreestanding");
4552 // Forward -f (flag) options which we can pass directly.
4553 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
4554 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
4555 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
4556 // Emulated TLS is enabled by default on Android, and can be enabled manually
4557 // with -femulated-tls.
4558 bool EmulatedTLSDefault = Triple.isAndroid();
4559 if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
4560 EmulatedTLSDefault))
4561 CmdArgs.push_back("-femulated-tls");
4562 // AltiVec-like language extensions aren't relevant for assembling.
4563 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm) {
4564 Args.AddLastArg(CmdArgs, options::OPT_faltivec);
4565 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
4567 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
4568 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
4570 // Forward flags for OpenMP
4571 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
4572 options::OPT_fno_openmp, false))
4573 switch (getOpenMPRuntime(getToolChain(), Args)) {
4576 // Clang can generate useful OpenMP code for these two runtime libraries.
4577 CmdArgs.push_back("-fopenmp");
4579 // If no option regarding the use of TLS in OpenMP codegeneration is
4580 // given, decide a default based on the target. Otherwise rely on the
4581 // options and pass the right information to the frontend.
4582 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
4583 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
4584 CmdArgs.push_back("-fnoopenmp-use-tls");
4587 // By default, if Clang doesn't know how to generate useful OpenMP code
4588 // for a specific runtime library, we just don't pass the '-fopenmp' flag
4589 // down to the actual compilation.
4590 // FIXME: It would be better to have a mode which *only* omits IR
4591 // generation based on the OpenMP support so that we get consistent
4592 // semantic analysis, etc.
4596 const SanitizerArgs &Sanitize = getToolChain().getSanitizerArgs();
4597 Sanitize.addArgs(getToolChain(), Args, CmdArgs, InputType);
4599 // Report an error for -faltivec on anything other than PowerPC.
4600 if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) {
4601 const llvm::Triple::ArchType Arch = getToolChain().getArch();
4602 if (!(Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
4603 Arch == llvm::Triple::ppc64le))
4604 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
4605 << "ppc/ppc64/ppc64le";
4608 // -fzvector is incompatible with -faltivec.
4609 if (Arg *A = Args.getLastArg(options::OPT_fzvector))
4610 if (Args.hasArg(options::OPT_faltivec))
4611 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
4614 if (getToolChain().SupportsProfiling())
4615 Args.AddLastArg(CmdArgs, options::OPT_pg);
4617 // -flax-vector-conversions is default.
4618 if (!Args.hasFlag(options::OPT_flax_vector_conversions,
4619 options::OPT_fno_lax_vector_conversions))
4620 CmdArgs.push_back("-fno-lax-vector-conversions");
4622 if (Args.getLastArg(options::OPT_fapple_kext) ||
4623 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
4624 CmdArgs.push_back("-fapple-kext");
4626 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4627 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4628 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4629 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
4630 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
4632 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4633 CmdArgs.push_back("-ftrapv-handler");
4634 CmdArgs.push_back(A->getValue());
4637 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4639 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4640 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4641 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4642 if (A->getOption().matches(options::OPT_fwrapv))
4643 CmdArgs.push_back("-fwrapv");
4644 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4645 options::OPT_fno_strict_overflow)) {
4646 if (A->getOption().matches(options::OPT_fno_strict_overflow))
4647 CmdArgs.push_back("-fwrapv");
4650 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4651 options::OPT_fno_reroll_loops))
4652 if (A->getOption().matches(options::OPT_freroll_loops))
4653 CmdArgs.push_back("-freroll-loops");
4655 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4656 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4657 options::OPT_fno_unroll_loops);
4659 Args.AddLastArg(CmdArgs, options::OPT_pthread);
4661 // -stack-protector=0 is default.
4662 unsigned StackProtectorLevel = 0;
4663 if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
4664 Args.ClaimAllArgs(options::OPT_fno_stack_protector);
4665 Args.ClaimAllArgs(options::OPT_fstack_protector_all);
4666 Args.ClaimAllArgs(options::OPT_fstack_protector_strong);
4667 Args.ClaimAllArgs(options::OPT_fstack_protector);
4668 } else if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
4669 options::OPT_fstack_protector_all,
4670 options::OPT_fstack_protector_strong,
4671 options::OPT_fstack_protector)) {
4672 if (A->getOption().matches(options::OPT_fstack_protector)) {
4673 StackProtectorLevel = std::max<unsigned>(
4675 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext));
4676 } else if (A->getOption().matches(options::OPT_fstack_protector_strong))
4677 StackProtectorLevel = LangOptions::SSPStrong;
4678 else if (A->getOption().matches(options::OPT_fstack_protector_all))
4679 StackProtectorLevel = LangOptions::SSPReq;
4681 StackProtectorLevel =
4682 getToolChain().GetDefaultStackProtectorLevel(KernelOrKext);
4684 if (StackProtectorLevel) {
4685 CmdArgs.push_back("-stack-protector");
4686 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
4689 // --param ssp-buffer-size=
4690 for (const Arg *A : Args.filtered(options::OPT__param)) {
4691 StringRef Str(A->getValue());
4692 if (Str.startswith("ssp-buffer-size=")) {
4693 if (StackProtectorLevel) {
4694 CmdArgs.push_back("-stack-protector-buffer-size");
4695 // FIXME: Verify the argument is a valid integer.
4696 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
4702 // Translate -mstackrealign
4703 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4705 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4707 if (Args.hasArg(options::OPT_mstack_alignment)) {
4708 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4709 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4712 if (Args.hasArg(options::OPT_mstack_probe_size)) {
4713 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4716 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4718 CmdArgs.push_back("-mstack-probe-size=0");
4721 switch (getToolChain().getArch()) {
4722 case llvm::Triple::aarch64:
4723 case llvm::Triple::aarch64_be:
4724 case llvm::Triple::arm:
4725 case llvm::Triple::armeb:
4726 case llvm::Triple::thumb:
4727 case llvm::Triple::thumbeb:
4728 CmdArgs.push_back("-fallow-half-arguments-and-returns");
4735 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4736 options::OPT_mno_restrict_it)) {
4737 if (A->getOption().matches(options::OPT_mrestrict_it)) {
4738 CmdArgs.push_back("-backend-option");
4739 CmdArgs.push_back("-arm-restrict-it");
4741 CmdArgs.push_back("-backend-option");
4742 CmdArgs.push_back("-arm-no-restrict-it");
4744 } else if (Triple.isOSWindows() &&
4745 (Triple.getArch() == llvm::Triple::arm ||
4746 Triple.getArch() == llvm::Triple::thumb)) {
4747 // Windows on ARM expects restricted IT blocks
4748 CmdArgs.push_back("-backend-option");
4749 CmdArgs.push_back("-arm-restrict-it");
4752 // Forward -f options with positive and negative forms; we translate
4754 if (Arg *A = Args.getLastArg(options::OPT_fprofile_sample_use_EQ)) {
4755 StringRef fname = A->getValue();
4756 if (!llvm::sys::fs::exists(fname))
4757 D.Diag(diag::err_drv_no_such_file) << fname;
4759 A->render(Args, CmdArgs);
4762 // -fbuiltin is default unless -mkernel is used.
4764 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
4765 !Args.hasArg(options::OPT_mkernel));
4767 CmdArgs.push_back("-fno-builtin");
4769 // -ffreestanding implies -fno-builtin.
4770 if (Args.hasArg(options::OPT_ffreestanding))
4771 UseBuiltins = false;
4773 // Process the -fno-builtin-* options.
4774 for (const auto &Arg : Args) {
4775 const Option &O = Arg->getOption();
4776 if (!O.matches(options::OPT_fno_builtin_))
4780 // If -fno-builtin is specified, then there's no need to pass the option to
4785 StringRef FuncName = Arg->getValue();
4786 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
4789 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4790 options::OPT_fno_assume_sane_operator_new))
4791 CmdArgs.push_back("-fno-assume-sane-operator-new");
4793 // -fblocks=0 is default.
4794 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
4795 getToolChain().IsBlocksDefault()) ||
4796 (Args.hasArg(options::OPT_fgnu_runtime) &&
4797 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4798 !Args.hasArg(options::OPT_fno_blocks))) {
4799 CmdArgs.push_back("-fblocks");
4801 if (!Args.hasArg(options::OPT_fgnu_runtime) &&
4802 !getToolChain().hasBlocksRuntime())
4803 CmdArgs.push_back("-fblocks-runtime-optional");
4806 // -fmodules enables the use of precompiled modules (off by default).
4807 // Users can pass -fno-cxx-modules to turn off modules support for
4808 // C++/Objective-C++ programs.
4809 bool HaveModules = false;
4810 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
4811 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
4812 options::OPT_fno_cxx_modules, true);
4813 if (AllowedInCXX || !types::isCXX(InputType)) {
4814 CmdArgs.push_back("-fmodules");
4819 // -fmodule-maps enables implicit reading of module map files. By default,
4820 // this is enabled if we are using precompiled modules.
4821 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
4822 options::OPT_fno_implicit_module_maps, HaveModules)) {
4823 CmdArgs.push_back("-fimplicit-module-maps");
4826 // -fmodules-decluse checks that modules used are declared so (off by
4828 if (Args.hasFlag(options::OPT_fmodules_decluse,
4829 options::OPT_fno_modules_decluse, false)) {
4830 CmdArgs.push_back("-fmodules-decluse");
4833 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
4834 // all #included headers are part of modules.
4835 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
4836 options::OPT_fno_modules_strict_decluse, false)) {
4837 CmdArgs.push_back("-fmodules-strict-decluse");
4840 // -fno-implicit-modules turns off implicitly compiling modules on demand.
4841 if (!Args.hasFlag(options::OPT_fimplicit_modules,
4842 options::OPT_fno_implicit_modules)) {
4843 CmdArgs.push_back("-fno-implicit-modules");
4846 // -fmodule-name specifies the module that is currently being built (or
4847 // used for header checking by -fmodule-maps).
4848 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name);
4850 // -fmodule-map-file can be used to specify files containing module
4852 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
4854 // -fmodule-file can be used to specify files containing precompiled modules.
4856 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
4858 Args.ClaimAllArgs(options::OPT_fmodule_file);
4860 // -fmodule-cache-path specifies where our implicitly-built module files
4861 // should be written.
4862 SmallString<128> Path;
4863 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
4864 Path = A->getValue();
4866 if (C.isForDiagnostics()) {
4867 // When generating crash reports, we want to emit the modules along with
4868 // the reproduction sources, so we ignore any provided module path.
4869 Path = Output.getFilename();
4870 llvm::sys::path::replace_extension(Path, ".cache");
4871 llvm::sys::path::append(Path, "modules");
4872 } else if (Path.empty()) {
4873 // No module path was provided: use the default.
4874 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Path);
4875 llvm::sys::path::append(Path, "org.llvm.clang.");
4876 appendUserToPath(Path);
4877 llvm::sys::path::append(Path, "ModuleCache");
4879 const char Arg[] = "-fmodules-cache-path=";
4880 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
4881 CmdArgs.push_back(Args.MakeArgString(Path));
4884 // When building modules and generating crashdumps, we need to dump a module
4885 // dependency VFS alongside the output.
4886 if (HaveModules && C.isForDiagnostics()) {
4887 SmallString<128> VFSDir(Output.getFilename());
4888 llvm::sys::path::replace_extension(VFSDir, ".cache");
4889 // Add the cache directory as a temp so the crash diagnostics pick it up.
4890 C.addTempFile(Args.MakeArgString(VFSDir));
4892 llvm::sys::path::append(VFSDir, "vfs");
4893 CmdArgs.push_back("-module-dependency-dir");
4894 CmdArgs.push_back(Args.MakeArgString(VFSDir));
4898 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
4900 // Pass through all -fmodules-ignore-macro arguments.
4901 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
4902 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
4903 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
4905 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
4907 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
4908 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
4909 D.Diag(diag::err_drv_argument_not_allowed_with)
4910 << A->getAsString(Args) << "-fbuild-session-timestamp";
4912 llvm::sys::fs::file_status Status;
4913 if (llvm::sys::fs::status(A->getValue(), Status))
4914 D.Diag(diag::err_drv_no_such_file) << A->getValue();
4915 CmdArgs.push_back(Args.MakeArgString(
4916 "-fbuild-session-timestamp=" +
4917 Twine((uint64_t)Status.getLastModificationTime().toEpochTime())));
4920 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
4921 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
4922 options::OPT_fbuild_session_file))
4923 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
4925 Args.AddLastArg(CmdArgs,
4926 options::OPT_fmodules_validate_once_per_build_session);
4929 Args.AddLastArg(CmdArgs, options::OPT_fmodules_validate_system_headers);
4931 // -faccess-control is default.
4932 if (Args.hasFlag(options::OPT_fno_access_control,
4933 options::OPT_faccess_control, false))
4934 CmdArgs.push_back("-fno-access-control");
4936 // -felide-constructors is the default.
4937 if (Args.hasFlag(options::OPT_fno_elide_constructors,
4938 options::OPT_felide_constructors, false))
4939 CmdArgs.push_back("-fno-elide-constructors");
4941 ToolChain::RTTIMode RTTIMode = getToolChain().getRTTIMode();
4943 if (KernelOrKext || (types::isCXX(InputType) &&
4944 (RTTIMode == ToolChain::RM_DisabledExplicitly ||
4945 RTTIMode == ToolChain::RM_DisabledImplicitly)))
4946 CmdArgs.push_back("-fno-rtti");
4948 // -fshort-enums=0 is default for all architectures except Hexagon.
4949 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
4950 getToolChain().getArch() == llvm::Triple::hexagon))
4951 CmdArgs.push_back("-fshort-enums");
4953 // -fsigned-char is default.
4954 if (Arg *A = Args.getLastArg(
4955 options::OPT_fsigned_char, options::OPT_fno_signed_char,
4956 options::OPT_funsigned_char, options::OPT_fno_unsigned_char)) {
4957 if (A->getOption().matches(options::OPT_funsigned_char) ||
4958 A->getOption().matches(options::OPT_fno_signed_char)) {
4959 CmdArgs.push_back("-fno-signed-char");
4961 } else if (!isSignedCharDefault(getToolChain().getTriple())) {
4962 CmdArgs.push_back("-fno-signed-char");
4965 // -fuse-cxa-atexit is default.
4967 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
4968 !IsWindowsCygnus && !IsWindowsGNU &&
4969 getToolChain().getTriple().getOS() != llvm::Triple::Solaris &&
4970 getToolChain().getArch() != llvm::Triple::hexagon &&
4971 getToolChain().getArch() != llvm::Triple::xcore &&
4972 ((getToolChain().getTriple().getVendor() !=
4973 llvm::Triple::MipsTechnologies) ||
4974 getToolChain().getTriple().hasEnvironment())) ||
4976 CmdArgs.push_back("-fno-use-cxa-atexit");
4978 // -fms-extensions=0 is default.
4979 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4981 CmdArgs.push_back("-fms-extensions");
4983 // -fno-use-line-directives is default.
4984 if (Args.hasFlag(options::OPT_fuse_line_directives,
4985 options::OPT_fno_use_line_directives, false))
4986 CmdArgs.push_back("-fuse-line-directives");
4988 // -fms-compatibility=0 is default.
4989 if (Args.hasFlag(options::OPT_fms_compatibility,
4990 options::OPT_fno_ms_compatibility,
4992 Args.hasFlag(options::OPT_fms_extensions,
4993 options::OPT_fno_ms_extensions, true))))
4994 CmdArgs.push_back("-fms-compatibility");
4996 // -fms-compatibility-version=18.00 is default.
4997 VersionTuple MSVT = visualstudio::getMSVCVersion(
4998 &D, getToolChain().getTriple(), Args, IsWindowsMSVC);
5001 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
5003 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
5004 if (ImplyVCPPCXXVer) {
5005 if (IsMSVC2015Compatible)
5006 CmdArgs.push_back("-std=c++14");
5008 CmdArgs.push_back("-std=c++11");
5011 // -fno-borland-extensions is default.
5012 if (Args.hasFlag(options::OPT_fborland_extensions,
5013 options::OPT_fno_borland_extensions, false))
5014 CmdArgs.push_back("-fborland-extensions");
5016 // -fno-declspec is default, except for PS4.
5017 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
5018 getToolChain().getTriple().isPS4()))
5019 CmdArgs.push_back("-fdeclspec");
5020 else if (Args.hasArg(options::OPT_fno_declspec))
5021 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
5023 // -fthreadsafe-static is default, except for MSVC compatibility versions less
5025 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
5026 options::OPT_fno_threadsafe_statics,
5027 !IsWindowsMSVC || IsMSVC2015Compatible))
5028 CmdArgs.push_back("-fno-threadsafe-statics");
5030 // -fno-delayed-template-parsing is default, except for Windows where MSVC STL
5032 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
5033 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
5034 CmdArgs.push_back("-fdelayed-template-parsing");
5036 // -fgnu-keywords default varies depending on language; only pass if
5038 if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
5039 options::OPT_fno_gnu_keywords))
5040 A->render(Args, CmdArgs);
5042 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
5044 CmdArgs.push_back("-fgnu89-inline");
5046 if (Args.hasArg(options::OPT_fno_inline))
5047 CmdArgs.push_back("-fno-inline");
5049 if (Args.hasArg(options::OPT_fno_inline_functions))
5050 CmdArgs.push_back("-fno-inline-functions");
5052 ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
5054 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and
5055 // legacy is the default. Except for deployment taget of 10.5,
5056 // next runtime is always legacy dispatch and -fno-objc-legacy-dispatch
5057 // gets ignored silently.
5058 if (objcRuntime.isNonFragile()) {
5059 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
5060 options::OPT_fno_objc_legacy_dispatch,
5061 objcRuntime.isLegacyDispatchDefaultForArch(
5062 getToolChain().getArch()))) {
5063 if (getToolChain().UseObjCMixedDispatch())
5064 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
5066 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
5070 // When ObjectiveC legacy runtime is in effect on MacOSX,
5071 // turn on the option to do Array/Dictionary subscripting
5073 if (getToolChain().getArch() == llvm::Triple::x86 &&
5074 getToolChain().getTriple().isMacOSX() &&
5075 !getToolChain().getTriple().isMacOSXVersionLT(10, 7) &&
5076 objcRuntime.getKind() == ObjCRuntime::FragileMacOSX &&
5077 objcRuntime.isNeXTFamily())
5078 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
5080 // -fencode-extended-block-signature=1 is default.
5081 if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) {
5082 CmdArgs.push_back("-fencode-extended-block-signature");
5085 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
5086 // NOTE: This logic is duplicated in ToolChains.cpp.
5087 bool ARC = isObjCAutoRefCount(Args);
5089 getToolChain().CheckObjCARC();
5091 CmdArgs.push_back("-fobjc-arc");
5093 // FIXME: It seems like this entire block, and several around it should be
5094 // wrapped in isObjC, but for now we just use it here as this is where it
5095 // was being used previously.
5096 if (types::isCXX(InputType) && types::isObjC(InputType)) {
5097 if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
5098 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
5100 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
5103 // Allow the user to enable full exceptions code emission.
5104 // We define off for Objective-CC, on for Objective-C++.
5105 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
5106 options::OPT_fno_objc_arc_exceptions,
5107 /*default*/ types::isCXX(InputType)))
5108 CmdArgs.push_back("-fobjc-arc-exceptions");
5112 // -fobjc-infer-related-result-type is the default, except in the Objective-C
5114 if (rewriteKind != RK_None)
5115 CmdArgs.push_back("-fno-objc-infer-related-result-type");
5117 // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only
5118 // takes precedence.
5119 const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only);
5121 GCArg = Args.getLastArg(options::OPT_fobjc_gc);
5124 D.Diag(diag::err_drv_objc_gc_arr) << GCArg->getAsString(Args);
5125 } else if (getToolChain().SupportsObjCGC()) {
5126 GCArg->render(Args, CmdArgs);
5128 // FIXME: We should move this to a hard error.
5129 D.Diag(diag::warn_drv_objc_gc_unsupported) << GCArg->getAsString(Args);
5133 // Pass down -fobjc-weak or -fno-objc-weak if present.
5134 if (types::isObjC(InputType)) {
5135 auto WeakArg = Args.getLastArg(options::OPT_fobjc_weak,
5136 options::OPT_fno_objc_weak);
5140 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
5141 D.Diag(diag::err_objc_weak_with_gc);
5142 } else if (!objcRuntime.allowsWeak()) {
5143 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
5144 D.Diag(diag::err_objc_weak_unsupported);
5146 WeakArg->render(Args, CmdArgs);
5150 if (Args.hasFlag(options::OPT_fapplication_extension,
5151 options::OPT_fno_application_extension, false))
5152 CmdArgs.push_back("-fapplication-extension");
5154 // Handle GCC-style exception args.
5155 if (!C.getDriver().IsCLMode())
5156 addExceptionArgs(Args, InputType, getToolChain(), KernelOrKext, objcRuntime,
5159 if (getToolChain().UseSjLjExceptions(Args))
5160 CmdArgs.push_back("-fsjlj-exceptions");
5162 // C++ "sane" operator new.
5163 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
5164 options::OPT_fno_assume_sane_operator_new))
5165 CmdArgs.push_back("-fno-assume-sane-operator-new");
5167 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
5169 if (Args.hasFlag(options::OPT_fsized_deallocation,
5170 options::OPT_fno_sized_deallocation, false))
5171 CmdArgs.push_back("-fsized-deallocation");
5173 // -fconstant-cfstrings is default, and may be subject to argument translation
5175 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
5176 options::OPT_fno_constant_cfstrings) ||
5177 !Args.hasFlag(options::OPT_mconstant_cfstrings,
5178 options::OPT_mno_constant_cfstrings))
5179 CmdArgs.push_back("-fno-constant-cfstrings");
5181 // -fshort-wchar default varies depending on platform; only
5182 // pass if specified.
5183 if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
5184 options::OPT_fno_short_wchar))
5185 A->render(Args, CmdArgs);
5187 // -fno-pascal-strings is default, only pass non-default.
5188 if (Args.hasFlag(options::OPT_fpascal_strings,
5189 options::OPT_fno_pascal_strings, false))
5190 CmdArgs.push_back("-fpascal-strings");
5192 // Honor -fpack-struct= and -fpack-struct, if given. Note that
5193 // -fno-pack-struct doesn't apply to -fpack-struct=.
5194 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
5195 std::string PackStructStr = "-fpack-struct=";
5196 PackStructStr += A->getValue();
5197 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
5198 } else if (Args.hasFlag(options::OPT_fpack_struct,
5199 options::OPT_fno_pack_struct, false)) {
5200 CmdArgs.push_back("-fpack-struct=1");
5203 // Handle -fmax-type-align=N and -fno-type-align
5204 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
5205 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
5206 if (!SkipMaxTypeAlign) {
5207 std::string MaxTypeAlignStr = "-fmax-type-align=";
5208 MaxTypeAlignStr += A->getValue();
5209 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5211 } else if (getToolChain().getTriple().isOSDarwin()) {
5212 if (!SkipMaxTypeAlign) {
5213 std::string MaxTypeAlignStr = "-fmax-type-align=16";
5214 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5218 // -fcommon is the default unless compiling kernel code or the target says so
5219 bool NoCommonDefault =
5220 KernelOrKext || isNoCommonDefault(getToolChain().getTriple());
5221 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
5223 CmdArgs.push_back("-fno-common");
5225 // -fsigned-bitfields is default, and clang doesn't yet support
5226 // -funsigned-bitfields.
5227 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
5228 options::OPT_funsigned_bitfields))
5229 D.Diag(diag::warn_drv_clang_unsupported)
5230 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
5232 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
5233 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
5234 D.Diag(diag::err_drv_clang_unsupported)
5235 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
5237 // -finput_charset=UTF-8 is default. Reject others
5238 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
5239 StringRef value = inputCharset->getValue();
5240 if (value != "UTF-8")
5241 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
5245 // -fexec_charset=UTF-8 is default. Reject others
5246 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
5247 StringRef value = execCharset->getValue();
5248 if (value != "UTF-8")
5249 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
5253 // -fcaret-diagnostics is default.
5254 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
5255 options::OPT_fno_caret_diagnostics, true))
5256 CmdArgs.push_back("-fno-caret-diagnostics");
5258 // -fdiagnostics-fixit-info is default, only pass non-default.
5259 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
5260 options::OPT_fno_diagnostics_fixit_info))
5261 CmdArgs.push_back("-fno-diagnostics-fixit-info");
5263 // Enable -fdiagnostics-show-option by default.
5264 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
5265 options::OPT_fno_diagnostics_show_option))
5266 CmdArgs.push_back("-fdiagnostics-show-option");
5269 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
5270 CmdArgs.push_back("-fdiagnostics-show-category");
5271 CmdArgs.push_back(A->getValue());
5274 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
5275 CmdArgs.push_back("-fdiagnostics-format");
5276 CmdArgs.push_back(A->getValue());
5279 if (Arg *A = Args.getLastArg(
5280 options::OPT_fdiagnostics_show_note_include_stack,
5281 options::OPT_fno_diagnostics_show_note_include_stack)) {
5282 if (A->getOption().matches(
5283 options::OPT_fdiagnostics_show_note_include_stack))
5284 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
5286 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
5289 // Color diagnostics are the default, unless the terminal doesn't support
5291 // Support both clang's -f[no-]color-diagnostics and gcc's
5292 // -f[no-]diagnostics-colors[=never|always|auto].
5293 enum { Colors_On, Colors_Off, Colors_Auto } ShowColors = Colors_Auto;
5294 for (const auto &Arg : Args) {
5295 const Option &O = Arg->getOption();
5296 if (!O.matches(options::OPT_fcolor_diagnostics) &&
5297 !O.matches(options::OPT_fdiagnostics_color) &&
5298 !O.matches(options::OPT_fno_color_diagnostics) &&
5299 !O.matches(options::OPT_fno_diagnostics_color) &&
5300 !O.matches(options::OPT_fdiagnostics_color_EQ))
5304 if (O.matches(options::OPT_fcolor_diagnostics) ||
5305 O.matches(options::OPT_fdiagnostics_color)) {
5306 ShowColors = Colors_On;
5307 } else if (O.matches(options::OPT_fno_color_diagnostics) ||
5308 O.matches(options::OPT_fno_diagnostics_color)) {
5309 ShowColors = Colors_Off;
5311 assert(O.matches(options::OPT_fdiagnostics_color_EQ));
5312 StringRef value(Arg->getValue());
5313 if (value == "always")
5314 ShowColors = Colors_On;
5315 else if (value == "never")
5316 ShowColors = Colors_Off;
5317 else if (value == "auto")
5318 ShowColors = Colors_Auto;
5320 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5321 << ("-fdiagnostics-color=" + value).str();
5324 if (ShowColors == Colors_On ||
5325 (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()))
5326 CmdArgs.push_back("-fcolor-diagnostics");
5328 if (Args.hasArg(options::OPT_fansi_escape_codes))
5329 CmdArgs.push_back("-fansi-escape-codes");
5331 if (!Args.hasFlag(options::OPT_fshow_source_location,
5332 options::OPT_fno_show_source_location))
5333 CmdArgs.push_back("-fno-show-source-location");
5335 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
5337 CmdArgs.push_back("-fno-show-column");
5339 if (!Args.hasFlag(options::OPT_fspell_checking,
5340 options::OPT_fno_spell_checking))
5341 CmdArgs.push_back("-fno-spell-checking");
5343 // -fno-asm-blocks is default.
5344 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
5346 CmdArgs.push_back("-fasm-blocks");
5348 // -fgnu-inline-asm is default.
5349 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
5350 options::OPT_fno_gnu_inline_asm, true))
5351 CmdArgs.push_back("-fno-gnu-inline-asm");
5353 // Enable vectorization per default according to the optimization level
5354 // selected. For optimization levels that want vectorization we use the alias
5355 // option to simplify the hasFlag logic.
5356 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
5357 OptSpecifier VectorizeAliasOption =
5358 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
5359 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
5360 options::OPT_fno_vectorize, EnableVec))
5361 CmdArgs.push_back("-vectorize-loops");
5363 // -fslp-vectorize is enabled based on the optimization level selected.
5364 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
5365 OptSpecifier SLPVectAliasOption =
5366 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
5367 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
5368 options::OPT_fno_slp_vectorize, EnableSLPVec))
5369 CmdArgs.push_back("-vectorize-slp");
5371 // -fno-slp-vectorize-aggressive is default.
5372 if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
5373 options::OPT_fno_slp_vectorize_aggressive, false))
5374 CmdArgs.push_back("-vectorize-slp-aggressive");
5376 if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
5377 A->render(Args, CmdArgs);
5379 // -fdollars-in-identifiers default varies depending on platform and
5380 // language; only pass if specified.
5381 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
5382 options::OPT_fno_dollars_in_identifiers)) {
5383 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
5384 CmdArgs.push_back("-fdollars-in-identifiers");
5386 CmdArgs.push_back("-fno-dollars-in-identifiers");
5389 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
5390 // practical purposes.
5391 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
5392 options::OPT_fno_unit_at_a_time)) {
5393 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
5394 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
5397 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
5398 options::OPT_fno_apple_pragma_pack, false))
5399 CmdArgs.push_back("-fapple-pragma-pack");
5401 // le32-specific flags:
5402 // -fno-math-builtin: clang should not convert math builtins to intrinsics
5404 if (getToolChain().getArch() == llvm::Triple::le32) {
5405 CmdArgs.push_back("-fno-math-builtin");
5408 // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM.
5410 // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941.
5412 if (getToolChain().getTriple().isOSDarwin() &&
5413 (getToolChain().getArch() == llvm::Triple::arm ||
5414 getToolChain().getArch() == llvm::Triple::thumb)) {
5415 if (!Args.hasArg(options::OPT_fbuiltin_strcat))
5416 CmdArgs.push_back("-fno-builtin-strcat");
5417 if (!Args.hasArg(options::OPT_fbuiltin_strcpy))
5418 CmdArgs.push_back("-fno-builtin-strcpy");
5422 // Enable rewrite includes if the user's asked for it or if we're generating
5424 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
5425 // nice to enable this when doing a crashdump for modules as well.
5426 if (Args.hasFlag(options::OPT_frewrite_includes,
5427 options::OPT_fno_rewrite_includes, false) ||
5428 (C.isForDiagnostics() && !HaveModules))
5429 CmdArgs.push_back("-frewrite-includes");
5431 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
5432 if (Arg *A = Args.getLastArg(options::OPT_traditional,
5433 options::OPT_traditional_cpp)) {
5434 if (isa<PreprocessJobAction>(JA))
5435 CmdArgs.push_back("-traditional-cpp");
5437 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
5440 Args.AddLastArg(CmdArgs, options::OPT_dM);
5441 Args.AddLastArg(CmdArgs, options::OPT_dD);
5443 // Handle serialized diagnostics.
5444 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
5445 CmdArgs.push_back("-serialize-diagnostic-file");
5446 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
5449 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
5450 CmdArgs.push_back("-fretain-comments-from-system-headers");
5452 // Forward -fcomment-block-commands to -cc1.
5453 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
5454 // Forward -fparse-all-comments to -cc1.
5455 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
5457 // Turn -fplugin=name.so into -load name.so
5458 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
5459 CmdArgs.push_back("-load");
5460 CmdArgs.push_back(A->getValue());
5464 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
5466 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
5467 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
5470 // We translate this by hand to the -cc1 argument, since nightly test uses
5471 // it and developers have been trained to spell it with -mllvm.
5472 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
5473 CmdArgs.push_back("-disable-llvm-optzns");
5475 A->render(Args, CmdArgs);
5478 // With -save-temps, we want to save the unoptimized bitcode output from the
5479 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
5481 if (C.getDriver().isSaveTempsEnabled() && isa<CompileJobAction>(JA))
5482 CmdArgs.push_back("-disable-llvm-passes");
5484 if (Output.getType() == types::TY_Dependencies) {
5485 // Handled with other dependency code.
5486 } else if (Output.isFilename()) {
5487 CmdArgs.push_back("-o");
5488 CmdArgs.push_back(Output.getFilename());
5490 assert(Output.isNothing() && "Invalid output.");
5493 addDashXForInput(Args, Input, CmdArgs);
5495 if (Input.isFilename())
5496 CmdArgs.push_back(Input.getFilename());
5498 Input.getInputArg().renderAsInput(Args, CmdArgs);
5500 Args.AddAllArgs(CmdArgs, options::OPT_undef);
5502 const char *Exec = getToolChain().getDriver().getClangProgramPath();
5504 // Optionally embed the -cc1 level arguments into the debug info, for build
5506 if (getToolChain().UseDwarfDebugFlags()) {
5507 ArgStringList OriginalArgs;
5508 for (const auto &Arg : Args)
5509 Arg->render(Args, OriginalArgs);
5511 SmallString<256> Flags;
5513 for (const char *OriginalArg : OriginalArgs) {
5514 SmallString<128> EscapedArg;
5515 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5517 Flags += EscapedArg;
5519 CmdArgs.push_back("-dwarf-debug-flags");
5520 CmdArgs.push_back(Args.MakeArgString(Flags));
5523 // Add the split debug info name to the command lines here so we
5524 // can propagate it to the backend.
5525 bool SplitDwarf = SplitDwarfArg && getToolChain().getTriple().isOSLinux() &&
5526 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
5527 isa<BackendJobAction>(JA));
5528 const char *SplitDwarfOut;
5530 CmdArgs.push_back("-split-dwarf-file");
5531 SplitDwarfOut = SplitDebugName(Args, Input);
5532 CmdArgs.push_back(SplitDwarfOut);
5535 // Host-side cuda compilation receives device-side outputs as Inputs[1...].
5536 // Include them with -fcuda-include-gpubinary.
5537 if (IsCuda && Inputs.size() > 1)
5538 for (auto I = std::next(Inputs.begin()), E = Inputs.end(); I != E; ++I) {
5539 CmdArgs.push_back("-fcuda-include-gpubinary");
5540 CmdArgs.push_back(I->getFilename());
5543 // Finally add the compile command to the compilation.
5544 if (Args.hasArg(options::OPT__SLASH_fallback) &&
5545 Output.getType() == types::TY_Object &&
5546 (InputType == types::TY_C || InputType == types::TY_CXX)) {
5548 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
5549 C.addCommand(llvm::make_unique<FallbackCommand>(
5550 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
5552 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
5555 // Handle the debug info splitting at object creation time if we're
5556 // creating an object.
5557 // TODO: Currently only works on linux with newer objcopy.
5558 if (SplitDwarf && !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
5559 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut);
5561 if (Arg *A = Args.getLastArg(options::OPT_pg))
5562 if (Args.hasArg(options::OPT_fomit_frame_pointer))
5563 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
5564 << A->getAsString(Args);
5566 // Claim some arguments which clang supports automatically.
5568 // -fpch-preprocess is used with gcc to add a special marker in the output to
5569 // include the PCH file. Clang's PTH solution is completely transparent, so we
5570 // do not need to deal with it at all.
5571 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
5573 // Claim some arguments which clang doesn't support, but we don't
5574 // care to warn the user about.
5575 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
5576 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
5578 // Disable warnings for clang -E -emit-llvm foo.c
5579 Args.ClaimAllArgs(options::OPT_emit_llvm);
5582 /// Add options related to the Objective-C runtime/ABI.
5584 /// Returns true if the runtime is non-fragile.
5585 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
5586 ArgStringList &cmdArgs,
5587 RewriteKind rewriteKind) const {
5588 // Look for the controlling runtime option.
5590 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
5591 options::OPT_fobjc_runtime_EQ);
5593 // Just forward -fobjc-runtime= to the frontend. This supercedes
5594 // options about fragility.
5596 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
5597 ObjCRuntime runtime;
5598 StringRef value = runtimeArg->getValue();
5599 if (runtime.tryParse(value)) {
5600 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
5604 runtimeArg->render(args, cmdArgs);
5608 // Otherwise, we'll need the ABI "version". Version numbers are
5609 // slightly confusing for historical reasons:
5610 // 1 - Traditional "fragile" ABI
5611 // 2 - Non-fragile ABI, version 1
5612 // 3 - Non-fragile ABI, version 2
5613 unsigned objcABIVersion = 1;
5614 // If -fobjc-abi-version= is present, use that to set the version.
5615 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
5616 StringRef value = abiArg->getValue();
5619 else if (value == "2")
5621 else if (value == "3")
5624 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
5626 // Otherwise, determine if we are using the non-fragile ABI.
5627 bool nonFragileABIIsDefault =
5628 (rewriteKind == RK_NonFragile ||
5629 (rewriteKind == RK_None &&
5630 getToolChain().IsObjCNonFragileABIDefault()));
5631 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
5632 options::OPT_fno_objc_nonfragile_abi,
5633 nonFragileABIIsDefault)) {
5634 // Determine the non-fragile ABI version to use.
5635 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
5636 unsigned nonFragileABIVersion = 1;
5638 unsigned nonFragileABIVersion = 2;
5642 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
5643 StringRef value = abiArg->getValue();
5645 nonFragileABIVersion = 1;
5646 else if (value == "2")
5647 nonFragileABIVersion = 2;
5649 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5653 objcABIVersion = 1 + nonFragileABIVersion;
5659 // We don't actually care about the ABI version other than whether
5660 // it's non-fragile.
5661 bool isNonFragile = objcABIVersion != 1;
5663 // If we have no runtime argument, ask the toolchain for its default runtime.
5664 // However, the rewriter only really supports the Mac runtime, so assume that.
5665 ObjCRuntime runtime;
5667 switch (rewriteKind) {
5669 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5672 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
5675 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5680 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
5681 // On Darwin, make this use the default behavior for the toolchain.
5682 if (getToolChain().getTriple().isOSDarwin()) {
5683 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5685 // Otherwise, build for a generic macosx port.
5687 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5692 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
5693 // Legacy behaviour is to target the gnustep runtime if we are in
5694 // non-fragile mode or the GCC runtime in fragile mode.
5696 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1, 6));
5698 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
5702 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
5706 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
5707 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
5714 EHFlags() : Synch(false), Asynch(false), NoExceptC(false) {}
5719 } // end anonymous namespace
5721 /// /EH controls whether to run destructor cleanups when exceptions are
5722 /// thrown. There are three modifiers:
5723 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
5724 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
5725 /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
5726 /// - c: Assume that extern "C" functions are implicitly noexcept. This
5727 /// modifier is an optimization, so we ignore it for now.
5728 /// The default is /EHs-c-, meaning cleanups are disabled.
5729 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
5732 std::vector<std::string> EHArgs =
5733 Args.getAllArgValues(options::OPT__SLASH_EH);
5734 for (auto EHVal : EHArgs) {
5735 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5738 EH.Asynch = maybeConsumeDash(EHVal, I);
5741 EH.NoExceptC = maybeConsumeDash(EHVal, I);
5744 EH.Synch = maybeConsumeDash(EHVal, I);
5749 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5757 void Clang::AddClangCLArgs(const ArgList &Args, ArgStringList &CmdArgs,
5758 enum CodeGenOptions::DebugInfoKind *DebugInfoKind,
5759 bool *EmitCodeView) const {
5760 unsigned RTOptionID = options::OPT__SLASH_MT;
5762 if (Args.hasArg(options::OPT__SLASH_LDd))
5763 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5764 // but defining _DEBUG is sticky.
5765 RTOptionID = options::OPT__SLASH_MTd;
5767 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5768 RTOptionID = A->getOption().getID();
5770 StringRef FlagForCRT;
5771 switch (RTOptionID) {
5772 case options::OPT__SLASH_MD:
5773 if (Args.hasArg(options::OPT__SLASH_LDd))
5774 CmdArgs.push_back("-D_DEBUG");
5775 CmdArgs.push_back("-D_MT");
5776 CmdArgs.push_back("-D_DLL");
5777 FlagForCRT = "--dependent-lib=msvcrt";
5779 case options::OPT__SLASH_MDd:
5780 CmdArgs.push_back("-D_DEBUG");
5781 CmdArgs.push_back("-D_MT");
5782 CmdArgs.push_back("-D_DLL");
5783 FlagForCRT = "--dependent-lib=msvcrtd";
5785 case options::OPT__SLASH_MT:
5786 if (Args.hasArg(options::OPT__SLASH_LDd))
5787 CmdArgs.push_back("-D_DEBUG");
5788 CmdArgs.push_back("-D_MT");
5789 FlagForCRT = "--dependent-lib=libcmt";
5791 case options::OPT__SLASH_MTd:
5792 CmdArgs.push_back("-D_DEBUG");
5793 CmdArgs.push_back("-D_MT");
5794 FlagForCRT = "--dependent-lib=libcmtd";
5797 llvm_unreachable("Unexpected option ID.");
5800 if (Args.hasArg(options::OPT__SLASH_Zl)) {
5801 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5803 CmdArgs.push_back(FlagForCRT.data());
5805 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5806 // users want. The /Za flag to cl.exe turns this off, but it's not
5807 // implemented in clang.
5808 CmdArgs.push_back("--dependent-lib=oldnames");
5811 // Both /showIncludes and /E (and /EP) write to stdout. Allowing both
5812 // would produce interleaved output, so ignore /showIncludes in such cases.
5813 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_EP))
5814 if (Arg *A = Args.getLastArg(options::OPT_show_includes))
5815 A->render(Args, CmdArgs);
5817 // This controls whether or not we emit RTTI data for polymorphic types.
5818 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
5820 CmdArgs.push_back("-fno-rtti-data");
5822 // Emit CodeView if -Z7 is present.
5823 *EmitCodeView = Args.hasArg(options::OPT__SLASH_Z7);
5824 bool EmitDwarf = Args.hasArg(options::OPT_gdwarf);
5825 // If we are emitting CV but not DWARF, don't build information that LLVM
5826 // can't yet process.
5827 if (*EmitCodeView && !EmitDwarf)
5828 *DebugInfoKind = CodeGenOptions::DebugLineTablesOnly;
5830 CmdArgs.push_back("-gcodeview");
5832 const Driver &D = getToolChain().getDriver();
5833 EHFlags EH = parseClangCLEHFlags(D, Args);
5834 // FIXME: Do something with NoExceptC.
5835 if (EH.Synch || EH.Asynch) {
5836 CmdArgs.push_back("-fcxx-exceptions");
5837 CmdArgs.push_back("-fexceptions");
5840 // /EP should expand to -E -P.
5841 if (Args.hasArg(options::OPT__SLASH_EP)) {
5842 CmdArgs.push_back("-E");
5843 CmdArgs.push_back("-P");
5846 unsigned VolatileOptionID;
5847 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5848 getToolChain().getArch() == llvm::Triple::x86)
5849 VolatileOptionID = options::OPT__SLASH_volatile_ms;
5851 VolatileOptionID = options::OPT__SLASH_volatile_iso;
5853 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5854 VolatileOptionID = A->getOption().getID();
5856 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5857 CmdArgs.push_back("-fms-volatile");
5859 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5860 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5861 if (MostGeneralArg && BestCaseArg)
5862 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5863 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5865 if (MostGeneralArg) {
5866 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5867 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5868 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5870 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5871 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5872 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5873 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5874 << FirstConflict->getAsString(Args)
5875 << SecondConflict->getAsString(Args);
5878 CmdArgs.push_back("-fms-memptr-rep=single");
5879 else if (MultipleArg)
5880 CmdArgs.push_back("-fms-memptr-rep=multiple");
5882 CmdArgs.push_back("-fms-memptr-rep=virtual");
5885 if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
5886 A->render(Args, CmdArgs);
5888 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5889 CmdArgs.push_back("-fdiagnostics-format");
5890 if (Args.hasArg(options::OPT__SLASH_fallback))
5891 CmdArgs.push_back("msvc-fallback");
5893 CmdArgs.push_back("msvc");
5897 visualstudio::Compiler *Clang::getCLFallback() const {
5899 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5900 return CLFallback.get();
5903 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5904 ArgStringList &CmdArgs) const {
5907 const llvm::Triple &Triple = getToolChain().getTriple();
5908 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5910 CmdArgs.push_back("-target-abi");
5911 CmdArgs.push_back(ABIName.data());
5914 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
5915 const InputInfo &Output, const InputInfoList &Inputs,
5916 const ArgList &Args,
5917 const char *LinkingOutput) const {
5918 ArgStringList CmdArgs;
5920 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5921 const InputInfo &Input = Inputs[0];
5923 std::string TripleStr =
5924 getToolChain().ComputeEffectiveClangTriple(Args, Input.getType());
5925 const llvm::Triple Triple(TripleStr);
5927 // Don't warn about "clang -w -c foo.s"
5928 Args.ClaimAllArgs(options::OPT_w);
5929 // and "clang -emit-llvm -c foo.s"
5930 Args.ClaimAllArgs(options::OPT_emit_llvm);
5932 claimNoWarnArgs(Args);
5934 // Invoke ourselves in -cc1as mode.
5936 // FIXME: Implement custom jobs for internal actions.
5937 CmdArgs.push_back("-cc1as");
5939 // Add the "effective" target triple.
5940 CmdArgs.push_back("-triple");
5941 CmdArgs.push_back(Args.MakeArgString(TripleStr));
5943 // Set the output mode, we currently only expect to be used as a real
5945 CmdArgs.push_back("-filetype");
5946 CmdArgs.push_back("obj");
5948 // Set the main file name, so that debug info works even with
5949 // -save-temps or preprocessed assembly.
5950 CmdArgs.push_back("-main-file-name");
5951 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
5953 // Add the target cpu
5954 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
5956 CmdArgs.push_back("-target-cpu");
5957 CmdArgs.push_back(Args.MakeArgString(CPU));
5960 // Add the target features
5961 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
5963 // Ignore explicit -force_cpusubtype_ALL option.
5964 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5966 // Pass along any -I options so we get proper .include search paths.
5967 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
5969 // Determine the original source input.
5970 const Action *SourceAction = &JA;
5971 while (SourceAction->getKind() != Action::InputClass) {
5972 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
5973 SourceAction = SourceAction->getInputs()[0];
5976 // Forward -g and handle debug info related flags, assuming we are dealing
5977 // with an actual assembly file.
5978 if (SourceAction->getType() == types::TY_Asm ||
5979 SourceAction->getType() == types::TY_PP_Asm) {
5980 bool WantDebug = false;
5981 unsigned DwarfVersion = 0;
5982 Args.ClaimAllArgs(options::OPT_g_Group);
5983 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
5984 WantDebug = !A->getOption().matches(options::OPT_g0) &&
5985 !A->getOption().matches(options::OPT_ggdb0);
5987 DwarfVersion = DwarfVersionNum(A->getSpelling());
5989 if (DwarfVersion == 0)
5990 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
5991 RenderDebugEnablingArgs(Args, CmdArgs,
5992 (WantDebug ? CodeGenOptions::LimitedDebugInfo
5993 : CodeGenOptions::NoDebugInfo),
5994 DwarfVersion, llvm::DebuggerKind::Default);
5996 // Add the -fdebug-compilation-dir flag if needed.
5997 addDebugCompDirArg(Args, CmdArgs);
5999 // Set the AT_producer to the clang version when using the integrated
6000 // assembler on assembly source files.
6001 CmdArgs.push_back("-dwarf-debug-producer");
6002 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
6004 // And pass along -I options
6005 Args.AddAllArgs(CmdArgs, options::OPT_I);
6008 // Handle -fPIC et al -- the relocation-model affects the assembler
6009 // for some targets.
6010 llvm::Reloc::Model RelocationModel;
6013 std::tie(RelocationModel, PICLevel, IsPIE) =
6014 ParsePICArgs(getToolChain(), Triple, Args);
6016 const char *RMName = RelocationModelName(RelocationModel);
6018 CmdArgs.push_back("-mrelocation-model");
6019 CmdArgs.push_back(RMName);
6022 // Optionally embed the -cc1as level arguments into the debug info, for build
6024 if (getToolChain().UseDwarfDebugFlags()) {
6025 ArgStringList OriginalArgs;
6026 for (const auto &Arg : Args)
6027 Arg->render(Args, OriginalArgs);
6029 SmallString<256> Flags;
6030 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6032 for (const char *OriginalArg : OriginalArgs) {
6033 SmallString<128> EscapedArg;
6034 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
6036 Flags += EscapedArg;
6038 CmdArgs.push_back("-dwarf-debug-flags");
6039 CmdArgs.push_back(Args.MakeArgString(Flags));
6042 // FIXME: Add -static support, once we have it.
6044 // Add target specific flags.
6045 switch (getToolChain().getArch()) {
6049 case llvm::Triple::mips:
6050 case llvm::Triple::mipsel:
6051 case llvm::Triple::mips64:
6052 case llvm::Triple::mips64el:
6053 AddMIPSTargetArgs(Args, CmdArgs);
6057 // Consume all the warning flags. Usually this would be handled more
6058 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
6059 // doesn't handle that so rather than warning about unused flags that are
6060 // actually used, we'll lie by omission instead.
6061 // FIXME: Stop lying and consume only the appropriate driver flags
6062 Args.ClaimAllArgs(options::OPT_W_Group);
6064 // Assemblers that want to know the dwarf version can't assume a value,
6065 // since the defaulting logic resides in the driver. Put in something
6066 // reasonable now, in case a subsequent "-Wa,-g" changes it.
6067 RenderDebugEnablingArgs(Args, CmdArgs, CodeGenOptions::NoDebugInfo,
6068 getToolChain().GetDefaultDwarfVersion(),
6069 llvm::DebuggerKind::Default);
6070 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
6071 getToolChain().getDriver());
6073 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
6075 assert(Output.isFilename() && "Unexpected lipo output.");
6076 CmdArgs.push_back("-o");
6077 CmdArgs.push_back(Output.getFilename());
6079 assert(Input.isFilename() && "Invalid input.");
6080 CmdArgs.push_back(Input.getFilename());
6082 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6083 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6085 // Handle the debug info splitting at object creation time if we're
6086 // creating an object.
6087 // TODO: Currently only works on linux with newer objcopy.
6088 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
6089 getToolChain().getTriple().isOSLinux())
6090 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
6091 SplitDebugName(Args, Input));
6094 void GnuTool::anchor() {}
6096 void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
6097 const InputInfo &Output,
6098 const InputInfoList &Inputs, const ArgList &Args,
6099 const char *LinkingOutput) const {
6100 const Driver &D = getToolChain().getDriver();
6101 ArgStringList CmdArgs;
6103 for (const auto &A : Args) {
6104 if (forwardToGCC(A->getOption())) {
6105 // It is unfortunate that we have to claim here, as this means
6106 // we will basically never report anything interesting for
6107 // platforms using a generic gcc, even if we are just using gcc
6108 // to get to the assembler.
6111 // Don't forward any -g arguments to assembly steps.
6112 if (isa<AssembleJobAction>(JA) &&
6113 A->getOption().matches(options::OPT_g_Group))
6116 // Don't forward any -W arguments to assembly and link steps.
6117 if ((isa<AssembleJobAction>(JA) || isa<LinkJobAction>(JA)) &&
6118 A->getOption().matches(options::OPT_W_Group))
6121 A->render(Args, CmdArgs);
6125 RenderExtraToolArgs(JA, CmdArgs);
6127 // If using a driver driver, force the arch.
6128 if (getToolChain().getTriple().isOSDarwin()) {
6129 CmdArgs.push_back("-arch");
6131 Args.MakeArgString(getToolChain().getDefaultUniversalArchName()));
6134 // Try to force gcc to match the tool chain we want, if we recognize
6137 // FIXME: The triple class should directly provide the information we want
6139 switch (getToolChain().getArch()) {
6142 case llvm::Triple::x86:
6143 case llvm::Triple::ppc:
6144 CmdArgs.push_back("-m32");
6146 case llvm::Triple::x86_64:
6147 case llvm::Triple::ppc64:
6148 case llvm::Triple::ppc64le:
6149 CmdArgs.push_back("-m64");
6151 case llvm::Triple::sparcel:
6152 CmdArgs.push_back("-EL");
6156 if (Output.isFilename()) {
6157 CmdArgs.push_back("-o");
6158 CmdArgs.push_back(Output.getFilename());
6160 assert(Output.isNothing() && "Unexpected output");
6161 CmdArgs.push_back("-fsyntax-only");
6164 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6166 // Only pass -x if gcc will understand it; otherwise hope gcc
6167 // understands the suffix correctly. The main use case this would go
6168 // wrong in is for linker inputs if they happened to have an odd
6169 // suffix; really the only way to get this to happen is a command
6170 // like '-x foobar a.c' which will treat a.c like a linker input.
6172 // FIXME: For the linker case specifically, can we safely convert
6173 // inputs into '-Wl,' options?
6174 for (const auto &II : Inputs) {
6175 // Don't try to pass LLVM or AST inputs to a generic gcc.
6176 if (types::isLLVMIR(II.getType()))
6177 D.Diag(diag::err_drv_no_linker_llvm_support)
6178 << getToolChain().getTripleString();
6179 else if (II.getType() == types::TY_AST)
6180 D.Diag(diag::err_drv_no_ast_support) << getToolChain().getTripleString();
6181 else if (II.getType() == types::TY_ModuleFile)
6182 D.Diag(diag::err_drv_no_module_support)
6183 << getToolChain().getTripleString();
6185 if (types::canTypeBeUserSpecified(II.getType())) {
6186 CmdArgs.push_back("-x");
6187 CmdArgs.push_back(types::getTypeName(II.getType()));
6190 if (II.isFilename())
6191 CmdArgs.push_back(II.getFilename());
6193 const Arg &A = II.getInputArg();
6195 // Reverse translate some rewritten options.
6196 if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) {
6197 CmdArgs.push_back("-lstdc++");
6201 // Don't render as input, we need gcc to do the translations.
6202 A.render(Args, CmdArgs);
6206 const std::string customGCCName = D.getCCCGenericGCCName();
6207 const char *GCCName;
6208 if (!customGCCName.empty())
6209 GCCName = customGCCName.c_str();
6210 else if (D.CCCIsCXX()) {
6215 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath(GCCName));
6216 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6219 void gcc::Preprocessor::RenderExtraToolArgs(const JobAction &JA,
6220 ArgStringList &CmdArgs) const {
6221 CmdArgs.push_back("-E");
6224 void gcc::Compiler::RenderExtraToolArgs(const JobAction &JA,
6225 ArgStringList &CmdArgs) const {
6226 const Driver &D = getToolChain().getDriver();
6228 switch (JA.getType()) {
6229 // If -flto, etc. are present then make sure not to force assembly output.
6230 case types::TY_LLVM_IR:
6231 case types::TY_LTO_IR:
6232 case types::TY_LLVM_BC:
6233 case types::TY_LTO_BC:
6234 CmdArgs.push_back("-c");
6236 // We assume we've got an "integrated" assembler in that gcc will produce an
6237 // object file itself.
6238 case types::TY_Object:
6239 CmdArgs.push_back("-c");
6241 case types::TY_PP_Asm:
6242 CmdArgs.push_back("-S");
6244 case types::TY_Nothing:
6245 CmdArgs.push_back("-fsyntax-only");
6248 D.Diag(diag::err_drv_invalid_gcc_output_type) << getTypeName(JA.getType());
6252 void gcc::Linker::RenderExtraToolArgs(const JobAction &JA,
6253 ArgStringList &CmdArgs) const {
6254 // The types are (hopefully) good enough.
6257 // Hexagon tools start.
6258 void hexagon::Assembler::RenderExtraToolArgs(const JobAction &JA,
6259 ArgStringList &CmdArgs) const {
6262 void hexagon::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6263 const InputInfo &Output,
6264 const InputInfoList &Inputs,
6265 const ArgList &Args,
6266 const char *LinkingOutput) const {
6267 claimNoWarnArgs(Args);
6269 auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
6270 const Driver &D = HTC.getDriver();
6271 ArgStringList CmdArgs;
6273 std::string MArchString = "-march=hexagon";
6274 CmdArgs.push_back(Args.MakeArgString(MArchString));
6276 RenderExtraToolArgs(JA, CmdArgs);
6278 std::string AsName = "hexagon-llvm-mc";
6279 std::string MCpuString = "-mcpu=hexagon" +
6280 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
6281 CmdArgs.push_back("-filetype=obj");
6282 CmdArgs.push_back(Args.MakeArgString(MCpuString));
6284 if (Output.isFilename()) {
6285 CmdArgs.push_back("-o");
6286 CmdArgs.push_back(Output.getFilename());
6288 assert(Output.isNothing() && "Unexpected output");
6289 CmdArgs.push_back("-fsyntax-only");
6292 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
6293 std::string N = llvm::utostr(G.getValue());
6294 CmdArgs.push_back(Args.MakeArgString(std::string("-gpsize=") + N));
6297 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6299 // Only pass -x if gcc will understand it; otherwise hope gcc
6300 // understands the suffix correctly. The main use case this would go
6301 // wrong in is for linker inputs if they happened to have an odd
6302 // suffix; really the only way to get this to happen is a command
6303 // like '-x foobar a.c' which will treat a.c like a linker input.
6305 // FIXME: For the linker case specifically, can we safely convert
6306 // inputs into '-Wl,' options?
6307 for (const auto &II : Inputs) {
6308 // Don't try to pass LLVM or AST inputs to a generic gcc.
6309 if (types::isLLVMIR(II.getType()))
6310 D.Diag(clang::diag::err_drv_no_linker_llvm_support)
6311 << HTC.getTripleString();
6312 else if (II.getType() == types::TY_AST)
6313 D.Diag(clang::diag::err_drv_no_ast_support)
6314 << HTC.getTripleString();
6315 else if (II.getType() == types::TY_ModuleFile)
6316 D.Diag(diag::err_drv_no_module_support)
6317 << HTC.getTripleString();
6319 if (II.isFilename())
6320 CmdArgs.push_back(II.getFilename());
6322 // Don't render as input, we need gcc to do the translations.
6323 // FIXME: What is this?
6324 II.getInputArg().render(Args, CmdArgs);
6327 auto *Exec = Args.MakeArgString(HTC.GetProgramPath(AsName.c_str()));
6328 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6331 void hexagon::Linker::RenderExtraToolArgs(const JobAction &JA,
6332 ArgStringList &CmdArgs) const {
6336 constructHexagonLinkArgs(Compilation &C, const JobAction &JA,
6337 const toolchains::HexagonToolChain &HTC,
6338 const InputInfo &Output, const InputInfoList &Inputs,
6339 const ArgList &Args, ArgStringList &CmdArgs,
6340 const char *LinkingOutput) {
6342 const Driver &D = HTC.getDriver();
6344 //----------------------------------------------------------------------------
6346 //----------------------------------------------------------------------------
6347 bool IsStatic = Args.hasArg(options::OPT_static);
6348 bool IsShared = Args.hasArg(options::OPT_shared);
6349 bool IsPIE = Args.hasArg(options::OPT_pie);
6350 bool IncStdLib = !Args.hasArg(options::OPT_nostdlib);
6351 bool IncStartFiles = !Args.hasArg(options::OPT_nostartfiles);
6352 bool IncDefLibs = !Args.hasArg(options::OPT_nodefaultlibs);
6354 bool UseShared = IsShared && !IsStatic;
6356 //----------------------------------------------------------------------------
6357 // Silence warnings for various options
6358 //----------------------------------------------------------------------------
6359 Args.ClaimAllArgs(options::OPT_g_Group);
6360 Args.ClaimAllArgs(options::OPT_emit_llvm);
6361 Args.ClaimAllArgs(options::OPT_w); // Other warning options are already
6362 // handled somewhere else.
6363 Args.ClaimAllArgs(options::OPT_static_libgcc);
6365 //----------------------------------------------------------------------------
6367 //----------------------------------------------------------------------------
6368 if (Args.hasArg(options::OPT_s))
6369 CmdArgs.push_back("-s");
6371 if (Args.hasArg(options::OPT_r))
6372 CmdArgs.push_back("-r");
6374 for (const auto &Opt : HTC.ExtraOpts)
6375 CmdArgs.push_back(Opt.c_str());
6377 CmdArgs.push_back("-march=hexagon");
6378 std::string CpuVer =
6379 toolchains::HexagonToolChain::GetTargetCPUVersion(Args).str();
6380 std::string MCpuString = "-mcpu=hexagon" + CpuVer;
6381 CmdArgs.push_back(Args.MakeArgString(MCpuString));
6384 CmdArgs.push_back("-shared");
6385 // The following should be the default, but doing as hexagon-gcc does.
6386 CmdArgs.push_back("-call_shared");
6390 CmdArgs.push_back("-static");
6392 if (IsPIE && !IsShared)
6393 CmdArgs.push_back("-pie");
6395 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
6396 std::string N = llvm::utostr(G.getValue());
6397 CmdArgs.push_back(Args.MakeArgString(std::string("-G") + N));
6398 UseG0 = G.getValue() == 0;
6401 //----------------------------------------------------------------------------
6403 //----------------------------------------------------------------------------
6404 CmdArgs.push_back("-o");
6405 CmdArgs.push_back(Output.getFilename());
6407 //----------------------------------------------------------------------------
6409 //----------------------------------------------------------------------------
6410 std::vector<std::string> OsLibs;
6411 bool HasStandalone = false;
6413 for (const Arg *A : Args.filtered(options::OPT_moslib_EQ)) {
6415 OsLibs.emplace_back(A->getValue());
6416 HasStandalone = HasStandalone || (OsLibs.back() == "standalone");
6418 if (OsLibs.empty()) {
6419 OsLibs.push_back("standalone");
6420 HasStandalone = true;
6423 //----------------------------------------------------------------------------
6425 //----------------------------------------------------------------------------
6426 const std::string MCpuSuffix = "/" + CpuVer;
6427 const std::string MCpuG0Suffix = MCpuSuffix + "/G0";
6428 const std::string RootDir =
6429 HTC.getHexagonTargetDir(D.InstalledDir, D.PrefixDirs) + "/";
6430 const std::string StartSubDir =
6431 "hexagon/lib" + (UseG0 ? MCpuG0Suffix : MCpuSuffix);
6433 auto Find = [&HTC] (const std::string &RootDir, const std::string &SubDir,
6434 const char *Name) -> std::string {
6435 std::string RelName = SubDir + Name;
6436 std::string P = HTC.GetFilePath(RelName.c_str());
6437 if (llvm::sys::fs::exists(P))
6439 return RootDir + RelName;
6442 if (IncStdLib && IncStartFiles) {
6444 if (HasStandalone) {
6445 std::string Crt0SA = Find(RootDir, StartSubDir, "/crt0_standalone.o");
6446 CmdArgs.push_back(Args.MakeArgString(Crt0SA));
6448 std::string Crt0 = Find(RootDir, StartSubDir, "/crt0.o");
6449 CmdArgs.push_back(Args.MakeArgString(Crt0));
6451 std::string Init = UseShared
6452 ? Find(RootDir, StartSubDir + "/pic", "/initS.o")
6453 : Find(RootDir, StartSubDir, "/init.o");
6454 CmdArgs.push_back(Args.MakeArgString(Init));
6457 //----------------------------------------------------------------------------
6458 // Library Search Paths
6459 //----------------------------------------------------------------------------
6460 const ToolChain::path_list &LibPaths = HTC.getFilePaths();
6461 for (const auto &LibPath : LibPaths)
6462 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
6464 //----------------------------------------------------------------------------
6466 //----------------------------------------------------------------------------
6467 Args.AddAllArgs(CmdArgs,
6468 {options::OPT_T_Group, options::OPT_e, options::OPT_s,
6469 options::OPT_t, options::OPT_u_Group});
6471 AddLinkerInputs(HTC, Inputs, Args, CmdArgs);
6473 //----------------------------------------------------------------------------
6475 //----------------------------------------------------------------------------
6476 if (IncStdLib && IncDefLibs) {
6478 HTC.AddCXXStdlibLibArgs(Args, CmdArgs);
6479 CmdArgs.push_back("-lm");
6482 CmdArgs.push_back("--start-group");
6485 for (const std::string &Lib : OsLibs)
6486 CmdArgs.push_back(Args.MakeArgString("-l" + Lib));
6487 CmdArgs.push_back("-lc");
6489 CmdArgs.push_back("-lgcc");
6491 CmdArgs.push_back("--end-group");
6494 //----------------------------------------------------------------------------
6496 //----------------------------------------------------------------------------
6497 if (IncStdLib && IncStartFiles) {
6498 std::string Fini = UseShared
6499 ? Find(RootDir, StartSubDir + "/pic", "/finiS.o")
6500 : Find(RootDir, StartSubDir, "/fini.o");
6501 CmdArgs.push_back(Args.MakeArgString(Fini));
6505 void hexagon::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6506 const InputInfo &Output,
6507 const InputInfoList &Inputs,
6508 const ArgList &Args,
6509 const char *LinkingOutput) const {
6510 auto &HTC = static_cast<const toolchains::HexagonToolChain&>(getToolChain());
6512 ArgStringList CmdArgs;
6513 constructHexagonLinkArgs(C, JA, HTC, Output, Inputs, Args, CmdArgs,
6516 std::string Linker = HTC.GetProgramPath("hexagon-link");
6517 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
6520 // Hexagon tools end.
6522 void amdgpu::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6523 const InputInfo &Output,
6524 const InputInfoList &Inputs,
6525 const ArgList &Args,
6526 const char *LinkingOutput) const {
6528 std::string Linker = getToolChain().GetProgramPath(getShortName());
6529 ArgStringList CmdArgs;
6530 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6531 CmdArgs.push_back("-o");
6532 CmdArgs.push_back(Output.getFilename());
6533 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Linker),
6536 // AMDGPU tools end.
6538 wasm::Linker::Linker(const ToolChain &TC)
6539 : GnuTool("wasm::Linker", "lld", TC) {}
6541 bool wasm::Linker::isLinkJob() const {
6545 bool wasm::Linker::hasIntegratedCPP() const {
6549 void wasm::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6550 const InputInfo &Output,
6551 const InputInfoList &Inputs,
6552 const ArgList &Args,
6553 const char *LinkingOutput) const {
6554 const char *Linker = Args.MakeArgString(getToolChain().GetLinkerPath());
6555 ArgStringList CmdArgs;
6556 CmdArgs.push_back("-flavor");
6557 CmdArgs.push_back("ld");
6559 // Enable garbage collection of unused input sections by default, since code
6560 // size is of particular importance. This is significantly facilitated by
6561 // the enabling of -ffunction-sections and -fdata-sections in
6562 // Clang::ConstructJob.
6563 if (areOptimizationsEnabled(Args))
6564 CmdArgs.push_back("--gc-sections");
6566 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
6567 CmdArgs.push_back("-o");
6568 CmdArgs.push_back(Output.getFilename());
6569 C.addCommand(llvm::make_unique<Command>(JA, *this, Linker, CmdArgs, Inputs));
6572 const std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
6577 MArch = Triple.getArchName();
6578 MArch = StringRef(MArch).split("+").first.lower();
6580 // Handle -march=native.
6581 if (MArch == "native") {
6582 std::string CPU = llvm::sys::getHostCPUName();
6583 if (CPU != "generic") {
6584 // Translate the native cpu into the architecture suffix for that CPU.
6585 StringRef Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
6586 // If there is no valid architecture suffix for this CPU we don't know how
6587 // to handle it, so return no architecture.
6591 MArch = std::string("arm") + Suffix.str();
6598 /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
6599 StringRef arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {
6600 std::string MArch = getARMArch(Arch, Triple);
6601 // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
6602 // here means an -march=native that we can't handle, so instead return no CPU.
6606 // We need to return an empty string here on invalid MArch values as the
6607 // various places that call this function can't cope with a null result.
6608 return Triple.getARMCPUForArch(MArch);
6611 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
6612 std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,
6613 const llvm::Triple &Triple) {
6614 // FIXME: Warn on inconsistent use of -mcpu and -march.
6615 // If we have -mcpu=, use that.
6617 std::string MCPU = StringRef(CPU).split("+").first.lower();
6618 // Handle -mcpu=native.
6619 if (MCPU == "native")
6620 return llvm::sys::getHostCPUName();
6625 return getARMCPUForMArch(Arch, Triple);
6628 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
6629 /// CPU (or Arch, if CPU is generic).
6630 // FIXME: This is redundant with -mcpu, why does LLVM use this.
6631 StringRef arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch,
6632 const llvm::Triple &Triple) {
6634 if (CPU == "generic") {
6635 std::string ARMArch = tools::arm::getARMArch(Arch, Triple);
6636 ArchKind = llvm::ARM::parseArch(ARMArch);
6637 if (ArchKind == llvm::ARM::AK_INVALID)
6638 // In case of generic Arch, i.e. "arm",
6639 // extract arch from default cpu of the Triple
6640 ArchKind = llvm::ARM::parseCPUArch(Triple.getARMCPUForArch(ARMArch));
6642 // FIXME: horrible hack to get around the fact that Cortex-A7 is only an
6643 // armv7k triple if it's actually been specified via "-arch armv7k".
6644 ArchKind = (Arch == "armv7k" || Arch == "thumbv7k")
6645 ? (unsigned)llvm::ARM::AK_ARMV7K
6646 : llvm::ARM::parseCPUArch(CPU);
6648 if (ArchKind == llvm::ARM::AK_INVALID)
6650 return llvm::ARM::getSubArch(ArchKind);
6653 void arm::appendEBLinkFlags(const ArgList &Args, ArgStringList &CmdArgs,
6654 const llvm::Triple &Triple) {
6655 if (Args.hasArg(options::OPT_r))
6658 // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
6659 // to generate BE-8 executables.
6660 if (getARMSubArchVersionNumber(Triple) >= 7 || isARMMProfile(Triple))
6661 CmdArgs.push_back("--be8");
6664 mips::NanEncoding mips::getSupportedNanEncoding(StringRef &CPU) {
6665 // Strictly speaking, mips32r2 and mips64r2 are NanLegacy-only since Nan2008
6666 // was first introduced in Release 3. However, other compilers have
6667 // traditionally allowed it for Release 2 so we should do the same.
6668 return (NanEncoding)llvm::StringSwitch<int>(CPU)
6669 .Case("mips1", NanLegacy)
6670 .Case("mips2", NanLegacy)
6671 .Case("mips3", NanLegacy)
6672 .Case("mips4", NanLegacy)
6673 .Case("mips5", NanLegacy)
6674 .Case("mips32", NanLegacy)
6675 .Case("mips32r2", NanLegacy | Nan2008)
6676 .Case("mips32r3", NanLegacy | Nan2008)
6677 .Case("mips32r5", NanLegacy | Nan2008)
6678 .Case("mips32r6", Nan2008)
6679 .Case("mips64", NanLegacy)
6680 .Case("mips64r2", NanLegacy | Nan2008)
6681 .Case("mips64r3", NanLegacy | Nan2008)
6682 .Case("mips64r5", NanLegacy | Nan2008)
6683 .Case("mips64r6", Nan2008)
6684 .Default(NanLegacy);
6687 bool mips::hasMipsAbiArg(const ArgList &Args, const char *Value) {
6688 Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
6689 return A && (A->getValue() == StringRef(Value));
6692 bool mips::isUCLibc(const ArgList &Args) {
6693 Arg *A = Args.getLastArg(options::OPT_m_libc_Group);
6694 return A && A->getOption().matches(options::OPT_muclibc);
6697 bool mips::isNaN2008(const ArgList &Args, const llvm::Triple &Triple) {
6698 if (Arg *NaNArg = Args.getLastArg(options::OPT_mnan_EQ))
6699 return llvm::StringSwitch<bool>(NaNArg->getValue())
6701 .Case("legacy", false)
6704 // NaN2008 is the default for MIPS32r6/MIPS64r6.
6705 return llvm::StringSwitch<bool>(getCPUName(Args, Triple))
6706 .Cases("mips32r6", "mips64r6", true)
6712 bool mips::isFPXXDefault(const llvm::Triple &Triple, StringRef CPUName,
6713 StringRef ABIName, mips::FloatABI FloatABI) {
6714 if (Triple.getVendor() != llvm::Triple::ImaginationTechnologies &&
6715 Triple.getVendor() != llvm::Triple::MipsTechnologies)
6718 if (ABIName != "32")
6721 // FPXX shouldn't be used if either -msoft-float or -mfloat-abi=soft is
6723 if (FloatABI == mips::FloatABI::Soft)
6726 return llvm::StringSwitch<bool>(CPUName)
6727 .Cases("mips2", "mips3", "mips4", "mips5", true)
6728 .Cases("mips32", "mips32r2", "mips32r3", "mips32r5", true)
6729 .Cases("mips64", "mips64r2", "mips64r3", "mips64r5", true)
6733 bool mips::shouldUseFPXX(const ArgList &Args, const llvm::Triple &Triple,
6734 StringRef CPUName, StringRef ABIName,
6735 mips::FloatABI FloatABI) {
6736 bool UseFPXX = isFPXXDefault(Triple, CPUName, ABIName, FloatABI);
6738 // FPXX shouldn't be used if -msingle-float is present.
6739 if (Arg *A = Args.getLastArg(options::OPT_msingle_float,
6740 options::OPT_mdouble_float))
6741 if (A->getOption().matches(options::OPT_msingle_float))
6747 llvm::Triple::ArchType darwin::getArchTypeForMachOArchName(StringRef Str) {
6748 // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for
6749 // archs which Darwin doesn't use.
6751 // The matching this routine does is fairly pointless, since it is neither the
6752 // complete architecture list, nor a reasonable subset. The problem is that
6753 // historically the driver driver accepts this and also ties its -march=
6754 // handling to the architecture name, so we need to be careful before removing
6757 // This code must be kept in sync with Clang's Darwin specific argument
6760 return llvm::StringSwitch<llvm::Triple::ArchType>(Str)
6761 .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc)
6762 .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc)
6763 .Case("ppc64", llvm::Triple::ppc64)
6764 .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86)
6765 .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4",
6767 .Cases("x86_64", "x86_64h", llvm::Triple::x86_64)
6768 // This is derived from the driver driver.
6769 .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm)
6770 .Cases("armv7", "armv7em", "armv7k", "armv7m", llvm::Triple::arm)
6771 .Cases("armv7s", "xscale", llvm::Triple::arm)
6772 .Case("arm64", llvm::Triple::aarch64)
6773 .Case("r600", llvm::Triple::r600)
6774 .Case("amdgcn", llvm::Triple::amdgcn)
6775 .Case("nvptx", llvm::Triple::nvptx)
6776 .Case("nvptx64", llvm::Triple::nvptx64)
6777 .Case("amdil", llvm::Triple::amdil)
6778 .Case("spir", llvm::Triple::spir)
6779 .Default(llvm::Triple::UnknownArch);
6782 void darwin::setTripleTypeForMachOArchName(llvm::Triple &T, StringRef Str) {
6783 const llvm::Triple::ArchType Arch = getArchTypeForMachOArchName(Str);
6786 if (Str == "x86_64h")
6788 else if (Str == "armv6m" || Str == "armv7m" || Str == "armv7em") {
6789 T.setOS(llvm::Triple::UnknownOS);
6790 T.setObjectFormat(llvm::Triple::MachO);
6794 const char *Clang::getBaseInputName(const ArgList &Args,
6795 const InputInfo &Input) {
6796 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
6799 const char *Clang::getBaseInputStem(const ArgList &Args,
6800 const InputInfoList &Inputs) {
6801 const char *Str = getBaseInputName(Args, Inputs[0]);
6803 if (const char *End = strrchr(Str, '.'))
6804 return Args.MakeArgString(std::string(Str, End));
6809 const char *Clang::getDependencyFileName(const ArgList &Args,
6810 const InputInfoList &Inputs) {
6811 // FIXME: Think about this more.
6814 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6815 std::string Str(OutputOpt->getValue());
6816 Res = Str.substr(0, Str.rfind('.'));
6818 Res = getBaseInputStem(Args, Inputs);
6820 return Args.MakeArgString(Res + ".d");
6823 void cloudabi::Linker::ConstructJob(Compilation &C, const JobAction &JA,
6824 const InputInfo &Output,
6825 const InputInfoList &Inputs,
6826 const ArgList &Args,
6827 const char *LinkingOutput) const {
6828 const ToolChain &ToolChain = getToolChain();
6829 const Driver &D = ToolChain.getDriver();
6830 ArgStringList CmdArgs;
6832 // Silence warning for "clang -g foo.o -o foo"
6833 Args.ClaimAllArgs(options::OPT_g_Group);
6834 // and "clang -emit-llvm foo.o -o foo"
6835 Args.ClaimAllArgs(options::OPT_emit_llvm);
6836 // and for "clang -w foo.o -o foo". Other warning options are already
6837 // handled somewhere else.
6838 Args.ClaimAllArgs(options::OPT_w);
6840 if (!D.SysRoot.empty())
6841 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
6843 // CloudABI only supports static linkage.
6844 CmdArgs.push_back("-Bstatic");
6845 CmdArgs.push_back("--eh-frame-hdr");
6846 CmdArgs.push_back("--gc-sections");
6848 if (Output.isFilename()) {
6849 CmdArgs.push_back("-o");
6850 CmdArgs.push_back(Output.getFilename());
6852 assert(Output.isNothing() && "Invalid output.");
6855 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
6856 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt0.o")));
6857 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtbegin.o")));
6860 Args.AddAllArgs(CmdArgs, options::OPT_L);
6861 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
6862 Args.AddAllArgs(CmdArgs,
6863 {options::OPT_T_Group, options::OPT_e, options::OPT_s,
6864 options::OPT_t, options::OPT_Z_Flag, options::OPT_r});
6867 AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
6869 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
6871 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
6873 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
6874 CmdArgs.push_back("-lc");
6875 CmdArgs.push_back("-lcompiler_rt");
6878 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
6879 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
6881 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
6882 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6885 void darwin::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
6886 const InputInfo &Output,
6887 const InputInfoList &Inputs,
6888 const ArgList &Args,
6889 const char *LinkingOutput) const {
6890 ArgStringList CmdArgs;
6892 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
6893 const InputInfo &Input = Inputs[0];
6895 // Determine the original source input.
6896 const Action *SourceAction = &JA;
6897 while (SourceAction->getKind() != Action::InputClass) {
6898 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6899 SourceAction = SourceAction->getInputs()[0];
6902 // If -fno-integrated-as is used add -Q to the darwin assember driver to make
6903 // sure it runs its system assembler not clang's integrated assembler.
6904 // Applicable to darwin11+ and Xcode 4+. darwin<10 lacked integrated-as.
6905 // FIXME: at run-time detect assembler capabilities or rely on version
6906 // information forwarded by -target-assembler-version.
6907 if (Args.hasArg(options::OPT_fno_integrated_as)) {
6908 const llvm::Triple &T(getToolChain().getTriple());
6909 if (!(T.isMacOSX() && T.isMacOSXVersionLT(10, 7)))
6910 CmdArgs.push_back("-Q");
6913 // Forward -g, assuming we are dealing with an actual assembly file.
6914 if (SourceAction->getType() == types::TY_Asm ||
6915 SourceAction->getType() == types::TY_PP_Asm) {
6916 if (Args.hasArg(options::OPT_gstabs))
6917 CmdArgs.push_back("--gstabs");
6918 else if (Args.hasArg(options::OPT_g_Group))
6919 CmdArgs.push_back("-g");
6922 // Derived from asm spec.
6923 AddMachOArch(Args, CmdArgs);
6925 // Use -force_cpusubtype_ALL on x86 by default.
6926 if (getToolChain().getArch() == llvm::Triple::x86 ||
6927 getToolChain().getArch() == llvm::Triple::x86_64 ||
6928 Args.hasArg(options::OPT_force__cpusubtype__ALL))
6929 CmdArgs.push_back("-force_cpusubtype_ALL");
6931 if (getToolChain().getArch() != llvm::Triple::x86_64 &&
6932 (((Args.hasArg(options::OPT_mkernel) ||
6933 Args.hasArg(options::OPT_fapple_kext)) &&
6934 getMachOToolChain().isKernelStatic()) ||
6935 Args.hasArg(options::OPT_static)))
6936 CmdArgs.push_back("-static");
6938 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
6940 assert(Output.isFilename() && "Unexpected lipo output.");
6941 CmdArgs.push_back("-o");
6942 CmdArgs.push_back(Output.getFilename());
6944 assert(Input.isFilename() && "Invalid input.");
6945 CmdArgs.push_back(Input.getFilename());
6947 // asm_final spec is empty.
6949 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
6950 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6953 void darwin::MachOTool::anchor() {}
6955 void darwin::MachOTool::AddMachOArch(const ArgList &Args,
6956 ArgStringList &CmdArgs) const {
6957 StringRef ArchName = getMachOToolChain().getMachOArchName(Args);
6959 // Derived from darwin_arch spec.
6960 CmdArgs.push_back("-arch");
6961 CmdArgs.push_back(Args.MakeArgString(ArchName));
6963 // FIXME: Is this needed anymore?
6964 if (ArchName == "arm")
6965 CmdArgs.push_back("-force_cpusubtype_ALL");
6968 bool darwin::Linker::NeedsTempPath(const InputInfoList &Inputs) const {
6969 // We only need to generate a temp path for LTO if we aren't compiling object
6970 // files. When compiling source files, we run 'dsymutil' after linking. We
6971 // don't run 'dsymutil' when compiling object files.
6972 for (const auto &Input : Inputs)
6973 if (Input.getType() != types::TY_Object)
6979 void darwin::Linker::AddLinkArgs(Compilation &C, const ArgList &Args,
6980 ArgStringList &CmdArgs,
6981 const InputInfoList &Inputs) const {
6982 const Driver &D = getToolChain().getDriver();
6983 const toolchains::MachO &MachOTC = getMachOToolChain();
6985 unsigned Version[3] = {0, 0, 0};
6986 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
6988 if (!Driver::GetReleaseVersion(A->getValue(), Version[0], Version[1],
6989 Version[2], HadExtra) ||
6991 D.Diag(diag::err_drv_invalid_version_number) << A->getAsString(Args);
6994 // Newer linkers support -demangle. Pass it if supported and not disabled by
6996 if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
6997 CmdArgs.push_back("-demangle");
6999 if (Args.hasArg(options::OPT_rdynamic) && Version[0] >= 137)
7000 CmdArgs.push_back("-export_dynamic");
7002 // If we are using App Extension restrictions, pass a flag to the linker
7003 // telling it that the compiled code has been audited.
7004 if (Args.hasFlag(options::OPT_fapplication_extension,
7005 options::OPT_fno_application_extension, false))
7006 CmdArgs.push_back("-application_extension");
7008 if (D.isUsingLTO()) {
7009 // If we are using LTO, then automatically create a temporary file path for
7010 // the linker to use, so that it's lifetime will extend past a possible
7012 if (Version[0] >= 116 && NeedsTempPath(Inputs)) {
7013 const char *TmpPath = C.getArgs().MakeArgString(
7014 D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object)));
7015 C.addTempFile(TmpPath);
7016 CmdArgs.push_back("-object_path_lto");
7017 CmdArgs.push_back(TmpPath);
7020 // Use -lto_library option to specify the libLTO.dylib path. Try to find
7021 // it in clang installed libraries. If not found, the option is not used
7022 // and 'ld' will use its default mechanism to search for libLTO.dylib.
7023 if (Version[0] >= 133) {
7024 // Search for libLTO in <InstalledDir>/../lib/libLTO.dylib
7025 StringRef P = llvm::sys::path::parent_path(D.getInstalledDir());
7026 SmallString<128> LibLTOPath(P);
7027 llvm::sys::path::append(LibLTOPath, "lib");
7028 llvm::sys::path::append(LibLTOPath, "libLTO.dylib");
7029 if (llvm::sys::fs::exists(LibLTOPath)) {
7030 CmdArgs.push_back("-lto_library");
7031 CmdArgs.push_back(C.getArgs().MakeArgString(LibLTOPath));
7033 D.Diag(diag::warn_drv_lto_libpath);
7038 // Derived from the "link" spec.
7039 Args.AddAllArgs(CmdArgs, options::OPT_static);
7040 if (!Args.hasArg(options::OPT_static))
7041 CmdArgs.push_back("-dynamic");
7042 if (Args.hasArg(options::OPT_fgnu_runtime)) {
7043 // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu
7044 // here. How do we wish to handle such things?
7047 if (!Args.hasArg(options::OPT_dynamiclib)) {
7048 AddMachOArch(Args, CmdArgs);
7049 // FIXME: Why do this only on this path?
7050 Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL);
7052 Args.AddLastArg(CmdArgs, options::OPT_bundle);
7053 Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader);
7054 Args.AddAllArgs(CmdArgs, options::OPT_client__name);
7057 if ((A = Args.getLastArg(options::OPT_compatibility__version)) ||
7058 (A = Args.getLastArg(options::OPT_current__version)) ||
7059 (A = Args.getLastArg(options::OPT_install__name)))
7060 D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
7063 Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace);
7064 Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs);
7065 Args.AddLastArg(CmdArgs, options::OPT_private__bundle);
7067 CmdArgs.push_back("-dylib");
7070 if ((A = Args.getLastArg(options::OPT_bundle)) ||
7071 (A = Args.getLastArg(options::OPT_bundle__loader)) ||
7072 (A = Args.getLastArg(options::OPT_client__name)) ||
7073 (A = Args.getLastArg(options::OPT_force__flat__namespace)) ||
7074 (A = Args.getLastArg(options::OPT_keep__private__externs)) ||
7075 (A = Args.getLastArg(options::OPT_private__bundle)))
7076 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
7079 Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version,
7080 "-dylib_compatibility_version");
7081 Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version,
7082 "-dylib_current_version");
7084 AddMachOArch(Args, CmdArgs);
7086 Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name,
7087 "-dylib_install_name");
7090 Args.AddLastArg(CmdArgs, options::OPT_all__load);
7091 Args.AddAllArgs(CmdArgs, options::OPT_allowable__client);
7092 Args.AddLastArg(CmdArgs, options::OPT_bind__at__load);
7093 if (MachOTC.isTargetIOSBased())
7094 Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal);
7095 Args.AddLastArg(CmdArgs, options::OPT_dead__strip);
7096 Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms);
7097 Args.AddAllArgs(CmdArgs, options::OPT_dylib__file);
7098 Args.AddLastArg(CmdArgs, options::OPT_dynamic);
7099 Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list);
7100 Args.AddLastArg(CmdArgs, options::OPT_flat__namespace);
7101 Args.AddAllArgs(CmdArgs, options::OPT_force__load);
7102 Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names);
7103 Args.AddAllArgs(CmdArgs, options::OPT_image__base);
7104 Args.AddAllArgs(CmdArgs, options::OPT_init);
7106 // Add the deployment target.
7107 MachOTC.addMinVersionArgs(Args, CmdArgs);
7109 Args.AddLastArg(CmdArgs, options::OPT_nomultidefs);
7110 Args.AddLastArg(CmdArgs, options::OPT_multi__module);
7111 Args.AddLastArg(CmdArgs, options::OPT_single__module);
7112 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined);
7113 Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused);
7116 Args.getLastArg(options::OPT_fpie, options::OPT_fPIE,
7117 options::OPT_fno_pie, options::OPT_fno_PIE)) {
7118 if (A->getOption().matches(options::OPT_fpie) ||
7119 A->getOption().matches(options::OPT_fPIE))
7120 CmdArgs.push_back("-pie");
7122 CmdArgs.push_back("-no_pie");
7125 Args.AddLastArg(CmdArgs, options::OPT_prebind);
7126 Args.AddLastArg(CmdArgs, options::OPT_noprebind);
7127 Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding);
7128 Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules);
7129 Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs);
7130 Args.AddAllArgs(CmdArgs, options::OPT_sectcreate);
7131 Args.AddAllArgs(CmdArgs, options::OPT_sectorder);
7132 Args.AddAllArgs(CmdArgs, options::OPT_seg1addr);
7133 Args.AddAllArgs(CmdArgs, options::OPT_segprot);
7134 Args.AddAllArgs(CmdArgs, options::OPT_segaddr);
7135 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr);
7136 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr);
7137 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table);
7138 Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename);
7139 Args.AddAllArgs(CmdArgs, options::OPT_sub__library);
7140 Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella);
7142 // Give --sysroot= preference, over the Apple specific behavior to also use
7143 // --isysroot as the syslibroot.
7144 StringRef sysroot = C.getSysRoot();
7145 if (sysroot != "") {
7146 CmdArgs.push_back("-syslibroot");
7147 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
7148 } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) {
7149 CmdArgs.push_back("-syslibroot");
7150 CmdArgs.push_back(A->getValue());
7153 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace);
7154 Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints);
7155 Args.AddAllArgs(CmdArgs, options::OPT_umbrella);
7156 Args.AddAllArgs(CmdArgs, options::OPT_undefined);
7157 Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list);
7158 Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches);
7159 Args.AddLastArg(CmdArgs, options::OPT_X_Flag);
7160 Args.AddAllArgs(CmdArgs, options::OPT_y);
7161 Args.AddLastArg(CmdArgs, options::OPT_w);
7162 Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size);
7163 Args.AddAllArgs(CmdArgs, options::OPT_segs__read__);
7164 Args.AddLastArg(CmdArgs, options::OPT_seglinkedit);
7165 Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit);
7166 Args.AddAllArgs(CmdArgs, options::OPT_sectalign);
7167 Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols);
7168 Args.AddAllArgs(CmdArgs, options::OPT_segcreate);
7169 Args.AddLastArg(CmdArgs, options::OPT_whyload);
7170 Args.AddLastArg(CmdArgs, options::OPT_whatsloaded);
7171 Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name);
7172 Args.AddLastArg(CmdArgs, options::OPT_dylinker);
7173 Args.AddLastArg(CmdArgs, options::OPT_Mach);
7176 void darwin::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7177 const InputInfo &Output,
7178 const InputInfoList &Inputs,
7179 const ArgList &Args,
7180 const char *LinkingOutput) const {
7181 assert(Output.getType() == types::TY_Image && "Invalid linker output type.");
7183 // If the number of arguments surpasses the system limits, we will encode the
7184 // input files in a separate file, shortening the command line. To this end,
7185 // build a list of input file names that can be passed via a file with the
7186 // -filelist linker option.
7187 llvm::opt::ArgStringList InputFileList;
7189 // The logic here is derived from gcc's behavior; most of which
7190 // comes from specs (starting with link_command). Consult gcc for
7191 // more information.
7192 ArgStringList CmdArgs;
7194 /// Hack(tm) to ignore linking errors when we are doing ARC migration.
7195 if (Args.hasArg(options::OPT_ccc_arcmt_check,
7196 options::OPT_ccc_arcmt_migrate)) {
7197 for (const auto &Arg : Args)
7200 Args.MakeArgString(getToolChain().GetProgramPath("touch"));
7201 CmdArgs.push_back(Output.getFilename());
7202 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, None));
7206 // I'm not sure why this particular decomposition exists in gcc, but
7207 // we follow suite for ease of comparison.
7208 AddLinkArgs(C, Args, CmdArgs, Inputs);
7210 // It seems that the 'e' option is completely ignored for dynamic executables
7211 // (the default), and with static executables, the last one wins, as expected.
7212 Args.AddAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
7213 options::OPT_Z_Flag, options::OPT_u_Group,
7214 options::OPT_e, options::OPT_r});
7216 // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
7217 // members of static archive libraries which implement Objective-C classes or
7219 if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX))
7220 CmdArgs.push_back("-ObjC");
7222 CmdArgs.push_back("-o");
7223 CmdArgs.push_back(Output.getFilename());
7225 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles))
7226 getMachOToolChain().addStartObjectFileArgs(Args, CmdArgs);
7228 // SafeStack requires its own runtime libraries
7229 // These libraries should be linked first, to make sure the
7230 // __safestack_init constructor executes before everything else
7231 if (getToolChain().getSanitizerArgs().needsSafeStackRt()) {
7232 getMachOToolChain().AddLinkRuntimeLib(Args, CmdArgs,
7233 "libclang_rt.safestack_osx.a",
7234 /*AlwaysLink=*/true);
7237 Args.AddAllArgs(CmdArgs, options::OPT_L);
7239 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7240 // Build the input file for -filelist (list of linker input files) in case we
7242 for (const auto &II : Inputs) {
7243 if (!II.isFilename()) {
7244 // This is a linker input argument.
7245 // We cannot mix input arguments and file names in a -filelist input, thus
7246 // we prematurely stop our list (remaining files shall be passed as
7248 if (InputFileList.size() > 0)
7254 InputFileList.push_back(II.getFilename());
7257 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs))
7258 addOpenMPRuntime(CmdArgs, getToolChain(), Args);
7260 if (isObjCRuntimeLinked(Args) &&
7261 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7262 // We use arclite library for both ARC and subscripting support.
7263 getMachOToolChain().AddLinkARCArgs(Args, CmdArgs);
7265 CmdArgs.push_back("-framework");
7266 CmdArgs.push_back("Foundation");
7268 CmdArgs.push_back("-lobjc");
7271 if (LinkingOutput) {
7272 CmdArgs.push_back("-arch_multiple");
7273 CmdArgs.push_back("-final_output");
7274 CmdArgs.push_back(LinkingOutput);
7277 if (Args.hasArg(options::OPT_fnested_functions))
7278 CmdArgs.push_back("-allow_stack_execute");
7280 getMachOToolChain().addProfileRTLibs(Args, CmdArgs);
7282 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7283 if (getToolChain().getDriver().CCCIsCXX())
7284 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7286 // link_ssp spec is empty.
7288 // Let the tool chain choose which runtime library to link.
7289 getMachOToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs);
7292 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7293 // endfile_spec is empty.
7296 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
7297 Args.AddAllArgs(CmdArgs, options::OPT_F);
7299 // -iframework should be forwarded as -F.
7300 for (const Arg *A : Args.filtered(options::OPT_iframework))
7301 CmdArgs.push_back(Args.MakeArgString(std::string("-F") + A->getValue()));
7303 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7304 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
7305 if (A->getValue() == StringRef("Accelerate")) {
7306 CmdArgs.push_back("-framework");
7307 CmdArgs.push_back("Accelerate");
7312 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7313 std::unique_ptr<Command> Cmd =
7314 llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs);
7315 Cmd->setInputFileList(std::move(InputFileList));
7316 C.addCommand(std::move(Cmd));
7319 void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA,
7320 const InputInfo &Output,
7321 const InputInfoList &Inputs,
7322 const ArgList &Args,
7323 const char *LinkingOutput) const {
7324 ArgStringList CmdArgs;
7326 CmdArgs.push_back("-create");
7327 assert(Output.isFilename() && "Unexpected lipo output.");
7329 CmdArgs.push_back("-output");
7330 CmdArgs.push_back(Output.getFilename());
7332 for (const auto &II : Inputs) {
7333 assert(II.isFilename() && "Unexpected lipo input.");
7334 CmdArgs.push_back(II.getFilename());
7337 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("lipo"));
7338 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7341 void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA,
7342 const InputInfo &Output,
7343 const InputInfoList &Inputs,
7344 const ArgList &Args,
7345 const char *LinkingOutput) const {
7346 ArgStringList CmdArgs;
7348 CmdArgs.push_back("-o");
7349 CmdArgs.push_back(Output.getFilename());
7351 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
7352 const InputInfo &Input = Inputs[0];
7353 assert(Input.isFilename() && "Unexpected dsymutil input.");
7354 CmdArgs.push_back(Input.getFilename());
7357 Args.MakeArgString(getToolChain().GetProgramPath("dsymutil"));
7358 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7361 void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA,
7362 const InputInfo &Output,
7363 const InputInfoList &Inputs,
7364 const ArgList &Args,
7365 const char *LinkingOutput) const {
7366 ArgStringList CmdArgs;
7367 CmdArgs.push_back("--verify");
7368 CmdArgs.push_back("--debug-info");
7369 CmdArgs.push_back("--eh-frame");
7370 CmdArgs.push_back("--quiet");
7372 assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
7373 const InputInfo &Input = Inputs[0];
7374 assert(Input.isFilename() && "Unexpected verify input");
7376 // Grabbing the output of the earlier dsymutil run.
7377 CmdArgs.push_back(Input.getFilename());
7380 Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump"));
7381 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7384 void solaris::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7385 const InputInfo &Output,
7386 const InputInfoList &Inputs,
7387 const ArgList &Args,
7388 const char *LinkingOutput) const {
7389 claimNoWarnArgs(Args);
7390 ArgStringList CmdArgs;
7392 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7394 CmdArgs.push_back("-o");
7395 CmdArgs.push_back(Output.getFilename());
7397 for (const auto &II : Inputs)
7398 CmdArgs.push_back(II.getFilename());
7400 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7401 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7404 void solaris::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7405 const InputInfo &Output,
7406 const InputInfoList &Inputs,
7407 const ArgList &Args,
7408 const char *LinkingOutput) const {
7409 ArgStringList CmdArgs;
7411 // Demangle C++ names in errors
7412 CmdArgs.push_back("-C");
7414 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
7415 CmdArgs.push_back("-e");
7416 CmdArgs.push_back("_start");
7419 if (Args.hasArg(options::OPT_static)) {
7420 CmdArgs.push_back("-Bstatic");
7421 CmdArgs.push_back("-dn");
7423 CmdArgs.push_back("-Bdynamic");
7424 if (Args.hasArg(options::OPT_shared)) {
7425 CmdArgs.push_back("-shared");
7427 CmdArgs.push_back("--dynamic-linker");
7429 Args.MakeArgString(getToolChain().GetFilePath("ld.so.1")));
7433 if (Output.isFilename()) {
7434 CmdArgs.push_back("-o");
7435 CmdArgs.push_back(Output.getFilename());
7437 assert(Output.isNothing() && "Invalid output.");
7440 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7441 if (!Args.hasArg(options::OPT_shared))
7443 Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
7445 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
7447 Args.MakeArgString(getToolChain().GetFilePath("values-Xa.o")));
7449 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7452 getToolChain().AddFilePathLibArgs(Args, CmdArgs);
7454 Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
7455 options::OPT_e, options::OPT_r});
7457 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7459 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7460 if (getToolChain().getDriver().CCCIsCXX())
7461 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7462 CmdArgs.push_back("-lgcc_s");
7463 CmdArgs.push_back("-lc");
7464 if (!Args.hasArg(options::OPT_shared)) {
7465 CmdArgs.push_back("-lgcc");
7466 CmdArgs.push_back("-lm");
7470 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7472 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7474 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
7476 getToolChain().addProfileRTLibs(Args, CmdArgs);
7478 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7479 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7482 void openbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7483 const InputInfo &Output,
7484 const InputInfoList &Inputs,
7485 const ArgList &Args,
7486 const char *LinkingOutput) const {
7487 claimNoWarnArgs(Args);
7488 ArgStringList CmdArgs;
7490 switch (getToolChain().getArch()) {
7491 case llvm::Triple::x86:
7492 // When building 32-bit code on OpenBSD/amd64, we have to explicitly
7493 // instruct as in the base system to assemble 32-bit code.
7494 CmdArgs.push_back("--32");
7497 case llvm::Triple::ppc:
7498 CmdArgs.push_back("-mppc");
7499 CmdArgs.push_back("-many");
7502 case llvm::Triple::sparc:
7503 case llvm::Triple::sparcel: {
7504 CmdArgs.push_back("-32");
7505 std::string CPU = getCPUName(Args, getToolChain().getTriple());
7506 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
7507 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7511 case llvm::Triple::sparcv9: {
7512 CmdArgs.push_back("-64");
7513 std::string CPU = getCPUName(Args, getToolChain().getTriple());
7514 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
7515 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7519 case llvm::Triple::mips64:
7520 case llvm::Triple::mips64el: {
7523 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7525 CmdArgs.push_back("-mabi");
7526 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
7528 if (getToolChain().getArch() == llvm::Triple::mips64)
7529 CmdArgs.push_back("-EB");
7531 CmdArgs.push_back("-EL");
7533 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7541 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7543 CmdArgs.push_back("-o");
7544 CmdArgs.push_back(Output.getFilename());
7546 for (const auto &II : Inputs)
7547 CmdArgs.push_back(II.getFilename());
7549 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7550 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7553 void openbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7554 const InputInfo &Output,
7555 const InputInfoList &Inputs,
7556 const ArgList &Args,
7557 const char *LinkingOutput) const {
7558 const Driver &D = getToolChain().getDriver();
7559 ArgStringList CmdArgs;
7561 // Silence warning for "clang -g foo.o -o foo"
7562 Args.ClaimAllArgs(options::OPT_g_Group);
7563 // and "clang -emit-llvm foo.o -o foo"
7564 Args.ClaimAllArgs(options::OPT_emit_llvm);
7565 // and for "clang -w foo.o -o foo". Other warning options are already
7566 // handled somewhere else.
7567 Args.ClaimAllArgs(options::OPT_w);
7569 if (getToolChain().getArch() == llvm::Triple::mips64)
7570 CmdArgs.push_back("-EB");
7571 else if (getToolChain().getArch() == llvm::Triple::mips64el)
7572 CmdArgs.push_back("-EL");
7574 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
7575 CmdArgs.push_back("-e");
7576 CmdArgs.push_back("__start");
7579 if (Args.hasArg(options::OPT_static)) {
7580 CmdArgs.push_back("-Bstatic");
7582 if (Args.hasArg(options::OPT_rdynamic))
7583 CmdArgs.push_back("-export-dynamic");
7584 CmdArgs.push_back("--eh-frame-hdr");
7585 CmdArgs.push_back("-Bdynamic");
7586 if (Args.hasArg(options::OPT_shared)) {
7587 CmdArgs.push_back("-shared");
7589 CmdArgs.push_back("-dynamic-linker");
7590 CmdArgs.push_back("/usr/libexec/ld.so");
7594 if (Args.hasArg(options::OPT_nopie))
7595 CmdArgs.push_back("-nopie");
7597 if (Output.isFilename()) {
7598 CmdArgs.push_back("-o");
7599 CmdArgs.push_back(Output.getFilename());
7601 assert(Output.isNothing() && "Invalid output.");
7604 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7605 if (!Args.hasArg(options::OPT_shared)) {
7606 if (Args.hasArg(options::OPT_pg))
7608 Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
7611 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
7613 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7616 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
7620 std::string Triple = getToolChain().getTripleString();
7621 if (Triple.substr(0, 6) == "x86_64")
7622 Triple.replace(0, 6, "amd64");
7624 Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple + "/4.2.1"));
7626 Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
7627 options::OPT_e, options::OPT_s, options::OPT_t,
7628 options::OPT_Z_Flag, options::OPT_r});
7630 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7632 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7634 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7635 if (Args.hasArg(options::OPT_pg))
7636 CmdArgs.push_back("-lm_p");
7638 CmdArgs.push_back("-lm");
7641 // FIXME: For some reason GCC passes -lgcc before adding
7642 // the default system libraries. Just mimic this for now.
7643 CmdArgs.push_back("-lgcc");
7645 if (Args.hasArg(options::OPT_pthread)) {
7646 if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
7647 CmdArgs.push_back("-lpthread_p");
7649 CmdArgs.push_back("-lpthread");
7652 if (!Args.hasArg(options::OPT_shared)) {
7653 if (Args.hasArg(options::OPT_pg))
7654 CmdArgs.push_back("-lc_p");
7656 CmdArgs.push_back("-lc");
7659 CmdArgs.push_back("-lgcc");
7662 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7663 if (!Args.hasArg(options::OPT_shared))
7665 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7668 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
7671 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7672 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7675 void bitrig::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7676 const InputInfo &Output,
7677 const InputInfoList &Inputs,
7678 const ArgList &Args,
7679 const char *LinkingOutput) const {
7680 claimNoWarnArgs(Args);
7681 ArgStringList CmdArgs;
7683 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7685 CmdArgs.push_back("-o");
7686 CmdArgs.push_back(Output.getFilename());
7688 for (const auto &II : Inputs)
7689 CmdArgs.push_back(II.getFilename());
7691 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7692 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7695 void bitrig::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7696 const InputInfo &Output,
7697 const InputInfoList &Inputs,
7698 const ArgList &Args,
7699 const char *LinkingOutput) const {
7700 const Driver &D = getToolChain().getDriver();
7701 ArgStringList CmdArgs;
7703 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_shared)) {
7704 CmdArgs.push_back("-e");
7705 CmdArgs.push_back("__start");
7708 if (Args.hasArg(options::OPT_static)) {
7709 CmdArgs.push_back("-Bstatic");
7711 if (Args.hasArg(options::OPT_rdynamic))
7712 CmdArgs.push_back("-export-dynamic");
7713 CmdArgs.push_back("--eh-frame-hdr");
7714 CmdArgs.push_back("-Bdynamic");
7715 if (Args.hasArg(options::OPT_shared)) {
7716 CmdArgs.push_back("-shared");
7718 CmdArgs.push_back("-dynamic-linker");
7719 CmdArgs.push_back("/usr/libexec/ld.so");
7723 if (Output.isFilename()) {
7724 CmdArgs.push_back("-o");
7725 CmdArgs.push_back(Output.getFilename());
7727 assert(Output.isNothing() && "Invalid output.");
7730 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7731 if (!Args.hasArg(options::OPT_shared)) {
7732 if (Args.hasArg(options::OPT_pg))
7734 Args.MakeArgString(getToolChain().GetFilePath("gcrt0.o")));
7737 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
7739 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
7742 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
7746 Args.AddAllArgs(CmdArgs,
7747 {options::OPT_L, options::OPT_T_Group, options::OPT_e});
7749 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
7751 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
7753 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
7754 if (Args.hasArg(options::OPT_pg))
7755 CmdArgs.push_back("-lm_p");
7757 CmdArgs.push_back("-lm");
7760 if (Args.hasArg(options::OPT_pthread)) {
7761 if (!Args.hasArg(options::OPT_shared) && Args.hasArg(options::OPT_pg))
7762 CmdArgs.push_back("-lpthread_p");
7764 CmdArgs.push_back("-lpthread");
7767 if (!Args.hasArg(options::OPT_shared)) {
7768 if (Args.hasArg(options::OPT_pg))
7769 CmdArgs.push_back("-lc_p");
7771 CmdArgs.push_back("-lc");
7775 switch (getToolChain().getArch()) {
7776 case llvm::Triple::arm:
7779 case llvm::Triple::x86:
7782 case llvm::Triple::x86_64:
7786 llvm_unreachable("Unsupported architecture");
7788 CmdArgs.push_back(Args.MakeArgString("-lclang_rt." + MyArch));
7791 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7792 if (!Args.hasArg(options::OPT_shared))
7794 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
7797 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
7800 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
7801 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7804 void freebsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
7805 const InputInfo &Output,
7806 const InputInfoList &Inputs,
7807 const ArgList &Args,
7808 const char *LinkingOutput) const {
7809 claimNoWarnArgs(Args);
7810 ArgStringList CmdArgs;
7812 // When building 32-bit code on FreeBSD/amd64, we have to explicitly
7813 // instruct as in the base system to assemble 32-bit code.
7814 switch (getToolChain().getArch()) {
7817 case llvm::Triple::x86:
7818 CmdArgs.push_back("--32");
7820 case llvm::Triple::ppc:
7821 CmdArgs.push_back("-a32");
7823 case llvm::Triple::mips:
7824 case llvm::Triple::mipsel:
7825 case llvm::Triple::mips64:
7826 case llvm::Triple::mips64el: {
7829 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
7831 CmdArgs.push_back("-march");
7832 CmdArgs.push_back(CPUName.data());
7834 CmdArgs.push_back("-mabi");
7835 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
7837 if (getToolChain().getArch() == llvm::Triple::mips ||
7838 getToolChain().getArch() == llvm::Triple::mips64)
7839 CmdArgs.push_back("-EB");
7841 CmdArgs.push_back("-EL");
7843 if (Arg *A = Args.getLastArg(options::OPT_G)) {
7844 StringRef v = A->getValue();
7845 CmdArgs.push_back(Args.MakeArgString("-G" + v));
7849 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7852 case llvm::Triple::arm:
7853 case llvm::Triple::armeb:
7854 case llvm::Triple::thumb:
7855 case llvm::Triple::thumbeb: {
7856 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
7858 if (ABI == arm::FloatABI::Hard)
7859 CmdArgs.push_back("-mfpu=vfp");
7861 CmdArgs.push_back("-mfpu=softvfp");
7863 switch (getToolChain().getTriple().getEnvironment()) {
7864 case llvm::Triple::GNUEABIHF:
7865 case llvm::Triple::GNUEABI:
7866 case llvm::Triple::EABI:
7867 CmdArgs.push_back("-meabi=5");
7871 CmdArgs.push_back("-matpcs");
7875 case llvm::Triple::sparc:
7876 case llvm::Triple::sparcel:
7877 case llvm::Triple::sparcv9: {
7878 std::string CPU = getCPUName(Args, getToolChain().getTriple());
7879 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
7880 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
7885 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
7887 CmdArgs.push_back("-o");
7888 CmdArgs.push_back(Output.getFilename());
7890 for (const auto &II : Inputs)
7891 CmdArgs.push_back(II.getFilename());
7893 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
7894 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
7897 void freebsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
7898 const InputInfo &Output,
7899 const InputInfoList &Inputs,
7900 const ArgList &Args,
7901 const char *LinkingOutput) const {
7902 const toolchains::FreeBSD &ToolChain =
7903 static_cast<const toolchains::FreeBSD &>(getToolChain());
7904 const Driver &D = ToolChain.getDriver();
7905 const llvm::Triple::ArchType Arch = ToolChain.getArch();
7907 !Args.hasArg(options::OPT_shared) &&
7908 (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
7909 ArgStringList CmdArgs;
7911 // Silence warning for "clang -g foo.o -o foo"
7912 Args.ClaimAllArgs(options::OPT_g_Group);
7913 // and "clang -emit-llvm foo.o -o foo"
7914 Args.ClaimAllArgs(options::OPT_emit_llvm);
7915 // and for "clang -w foo.o -o foo". Other warning options are already
7916 // handled somewhere else.
7917 Args.ClaimAllArgs(options::OPT_w);
7919 if (!D.SysRoot.empty())
7920 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
7923 CmdArgs.push_back("-pie");
7925 if (Args.hasArg(options::OPT_static)) {
7926 CmdArgs.push_back("-Bstatic");
7928 if (Args.hasArg(options::OPT_rdynamic))
7929 CmdArgs.push_back("-export-dynamic");
7930 CmdArgs.push_back("--eh-frame-hdr");
7931 if (Args.hasArg(options::OPT_shared)) {
7932 CmdArgs.push_back("-Bshareable");
7934 CmdArgs.push_back("-dynamic-linker");
7935 CmdArgs.push_back("/libexec/ld-elf.so.1");
7937 if (ToolChain.getTriple().getOSMajorVersion() >= 9) {
7938 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc ||
7939 Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
7940 CmdArgs.push_back("--hash-style=both");
7943 CmdArgs.push_back("--enable-new-dtags");
7946 // When building 32-bit code on FreeBSD/amd64, we have to explicitly
7947 // instruct ld in the base system to link 32-bit code.
7948 if (Arch == llvm::Triple::x86) {
7949 CmdArgs.push_back("-m");
7950 CmdArgs.push_back("elf_i386_fbsd");
7953 if (Arch == llvm::Triple::ppc) {
7954 CmdArgs.push_back("-m");
7955 CmdArgs.push_back("elf32ppc_fbsd");
7958 if (Arg *A = Args.getLastArg(options::OPT_G)) {
7959 if (ToolChain.getArch() == llvm::Triple::mips ||
7960 ToolChain.getArch() == llvm::Triple::mipsel ||
7961 ToolChain.getArch() == llvm::Triple::mips64 ||
7962 ToolChain.getArch() == llvm::Triple::mips64el) {
7963 StringRef v = A->getValue();
7964 CmdArgs.push_back(Args.MakeArgString("-G" + v));
7969 if (Output.isFilename()) {
7970 CmdArgs.push_back("-o");
7971 CmdArgs.push_back(Output.getFilename());
7973 assert(Output.isNothing() && "Invalid output.");
7976 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
7977 const char *crt1 = nullptr;
7978 if (!Args.hasArg(options::OPT_shared)) {
7979 if (Args.hasArg(options::OPT_pg))
7987 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
7989 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
7991 const char *crtbegin = nullptr;
7992 if (Args.hasArg(options::OPT_static))
7993 crtbegin = "crtbeginT.o";
7994 else if (Args.hasArg(options::OPT_shared) || IsPIE)
7995 crtbegin = "crtbeginS.o";
7997 crtbegin = "crtbegin.o";
7999 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
8002 Args.AddAllArgs(CmdArgs, options::OPT_L);
8003 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
8004 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8005 Args.AddAllArgs(CmdArgs, options::OPT_e);
8006 Args.AddAllArgs(CmdArgs, options::OPT_s);
8007 Args.AddAllArgs(CmdArgs, options::OPT_t);
8008 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
8009 Args.AddAllArgs(CmdArgs, options::OPT_r);
8012 AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
8014 bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
8015 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
8017 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8018 addOpenMPRuntime(CmdArgs, ToolChain, Args);
8020 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
8021 if (Args.hasArg(options::OPT_pg))
8022 CmdArgs.push_back("-lm_p");
8024 CmdArgs.push_back("-lm");
8026 if (NeedsSanitizerDeps)
8027 linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
8028 // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
8029 // the default system libraries. Just mimic this for now.
8030 if (Args.hasArg(options::OPT_pg))
8031 CmdArgs.push_back("-lgcc_p");
8033 CmdArgs.push_back("-lgcc");
8034 if (Args.hasArg(options::OPT_static)) {
8035 CmdArgs.push_back("-lgcc_eh");
8036 } else if (Args.hasArg(options::OPT_pg)) {
8037 CmdArgs.push_back("-lgcc_eh_p");
8039 CmdArgs.push_back("--as-needed");
8040 CmdArgs.push_back("-lgcc_s");
8041 CmdArgs.push_back("--no-as-needed");
8044 if (Args.hasArg(options::OPT_pthread)) {
8045 if (Args.hasArg(options::OPT_pg))
8046 CmdArgs.push_back("-lpthread_p");
8048 CmdArgs.push_back("-lpthread");
8051 if (Args.hasArg(options::OPT_pg)) {
8052 if (Args.hasArg(options::OPT_shared))
8053 CmdArgs.push_back("-lc");
8055 CmdArgs.push_back("-lc_p");
8056 CmdArgs.push_back("-lgcc_p");
8058 CmdArgs.push_back("-lc");
8059 CmdArgs.push_back("-lgcc");
8062 if (Args.hasArg(options::OPT_static)) {
8063 CmdArgs.push_back("-lgcc_eh");
8064 } else if (Args.hasArg(options::OPT_pg)) {
8065 CmdArgs.push_back("-lgcc_eh_p");
8067 CmdArgs.push_back("--as-needed");
8068 CmdArgs.push_back("-lgcc_s");
8069 CmdArgs.push_back("--no-as-needed");
8073 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8074 if (Args.hasArg(options::OPT_shared) || IsPIE)
8075 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
8077 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
8078 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8081 ToolChain.addProfileRTLibs(Args, CmdArgs);
8083 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8084 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8087 void netbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8088 const InputInfo &Output,
8089 const InputInfoList &Inputs,
8090 const ArgList &Args,
8091 const char *LinkingOutput) const {
8092 claimNoWarnArgs(Args);
8093 ArgStringList CmdArgs;
8095 // GNU as needs different flags for creating the correct output format
8096 // on architectures with different ABIs or optional feature sets.
8097 switch (getToolChain().getArch()) {
8098 case llvm::Triple::x86:
8099 CmdArgs.push_back("--32");
8101 case llvm::Triple::arm:
8102 case llvm::Triple::armeb:
8103 case llvm::Triple::thumb:
8104 case llvm::Triple::thumbeb: {
8105 StringRef MArch, MCPU;
8106 getARMArchCPUFromArgs(Args, MArch, MCPU, /*FromAs*/ true);
8108 arm::getARMTargetCPU(MCPU, MArch, getToolChain().getTriple());
8109 CmdArgs.push_back(Args.MakeArgString("-mcpu=" + Arch));
8113 case llvm::Triple::mips:
8114 case llvm::Triple::mipsel:
8115 case llvm::Triple::mips64:
8116 case llvm::Triple::mips64el: {
8119 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8121 CmdArgs.push_back("-march");
8122 CmdArgs.push_back(CPUName.data());
8124 CmdArgs.push_back("-mabi");
8125 CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data());
8127 if (getToolChain().getArch() == llvm::Triple::mips ||
8128 getToolChain().getArch() == llvm::Triple::mips64)
8129 CmdArgs.push_back("-EB");
8131 CmdArgs.push_back("-EL");
8133 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8137 case llvm::Triple::sparc:
8138 case llvm::Triple::sparcel: {
8139 CmdArgs.push_back("-32");
8140 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8141 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8142 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8146 case llvm::Triple::sparcv9: {
8147 CmdArgs.push_back("-64");
8148 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8149 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8150 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8158 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8160 CmdArgs.push_back("-o");
8161 CmdArgs.push_back(Output.getFilename());
8163 for (const auto &II : Inputs)
8164 CmdArgs.push_back(II.getFilename());
8166 const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as")));
8167 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8170 void netbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8171 const InputInfo &Output,
8172 const InputInfoList &Inputs,
8173 const ArgList &Args,
8174 const char *LinkingOutput) const {
8175 const Driver &D = getToolChain().getDriver();
8176 ArgStringList CmdArgs;
8178 if (!D.SysRoot.empty())
8179 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8181 CmdArgs.push_back("--eh-frame-hdr");
8182 if (Args.hasArg(options::OPT_static)) {
8183 CmdArgs.push_back("-Bstatic");
8185 if (Args.hasArg(options::OPT_rdynamic))
8186 CmdArgs.push_back("-export-dynamic");
8187 if (Args.hasArg(options::OPT_shared)) {
8188 CmdArgs.push_back("-Bshareable");
8190 CmdArgs.push_back("-dynamic-linker");
8191 CmdArgs.push_back("/libexec/ld.elf_so");
8195 // Many NetBSD architectures support more than one ABI.
8196 // Determine the correct emulation for ld.
8197 switch (getToolChain().getArch()) {
8198 case llvm::Triple::x86:
8199 CmdArgs.push_back("-m");
8200 CmdArgs.push_back("elf_i386");
8202 case llvm::Triple::arm:
8203 case llvm::Triple::thumb:
8204 CmdArgs.push_back("-m");
8205 switch (getToolChain().getTriple().getEnvironment()) {
8206 case llvm::Triple::EABI:
8207 case llvm::Triple::GNUEABI:
8208 CmdArgs.push_back("armelf_nbsd_eabi");
8210 case llvm::Triple::EABIHF:
8211 case llvm::Triple::GNUEABIHF:
8212 CmdArgs.push_back("armelf_nbsd_eabihf");
8215 CmdArgs.push_back("armelf_nbsd");
8219 case llvm::Triple::armeb:
8220 case llvm::Triple::thumbeb:
8221 arm::appendEBLinkFlags(
8223 llvm::Triple(getToolChain().ComputeEffectiveClangTriple(Args)));
8224 CmdArgs.push_back("-m");
8225 switch (getToolChain().getTriple().getEnvironment()) {
8226 case llvm::Triple::EABI:
8227 case llvm::Triple::GNUEABI:
8228 CmdArgs.push_back("armelfb_nbsd_eabi");
8230 case llvm::Triple::EABIHF:
8231 case llvm::Triple::GNUEABIHF:
8232 CmdArgs.push_back("armelfb_nbsd_eabihf");
8235 CmdArgs.push_back("armelfb_nbsd");
8239 case llvm::Triple::mips64:
8240 case llvm::Triple::mips64el:
8241 if (mips::hasMipsAbiArg(Args, "32")) {
8242 CmdArgs.push_back("-m");
8243 if (getToolChain().getArch() == llvm::Triple::mips64)
8244 CmdArgs.push_back("elf32btsmip");
8246 CmdArgs.push_back("elf32ltsmip");
8247 } else if (mips::hasMipsAbiArg(Args, "64")) {
8248 CmdArgs.push_back("-m");
8249 if (getToolChain().getArch() == llvm::Triple::mips64)
8250 CmdArgs.push_back("elf64btsmip");
8252 CmdArgs.push_back("elf64ltsmip");
8255 case llvm::Triple::ppc:
8256 CmdArgs.push_back("-m");
8257 CmdArgs.push_back("elf32ppc_nbsd");
8260 case llvm::Triple::ppc64:
8261 case llvm::Triple::ppc64le:
8262 CmdArgs.push_back("-m");
8263 CmdArgs.push_back("elf64ppc");
8266 case llvm::Triple::sparc:
8267 CmdArgs.push_back("-m");
8268 CmdArgs.push_back("elf32_sparc");
8271 case llvm::Triple::sparcv9:
8272 CmdArgs.push_back("-m");
8273 CmdArgs.push_back("elf64_sparc");
8280 if (Output.isFilename()) {
8281 CmdArgs.push_back("-o");
8282 CmdArgs.push_back(Output.getFilename());
8284 assert(Output.isNothing() && "Invalid output.");
8287 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8288 if (!Args.hasArg(options::OPT_shared)) {
8290 Args.MakeArgString(getToolChain().GetFilePath("crt0.o")));
8292 Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8294 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
8297 Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
8299 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
8303 Args.AddAllArgs(CmdArgs, options::OPT_L);
8304 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
8305 Args.AddAllArgs(CmdArgs, options::OPT_e);
8306 Args.AddAllArgs(CmdArgs, options::OPT_s);
8307 Args.AddAllArgs(CmdArgs, options::OPT_t);
8308 Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag);
8309 Args.AddAllArgs(CmdArgs, options::OPT_r);
8311 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
8313 unsigned Major, Minor, Micro;
8314 getToolChain().getTriple().getOSVersion(Major, Minor, Micro);
8315 bool useLibgcc = true;
8316 if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 49) || Major == 0) {
8317 switch (getToolChain().getArch()) {
8318 case llvm::Triple::aarch64:
8319 case llvm::Triple::arm:
8320 case llvm::Triple::armeb:
8321 case llvm::Triple::thumb:
8322 case llvm::Triple::thumbeb:
8323 case llvm::Triple::ppc:
8324 case llvm::Triple::ppc64:
8325 case llvm::Triple::ppc64le:
8326 case llvm::Triple::sparc:
8327 case llvm::Triple::sparcv9:
8328 case llvm::Triple::x86:
8329 case llvm::Triple::x86_64:
8337 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8338 addOpenMPRuntime(CmdArgs, getToolChain(), Args);
8340 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
8341 CmdArgs.push_back("-lm");
8343 if (Args.hasArg(options::OPT_pthread))
8344 CmdArgs.push_back("-lpthread");
8345 CmdArgs.push_back("-lc");
8348 if (Args.hasArg(options::OPT_static)) {
8349 // libgcc_eh depends on libc, so resolve as much as possible,
8350 // pull in any new requirements from libc and then get the rest
8352 CmdArgs.push_back("-lgcc_eh");
8353 CmdArgs.push_back("-lc");
8354 CmdArgs.push_back("-lgcc");
8356 CmdArgs.push_back("-lgcc");
8357 CmdArgs.push_back("--as-needed");
8358 CmdArgs.push_back("-lgcc_s");
8359 CmdArgs.push_back("--no-as-needed");
8364 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8365 if (!Args.hasArg(options::OPT_shared))
8367 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
8370 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
8371 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
8374 getToolChain().addProfileRTLibs(Args, CmdArgs);
8376 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
8377 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8380 void gnutools::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
8381 const InputInfo &Output,
8382 const InputInfoList &Inputs,
8383 const ArgList &Args,
8384 const char *LinkingOutput) const {
8385 claimNoWarnArgs(Args);
8387 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
8388 llvm::Triple Triple = llvm::Triple(TripleStr);
8390 ArgStringList CmdArgs;
8392 llvm::Reloc::Model RelocationModel;
8395 std::tie(RelocationModel, PICLevel, IsPIE) =
8396 ParsePICArgs(getToolChain(), Triple, Args);
8398 switch (getToolChain().getArch()) {
8401 // Add --32/--64 to make sure we get the format we want.
8402 // This is incomplete
8403 case llvm::Triple::x86:
8404 CmdArgs.push_back("--32");
8406 case llvm::Triple::x86_64:
8407 if (getToolChain().getTriple().getEnvironment() == llvm::Triple::GNUX32)
8408 CmdArgs.push_back("--x32");
8410 CmdArgs.push_back("--64");
8412 case llvm::Triple::ppc:
8413 CmdArgs.push_back("-a32");
8414 CmdArgs.push_back("-mppc");
8415 CmdArgs.push_back("-many");
8417 case llvm::Triple::ppc64:
8418 CmdArgs.push_back("-a64");
8419 CmdArgs.push_back("-mppc64");
8420 CmdArgs.push_back("-many");
8422 case llvm::Triple::ppc64le:
8423 CmdArgs.push_back("-a64");
8424 CmdArgs.push_back("-mppc64");
8425 CmdArgs.push_back("-many");
8426 CmdArgs.push_back("-mlittle-endian");
8428 case llvm::Triple::sparc:
8429 case llvm::Triple::sparcel: {
8430 CmdArgs.push_back("-32");
8431 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8432 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8433 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8436 case llvm::Triple::sparcv9: {
8437 CmdArgs.push_back("-64");
8438 std::string CPU = getCPUName(Args, getToolChain().getTriple());
8439 CmdArgs.push_back(getSparcAsmModeForCPU(CPU, getToolChain().getTriple()));
8440 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8443 case llvm::Triple::arm:
8444 case llvm::Triple::armeb:
8445 case llvm::Triple::thumb:
8446 case llvm::Triple::thumbeb: {
8447 const llvm::Triple &Triple2 = getToolChain().getTriple();
8448 switch (Triple2.getSubArch()) {
8449 case llvm::Triple::ARMSubArch_v7:
8450 CmdArgs.push_back("-mfpu=neon");
8452 case llvm::Triple::ARMSubArch_v8:
8453 CmdArgs.push_back("-mfpu=crypto-neon-fp-armv8");
8459 switch (arm::getARMFloatABI(getToolChain(), Args)) {
8460 case arm::FloatABI::Invalid: llvm_unreachable("must have an ABI!");
8461 case arm::FloatABI::Soft:
8462 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=soft"));
8464 case arm::FloatABI::SoftFP:
8465 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=softfp"));
8467 case arm::FloatABI::Hard:
8468 CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=hard"));
8472 Args.AddLastArg(CmdArgs, options::OPT_march_EQ);
8474 // FIXME: remove krait check when GNU tools support krait cpu
8475 // for now replace it with -march=armv7-a to avoid a lower
8476 // march from being picked in the absence of a cpu flag.
8478 if ((A = Args.getLastArg(options::OPT_mcpu_EQ)) &&
8479 StringRef(A->getValue()).lower() == "krait")
8480 CmdArgs.push_back("-march=armv7-a");
8482 Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ);
8483 Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ);
8486 case llvm::Triple::mips:
8487 case llvm::Triple::mipsel:
8488 case llvm::Triple::mips64:
8489 case llvm::Triple::mips64el: {
8492 mips::getMipsCPUAndABI(Args, getToolChain().getTriple(), CPUName, ABIName);
8493 ABIName = getGnuCompatibleMipsABIName(ABIName);
8495 CmdArgs.push_back("-march");
8496 CmdArgs.push_back(CPUName.data());
8498 CmdArgs.push_back("-mabi");
8499 CmdArgs.push_back(ABIName.data());
8501 // -mno-shared should be emitted unless -fpic, -fpie, -fPIC, -fPIE,
8502 // or -mshared (not implemented) is in effect.
8503 if (RelocationModel == llvm::Reloc::Static)
8504 CmdArgs.push_back("-mno-shared");
8506 // LLVM doesn't support -mplt yet and acts as if it is always given.
8507 // However, -mplt has no effect with the N64 ABI.
8508 CmdArgs.push_back(ABIName == "64" ? "-KPIC" : "-call_nonpic");
8510 if (getToolChain().getArch() == llvm::Triple::mips ||
8511 getToolChain().getArch() == llvm::Triple::mips64)
8512 CmdArgs.push_back("-EB");
8514 CmdArgs.push_back("-EL");
8516 if (Arg *A = Args.getLastArg(options::OPT_mnan_EQ)) {
8517 if (StringRef(A->getValue()) == "2008")
8518 CmdArgs.push_back(Args.MakeArgString("-mnan=2008"));
8521 // Add the last -mfp32/-mfpxx/-mfp64 or -mfpxx if it is enabled by default.
8522 if (Arg *A = Args.getLastArg(options::OPT_mfp32, options::OPT_mfpxx,
8523 options::OPT_mfp64)) {
8525 A->render(Args, CmdArgs);
8526 } else if (mips::shouldUseFPXX(
8527 Args, getToolChain().getTriple(), CPUName, ABIName,
8528 getMipsFloatABI(getToolChain().getDriver(), Args)))
8529 CmdArgs.push_back("-mfpxx");
8531 // Pass on -mmips16 or -mno-mips16. However, the assembler equivalent of
8532 // -mno-mips16 is actually -no-mips16.
8534 Args.getLastArg(options::OPT_mips16, options::OPT_mno_mips16)) {
8535 if (A->getOption().matches(options::OPT_mips16)) {
8537 A->render(Args, CmdArgs);
8540 CmdArgs.push_back("-no-mips16");
8544 Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
8545 options::OPT_mno_micromips);
8546 Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
8547 Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
8549 if (Arg *A = Args.getLastArg(options::OPT_mmsa, options::OPT_mno_msa)) {
8550 // Do not use AddLastArg because not all versions of MIPS assembler
8551 // support -mmsa / -mno-msa options.
8552 if (A->getOption().matches(options::OPT_mmsa))
8553 CmdArgs.push_back(Args.MakeArgString("-mmsa"));
8556 Args.AddLastArg(CmdArgs, options::OPT_mhard_float,
8557 options::OPT_msoft_float);
8559 Args.AddLastArg(CmdArgs, options::OPT_mdouble_float,
8560 options::OPT_msingle_float);
8562 Args.AddLastArg(CmdArgs, options::OPT_modd_spreg,
8563 options::OPT_mno_odd_spreg);
8565 AddAssemblerKPIC(getToolChain(), Args, CmdArgs);
8568 case llvm::Triple::systemz: {
8569 // Always pass an -march option, since our default of z10 is later
8570 // than the GNU assembler's default.
8571 StringRef CPUName = getSystemZTargetCPU(Args);
8572 CmdArgs.push_back(Args.MakeArgString("-march=" + CPUName));
8577 Args.AddAllArgs(CmdArgs, options::OPT_I);
8578 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
8580 CmdArgs.push_back("-o");
8581 CmdArgs.push_back(Output.getFilename());
8583 for (const auto &II : Inputs)
8584 CmdArgs.push_back(II.getFilename());
8586 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
8587 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8589 // Handle the debug info splitting at object creation time if we're
8590 // creating an object.
8591 // TODO: Currently only works on linux with newer objcopy.
8592 if (Args.hasArg(options::OPT_gsplit_dwarf) &&
8593 getToolChain().getTriple().isOSLinux())
8594 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
8595 SplitDebugName(Args, Inputs[0]));
8598 static void AddLibgcc(const llvm::Triple &Triple, const Driver &D,
8599 ArgStringList &CmdArgs, const ArgList &Args) {
8600 bool isAndroid = Triple.isAndroid();
8601 bool isCygMing = Triple.isOSCygMing();
8602 bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) ||
8603 Args.hasArg(options::OPT_static);
8605 CmdArgs.push_back("-lgcc");
8607 if (StaticLibgcc || isAndroid) {
8609 CmdArgs.push_back("-lgcc");
8611 if (!D.CCCIsCXX() && !isCygMing)
8612 CmdArgs.push_back("--as-needed");
8613 CmdArgs.push_back("-lgcc_s");
8614 if (!D.CCCIsCXX() && !isCygMing)
8615 CmdArgs.push_back("--no-as-needed");
8618 if (StaticLibgcc && !isAndroid)
8619 CmdArgs.push_back("-lgcc_eh");
8620 else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX())
8621 CmdArgs.push_back("-lgcc");
8623 // According to Android ABI, we have to link with libdl if we are
8624 // linking with non-static libgcc.
8626 // NOTE: This fixes a link error on Android MIPS as well. The non-static
8627 // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl.
8628 if (isAndroid && !StaticLibgcc)
8629 CmdArgs.push_back("-ldl");
8632 static std::string getLinuxDynamicLinker(const ArgList &Args,
8633 const toolchains::Linux &ToolChain) {
8634 const llvm::Triple::ArchType Arch = ToolChain.getArch();
8636 if (ToolChain.getTriple().isAndroid()) {
8637 if (ToolChain.getTriple().isArch64Bit())
8638 return "/system/bin/linker64";
8640 return "/system/bin/linker";
8641 } else if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::sparc ||
8642 Arch == llvm::Triple::sparcel)
8643 return "/lib/ld-linux.so.2";
8644 else if (Arch == llvm::Triple::aarch64)
8645 return "/lib/ld-linux-aarch64.so.1";
8646 else if (Arch == llvm::Triple::aarch64_be)
8647 return "/lib/ld-linux-aarch64_be.so.1";
8648 else if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb) {
8649 if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
8650 arm::getARMFloatABI(ToolChain, Args) == arm::FloatABI::Hard)
8651 return "/lib/ld-linux-armhf.so.3";
8653 return "/lib/ld-linux.so.3";
8654 } else if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb) {
8655 // TODO: check which dynamic linker name.
8656 if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF ||
8657 arm::getARMFloatABI(ToolChain, Args) == arm::FloatABI::Hard)
8658 return "/lib/ld-linux-armhf.so.3";
8660 return "/lib/ld-linux.so.3";
8661 } else if (Arch == llvm::Triple::mips || Arch == llvm::Triple::mipsel ||
8662 Arch == llvm::Triple::mips64 || Arch == llvm::Triple::mips64el) {
8663 std::string LibDir =
8664 "/lib" + mips::getMipsABILibSuffix(Args, ToolChain.getTriple());
8666 bool IsNaN2008 = mips::isNaN2008(Args, ToolChain.getTriple());
8667 if (mips::isUCLibc(Args))
8668 LibName = IsNaN2008 ? "ld-uClibc-mipsn8.so.0" : "ld-uClibc.so.0";
8669 else if (!ToolChain.getTriple().hasEnvironment()) {
8670 bool LE = (ToolChain.getTriple().getArch() == llvm::Triple::mipsel) ||
8671 (ToolChain.getTriple().getArch() == llvm::Triple::mips64el);
8672 LibName = LE ? "ld-musl-mipsel.so.1" : "ld-musl-mips.so.1";
8674 LibName = IsNaN2008 ? "ld-linux-mipsn8.so.1" : "ld.so.1";
8676 return (LibDir + "/" + LibName).str();
8677 } else if (Arch == llvm::Triple::ppc)
8678 return "/lib/ld.so.1";
8679 else if (Arch == llvm::Triple::ppc64) {
8680 if (ppc::hasPPCAbiArg(Args, "elfv2"))
8681 return "/lib64/ld64.so.2";
8682 return "/lib64/ld64.so.1";
8683 } else if (Arch == llvm::Triple::ppc64le) {
8684 if (ppc::hasPPCAbiArg(Args, "elfv1"))
8685 return "/lib64/ld64.so.1";
8686 return "/lib64/ld64.so.2";
8687 } else if (Arch == llvm::Triple::systemz)
8688 return "/lib/ld64.so.1";
8689 else if (Arch == llvm::Triple::sparcv9)
8690 return "/lib64/ld-linux.so.2";
8691 else if (Arch == llvm::Triple::x86_64 &&
8692 ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUX32)
8693 return "/libx32/ld-linux-x32.so.2";
8695 return "/lib64/ld-linux-x86-64.so.2";
8698 static void AddRunTimeLibs(const ToolChain &TC, const Driver &D,
8699 ArgStringList &CmdArgs, const ArgList &Args) {
8700 // Make use of compiler-rt if --rtlib option is used
8701 ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(Args);
8704 case ToolChain::RLT_CompilerRT:
8705 switch (TC.getTriple().getOS()) {
8707 llvm_unreachable("unsupported OS");
8708 case llvm::Triple::Win32:
8709 case llvm::Triple::Linux:
8710 addClangRT(TC, Args, CmdArgs);
8714 case ToolChain::RLT_Libgcc:
8715 AddLibgcc(TC.getTriple(), D, CmdArgs, Args);
8720 static const char *getLDMOption(const llvm::Triple &T, const ArgList &Args) {
8721 switch (T.getArch()) {
8722 case llvm::Triple::x86:
8724 case llvm::Triple::aarch64:
8725 return "aarch64linux";
8726 case llvm::Triple::aarch64_be:
8727 return "aarch64_be_linux";
8728 case llvm::Triple::arm:
8729 case llvm::Triple::thumb:
8730 return "armelf_linux_eabi";
8731 case llvm::Triple::armeb:
8732 case llvm::Triple::thumbeb:
8733 return "armebelf_linux_eabi"; /* TODO: check which NAME. */
8734 case llvm::Triple::ppc:
8735 return "elf32ppclinux";
8736 case llvm::Triple::ppc64:
8738 case llvm::Triple::ppc64le:
8740 case llvm::Triple::sparc:
8741 case llvm::Triple::sparcel:
8742 return "elf32_sparc";
8743 case llvm::Triple::sparcv9:
8744 return "elf64_sparc";
8745 case llvm::Triple::mips:
8746 return "elf32btsmip";
8747 case llvm::Triple::mipsel:
8748 return "elf32ltsmip";
8749 case llvm::Triple::mips64:
8750 if (mips::hasMipsAbiArg(Args, "n32"))
8751 return "elf32btsmipn32";
8752 return "elf64btsmip";
8753 case llvm::Triple::mips64el:
8754 if (mips::hasMipsAbiArg(Args, "n32"))
8755 return "elf32ltsmipn32";
8756 return "elf64ltsmip";
8757 case llvm::Triple::systemz:
8758 return "elf64_s390";
8759 case llvm::Triple::x86_64:
8760 if (T.getEnvironment() == llvm::Triple::GNUX32)
8761 return "elf32_x86_64";
8762 return "elf_x86_64";
8764 llvm_unreachable("Unexpected arch");
8768 void gnutools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
8769 const InputInfo &Output,
8770 const InputInfoList &Inputs,
8771 const ArgList &Args,
8772 const char *LinkingOutput) const {
8773 const toolchains::Linux &ToolChain =
8774 static_cast<const toolchains::Linux &>(getToolChain());
8775 const Driver &D = ToolChain.getDriver();
8777 std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args);
8778 llvm::Triple Triple = llvm::Triple(TripleStr);
8780 const llvm::Triple::ArchType Arch = ToolChain.getArch();
8781 const bool isAndroid = ToolChain.getTriple().isAndroid();
8783 !Args.hasArg(options::OPT_shared) && !Args.hasArg(options::OPT_static) &&
8784 (Args.hasArg(options::OPT_pie) || ToolChain.isPIEDefault());
8785 const bool HasCRTBeginEndFiles =
8786 ToolChain.getTriple().hasEnvironment() ||
8787 (ToolChain.getTriple().getVendor() != llvm::Triple::MipsTechnologies);
8789 ArgStringList CmdArgs;
8791 // Silence warning for "clang -g foo.o -o foo"
8792 Args.ClaimAllArgs(options::OPT_g_Group);
8793 // and "clang -emit-llvm foo.o -o foo"
8794 Args.ClaimAllArgs(options::OPT_emit_llvm);
8795 // and for "clang -w foo.o -o foo". Other warning options are already
8796 // handled somewhere else.
8797 Args.ClaimAllArgs(options::OPT_w);
8799 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
8800 if (llvm::sys::path::filename(Exec) == "lld") {
8801 CmdArgs.push_back("-flavor");
8802 CmdArgs.push_back("old-gnu");
8803 CmdArgs.push_back("-target");
8804 CmdArgs.push_back(Args.MakeArgString(getToolChain().getTripleString()));
8807 if (!D.SysRoot.empty())
8808 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
8811 CmdArgs.push_back("-pie");
8813 if (Args.hasArg(options::OPT_rdynamic))
8814 CmdArgs.push_back("-export-dynamic");
8816 if (Args.hasArg(options::OPT_s))
8817 CmdArgs.push_back("-s");
8819 if (Arch == llvm::Triple::armeb || Arch == llvm::Triple::thumbeb)
8820 arm::appendEBLinkFlags(Args, CmdArgs, Triple);
8822 for (const auto &Opt : ToolChain.ExtraOpts)
8823 CmdArgs.push_back(Opt.c_str());
8825 if (!Args.hasArg(options::OPT_static)) {
8826 CmdArgs.push_back("--eh-frame-hdr");
8829 CmdArgs.push_back("-m");
8830 CmdArgs.push_back(getLDMOption(ToolChain.getTriple(), Args));
8832 if (Args.hasArg(options::OPT_static)) {
8833 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
8834 Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb)
8835 CmdArgs.push_back("-Bstatic");
8837 CmdArgs.push_back("-static");
8838 } else if (Args.hasArg(options::OPT_shared)) {
8839 CmdArgs.push_back("-shared");
8842 if (Arch == llvm::Triple::arm || Arch == llvm::Triple::armeb ||
8843 Arch == llvm::Triple::thumb || Arch == llvm::Triple::thumbeb ||
8844 (!Args.hasArg(options::OPT_static) &&
8845 !Args.hasArg(options::OPT_shared))) {
8846 CmdArgs.push_back("-dynamic-linker");
8847 CmdArgs.push_back(Args.MakeArgString(
8848 D.DyldPrefix + getLinuxDynamicLinker(Args, ToolChain)));
8851 CmdArgs.push_back("-o");
8852 CmdArgs.push_back(Output.getFilename());
8854 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
8856 const char *crt1 = nullptr;
8857 if (!Args.hasArg(options::OPT_shared)) {
8858 if (Args.hasArg(options::OPT_pg))
8866 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
8868 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
8871 const char *crtbegin;
8872 if (Args.hasArg(options::OPT_static))
8873 crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
8874 else if (Args.hasArg(options::OPT_shared))
8875 crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
8877 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
8879 crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
8881 if (HasCRTBeginEndFiles)
8882 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
8884 // Add crtfastmath.o if available and fast math is enabled.
8885 ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
8888 Args.AddAllArgs(CmdArgs, options::OPT_L);
8889 Args.AddAllArgs(CmdArgs, options::OPT_u);
8891 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
8894 AddGoldPlugin(ToolChain, Args, CmdArgs, D.getLTOMode() == LTOK_Thin);
8896 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
8897 CmdArgs.push_back("--no-demangle");
8899 bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
8900 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
8901 // The profile runtime also needs access to system libraries.
8902 getToolChain().addProfileRTLibs(Args, CmdArgs);
8905 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
8906 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
8907 !Args.hasArg(options::OPT_static);
8908 if (OnlyLibstdcxxStatic)
8909 CmdArgs.push_back("-Bstatic");
8910 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
8911 if (OnlyLibstdcxxStatic)
8912 CmdArgs.push_back("-Bdynamic");
8913 CmdArgs.push_back("-lm");
8915 // Silence warnings when linking C code with a C++ '-stdlib' argument.
8916 Args.ClaimAllArgs(options::OPT_stdlib_EQ);
8918 if (!Args.hasArg(options::OPT_nostdlib)) {
8919 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
8920 if (Args.hasArg(options::OPT_static))
8921 CmdArgs.push_back("--start-group");
8923 if (NeedsSanitizerDeps)
8924 linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
8926 bool WantPthread = Args.hasArg(options::OPT_pthread) ||
8927 Args.hasArg(options::OPT_pthreads);
8929 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
8930 options::OPT_fno_openmp, false)) {
8931 // OpenMP runtimes implies pthreads when using the GNU toolchain.
8932 // FIXME: Does this really make sense for all GNU toolchains?
8935 // Also link the particular OpenMP runtimes.
8936 switch (getOpenMPRuntime(ToolChain, Args)) {
8938 CmdArgs.push_back("-lomp");
8941 CmdArgs.push_back("-lgomp");
8943 // FIXME: Exclude this for platforms with libgomp that don't require
8944 // librt. Most modern Linux platforms require it, but some may not.
8945 CmdArgs.push_back("-lrt");
8948 CmdArgs.push_back("-liomp5");
8951 // Already diagnosed.
8956 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
8958 if (WantPthread && !isAndroid)
8959 CmdArgs.push_back("-lpthread");
8961 CmdArgs.push_back("-lc");
8963 if (Args.hasArg(options::OPT_static))
8964 CmdArgs.push_back("--end-group");
8966 AddRunTimeLibs(ToolChain, D, CmdArgs, Args);
8969 if (!Args.hasArg(options::OPT_nostartfiles)) {
8971 if (Args.hasArg(options::OPT_shared))
8972 crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
8974 crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
8976 crtend = isAndroid ? "crtend_android.o" : "crtend.o";
8978 if (HasCRTBeginEndFiles)
8979 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
8981 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
8985 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
8988 // NaCl ARM assembly (inline or standalone) can be written with a set of macros
8989 // for the various SFI requirements like register masking. The assembly tool
8990 // inserts the file containing the macros as an input into all the assembly
8992 void nacltools::AssemblerARM::ConstructJob(Compilation &C, const JobAction &JA,
8993 const InputInfo &Output,
8994 const InputInfoList &Inputs,
8995 const ArgList &Args,
8996 const char *LinkingOutput) const {
8997 const toolchains::NaClToolChain &ToolChain =
8998 static_cast<const toolchains::NaClToolChain &>(getToolChain());
8999 InputInfo NaClMacros(types::TY_PP_Asm, ToolChain.GetNaClArmMacrosPath(),
9000 "nacl-arm-macros.s");
9001 InputInfoList NewInputs;
9002 NewInputs.push_back(NaClMacros);
9003 NewInputs.append(Inputs.begin(), Inputs.end());
9004 gnutools::Assembler::ConstructJob(C, JA, Output, NewInputs, Args,
9008 // This is quite similar to gnutools::Linker::ConstructJob with changes that
9009 // we use static by default, do not yet support sanitizers or LTO, and a few
9010 // others. Eventually we can support more of that and hopefully migrate back
9011 // to gnutools::Linker.
9012 void nacltools::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9013 const InputInfo &Output,
9014 const InputInfoList &Inputs,
9015 const ArgList &Args,
9016 const char *LinkingOutput) const {
9018 const toolchains::NaClToolChain &ToolChain =
9019 static_cast<const toolchains::NaClToolChain &>(getToolChain());
9020 const Driver &D = ToolChain.getDriver();
9021 const llvm::Triple::ArchType Arch = ToolChain.getArch();
9022 const bool IsStatic =
9023 !Args.hasArg(options::OPT_dynamic) && !Args.hasArg(options::OPT_shared);
9025 ArgStringList CmdArgs;
9027 // Silence warning for "clang -g foo.o -o foo"
9028 Args.ClaimAllArgs(options::OPT_g_Group);
9029 // and "clang -emit-llvm foo.o -o foo"
9030 Args.ClaimAllArgs(options::OPT_emit_llvm);
9031 // and for "clang -w foo.o -o foo". Other warning options are already
9032 // handled somewhere else.
9033 Args.ClaimAllArgs(options::OPT_w);
9035 if (!D.SysRoot.empty())
9036 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9038 if (Args.hasArg(options::OPT_rdynamic))
9039 CmdArgs.push_back("-export-dynamic");
9041 if (Args.hasArg(options::OPT_s))
9042 CmdArgs.push_back("-s");
9044 // NaClToolChain doesn't have ExtraOpts like Linux; the only relevant flag
9045 // from there is --build-id, which we do want.
9046 CmdArgs.push_back("--build-id");
9049 CmdArgs.push_back("--eh-frame-hdr");
9051 CmdArgs.push_back("-m");
9052 if (Arch == llvm::Triple::x86)
9053 CmdArgs.push_back("elf_i386_nacl");
9054 else if (Arch == llvm::Triple::arm)
9055 CmdArgs.push_back("armelf_nacl");
9056 else if (Arch == llvm::Triple::x86_64)
9057 CmdArgs.push_back("elf_x86_64_nacl");
9058 else if (Arch == llvm::Triple::mipsel)
9059 CmdArgs.push_back("mipselelf_nacl");
9061 D.Diag(diag::err_target_unsupported_arch) << ToolChain.getArchName()
9065 CmdArgs.push_back("-static");
9066 else if (Args.hasArg(options::OPT_shared))
9067 CmdArgs.push_back("-shared");
9069 CmdArgs.push_back("-o");
9070 CmdArgs.push_back(Output.getFilename());
9071 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9072 if (!Args.hasArg(options::OPT_shared))
9073 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crt1.o")));
9074 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
9076 const char *crtbegin;
9078 crtbegin = "crtbeginT.o";
9079 else if (Args.hasArg(options::OPT_shared))
9080 crtbegin = "crtbeginS.o";
9082 crtbegin = "crtbegin.o";
9083 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
9086 Args.AddAllArgs(CmdArgs, options::OPT_L);
9087 Args.AddAllArgs(CmdArgs, options::OPT_u);
9089 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
9091 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
9092 CmdArgs.push_back("--no-demangle");
9094 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
9097 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9098 bool OnlyLibstdcxxStatic =
9099 Args.hasArg(options::OPT_static_libstdcxx) && !IsStatic;
9100 if (OnlyLibstdcxxStatic)
9101 CmdArgs.push_back("-Bstatic");
9102 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
9103 if (OnlyLibstdcxxStatic)
9104 CmdArgs.push_back("-Bdynamic");
9105 CmdArgs.push_back("-lm");
9108 if (!Args.hasArg(options::OPT_nostdlib)) {
9109 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9110 // Always use groups, since it has no effect on dynamic libraries.
9111 CmdArgs.push_back("--start-group");
9112 CmdArgs.push_back("-lc");
9113 // NaCl's libc++ currently requires libpthread, so just always include it
9114 // in the group for C++.
9115 if (Args.hasArg(options::OPT_pthread) ||
9116 Args.hasArg(options::OPT_pthreads) || D.CCCIsCXX()) {
9117 // Gold, used by Mips, handles nested groups differently than ld, and
9118 // without '-lnacl' it prefers symbols from libpthread.a over libnacl.a,
9119 // which is not a desired behaviour here.
9120 // See https://sourceware.org/ml/binutils/2015-03/msg00034.html
9121 if (getToolChain().getArch() == llvm::Triple::mipsel)
9122 CmdArgs.push_back("-lnacl");
9124 CmdArgs.push_back("-lpthread");
9127 CmdArgs.push_back("-lgcc");
9128 CmdArgs.push_back("--as-needed");
9130 CmdArgs.push_back("-lgcc_eh");
9132 CmdArgs.push_back("-lgcc_s");
9133 CmdArgs.push_back("--no-as-needed");
9135 // Mips needs to create and use pnacl_legacy library that contains
9136 // definitions from bitcode/pnaclmm.c and definitions for
9137 // __nacl_tp_tls_offset() and __nacl_tp_tdb_offset().
9138 if (getToolChain().getArch() == llvm::Triple::mipsel)
9139 CmdArgs.push_back("-lpnacl_legacy");
9141 CmdArgs.push_back("--end-group");
9144 if (!Args.hasArg(options::OPT_nostartfiles)) {
9146 if (Args.hasArg(options::OPT_shared))
9147 crtend = "crtendS.o";
9149 crtend = "crtend.o";
9151 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
9152 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
9156 const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
9157 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9160 void minix::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9161 const InputInfo &Output,
9162 const InputInfoList &Inputs,
9163 const ArgList &Args,
9164 const char *LinkingOutput) const {
9165 claimNoWarnArgs(Args);
9166 ArgStringList CmdArgs;
9168 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9170 CmdArgs.push_back("-o");
9171 CmdArgs.push_back(Output.getFilename());
9173 for (const auto &II : Inputs)
9174 CmdArgs.push_back(II.getFilename());
9176 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9177 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9180 void minix::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9181 const InputInfo &Output,
9182 const InputInfoList &Inputs,
9183 const ArgList &Args,
9184 const char *LinkingOutput) const {
9185 const Driver &D = getToolChain().getDriver();
9186 ArgStringList CmdArgs;
9188 if (Output.isFilename()) {
9189 CmdArgs.push_back("-o");
9190 CmdArgs.push_back(Output.getFilename());
9192 assert(Output.isNothing() && "Invalid output.");
9195 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9196 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
9197 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
9199 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
9200 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
9203 Args.AddAllArgs(CmdArgs,
9204 {options::OPT_L, options::OPT_T_Group, options::OPT_e});
9206 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9208 getToolChain().addProfileRTLibs(Args, CmdArgs);
9210 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9212 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
9213 CmdArgs.push_back("-lm");
9217 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9218 if (Args.hasArg(options::OPT_pthread))
9219 CmdArgs.push_back("-lpthread");
9220 CmdArgs.push_back("-lc");
9221 CmdArgs.push_back("-lCompilerRT-Generic");
9222 CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib");
9224 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9227 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9228 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9233 // For now, DragonFly Assemble does just about the same as for
9234 // FreeBSD, but this may change soon.
9235 void dragonfly::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9236 const InputInfo &Output,
9237 const InputInfoList &Inputs,
9238 const ArgList &Args,
9239 const char *LinkingOutput) const {
9240 claimNoWarnArgs(Args);
9241 ArgStringList CmdArgs;
9243 // When building 32-bit code on DragonFly/pc64, we have to explicitly
9244 // instruct as in the base system to assemble 32-bit code.
9245 if (getToolChain().getArch() == llvm::Triple::x86)
9246 CmdArgs.push_back("--32");
9248 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9250 CmdArgs.push_back("-o");
9251 CmdArgs.push_back(Output.getFilename());
9253 for (const auto &II : Inputs)
9254 CmdArgs.push_back(II.getFilename());
9256 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9257 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9260 void dragonfly::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9261 const InputInfo &Output,
9262 const InputInfoList &Inputs,
9263 const ArgList &Args,
9264 const char *LinkingOutput) const {
9265 const Driver &D = getToolChain().getDriver();
9266 ArgStringList CmdArgs;
9268 if (!D.SysRoot.empty())
9269 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9271 CmdArgs.push_back("--eh-frame-hdr");
9272 if (Args.hasArg(options::OPT_static)) {
9273 CmdArgs.push_back("-Bstatic");
9275 if (Args.hasArg(options::OPT_rdynamic))
9276 CmdArgs.push_back("-export-dynamic");
9277 if (Args.hasArg(options::OPT_shared))
9278 CmdArgs.push_back("-Bshareable");
9280 CmdArgs.push_back("-dynamic-linker");
9281 CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
9283 CmdArgs.push_back("--hash-style=gnu");
9284 CmdArgs.push_back("--enable-new-dtags");
9287 // When building 32-bit code on DragonFly/pc64, we have to explicitly
9288 // instruct ld in the base system to link 32-bit code.
9289 if (getToolChain().getArch() == llvm::Triple::x86) {
9290 CmdArgs.push_back("-m");
9291 CmdArgs.push_back("elf_i386");
9294 if (Output.isFilename()) {
9295 CmdArgs.push_back("-o");
9296 CmdArgs.push_back(Output.getFilename());
9298 assert(Output.isNothing() && "Invalid output.");
9301 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9302 if (!Args.hasArg(options::OPT_shared)) {
9303 if (Args.hasArg(options::OPT_pg))
9305 Args.MakeArgString(getToolChain().GetFilePath("gcrt1.o")));
9307 if (Args.hasArg(options::OPT_pie))
9309 Args.MakeArgString(getToolChain().GetFilePath("Scrt1.o")));
9312 Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
9315 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
9316 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
9318 Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
9321 Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
9324 Args.AddAllArgs(CmdArgs,
9325 {options::OPT_L, options::OPT_T_Group, options::OPT_e});
9327 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9329 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9330 CmdArgs.push_back("-L/usr/lib/gcc50");
9332 if (!Args.hasArg(options::OPT_static)) {
9333 CmdArgs.push_back("-rpath");
9334 CmdArgs.push_back("/usr/lib/gcc50");
9338 getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs);
9339 CmdArgs.push_back("-lm");
9342 if (Args.hasArg(options::OPT_pthread))
9343 CmdArgs.push_back("-lpthread");
9345 if (!Args.hasArg(options::OPT_nolibc)) {
9346 CmdArgs.push_back("-lc");
9349 if (Args.hasArg(options::OPT_static) ||
9350 Args.hasArg(options::OPT_static_libgcc)) {
9351 CmdArgs.push_back("-lgcc");
9352 CmdArgs.push_back("-lgcc_eh");
9354 if (Args.hasArg(options::OPT_shared_libgcc)) {
9355 CmdArgs.push_back("-lgcc_pic");
9356 if (!Args.hasArg(options::OPT_shared))
9357 CmdArgs.push_back("-lgcc");
9359 CmdArgs.push_back("-lgcc");
9360 CmdArgs.push_back("--as-needed");
9361 CmdArgs.push_back("-lgcc_pic");
9362 CmdArgs.push_back("--no-as-needed");
9367 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9368 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
9370 Args.MakeArgString(getToolChain().GetFilePath("crtendS.o")));
9373 Args.MakeArgString(getToolChain().GetFilePath("crtend.o")));
9374 CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o")));
9377 getToolChain().addProfileRTLibs(Args, CmdArgs);
9379 const char *Exec = Args.MakeArgString(getToolChain().GetLinkerPath());
9380 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9383 // Try to find Exe from a Visual Studio distribution. This first tries to find
9384 // an installed copy of Visual Studio and, failing that, looks in the PATH,
9385 // making sure that whatever executable that's found is not a same-named exe
9386 // from clang itself to prevent clang from falling back to itself.
9387 static std::string FindVisualStudioExecutable(const ToolChain &TC,
9389 const char *ClangProgramPath) {
9390 const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
9391 std::string visualStudioBinDir;
9392 if (MSVC.getVisualStudioBinariesFolder(ClangProgramPath,
9393 visualStudioBinDir)) {
9394 SmallString<128> FilePath(visualStudioBinDir);
9395 llvm::sys::path::append(FilePath, Exe);
9396 if (llvm::sys::fs::can_execute(FilePath.c_str()))
9397 return FilePath.str();
9403 void visualstudio::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9404 const InputInfo &Output,
9405 const InputInfoList &Inputs,
9406 const ArgList &Args,
9407 const char *LinkingOutput) const {
9408 ArgStringList CmdArgs;
9409 const ToolChain &TC = getToolChain();
9411 assert((Output.isFilename() || Output.isNothing()) && "invalid output");
9412 if (Output.isFilename())
9414 Args.MakeArgString(std::string("-out:") + Output.getFilename()));
9416 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles) &&
9417 !C.getDriver().IsCLMode())
9418 CmdArgs.push_back("-defaultlib:libcmt");
9420 if (!llvm::sys::Process::GetEnv("LIB")) {
9421 // If the VC environment hasn't been configured (perhaps because the user
9422 // did not run vcvarsall), try to build a consistent link environment. If
9423 // the environment variable is set however, assume the user knows what
9425 std::string VisualStudioDir;
9426 const auto &MSVC = static_cast<const toolchains::MSVCToolChain &>(TC);
9427 if (MSVC.getVisualStudioInstallDir(VisualStudioDir)) {
9428 SmallString<128> LibDir(VisualStudioDir);
9429 llvm::sys::path::append(LibDir, "VC", "lib");
9430 switch (MSVC.getArch()) {
9431 case llvm::Triple::x86:
9432 // x86 just puts the libraries directly in lib
9434 case llvm::Triple::x86_64:
9435 llvm::sys::path::append(LibDir, "amd64");
9437 case llvm::Triple::arm:
9438 llvm::sys::path::append(LibDir, "arm");
9444 Args.MakeArgString(std::string("-libpath:") + LibDir.c_str()));
9446 if (MSVC.useUniversalCRT(VisualStudioDir)) {
9447 std::string UniversalCRTLibPath;
9448 if (MSVC.getUniversalCRTLibraryPath(UniversalCRTLibPath))
9449 CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
9450 UniversalCRTLibPath.c_str()));
9454 std::string WindowsSdkLibPath;
9455 if (MSVC.getWindowsSDKLibraryPath(WindowsSdkLibPath))
9456 CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
9457 WindowsSdkLibPath.c_str()));
9460 CmdArgs.push_back("-nologo");
9462 if (Args.hasArg(options::OPT_g_Group, options::OPT__SLASH_Z7))
9463 CmdArgs.push_back("-debug");
9465 bool DLL = Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd,
9466 options::OPT_shared);
9468 CmdArgs.push_back(Args.MakeArgString("-dll"));
9470 SmallString<128> ImplibName(Output.getFilename());
9471 llvm::sys::path::replace_extension(ImplibName, "lib");
9472 CmdArgs.push_back(Args.MakeArgString(std::string("-implib:") + ImplibName));
9475 if (TC.getSanitizerArgs().needsAsanRt()) {
9476 CmdArgs.push_back(Args.MakeArgString("-debug"));
9477 CmdArgs.push_back(Args.MakeArgString("-incremental:no"));
9478 if (Args.hasArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd)) {
9479 for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
9480 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
9481 // Make sure the dynamic runtime thunk is not optimized out at link time
9482 // to ensure proper SEH handling.
9483 CmdArgs.push_back(Args.MakeArgString("-include:___asan_seh_interceptor"));
9485 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
9487 for (const auto &Lib : {"asan", "asan_cxx"})
9488 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
9492 Args.AddAllArgValues(CmdArgs, options::OPT__SLASH_link);
9494 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
9495 options::OPT_fno_openmp, false)) {
9496 CmdArgs.push_back("-nodefaultlib:vcomp.lib");
9497 CmdArgs.push_back("-nodefaultlib:vcompd.lib");
9498 CmdArgs.push_back(Args.MakeArgString(std::string("-libpath:") +
9499 TC.getDriver().Dir + "/../lib"));
9500 switch (getOpenMPRuntime(getToolChain(), Args)) {
9502 CmdArgs.push_back("-defaultlib:libomp.lib");
9505 CmdArgs.push_back("-defaultlib:libiomp5md.lib");
9510 // Already diagnosed.
9515 // Add filenames, libraries, and other linker inputs.
9516 for (const auto &Input : Inputs) {
9517 if (Input.isFilename()) {
9518 CmdArgs.push_back(Input.getFilename());
9522 const Arg &A = Input.getInputArg();
9524 // Render -l options differently for the MSVC linker.
9525 if (A.getOption().matches(options::OPT_l)) {
9526 StringRef Lib = A.getValue();
9527 const char *LinkLibArg;
9528 if (Lib.endswith(".lib"))
9529 LinkLibArg = Args.MakeArgString(Lib);
9531 LinkLibArg = Args.MakeArgString(Lib + ".lib");
9532 CmdArgs.push_back(LinkLibArg);
9536 // Otherwise, this is some other kind of linker input option like -Wl, -z,
9537 // or -L. Render it, even if MSVC doesn't understand it.
9538 A.renderAsInput(Args, CmdArgs);
9541 TC.addProfileRTLibs(Args, CmdArgs);
9543 // We need to special case some linker paths. In the case of lld, we need to
9544 // translate 'lld' into 'lld-link', and in the case of the regular msvc
9545 // linker, we need to use a special search algorithm.
9546 llvm::SmallString<128> linkPath;
9547 StringRef Linker = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "link");
9548 if (Linker.equals_lower("lld"))
9549 Linker = "lld-link";
9551 if (Linker.equals_lower("link")) {
9552 // If we're using the MSVC linker, it's not sufficient to just use link
9553 // from the program PATH, because other environments like GnuWin32 install
9554 // their own link.exe which may come first.
9555 linkPath = FindVisualStudioExecutable(TC, "link.exe",
9556 C.getDriver().getClangProgramPath());
9559 llvm::sys::path::replace_extension(linkPath, "exe");
9560 linkPath = TC.GetProgramPath(linkPath.c_str());
9563 const char *Exec = Args.MakeArgString(linkPath);
9564 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9567 void visualstudio::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
9568 const InputInfo &Output,
9569 const InputInfoList &Inputs,
9570 const ArgList &Args,
9571 const char *LinkingOutput) const {
9572 C.addCommand(GetCommand(C, JA, Output, Inputs, Args, LinkingOutput));
9575 std::unique_ptr<Command> visualstudio::Compiler::GetCommand(
9576 Compilation &C, const JobAction &JA, const InputInfo &Output,
9577 const InputInfoList &Inputs, const ArgList &Args,
9578 const char *LinkingOutput) const {
9579 ArgStringList CmdArgs;
9580 CmdArgs.push_back("/nologo");
9581 CmdArgs.push_back("/c"); // Compile only.
9582 CmdArgs.push_back("/W0"); // No warnings.
9584 // The goal is to be able to invoke this tool correctly based on
9585 // any flag accepted by clang-cl.
9587 // These are spelled the same way in clang and cl.exe,.
9588 Args.AddAllArgs(CmdArgs, {options::OPT_D, options::OPT_U, options::OPT_I});
9590 // Optimization level.
9591 if (Arg *A = Args.getLastArg(options::OPT_fbuiltin, options::OPT_fno_builtin))
9592 CmdArgs.push_back(A->getOption().getID() == options::OPT_fbuiltin ? "/Oi"
9594 if (Arg *A = Args.getLastArg(options::OPT_O, options::OPT_O0)) {
9595 if (A->getOption().getID() == options::OPT_O0) {
9596 CmdArgs.push_back("/Od");
9598 CmdArgs.push_back("/Og");
9600 StringRef OptLevel = A->getValue();
9601 if (OptLevel == "s" || OptLevel == "z")
9602 CmdArgs.push_back("/Os");
9604 CmdArgs.push_back("/Ot");
9606 CmdArgs.push_back("/Ob2");
9609 if (Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
9610 options::OPT_fno_omit_frame_pointer))
9611 CmdArgs.push_back(A->getOption().getID() == options::OPT_fomit_frame_pointer
9614 if (!Args.hasArg(options::OPT_fwritable_strings))
9615 CmdArgs.push_back("/GF");
9617 // Flags for which clang-cl has an alias.
9618 // FIXME: How can we ensure this stays in sync with relevant clang-cl options?
9620 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
9622 CmdArgs.push_back("/GR-");
9623 if (Arg *A = Args.getLastArg(options::OPT_ffunction_sections,
9624 options::OPT_fno_function_sections))
9625 CmdArgs.push_back(A->getOption().getID() == options::OPT_ffunction_sections
9628 if (Arg *A = Args.getLastArg(options::OPT_fdata_sections,
9629 options::OPT_fno_data_sections))
9631 A->getOption().getID() == options::OPT_fdata_sections ? "/Gw" : "/Gw-");
9632 if (Args.hasArg(options::OPT_fsyntax_only))
9633 CmdArgs.push_back("/Zs");
9634 if (Args.hasArg(options::OPT_g_Flag, options::OPT_gline_tables_only,
9635 options::OPT__SLASH_Z7))
9636 CmdArgs.push_back("/Z7");
9638 std::vector<std::string> Includes =
9639 Args.getAllArgValues(options::OPT_include);
9640 for (const auto &Include : Includes)
9641 CmdArgs.push_back(Args.MakeArgString(std::string("/FI") + Include));
9643 // Flags that can simply be passed through.
9644 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LD);
9645 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_LDd);
9646 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_EH);
9647 Args.AddAllArgs(CmdArgs, options::OPT__SLASH_Zl);
9649 // The order of these flags is relevant, so pick the last one.
9650 if (Arg *A = Args.getLastArg(options::OPT__SLASH_MD, options::OPT__SLASH_MDd,
9651 options::OPT__SLASH_MT, options::OPT__SLASH_MTd))
9652 A->render(Args, CmdArgs);
9655 assert(Inputs.size() == 1);
9656 const InputInfo &II = Inputs[0];
9657 assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX);
9658 CmdArgs.push_back(II.getType() == types::TY_C ? "/Tc" : "/Tp");
9659 if (II.isFilename())
9660 CmdArgs.push_back(II.getFilename());
9662 II.getInputArg().renderAsInput(Args, CmdArgs);
9665 assert(Output.getType() == types::TY_Object);
9667 Args.MakeArgString(std::string("/Fo") + Output.getFilename());
9668 CmdArgs.push_back(Fo);
9670 const Driver &D = getToolChain().getDriver();
9671 std::string Exec = FindVisualStudioExecutable(getToolChain(), "cl.exe",
9672 D.getClangProgramPath());
9673 return llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
9678 void MinGW::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9679 const InputInfo &Output,
9680 const InputInfoList &Inputs,
9681 const ArgList &Args,
9682 const char *LinkingOutput) const {
9683 claimNoWarnArgs(Args);
9684 ArgStringList CmdArgs;
9686 if (getToolChain().getArch() == llvm::Triple::x86) {
9687 CmdArgs.push_back("--32");
9688 } else if (getToolChain().getArch() == llvm::Triple::x86_64) {
9689 CmdArgs.push_back("--64");
9692 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9694 CmdArgs.push_back("-o");
9695 CmdArgs.push_back(Output.getFilename());
9697 for (const auto &II : Inputs)
9698 CmdArgs.push_back(II.getFilename());
9700 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
9701 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9703 if (Args.hasArg(options::OPT_gsplit_dwarf))
9704 SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
9705 SplitDebugName(Args, Inputs[0]));
9708 void MinGW::Linker::AddLibGCC(const ArgList &Args,
9709 ArgStringList &CmdArgs) const {
9710 if (Args.hasArg(options::OPT_mthreads))
9711 CmdArgs.push_back("-lmingwthrd");
9712 CmdArgs.push_back("-lmingw32");
9714 // Make use of compiler-rt if --rtlib option is used
9715 ToolChain::RuntimeLibType RLT = getToolChain().GetRuntimeLibType(Args);
9716 if (RLT == ToolChain::RLT_Libgcc) {
9717 bool Static = Args.hasArg(options::OPT_static_libgcc) ||
9718 Args.hasArg(options::OPT_static);
9719 bool Shared = Args.hasArg(options::OPT_shared);
9720 bool CXX = getToolChain().getDriver().CCCIsCXX();
9722 if (Static || (!CXX && !Shared)) {
9723 CmdArgs.push_back("-lgcc");
9724 CmdArgs.push_back("-lgcc_eh");
9726 CmdArgs.push_back("-lgcc_s");
9727 CmdArgs.push_back("-lgcc");
9730 AddRunTimeLibs(getToolChain(), getToolChain().getDriver(), CmdArgs, Args);
9733 CmdArgs.push_back("-lmoldname");
9734 CmdArgs.push_back("-lmingwex");
9735 CmdArgs.push_back("-lmsvcrt");
9738 void MinGW::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9739 const InputInfo &Output,
9740 const InputInfoList &Inputs,
9741 const ArgList &Args,
9742 const char *LinkingOutput) const {
9743 const ToolChain &TC = getToolChain();
9744 const Driver &D = TC.getDriver();
9745 // const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
9747 ArgStringList CmdArgs;
9749 // Silence warning for "clang -g foo.o -o foo"
9750 Args.ClaimAllArgs(options::OPT_g_Group);
9751 // and "clang -emit-llvm foo.o -o foo"
9752 Args.ClaimAllArgs(options::OPT_emit_llvm);
9753 // and for "clang -w foo.o -o foo". Other warning options are already
9754 // handled somewhere else.
9755 Args.ClaimAllArgs(options::OPT_w);
9757 StringRef LinkerName = Args.getLastArgValue(options::OPT_fuse_ld_EQ, "ld");
9758 if (LinkerName.equals_lower("lld")) {
9759 CmdArgs.push_back("-flavor");
9760 CmdArgs.push_back("gnu");
9761 } else if (!LinkerName.equals_lower("ld")) {
9762 D.Diag(diag::err_drv_unsupported_linker) << LinkerName;
9765 if (!D.SysRoot.empty())
9766 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
9768 if (Args.hasArg(options::OPT_s))
9769 CmdArgs.push_back("-s");
9771 CmdArgs.push_back("-m");
9772 if (TC.getArch() == llvm::Triple::x86)
9773 CmdArgs.push_back("i386pe");
9774 if (TC.getArch() == llvm::Triple::x86_64)
9775 CmdArgs.push_back("i386pep");
9776 if (TC.getArch() == llvm::Triple::arm)
9777 CmdArgs.push_back("thumb2pe");
9779 if (Args.hasArg(options::OPT_mwindows)) {
9780 CmdArgs.push_back("--subsystem");
9781 CmdArgs.push_back("windows");
9782 } else if (Args.hasArg(options::OPT_mconsole)) {
9783 CmdArgs.push_back("--subsystem");
9784 CmdArgs.push_back("console");
9787 if (Args.hasArg(options::OPT_static))
9788 CmdArgs.push_back("-Bstatic");
9790 if (Args.hasArg(options::OPT_mdll))
9791 CmdArgs.push_back("--dll");
9792 else if (Args.hasArg(options::OPT_shared))
9793 CmdArgs.push_back("--shared");
9794 CmdArgs.push_back("-Bdynamic");
9795 if (Args.hasArg(options::OPT_mdll) || Args.hasArg(options::OPT_shared)) {
9796 CmdArgs.push_back("-e");
9797 if (TC.getArch() == llvm::Triple::x86)
9798 CmdArgs.push_back("_DllMainCRTStartup@12");
9800 CmdArgs.push_back("DllMainCRTStartup");
9801 CmdArgs.push_back("--enable-auto-image-base");
9805 CmdArgs.push_back("-o");
9806 CmdArgs.push_back(Output.getFilename());
9808 Args.AddAllArgs(CmdArgs, options::OPT_e);
9809 // FIXME: add -N, -n flags
9810 Args.AddLastArg(CmdArgs, options::OPT_r);
9811 Args.AddLastArg(CmdArgs, options::OPT_s);
9812 Args.AddLastArg(CmdArgs, options::OPT_t);
9813 Args.AddAllArgs(CmdArgs, options::OPT_u_Group);
9814 Args.AddLastArg(CmdArgs, options::OPT_Z_Flag);
9816 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
9817 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_mdll)) {
9818 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("dllcrt2.o")));
9820 if (Args.hasArg(options::OPT_municode))
9821 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2u.o")));
9823 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crt2.o")));
9825 if (Args.hasArg(options::OPT_pg))
9826 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("gcrt2.o")));
9827 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
9830 Args.AddAllArgs(CmdArgs, options::OPT_L);
9831 TC.AddFilePathLibArgs(Args, CmdArgs);
9832 AddLinkerInputs(TC, Inputs, Args, CmdArgs);
9834 // TODO: Add ASan stuff here
9836 // TODO: Add profile stuff here
9839 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
9840 bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) &&
9841 !Args.hasArg(options::OPT_static);
9842 if (OnlyLibstdcxxStatic)
9843 CmdArgs.push_back("-Bstatic");
9844 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
9845 if (OnlyLibstdcxxStatic)
9846 CmdArgs.push_back("-Bdynamic");
9849 if (!Args.hasArg(options::OPT_nostdlib)) {
9850 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
9851 if (Args.hasArg(options::OPT_static))
9852 CmdArgs.push_back("--start-group");
9854 if (Args.hasArg(options::OPT_fstack_protector) ||
9855 Args.hasArg(options::OPT_fstack_protector_strong) ||
9856 Args.hasArg(options::OPT_fstack_protector_all)) {
9857 CmdArgs.push_back("-lssp_nonshared");
9858 CmdArgs.push_back("-lssp");
9860 if (Args.hasArg(options::OPT_fopenmp))
9861 CmdArgs.push_back("-lgomp");
9863 AddLibGCC(Args, CmdArgs);
9865 if (Args.hasArg(options::OPT_pg))
9866 CmdArgs.push_back("-lgmon");
9868 if (Args.hasArg(options::OPT_pthread))
9869 CmdArgs.push_back("-lpthread");
9871 // add system libraries
9872 if (Args.hasArg(options::OPT_mwindows)) {
9873 CmdArgs.push_back("-lgdi32");
9874 CmdArgs.push_back("-lcomdlg32");
9876 CmdArgs.push_back("-ladvapi32");
9877 CmdArgs.push_back("-lshell32");
9878 CmdArgs.push_back("-luser32");
9879 CmdArgs.push_back("-lkernel32");
9881 if (Args.hasArg(options::OPT_static))
9882 CmdArgs.push_back("--end-group");
9883 else if (!LinkerName.equals_lower("lld"))
9884 AddLibGCC(Args, CmdArgs);
9887 if (!Args.hasArg(options::OPT_nostartfiles)) {
9888 // Add crtfastmath.o if available and fast math is enabled.
9889 TC.AddFastMathRuntimeIfAvailable(Args, CmdArgs);
9891 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
9894 const char *Exec = Args.MakeArgString(TC.GetProgramPath(LinkerName.data()));
9895 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9899 // We pass assemble and link construction to the xcc tool.
9901 void XCore::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9902 const InputInfo &Output,
9903 const InputInfoList &Inputs,
9904 const ArgList &Args,
9905 const char *LinkingOutput) const {
9906 claimNoWarnArgs(Args);
9907 ArgStringList CmdArgs;
9909 CmdArgs.push_back("-o");
9910 CmdArgs.push_back(Output.getFilename());
9912 CmdArgs.push_back("-c");
9914 if (Args.hasArg(options::OPT_v))
9915 CmdArgs.push_back("-v");
9917 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
9918 if (!A->getOption().matches(options::OPT_g0))
9919 CmdArgs.push_back("-g");
9921 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
9923 CmdArgs.push_back("-fverbose-asm");
9925 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9927 for (const auto &II : Inputs)
9928 CmdArgs.push_back(II.getFilename());
9930 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
9931 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9934 void XCore::Linker::ConstructJob(Compilation &C, const JobAction &JA,
9935 const InputInfo &Output,
9936 const InputInfoList &Inputs,
9937 const ArgList &Args,
9938 const char *LinkingOutput) const {
9939 ArgStringList CmdArgs;
9941 if (Output.isFilename()) {
9942 CmdArgs.push_back("-o");
9943 CmdArgs.push_back(Output.getFilename());
9945 assert(Output.isNothing() && "Invalid output.");
9948 if (Args.hasArg(options::OPT_v))
9949 CmdArgs.push_back("-v");
9951 // Pass -fexceptions through to the linker if it was present.
9952 if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
9954 CmdArgs.push_back("-fexceptions");
9956 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
9958 const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("xcc"));
9959 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
9962 void CrossWindows::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
9963 const InputInfo &Output,
9964 const InputInfoList &Inputs,
9965 const ArgList &Args,
9966 const char *LinkingOutput) const {
9967 claimNoWarnArgs(Args);
9969 static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
9970 ArgStringList CmdArgs;
9973 switch (TC.getArch()) {
9975 llvm_unreachable("unsupported architecture");
9976 case llvm::Triple::arm:
9977 case llvm::Triple::thumb:
9979 case llvm::Triple::x86:
9980 CmdArgs.push_back("--32");
9982 case llvm::Triple::x86_64:
9983 CmdArgs.push_back("--64");
9987 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
9989 CmdArgs.push_back("-o");
9990 CmdArgs.push_back(Output.getFilename());
9992 for (const auto &Input : Inputs)
9993 CmdArgs.push_back(Input.getFilename());
9995 const std::string Assembler = TC.GetProgramPath("as");
9996 Exec = Args.MakeArgString(Assembler);
9998 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10001 void CrossWindows::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10002 const InputInfo &Output,
10003 const InputInfoList &Inputs,
10004 const ArgList &Args,
10005 const char *LinkingOutput) const {
10007 static_cast<const toolchains::CrossWindowsToolChain &>(getToolChain());
10008 const llvm::Triple &T = TC.getTriple();
10009 const Driver &D = TC.getDriver();
10010 SmallString<128> EntryPoint;
10011 ArgStringList CmdArgs;
10014 // Silence warning for "clang -g foo.o -o foo"
10015 Args.ClaimAllArgs(options::OPT_g_Group);
10016 // and "clang -emit-llvm foo.o -o foo"
10017 Args.ClaimAllArgs(options::OPT_emit_llvm);
10018 // and for "clang -w foo.o -o foo"
10019 Args.ClaimAllArgs(options::OPT_w);
10020 // Other warning options are already handled somewhere else.
10022 if (!D.SysRoot.empty())
10023 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10025 if (Args.hasArg(options::OPT_pie))
10026 CmdArgs.push_back("-pie");
10027 if (Args.hasArg(options::OPT_rdynamic))
10028 CmdArgs.push_back("-export-dynamic");
10029 if (Args.hasArg(options::OPT_s))
10030 CmdArgs.push_back("--strip-all");
10032 CmdArgs.push_back("-m");
10033 switch (TC.getArch()) {
10035 llvm_unreachable("unsupported architecture");
10036 case llvm::Triple::arm:
10037 case llvm::Triple::thumb:
10038 // FIXME: this is incorrect for WinCE
10039 CmdArgs.push_back("thumb2pe");
10041 case llvm::Triple::x86:
10042 CmdArgs.push_back("i386pe");
10043 EntryPoint.append("_");
10045 case llvm::Triple::x86_64:
10046 CmdArgs.push_back("i386pep");
10050 if (Args.hasArg(options::OPT_shared)) {
10051 switch (T.getArch()) {
10053 llvm_unreachable("unsupported architecture");
10054 case llvm::Triple::arm:
10055 case llvm::Triple::thumb:
10056 case llvm::Triple::x86_64:
10057 EntryPoint.append("_DllMainCRTStartup");
10059 case llvm::Triple::x86:
10060 EntryPoint.append("_DllMainCRTStartup@12");
10064 CmdArgs.push_back("-shared");
10065 CmdArgs.push_back("-Bdynamic");
10067 CmdArgs.push_back("--enable-auto-image-base");
10069 CmdArgs.push_back("--entry");
10070 CmdArgs.push_back(Args.MakeArgString(EntryPoint));
10072 EntryPoint.append("mainCRTStartup");
10074 CmdArgs.push_back(Args.hasArg(options::OPT_static) ? "-Bstatic"
10077 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10078 CmdArgs.push_back("--entry");
10079 CmdArgs.push_back(Args.MakeArgString(EntryPoint));
10082 // FIXME: handle subsystem
10085 // NOTE: deal with multiple definitions on Windows (e.g. COMDAT)
10086 CmdArgs.push_back("--allow-multiple-definition");
10088 CmdArgs.push_back("-o");
10089 CmdArgs.push_back(Output.getFilename());
10091 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_rdynamic)) {
10092 SmallString<261> ImpLib(Output.getFilename());
10093 llvm::sys::path::replace_extension(ImpLib, ".lib");
10095 CmdArgs.push_back("--out-implib");
10096 CmdArgs.push_back(Args.MakeArgString(ImpLib));
10099 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10100 const std::string CRTPath(D.SysRoot + "/usr/lib/");
10101 const char *CRTBegin;
10104 Args.hasArg(options::OPT_shared) ? "crtbeginS.obj" : "crtbegin.obj";
10105 CmdArgs.push_back(Args.MakeArgString(CRTPath + CRTBegin));
10108 Args.AddAllArgs(CmdArgs, options::OPT_L);
10109 TC.AddFilePathLibArgs(Args, CmdArgs);
10110 AddLinkerInputs(TC, Inputs, Args, CmdArgs);
10112 if (D.CCCIsCXX() && !Args.hasArg(options::OPT_nostdlib) &&
10113 !Args.hasArg(options::OPT_nodefaultlibs)) {
10114 bool StaticCXX = Args.hasArg(options::OPT_static_libstdcxx) &&
10115 !Args.hasArg(options::OPT_static);
10117 CmdArgs.push_back("-Bstatic");
10118 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
10120 CmdArgs.push_back("-Bdynamic");
10123 if (!Args.hasArg(options::OPT_nostdlib)) {
10124 if (!Args.hasArg(options::OPT_nodefaultlibs)) {
10125 // TODO handle /MT[d] /MD[d]
10126 CmdArgs.push_back("-lmsvcrt");
10127 AddRunTimeLibs(TC, D, CmdArgs, Args);
10131 if (TC.getSanitizerArgs().needsAsanRt()) {
10132 // TODO handle /MT[d] /MD[d]
10133 if (Args.hasArg(options::OPT_shared)) {
10134 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "asan_dll_thunk"));
10136 for (const auto &Lib : {"asan_dynamic", "asan_dynamic_runtime_thunk"})
10137 CmdArgs.push_back(TC.getCompilerRTArgString(Args, Lib));
10138 // Make sure the dynamic runtime thunk is not optimized out at link time
10139 // to ensure proper SEH handling.
10140 CmdArgs.push_back(Args.MakeArgString("--undefined"));
10141 CmdArgs.push_back(Args.MakeArgString(TC.getArch() == llvm::Triple::x86
10142 ? "___asan_seh_interceptor"
10143 : "__asan_seh_interceptor"));
10147 Exec = Args.MakeArgString(TC.GetLinkerPath());
10149 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10152 void tools::SHAVE::Compiler::ConstructJob(Compilation &C, const JobAction &JA,
10153 const InputInfo &Output,
10154 const InputInfoList &Inputs,
10155 const ArgList &Args,
10156 const char *LinkingOutput) const {
10157 ArgStringList CmdArgs;
10158 assert(Inputs.size() == 1);
10159 const InputInfo &II = Inputs[0];
10160 assert(II.getType() == types::TY_C || II.getType() == types::TY_CXX ||
10161 II.getType() == types::TY_PP_CXX);
10163 if (JA.getKind() == Action::PreprocessJobClass) {
10164 Args.ClaimAllArgs();
10165 CmdArgs.push_back("-E");
10167 assert(Output.getType() == types::TY_PP_Asm); // Require preprocessed asm.
10168 CmdArgs.push_back("-S");
10169 CmdArgs.push_back("-fno-exceptions"); // Always do this even if unspecified.
10171 CmdArgs.push_back("-mcpu=myriad2");
10172 CmdArgs.push_back("-DMYRIAD2");
10174 // Append all -I, -iquote, -isystem paths, defines/undefines,
10175 // 'f' flags, optimize flags, and warning options.
10176 // These are spelled the same way in clang and moviCompile.
10177 Args.AddAllArgs(CmdArgs, {options::OPT_I_Group, options::OPT_clang_i_Group,
10178 options::OPT_std_EQ, options::OPT_D, options::OPT_U,
10179 options::OPT_f_Group, options::OPT_f_clang_Group,
10180 options::OPT_g_Group, options::OPT_M_Group,
10181 options::OPT_O_Group, options::OPT_W_Group});
10183 // If we're producing a dependency file, and assembly is the final action,
10184 // then the name of the target in the dependency file should be the '.o'
10185 // file, not the '.s' file produced by this step. For example, instead of
10186 // /tmp/mumble.s: mumble.c .../someheader.h
10187 // the filename on the lefthand side should be "mumble.o"
10188 if (Args.getLastArg(options::OPT_MF) && !Args.getLastArg(options::OPT_MT) &&
10189 C.getActions().size() == 1 &&
10190 C.getActions()[0]->getKind() == Action::AssembleJobClass) {
10191 Arg *A = Args.getLastArg(options::OPT_o);
10193 CmdArgs.push_back("-MT");
10194 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
10198 CmdArgs.push_back(II.getFilename());
10199 CmdArgs.push_back("-o");
10200 CmdArgs.push_back(Output.getFilename());
10203 Args.MakeArgString(getToolChain().GetProgramPath("moviCompile"));
10204 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10208 void tools::SHAVE::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
10209 const InputInfo &Output,
10210 const InputInfoList &Inputs,
10211 const ArgList &Args,
10212 const char *LinkingOutput) const {
10213 ArgStringList CmdArgs;
10215 assert(Inputs.size() == 1);
10216 const InputInfo &II = Inputs[0];
10217 assert(II.getType() == types::TY_PP_Asm); // Require preprocessed asm input.
10218 assert(Output.getType() == types::TY_Object);
10220 CmdArgs.push_back("-no6thSlotCompression");
10221 CmdArgs.push_back("-cv:myriad2"); // Chip Version
10222 CmdArgs.push_back("-noSPrefixing");
10223 CmdArgs.push_back("-a"); // Mystery option.
10224 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10225 for (const Arg *A : Args.filtered(options::OPT_I, options::OPT_isystem)) {
10228 Args.MakeArgString(std::string("-i:") + A->getValue(0)));
10230 CmdArgs.push_back("-elf"); // Output format.
10231 CmdArgs.push_back(II.getFilename());
10233 Args.MakeArgString(std::string("-o:") + Output.getFilename()));
10236 Args.MakeArgString(getToolChain().GetProgramPath("moviAsm"));
10237 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10241 void tools::Myriad::Linker::ConstructJob(Compilation &C, const JobAction &JA,
10242 const InputInfo &Output,
10243 const InputInfoList &Inputs,
10244 const ArgList &Args,
10245 const char *LinkingOutput) const {
10247 static_cast<const toolchains::MyriadToolChain &>(getToolChain());
10248 const llvm::Triple &T = TC.getTriple();
10249 ArgStringList CmdArgs;
10250 bool UseStartfiles =
10251 !Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles);
10252 bool UseDefaultLibs =
10253 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs);
10255 if (T.getArch() == llvm::Triple::sparc)
10256 CmdArgs.push_back("-EB");
10257 else // SHAVE assumes little-endian, and sparcel is expressly so.
10258 CmdArgs.push_back("-EL");
10260 // The remaining logic is mostly like gnutools::Linker::ConstructJob,
10261 // but we never pass through a --sysroot option and various other bits.
10262 // For example, there are no sanitizers (yet) nor gold linker.
10264 // Eat some arguments that may be present but have no effect.
10265 Args.ClaimAllArgs(options::OPT_g_Group);
10266 Args.ClaimAllArgs(options::OPT_w);
10267 Args.ClaimAllArgs(options::OPT_static_libgcc);
10269 if (Args.hasArg(options::OPT_s)) // Pass the 'strip' option.
10270 CmdArgs.push_back("-s");
10272 CmdArgs.push_back("-o");
10273 CmdArgs.push_back(Output.getFilename());
10275 if (UseStartfiles) {
10276 // If you want startfiles, it means you want the builtin crti and crtbegin,
10277 // but not crt0. Myriad link commands provide their own crt0.o as needed.
10278 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crti.o")));
10279 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtbegin.o")));
10282 Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
10283 options::OPT_e, options::OPT_s, options::OPT_t,
10284 options::OPT_Z_Flag, options::OPT_r});
10286 TC.AddFilePathLibArgs(Args, CmdArgs);
10288 AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs);
10290 if (UseDefaultLibs) {
10291 if (C.getDriver().CCCIsCXX())
10292 CmdArgs.push_back("-lstdc++");
10293 if (T.getOS() == llvm::Triple::RTEMS) {
10294 CmdArgs.push_back("--start-group");
10295 CmdArgs.push_back("-lc");
10296 // You must provide your own "-L" option to enable finding these.
10297 CmdArgs.push_back("-lrtemscpu");
10298 CmdArgs.push_back("-lrtemsbsp");
10299 CmdArgs.push_back("--end-group");
10301 CmdArgs.push_back("-lc");
10303 CmdArgs.push_back("-lgcc");
10305 if (UseStartfiles) {
10306 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtend.o")));
10307 CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath("crtn.o")));
10311 Args.MakeArgString(TC.GetProgramPath("sparc-myriad-elf-ld"));
10312 C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(Exec),
10316 void PS4cpu::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
10317 const InputInfo &Output,
10318 const InputInfoList &Inputs,
10319 const ArgList &Args,
10320 const char *LinkingOutput) const {
10321 claimNoWarnArgs(Args);
10322 ArgStringList CmdArgs;
10324 Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
10326 CmdArgs.push_back("-o");
10327 CmdArgs.push_back(Output.getFilename());
10329 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
10330 const InputInfo &Input = Inputs[0];
10331 assert(Input.isFilename() && "Invalid input.");
10332 CmdArgs.push_back(Input.getFilename());
10335 Args.MakeArgString(getToolChain().GetProgramPath("ps4-as"));
10336 C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
10339 static void AddPS4SanitizerArgs(const ToolChain &TC, ArgStringList &CmdArgs) {
10340 const SanitizerArgs &SanArgs = TC.getSanitizerArgs();
10341 if (SanArgs.needsUbsanRt()) {
10342 CmdArgs.push_back("-lSceDbgUBSanitizer_stub_weak");
10344 if (SanArgs.needsAsanRt()) {
10345 CmdArgs.push_back("-lSceDbgAddressSanitizer_stub_weak");
10349 static void ConstructPS4LinkJob(const Tool &T, Compilation &C,
10350 const JobAction &JA, const InputInfo &Output,
10351 const InputInfoList &Inputs,
10352 const ArgList &Args,
10353 const char *LinkingOutput) {
10354 const toolchains::FreeBSD &ToolChain =
10355 static_cast<const toolchains::FreeBSD &>(T.getToolChain());
10356 const Driver &D = ToolChain.getDriver();
10357 ArgStringList CmdArgs;
10359 // Silence warning for "clang -g foo.o -o foo"
10360 Args.ClaimAllArgs(options::OPT_g_Group);
10361 // and "clang -emit-llvm foo.o -o foo"
10362 Args.ClaimAllArgs(options::OPT_emit_llvm);
10363 // and for "clang -w foo.o -o foo". Other warning options are already
10364 // handled somewhere else.
10365 Args.ClaimAllArgs(options::OPT_w);
10367 if (!D.SysRoot.empty())
10368 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10370 if (Args.hasArg(options::OPT_pie))
10371 CmdArgs.push_back("-pie");
10373 if (Args.hasArg(options::OPT_rdynamic))
10374 CmdArgs.push_back("-export-dynamic");
10375 if (Args.hasArg(options::OPT_shared))
10376 CmdArgs.push_back("--oformat=so");
10378 if (Output.isFilename()) {
10379 CmdArgs.push_back("-o");
10380 CmdArgs.push_back(Output.getFilename());
10382 assert(Output.isNothing() && "Invalid output.");
10385 AddPS4SanitizerArgs(ToolChain, CmdArgs);
10387 Args.AddAllArgs(CmdArgs, options::OPT_L);
10388 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
10389 Args.AddAllArgs(CmdArgs, options::OPT_e);
10390 Args.AddAllArgs(CmdArgs, options::OPT_s);
10391 Args.AddAllArgs(CmdArgs, options::OPT_t);
10392 Args.AddAllArgs(CmdArgs, options::OPT_r);
10394 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
10395 CmdArgs.push_back("--no-demangle");
10397 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
10399 if (Args.hasArg(options::OPT_pthread)) {
10400 CmdArgs.push_back("-lpthread");
10403 const char *Exec = Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld"));
10405 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
10408 static void ConstructGoldLinkJob(const Tool &T, Compilation &C,
10409 const JobAction &JA, const InputInfo &Output,
10410 const InputInfoList &Inputs,
10411 const ArgList &Args,
10412 const char *LinkingOutput) {
10413 const toolchains::FreeBSD &ToolChain =
10414 static_cast<const toolchains::FreeBSD &>(T.getToolChain());
10415 const Driver &D = ToolChain.getDriver();
10416 ArgStringList CmdArgs;
10418 // Silence warning for "clang -g foo.o -o foo"
10419 Args.ClaimAllArgs(options::OPT_g_Group);
10420 // and "clang -emit-llvm foo.o -o foo"
10421 Args.ClaimAllArgs(options::OPT_emit_llvm);
10422 // and for "clang -w foo.o -o foo". Other warning options are already
10423 // handled somewhere else.
10424 Args.ClaimAllArgs(options::OPT_w);
10426 if (!D.SysRoot.empty())
10427 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
10429 if (Args.hasArg(options::OPT_pie))
10430 CmdArgs.push_back("-pie");
10432 if (Args.hasArg(options::OPT_static)) {
10433 CmdArgs.push_back("-Bstatic");
10435 if (Args.hasArg(options::OPT_rdynamic))
10436 CmdArgs.push_back("-export-dynamic");
10437 CmdArgs.push_back("--eh-frame-hdr");
10438 if (Args.hasArg(options::OPT_shared)) {
10439 CmdArgs.push_back("-Bshareable");
10441 CmdArgs.push_back("-dynamic-linker");
10442 CmdArgs.push_back("/libexec/ld-elf.so.1");
10444 CmdArgs.push_back("--enable-new-dtags");
10447 if (Output.isFilename()) {
10448 CmdArgs.push_back("-o");
10449 CmdArgs.push_back(Output.getFilename());
10451 assert(Output.isNothing() && "Invalid output.");
10454 AddPS4SanitizerArgs(ToolChain, CmdArgs);
10456 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10457 const char *crt1 = nullptr;
10458 if (!Args.hasArg(options::OPT_shared)) {
10459 if (Args.hasArg(options::OPT_pg))
10461 else if (Args.hasArg(options::OPT_pie))
10467 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1)));
10469 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o")));
10471 const char *crtbegin = nullptr;
10472 if (Args.hasArg(options::OPT_static))
10473 crtbegin = "crtbeginT.o";
10474 else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
10475 crtbegin = "crtbeginS.o";
10477 crtbegin = "crtbegin.o";
10479 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
10482 Args.AddAllArgs(CmdArgs, options::OPT_L);
10483 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
10484 Args.AddAllArgs(CmdArgs, options::OPT_T_Group);
10485 Args.AddAllArgs(CmdArgs, options::OPT_e);
10486 Args.AddAllArgs(CmdArgs, options::OPT_s);
10487 Args.AddAllArgs(CmdArgs, options::OPT_t);
10488 Args.AddAllArgs(CmdArgs, options::OPT_r);
10490 if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
10491 CmdArgs.push_back("--no-demangle");
10493 AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
10495 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
10496 // For PS4, we always want to pass libm, libstdc++ and libkernel
10497 // libraries for both C and C++ compilations.
10498 CmdArgs.push_back("-lkernel");
10499 if (D.CCCIsCXX()) {
10500 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
10501 if (Args.hasArg(options::OPT_pg))
10502 CmdArgs.push_back("-lm_p");
10504 CmdArgs.push_back("-lm");
10506 // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding
10507 // the default system libraries. Just mimic this for now.
10508 if (Args.hasArg(options::OPT_pg))
10509 CmdArgs.push_back("-lgcc_p");
10511 CmdArgs.push_back("-lcompiler_rt");
10512 if (Args.hasArg(options::OPT_static)) {
10513 CmdArgs.push_back("-lstdc++");
10514 } else if (Args.hasArg(options::OPT_pg)) {
10515 CmdArgs.push_back("-lgcc_eh_p");
10517 CmdArgs.push_back("--as-needed");
10518 CmdArgs.push_back("-lstdc++");
10519 CmdArgs.push_back("--no-as-needed");
10522 if (Args.hasArg(options::OPT_pthread)) {
10523 if (Args.hasArg(options::OPT_pg))
10524 CmdArgs.push_back("-lpthread_p");
10526 CmdArgs.push_back("-lpthread");
10529 if (Args.hasArg(options::OPT_pg)) {
10530 if (Args.hasArg(options::OPT_shared))
10531 CmdArgs.push_back("-lc");
10533 if (Args.hasArg(options::OPT_static)) {
10534 CmdArgs.push_back("--start-group");
10535 CmdArgs.push_back("-lc_p");
10536 CmdArgs.push_back("-lpthread_p");
10537 CmdArgs.push_back("--end-group");
10539 CmdArgs.push_back("-lc_p");
10542 CmdArgs.push_back("-lgcc_p");
10544 if (Args.hasArg(options::OPT_static)) {
10545 CmdArgs.push_back("--start-group");
10546 CmdArgs.push_back("-lc");
10547 CmdArgs.push_back("-lpthread");
10548 CmdArgs.push_back("--end-group");
10550 CmdArgs.push_back("-lc");
10552 CmdArgs.push_back("-lcompiler_rt");
10555 if (Args.hasArg(options::OPT_static)) {
10556 CmdArgs.push_back("-lstdc++");
10557 } else if (Args.hasArg(options::OPT_pg)) {
10558 CmdArgs.push_back("-lgcc_eh_p");
10560 CmdArgs.push_back("--as-needed");
10561 CmdArgs.push_back("-lstdc++");
10562 CmdArgs.push_back("--no-as-needed");
10566 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles)) {
10567 if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
10568 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o")));
10570 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o")));
10571 CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o")));
10575 #ifdef LLVM_ON_WIN32
10576 Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld.gold"));
10578 Args.MakeArgString(ToolChain.GetProgramPath("ps4-ld"));
10581 C.addCommand(llvm::make_unique<Command>(JA, T, Exec, CmdArgs, Inputs));
10584 void PS4cpu::Link::ConstructJob(Compilation &C, const JobAction &JA,
10585 const InputInfo &Output,
10586 const InputInfoList &Inputs,
10587 const ArgList &Args,
10588 const char *LinkingOutput) const {
10589 const toolchains::FreeBSD &ToolChain =
10590 static_cast<const toolchains::FreeBSD &>(getToolChain());
10591 const Driver &D = ToolChain.getDriver();
10593 StringRef LinkerOptName;
10594 if (const Arg *A = Args.getLastArg(options::OPT_fuse_ld_EQ)) {
10595 LinkerOptName = A->getValue();
10596 if (LinkerOptName != "ps4" && LinkerOptName != "gold")
10597 D.Diag(diag::err_drv_unsupported_linker) << LinkerOptName;
10600 if (LinkerOptName == "gold")
10602 else if (LinkerOptName == "ps4")
10605 PS4Linker = !Args.hasArg(options::OPT_shared);
10608 ConstructPS4LinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);
10610 ConstructGoldLinkJob(*this, C, JA, Output, Inputs, Args, LinkingOutput);